diff --git a/Start-DefectRAG.cmd b/Start-DefectRAG.cmd new file mode 100644 index 0000000000000000000000000000000000000000..4a5657587b89ad05dfcc855ee2c017cbee9d75e8 --- /dev/null +++ b/Start-DefectRAG.cmd @@ -0,0 +1,3 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Start-DefectRAG.ps1" %* +pause diff --git a/Start-DefectRAG.ps1 b/Start-DefectRAG.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..0891629cfc9d740e980eb627be309433fde44063 --- /dev/null +++ b/Start-DefectRAG.ps1 @@ -0,0 +1,39 @@ +param([switch]$Setup,[switch]$NoBrowser,[switch]$Verify,[int]$Port=8765,[string]$PythonPath='') +$ErrorActionPreference='Stop' +Set-Location $PSScriptRoot +$env:USE_TF='0' +$localDeps=Join-Path $PSScriptRoot '.python-deps' +if (Test-Path -LiteralPath $localDeps) { $env:PYTHONPATH=$localDeps } +$pythonExe=Join-Path $PSScriptRoot '.venv\Scripts\python.exe' +if ($PythonPath) { $pythonExe=$PythonPath } +elseif (-not (Test-Path -LiteralPath $pythonExe)) { + # No .venv: use DEFECTRAG_PYTHON or the conda env "defectrag" when present. + . (Join-Path $PSScriptRoot 'deployment\project_python.ps1') + try { $pythonExe=Get-ProjectPython } catch { } +} +if (-not (Test-Path -LiteralPath $pythonExe)) { + if (-not $Setup) { throw 'First run: .\Start-DefectRAG.ps1 -Setup. This installs dependencies into a separate venv.' } + & py -3.11 -m venv .venv + if ($LASTEXITCODE -ne 0) { throw 'Python 3.11 is required for automatic setup. Install Python or pass -PythonPath to an existing compatible environment.' } +} +if ($Setup) { + & $pythonExe -m pip install -r requirements.txt + if ($LASTEXITCODE -ne 0) { throw 'Dependency setup failed. Check your network and Python version.' } +} +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.' } +if (-not (Test-Path -LiteralPath 'frontend\dist\index.html')) { + & npm.cmd ci --prefix frontend --no-audit --no-fund + if ($LASTEXITCODE -ne 0) { throw 'Frontend dependency installation failed' } + & npm.cmd run build --prefix frontend + if ($LASTEXITCODE -ne 0) { throw 'Frontend build failed' } +} +if ($Verify) { + & $pythonExe -m scripts.verify_startup + if ($LASTEXITCODE -ne 0) { throw 'Startup validation failed' } + exit 0 +} +Write-Host "DefectRAG: http://127.0.0.1:$Port" +Write-Host 'For generated answers, run Ollama with qwen2.5:3b. Retrieval fallback remains available.' +if (-not $NoBrowser) { Start-Process "http://127.0.0.1:$Port" } +& $pythonExe -m uvicorn backend.main:app --host 127.0.0.1 --port $Port +exit $LASTEXITCODE diff --git a/scripts/consolidate_environment.py b/scripts/consolidate_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..c801117192d2105c07dea00db23590902e4c9f70 --- /dev/null +++ b/scripts/consolidate_environment.py @@ -0,0 +1,117 @@ +"""Repair an already moved Windows venv, or verify the consolidated local app. + +No package downloads, model fitting, archive creation or directory deletion. +Run with the moved .venv/Scripts/python.exe. Moves are handled separately. +""" +import argparse +import importlib.metadata +import json +from pathlib import Path +import sqlite3 +import subprocess +import sys +import venv + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +SUPPORT = ROOT / 'development-support' + + +def save(name, result): + SUPPORT.mkdir(exist_ok=True) + (SUPPORT / name).write_text(json.dumps(result, indent=2), encoding='utf-8') + print(json.dumps(result, indent=2), flush=True) + + +def repair(): + target = ROOT / '.venv' + assert Path(sys.prefix).resolve() == target.resolve(), 'Use this project virtual environment' + assert (ROOT / '.python-deps').is_dir(), 'Local dependency overlay missing' + site = target / 'Lib/site-packages' + (site / 'defectrag-local-deps.pth').write_text('../../../.python-deps\n', encoding='utf-8') + # Refresh activation/configuration without reinstalling packages or copying + # the running executable. Installed CUDA libraries stay untouched. + builder = venv.EnvBuilder(with_pip=False) + context = builder.ensure_directories(str(target)) + builder.create_configuration(context) + builder.setup_scripts(context) + from pip._vendor.distlib.scripts import ScriptMaker + maker = ScriptMaker(None, str(target / 'Scripts')) + maker.executable = str(target / 'Scripts/python.exe') + maker.clobber = True + maker.variants = {''} + written = set() + for distribution in importlib.metadata.distributions(): + for entry in distribution.entry_points: + if entry.group not in ('console_scripts', 'gui_scripts') or entry.name in written: + continue + if Path(entry.name).name != entry.name: + raise ValueError('Unsafe installed entry point') + maker.make(entry.name + ' = ' + entry.value, + options={'gui': entry.group == 'gui_scripts'}) + written.add(entry.name) + for name in ('pip', 'pip3', 'pip3.12'): + maker.make(name + ' = pip._internal.cli.main:main') + save('environment-relocation.json', {'status': 'passed', 'python': sys.executable, + 'repaired_console_entry_points': len(written), 'packages_reinstalled': False}) + + +def verify(): + import torch + from backend.config import Settings, CATEGORIES + from backend.main import create_app + from fastapi.testclient import TestClient + from backend.vision import sha256 + assert Path(sys.prefix).resolve() == (ROOT / '.venv').resolve() + for module in ('fastapi', 'uvicorn', 'transformers', 'langchain_core', + 'langchain_community', 'langchain_text_splitters', 'langgraph'): + __import__(module) + verified = 0 + for experiment in ('official_visa_v1', 'dinov2_highres_v1'): + for category in CATEGORIES: + folder = ROOT / 'experiments' / experiment / category + receipt = json.loads((folder / 'complete.json').read_text()) + for name, expected in receipt['files'].items(): + assert sha256(folder / name) == expected, str(folder / name) + verified += 1 + # Private rows must survive consolidation unchanged. + backup = SUPPORT / 'saved-runtime/desktop-before-highres.sqlite3' + with sqlite3.connect(backup.as_uri() + '?mode=ro', uri=True) as old: + with sqlite3.connect((ROOT / 'runtime/inspection.sqlite3').as_uri() + '?mode=ro', uri=True) as current: + for table in ('inspections', 'messages'): + rows = set(current.execute('select * from ' + table).fetchall()) + assert all(row in rows for row in old.execute('select * from ' + table)) + app = create_app(Settings(data=ROOT / 'runtime/consolidation-check')) + with TestClient(app) as client: + assert client.get('/').status_code == 200 + assert client.get('/api/health').status_code == 200 + sample = ROOT / 'samples/pcb1_anomalous.jpg' + response = client.post('/api/inspect', data={'category': 'pcb1', 'batch': 'consolidation-check'}, + files={'file': (sample.name, sample.read_bytes(), 'image/jpeg')}) + response.raise_for_status() + record = response.json()['data'] + assert record['model_id'] == 'dinov2-highres-pcb1-v1' + assert client.get(record['heatmap_url']).status_code == 200 + answer = client.post('/api/assistant', json={'inspection_id': record['id'], + 'question': 'Is this image anomalous?'}) + answer.raise_for_status() + assert record['verdict'] in answer.json()['data']['answer'] + for executable in ('pip.exe', 'uvicorn.exe'): + subprocess.run([str(ROOT / '.venv/Scripts' / executable), '--version'], check=True) + save('consolidation-verification.json', {'status': 'passed', 'python': sys.executable, + 'torch': torch.__version__, 'cuda': torch.cuda.is_available(), + 'experiment_files_hash_verified': verified, 'complete_experiments': 2, + 'categories_each': 12, 'private_history': 'preserved', + 'real_api_inspection': {key: record[key] for key in ('model_id', 'score', 'verdict', 'device')}, + 'assistant': 'passed', 'console_launchers': 'passed', 'packages_reinstalled': False}) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--repair', action='store_true') + parser.add_argument('--verify', action='store_true') + args = parser.parse_args() + if args.repair: + repair() + if args.verify: + verify() diff --git a/scripts/diagnose_encoder.py b/scripts/diagnose_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..9c882ae13fbe25a5f4be9a3a268e148c7861fa65 --- /dev/null +++ b/scripts/diagnose_encoder.py @@ -0,0 +1,146 @@ +"""Where does the frozen DINOv2 detector fail? A read-only diagnostic. + + python -m scripts.diagnose_encoder + +It reads only files that already exist: the cached per-image test scores and held-out normal +calibration scores in experiments/dinov2_highres_v1// (thresholds are rebuilt from the +calibration scores: q95 for every category, plus the deployed q80 for Macaroni1/2), the VisA annotation +CSV (defect type text) and the VisA masks (defect size). +No model is loaded, nothing is trained and nothing in the app is changed. Masks are used for +diagnosis only. Results are written to results/encoder_diagnostic.json. + +These test images were already seen during development, so the figures are descriptive, not a +fresh validation. +""" + +import csv +import json + +import numpy as np +from PIL import Image + +from backend.config import ROOT + +RUNS = ROOT / "experiments" / "dinov2_highres_v1" +VISA = ROOT / "VisA_20220922" +OUT = ROOT / "results" / "encoder_diagnostic.json" +MIN_GROUP = 8 # below this many anomalous images a rate is too noisy to read +DEPLOYED_BANK = 3 # bank_3 is the operational bank; banks 0-2 are the benchmark seeds +DEPLOYED_QUANTILE = {"macaroni1": 0.80, "macaroni2": 0.80} # macaroni-recall-v1 policy; every other category is q95 + + +def auroc(positive, negative): + """Probability that a random anomaly scores higher than a random normal (ties count half).""" + p, n = np.asarray(positive, float), np.asarray(negative, float) + if len(p) == 0 or len(n) == 0: + return None + greater = (p[:, None] > n[None, :]).sum() + ties = (p[:, None] == n[None, :]).sum() + return float((greater + 0.5 * ties) / (len(p) * len(n))) + + +def mask_fraction(path): + with Image.open(path) as image: + return float((np.asarray(image.convert("L")) > 0).mean()) + + +def analyse(category): + rows = json.loads((RUNS / category / "test_progress.json").read_text(encoding="utf-8")) + calibration = json.loads((RUNS / category / "normal_calibration.json").read_text(encoding="utf-8")) + held_out = np.array([p["score"] for p in calibration["predictions"]]) + annotations = {r["image"]: r for r in csv.DictReader((VISA / category / "image_anno.csv").open(encoding="utf-8"))} + # The cards in models/highres still hold the older "maximum held-out normal" threshold. The deployed + # thresholds are linear quantiles of the held-out normal scores: q95 everywhere, q80 for Macaroni1/2. + q95 = float(np.quantile(held_out, 0.95)) + deployed_quantile = DEPLOYED_QUANTILE.get(category, 0.95) + threshold = float(np.quantile(held_out, deployed_quantile)) + items = [] + for row in rows: + note = annotations[row["image"]] + entry = {"label": row["label"], "score": row["scores"][DEPLOYED_BANK], "image": row["image"]} + if row["label"] == 1: + entry["types"] = [t.strip() for t in note["label"].split(",") if t.strip()] or ["unlabelled"] + entry["area"] = mask_fraction(VISA / note["mask"]) if note["mask"] else None + items.append(entry) + normal = np.array([i["score"] for i in items if i["label"] == 0]) + anomaly = [i for i in items if i["label"] == 1] + anomaly_scores = np.array([i["score"] for i in anomaly]) + seeds = [auroc([r["scores"][b] for r in rows if r["label"] == 1], [r["scores"][b] for r in rows if r["label"] == 0]) + for b in range(len(rows[0]["scores"]))] + result = { + "deployed_policy": f"q{round(deployed_quantile * 100)}", + "threshold": threshold, + "threshold_q95": q95, + "recall_at_q95": float((anomaly_scores >= q95).mean()), + "normal_false_alarm_rate_at_q95": float((normal >= q95).mean()), + "n_normal": int(len(normal)), + "n_anomaly": int(len(anomaly)), + "auroc_deployed": auroc(anomaly_scores, normal), + "auroc_all_banks": [round(s, 4) for s in seeds], + "recall_at_threshold": float((anomaly_scores >= threshold).mean()), + "normal_false_alarm_rate": float((normal >= threshold).mean()), + "normal_score_median": float(np.median(normal)), + "normal_score_p95": float(np.percentile(normal, 95)), + "anomaly_score_median": float(np.median(anomaly_scores)), + } + by_type = {} + for name in sorted({t for i in anomaly for t in i["types"]}): + group = [i["score"] for i in anomaly if name in i["types"]] + by_type[name] = { + "n": len(group), + "detected_at_threshold": float((np.array(group) >= threshold).mean()), + "auroc_vs_normals": auroc(group, normal), + } + result["by_defect_type"] = by_type + sized = [i for i in anomaly if i.get("area") is not None] + if len(sized) >= 3 * MIN_GROUP: + cuts = np.quantile([i["area"] for i in sized], [1 / 3, 2 / 3]) + buckets = {"small": lambda a: a <= cuts[0], "medium": lambda a: cuts[0] < a <= cuts[1], "large": lambda a: a > cuts[1]} + by_size = {} + for name, test in buckets.items(): + group = [i for i in sized if test(i["area"])] + scores = np.array([i["score"] for i in group]) + by_size[name] = { + "n": len(group), + "median_mask_area_percent": round(100 * float(np.median([i["area"] for i in group])), 3), + "detected_at_threshold": float((scores >= threshold).mean()), + "auroc_vs_normals": auroc(scores, normal), + } + result["by_defect_size"] = by_size + return result + + +def main(): + categories = sorted(p.name for p in RUNS.iterdir() if (p / "test_progress.json").exists()) + report = {} + for category in categories: + report[category] = analyse(category) + OUT.write_text(json.dumps(report, indent=2), encoding="utf-8") + + print("Per category, deployed bank (descriptive, development-exposed test set).") + print("AUROC does not depend on the threshold. 'q95' columns compare every category on the same policy;") + print("'deployed' shows the policy the app really uses (q80 for macaroni1/2).\n") + print(f"{'category':<11}{'AUROC':>7}{'bank spread':>13} | {'q95 recall':>10}{'q95 false':>10} | {'deployed':>8}{'recall':>8}{'false':>7}") + for name, r in sorted(report.items(), key=lambda kv: kv[1]["auroc_deployed"]): + spread = max(r["auroc_all_banks"]) - min(r["auroc_all_banks"]) + 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%} | " + f"{r['deployed_policy']:>8}{r['recall_at_threshold']:>8.0%}{r['normal_false_alarm_rate']:>7.0%}") + print("\nWeakest categories: by defect size (small / medium / large thirds of the anomalous test images)") + for name, r in sorted(report.items(), key=lambda kv: kv[1]["auroc_deployed"])[:5]: + size = r.get("by_defect_size") + if not size: + continue + cells = " ".join(f"{k}: AUROC {v['auroc_vs_normals']:.2f}, found {v['detected_at_threshold']:.0%} " + f"(median {v['median_mask_area_percent']}% of image)" for k, v in size.items()) + print(f" {name:<10}{cells}") + print(f"\nWeakest categories: by defect type (groups with at least {MIN_GROUP} images)") + for name, r in sorted(report.items(), key=lambda kv: kv[1]["auroc_deployed"])[:5]: + print(f" {name}") + for kind, v in sorted(r["by_defect_type"].items(), key=lambda kv: kv[1]["auroc_vs_normals"]): + if v["n"] >= MIN_GROUP: + print(f" {kind[:60]:<60} n={v['n']:<3} AUROC {v['auroc_vs_normals']:.2f} found {v['detected_at_threshold']:.0%}") + print(f"\nWritten to {OUT.relative_to(ROOT)}. Nothing else was touched.") + + +if __name__ == "__main__": + main() diff --git a/scripts/diagnose_rag.py b/scripts/diagnose_rag.py new file mode 100644 index 0000000000000000000000000000000000000000..100adc56c656abe3679d636d8eee83a27408c2bc --- /dev/null +++ b/scripts/diagnose_rag.py @@ -0,0 +1,24 @@ +"""Read existing local inspection evidence and capture one raw Qwen response.""" +import json +import httpx +from backend.config import ROOT +from backend.rag import PROMPT + +def main(): + with httpx.Client(timeout=100,trust_env=False) as client: + base='http://127.0.0.1:8766' + health=client.get(base+'/api/health');health.raise_for_status() + records=client.get(base+'/api/inspections?category=pcb1').json()['data'] + record=records[-1] + question='Explain this anomaly score and its limitations.' + response=client.post(base+'/api/retrieve',json={'question':question+' pcb1 anomaly inspection'}) + response.raise_for_status();evidence=response.json()['data'] + fields={k:record.get(k) for k in ('category','verdict','score','threshold','scope','localization')} + prompt=PROMPT.format(inspection=json.dumps(fields),history='[]',question=question,evidence=json.dumps(evidence)) + 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}}) + response.raise_for_status() + body=response.json() + report={'inspection_id':record['id'],'question':question,'evidence':evidence,'raw_response':body} + (ROOT/'results'/'rag_diagnostic.json').write_text(json.dumps(report,indent=2)) + 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) +if __name__=='__main__':main() diff --git a/scripts/download_visa.py b/scripts/download_visa.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e3fdf0dc164e956e65e93b667b36bb91d0f620 --- /dev/null +++ b/scripts/download_visa.py @@ -0,0 +1,31 @@ +"""Explicit opt-in downloader. No download happens during app startup.""" +import argparse +import hashlib +import tarfile +import urllib.request +from pathlib import Path + +URL='https://amazon-visual-anomaly.s3.us-west-2.amazonaws.com/VisA_20220922.tar' +EXPECTED='2eb8690c803ab37de0324772964100169ec8ba1fa3f7e94291c9ca673f40f362' +def main(): + parser=argparse.ArgumentParser() + parser.add_argument('--destination',type=Path,required=True) + parser.add_argument('--authorize-download',action='store_true',help='Explicit approval for the multi-GB dataset download') + args=parser.parse_args() + if not args.authorize_download: parser.error('Major dataset download requires --authorize-download') + args.destination.mkdir(parents=True,exist_ok=True) + archive=args.destination/'VisA_20220922.tar' + if not archive.exists(): urllib.request.urlretrieve(URL,archive) + digest=hashlib.sha256() + with archive.open('rb') as stream: + for block in iter(lambda:stream.read(1024*1024),b''):digest.update(block) + if digest.hexdigest()!=EXPECTED: raise RuntimeError('Dataset archive checksum mismatch; extraction refused') + with tarfile.open(archive) as tar: + # Python 3.11.8+ provides the data filter; refuse links and traversal explicitly too. + base=args.destination.resolve() + for item in tar.getmembers(): + target=(base/item.name).resolve() + if not target.is_relative_to(base) or item.issym() or item.islnk(): raise ValueError('Unsafe archive member') + tar.extractall(base,filter='data') + print('Dataset extracted and checksum verified') +if __name__=='__main__': main() diff --git a/scripts/encoder_banks.py b/scripts/encoder_banks.py new file mode 100644 index 0000000000000000000000000000000000000000..32001639d5d1af48a2c0a0138db429ea8c7f15a5 --- /dev/null +++ b/scripts/encoder_banks.py @@ -0,0 +1,225 @@ +"""Smaller banks, rotated banks and a DINOv3 bank (round 3 of the detector study; needs the GPU). + + python -m scripts.encoder_banks --smoke --categories macaroni2 # quick check + python -m scripts.encoder_banks # all 12 categories + +Round 2 (scripts.encoder_candidates) showed that using every normal patch as the memory bank beats the deployed +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 +and still keep the gain, and tests two more ideas. Nothing is trained and nothing in the app is changed. Candidates, +fixed before any result: + + cap128/256/512 random patches per training image (3/4 foreground, 1/4 other, the deployed recipe scaled up) + core32k/64k/96k greedy farthest-point coreset of all patches (random 128-d projection, the PatchCore idea) + rot four rotations (0/90/180/270 degrees) of every training image, 256 random patches each; about + as many patches as the full bank, so the full bank is its control + dinov3full the retained DINOv3 ViT-S/16 with a full bank, scored over all patches (no foreground mask) + base the deployed bank, recomputed to prove the harness matches the app + +Scores are written to experiments/dinov2_banks/.json; scripts.encoder_candidates_report merges them with the +round-2 scores. Test images were already seen during development, so results are descriptive. +""" + +import argparse +import json +import time + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image +from transformers import AutoModel + +from backend.config import CATEGORIES, ROOT +from backend.highres import HighResolutionEncoder, foreground_mask +from backend.vision import distances +from scripts.diagnose_encoder import auroc +from scripts.encoder_candidates import RUNS, SOURCE, encode, knn_distance, open_image, top_mean + +OUT = ROOT / "experiments" / "dinov2_banks" +DINOV3 = ROOT / "models" / "encoder" +CAPS = (128, 256, 512) +CORESETS = {"core32k": 32768, "core64k": 65536, "core96k": 98304} +ROTATION_CAP = 256 +PROJECTION = 128 +ROTATIONS = (None, Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, Image.Transpose.ROTATE_270) +CANDIDATES = ("base", *(f"cap{c}" for c in CAPS), *CORESETS, "rot", "dinov3full") + + +class Dinov3: + """The retained DINOv3 ViT-S/16, frozen, with the same short-edge-448 preprocessing as the DINOv2 detector.""" + + def __init__(self, device): + self.device = device + self.model = AutoModel.from_pretrained(str(DINOV3), local_files_only=True).eval().to(device).half() + self.model.requires_grad_(False) + self.patch = int(self.model.config.patch_size) + self.skip = 1 + int(self.model.config.num_register_tokens) + self.mean = torch.tensor([0.485, 0.456, 0.406], device=device, dtype=torch.half)[:, None, None] + self.std = torch.tensor([0.229, 0.224, 0.225], device=device, dtype=torch.half)[:, None, None] + + @torch.inference_mode() + def patches(self, image, resolution=448): + width, height = image.size + factor = resolution / min(width, height) + resized = (int(width * factor), int(height * factor)) + cropped = tuple(v - v % self.patch for v in resized) + pixels = np.array(image.resize(resized, Image.Resampling.BICUBIC).crop((0, 0, *cropped)), copy=True) + values = torch.from_numpy(pixels).permute(2, 0, 1).to(self.device, dtype=torch.half) / 255 + out = self.model(pixel_values=((values - self.mean) / self.std)[None]).last_hidden_state[0, self.skip :] + return F.normalize(out.float(), dim=-1) + + +def pick(mask, cap, rng): + """Random patch indices: 3/4 of the cap from the foreground, 1/4 from the rest (the deployed 48 + 16 recipe).""" + foreground, other = np.flatnonzero(mask), np.flatnonzero(~mask) + return np.r_[ + rng.choice(foreground, min(cap * 3 // 4, len(foreground)), replace=False), + rng.choice(other, min(cap // 4, len(other)), replace=False), + ].astype(int) + + +@torch.inference_mode() +def greedy_coreset(points, count, seed): + """Farthest-point selection in a random 128-d projection. The first n picks form the n-patch coreset.""" + device = points.device + generator = torch.Generator(device=device).manual_seed(seed) + projection = torch.randn(points.shape[1], PROJECTION, device=device, generator=generator) / PROJECTION**0.5 + small = torch.cat([(part.float() @ projection).half() for part in points.split(65536)]) + norms = (small.float() ** 2).sum(1) + first = torch.randint(len(small), (1,), device=device, generator=generator)[0] + chosen = torch.empty(count, dtype=torch.long, device=device) + chosen[0] = first + nearest = (norms - 2 * (small @ small[first]).float() + norms[first]).clamp_min(0) + for i in range(1, count): + index = nearest.argmax() + chosen[i] = index + nearest = torch.minimum(nearest, (norms - 2 * (small @ small[index]).float() + norms[index]).clamp_min(0)) + return chosen + + +def run_category(category, encoder, smoke): + run = RUNS / category + split = json.loads((run / "split.json").read_text(encoding="utf-8")) + calibration = json.loads((run / "normal_calibration.json").read_text(encoding="utf-8")) + cached = {r["image"]: r["scores"][3] for r in json.loads((run / "test_progress.json").read_text(encoding="utf-8"))} + held_names = [p["image"] for p in calibration["predictions"]] + skip = set(held_names) + fit_names = [r["image"] for r in split["train"] if r["image"] not in skip] + test_rows = split["test"] + if smoke: + fit_names, held_names = fit_names[:100], held_names[:20] + test_rows = test_rows[:: max(1, len(test_rows) // 40)] + names = held_names + [r["image"] for r in test_rows] + device = encoder.device + started = time.perf_counter() + scores = {name: {} for name in names} + + # DINOv2: encode every training normal and build the sampled, coreset and rotated banks. + fine, capped, rotated = [], {c: [] for c in CAPS}, [] + for number, name in enumerate(fit_names): + image = open_image(name) + for turn, rotation in enumerate(ROTATIONS): + view = image if rotation is None else image.transpose(rotation) + tokens, _, grid = encode(encoder, view, 448) + mask = foreground_mask(tokens, grid) + normal = F.normalize(tokens, dim=-1).half() + rng = np.random.default_rng(1000 * number + turn) + rotated.append(normal[torch.as_tensor(pick(mask, ROTATION_CAP, rng), device=device)]) + if turn == 0: + fine.append(normal) + for cap in CAPS: + capped[cap].append( + normal[torch.as_tensor(pick(mask, cap, np.random.default_rng(number + cap)), device=device)] + ) + banks = {f"cap{c}": torch.cat(parts) for c, parts in capped.items()} + banks["rot"] = torch.cat(rotated) + everything = torch.cat(fine) + del fine, capped, rotated + coreset = greedy_coreset(everything, max(CORESETS.values()), seed=42) + for label, size in CORESETS.items(): + banks[label] = everything[coreset[:size]].clone() + sizes = {label: len(bank) for label, bank in banks.items()} + sizes["all_patches"] = len(everything) + del everything + with np.load(run / "bank_3.npz") as saved: + base_bank = F.normalize(torch.from_numpy(saved["patches"].astype("float32")).to(device), dim=-1) + sizes["base"] = len(base_bank) + fit_seconds = time.perf_counter() - started + + for name in names: + tokens, _, grid = encode(encoder, open_image(name), 448) + mask = torch.as_tensor(foreground_mask(tokens, grid), device=device) + normal = F.normalize(tokens, dim=-1) + scores[name]["base"] = top_mean(distances(normal, base_bank), mask) + for label, bank in banks.items(): + scores[name][label] = top_mean(knn_distance(normal, bank), mask) + del banks, base_bank + torch.cuda.empty_cache() + + # DINOv3: a full bank, scored over all patches. + third = Dinov3(device) + bank = torch.cat([third.patches(open_image(n)).half() for n in fit_names]) + sizes["dinov3full"] = len(bank) + for name in names: + patches = third.patches(open_image(name)) + everywhere = torch.ones(len(patches), dtype=torch.bool, device=device) + scores[name]["dinov3full"] = top_mean(knn_distance(patches, bank), everywhere) + del bank, third + torch.cuda.empty_cache() + + differences = [abs(scores[r["image"]]["base"] - cached[r["image"]]) for r in test_rows] + return { + "category": category, + "smoke": smoke, + "n_fit": len(fit_names), + "bank_patches": sizes, + "reproduction": { + "test_max_abs_difference": max(differences), + "test_mean_abs_difference": float(np.mean(differences)), + }, + "seconds_fit": round(fit_seconds, 1), + "seconds_total": round(time.perf_counter() - started, 1), + "heldout": {n: scores[n] for n in held_names}, + "test": {r["image"]: scores[r["image"]] for r in test_rows}, + "labels": {r["image"]: 0 if r["label"] == "normal" else 1 for r in test_rows}, + } + + +def summarise(record): + labels = record["labels"] + positive = [n for n, v in labels.items() if v == 1] + negative = [n for n, v in labels.items() if v == 0] + return " ".join( + f"{c} {auroc([record['test'][n][c] for n in positive], [record['test'][n][c] for n in negative]):.3f}" + for c in CANDIDATES + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--categories", nargs="+", choices=CATEGORIES, default=list(CATEGORIES)) + parser.add_argument("--smoke", action="store_true", help="100 fit images, 20 held-out, about 40 test images") + parser.add_argument("--force", action="store_true", help="recompute categories that already have a result file") + args = parser.parse_args() + OUT.mkdir(parents=True, exist_ok=True) + encoder = HighResolutionEncoder(SOURCE) + for category in args.categories: + target = OUT / (f"{category}.smoke.json" if args.smoke else f"{category}.json") + if target.exists() and not args.force: + print(f"{category}: already done ({target.name})", flush=True) + continue + record = run_category(category, encoder, args.smoke) + torch.cuda.empty_cache() + target.write_text(json.dumps(record), encoding="utf-8") + rep = record["reproduction"] + print( + f"{category}: {record['seconds_total']} s (fit {record['seconds_fit']} s) | reproduces the app: " + f"max diff {rep['test_max_abs_difference']:.4f}", + flush=True, + ) + print(" bank patches " + " ".join(f"{k}={v:,}" for k, v in record["bank_patches"].items()), flush=True) + print(" AUROC " + summarise(record), flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/encoder_banks_report.py b/scripts/encoder_banks_report.py new file mode 100644 index 0000000000000000000000000000000000000000..d722de3e8ce7ce4465ef01b3a71f884d7ea93065 --- /dev/null +++ b/scripts/encoder_banks_report.py @@ -0,0 +1,167 @@ +"""Report for round 3 (CPU only; run scripts.encoder_banks first). + + python -m scripts.encoder_banks_report + +Merges the round-3 scores (experiments/dinov2_banks) with the round-2 scores (experiments/dinov2_candidates) and uses +the same rules as scripts.encoder_candidates_report: scores standardised with the 90 held-out normals only, paired +bootstrap 95% intervals of the AUROC difference, thresholds from held-out normals only. The one fusion is fixed +here, before any result: the full DINOv2 bank averaged with the DINOv3 full bank. Descriptive only, because the test +images were already seen during development. +""" + +import json + +import numpy as np + +from backend.config import ROOT +from scripts.diagnose_encoder import auroc +from scripts.encoder_candidates_report import ( + DEPLOYED_QUANTILE, + HARD_TYPES, + RESULTS, + anomaly_types, + bootstrap_difference, + standardised, +) + +BANKS = ROOT / "experiments" / "dinov2_banks" +OUT = ROOT / "results" / "encoder_banks.json" +SIZES = ("base", "cap128", "cap256", "cap512", "core32k", "core64k", "core96k", "full") +OTHERS = ("base", "full", "rot", "dinov3full", "full+dinov3full") +FUSION = {"full+dinov3full": ("full", "dinov3full")} +WEAK = ("macaroni1", "macaroni2", "pcb2") +BYTES_PER_PATCH = 384 * 2 # half precision + + +def load(): + merged = {} + for path in sorted(BANKS.glob("*.json")): + if ".smoke" in path.name: + continue + banks = json.loads(path.read_text(encoding="utf-8")) + earlier = json.loads((RESULTS / path.name).read_text(encoding="utf-8")) + for split in ("heldout", "test"): + for name, scores in banks[split].items(): + earlier[split][name].update(scores) + earlier["bank_patches"].update(banks["bank_patches"]) + earlier["bank_patches"]["all_patches"] = banks["bank_patches"]["all_patches"] + earlier["reproduction_round3"] = banks["reproduction"]["test_max_abs_difference"] + merged[path.stem] = earlier + return merged + + +def main(): + rng = np.random.default_rng(2027) + records = load() + categories = list(records) + methods = [m for m in dict.fromkeys(SIZES + OTHERS) if m != "base"] + report = {} + for category, record in records.items(): + names = sorted(record["test"]) + labels = np.array([record["labels"][n] for n in names]) + _, base_test = standardised(record, ("base",)) + _, full_test = standardised(record, ("full",)) + entry = {} + for name in ["base"] + methods: + got = standardised(record, FUSION.get(name, (name,))) + if got is None: + continue + held, test = got + result = { + "auroc": auroc(test[labels == 1], test[labels == 0]), + "vs_base": None if name == "base" else bootstrap_difference(labels, test, base_test, rng).tolist(), + "vs_full": None + if name in ("base", "full") + else bootstrap_difference(labels, test, full_test, rng).tolist(), + } + for label, quantile in (("q95", 0.95), ("deployed", DEPLOYED_QUANTILE.get(category, 0.95))): + threshold = np.quantile(held, quantile) + result[f"recall_{label}"] = float((test[labels == 1] >= threshold).mean()) + result[f"false_alarm_{label}"] = float((test[labels == 0] >= threshold).mean()) + if category in HARD_TYPES: + kinds = anomaly_types(category, names) + hard = np.array([HARD_TYPES[category] in kinds[n] for n in names]) + result["auroc_hard_type"] = auroc(test[hard & (labels == 1)], test[labels == 0]) + entry[name] = result + report[category] = entry + OUT.write_text(json.dumps(report, indent=2), encoding="utf-8") + print( + f"Categories analysed: {len(categories)} (round-3 harness reproduces the app within " + f"{max(r['reproduction_round3'] for r in records.values()):.5f})\n" + ) + + def mark(m, key): + interval = m.get(key) + if not interval: + return " " + return " ▲" if interval[0] > 0 else " ▼" if interval[1] < 0 else " " + + def table(columns, key, title): + print(title) + print(f"{'category':<11}" + "".join(f"{c:>17}" for c in columns)) + for category in categories: + cells = [] + for c in columns: + m = report[category].get(c) + cells.append(f"{'n/a':>17}" if m is None else f"{m['auroc']:>15.3f}{mark(m, key)}") + print(f"{category:<11}" + "".join(cells)) + means = [] + for c in columns: + values = [report[k][c]["auroc"] for k in categories if c in report[k]] + means.append(f"{np.mean(values):>17.3f}" if len(values) == len(categories) else f"{'n/a':>17}") + print(f"{'MEAN':<11}" + "".join(means) + "\n") + + table(SIZES, "vs_base", "Bank size: AUROC (▲/▼ = clearly better/worse than the deployed bank)") + + print("Bank size summary") + print( + f"{'bank':<10}{'patches/cat':>13}{'MB (analysed)':>15}{'mean AUROC':>12}{'gain kept':>11}{'weak 3':>8}{'worse than full':>17}" + ) + base_mean = np.mean([report[k]["base"]["auroc"] for k in categories]) + full_mean = np.mean([report[k]["full"]["auroc"] for k in categories]) + for name in SIZES: + sizes = [record["bank_patches"][name] for record in records.values()] + mean = np.mean([report[k][name]["auroc"] for k in categories]) + weak_values = [report[k][name]["auroc"] for k in WEAK if k in report] + weak = np.mean(weak_values) if weak_values else float("nan") + worse = sum(1 for k in categories if mark(report[k][name], "vs_full") == " ▼") + kept = (mean - base_mean) / (full_mean - base_mean) + print( + 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}" + ) + print() + + table(OTHERS, "vs_full", "Rotation and DINOv3: AUROC (▲/▼ = clearly better/worse than the FULL bank)") + + cols = ("base", "full", "cap512", "core64k", "core96k", "rot", "dinov3full") + print("Hard defect types (AUROC of that type against all normals)") + print(f"{'category / type':<40}" + "".join(f"{c:>12}" for c in cols)) + for category, kind in HARD_TYPES.items(): + if category in report: + values = [report[category].get(c, {}).get("auroc_hard_type") for c in cols] + print( + f"{category + ' / ' + kind:<40}" + + "".join(f"{'n/a':>12}" if v is None else f"{v:>12.3f}" for v in values) + ) + + affordable = [m for m in SIZES if m not in ("base", "full")] + best = max(affordable, key=lambda m: np.mean([report[k][m]["auroc"] for k in categories])) + print( + f"\nOperating points, q95 for every category (best affordable bank by mean AUROC: {best}); " + "deployed = q80 for macaroni1/2" + ) + print( + f"{'category':<11}{'method':<10}{'AUROC':>7}{'q95 recall':>12}{'q95 false':>11}{'dep. recall':>13}{'dep. false':>12}" + ) + for category in (c for c in ("macaroni1", "macaroni2", "pcb2", "candle", "cashew") if c in report): + for name in ("base", best, "full"): + m = report[category][name] + print( + f"{category:<11}{name:<10}{m['auroc']:>7.3f}{m['recall_q95']:>12.0%}{m['false_alarm_q95']:>11.0%}" + f"{m['recall_deployed']:>13.0%}{m['false_alarm_deployed']:>12.0%}" + ) + print("\nWritten to results/encoder_banks.json. Descriptive only (test images already seen in development).") + + +if __name__ == "__main__": + main() diff --git a/scripts/encoder_candidates.py b/scripts/encoder_candidates.py new file mode 100644 index 0000000000000000000000000000000000000000..aa9405fbe31e125b6be3ec09bab39f965cbe9ac6 --- /dev/null +++ b/scripts/encoder_candidates.py @@ -0,0 +1,240 @@ +"""Score extra detector candidates on the frozen DINOv2 features (step 1 of 2: needs the GPU). + + python -m scripts.encoder_candidates --smoke --categories macaroni2 # quick check, about a minute + python -m scripts.encoder_candidates # all 12 categories + +Nothing is trained and nothing in the app is changed. For each category it encodes the official VisA training normals +(the 810 used to fit the deployed bank), the 90 held-out normals and the 200 official test images, and records one +score per image for each candidate. Step 2 (scripts.encoder_candidates_report, CPU only) compares them. + +Candidates (all fixed before looking at any result; the same top-1% foreground rule as the app): + base the deployed bank (32,768 sampled patches), recomputed here to prove the harness matches the app + full every patch of every fit normal as the bank (no sampling) + fullfg only the foreground patches of every fit normal + pos position-aware: nearest normal patch at the same place, within one patch of shift (aligned objects) + cls image-level distance between class tokens (global view) + meanpool image-level distance between mean foreground patch features + coarse the same idea at half the resolution (short edge 224) with a full bank (wider context) + +Masks and defect labels are never read here. Test images were already seen during development, so results are +descriptive, not a fresh validation. +""" + +import argparse +import json +import math +import time + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image + +from backend.config import CATEGORIES, ROOT +from backend.highres import HighResolutionEncoder, foreground_mask +from backend.vision import distances +from scripts.diagnose_encoder import auroc + +RUNS = ROOT / "experiments" / "dinov2_highres_v1" +OUT = ROOT / "experiments" / "dinov2_candidates" +VISA = ROOT / "VisA_20220922" +SOURCE = ROOT / "models" / "encoder_dinov2" +OFFSETS = [(dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)] +CANDIDATES = ("base", "full", "fullfg", "pos", "cls", "meanpool", "coarse") + + +@torch.inference_mode() +def encode(encoder, image, resolution): + """Same preprocessing as HighResolutionEncoder.encode, but also returns the class token.""" + width, height = image.size + factor = resolution / min(width, height) + resized = (int(width * factor), int(height * factor)) + cropped = tuple(v - v % encoder.patch_size for v in resized) + pixels = np.array(image.resize(resized, Image.Resampling.BICUBIC).crop((0, 0, *cropped)), copy=True) + values = torch.from_numpy(pixels).permute(2, 0, 1).to(encoder.device, dtype=encoder.dtype) / 255 + out = encoder.model(pixel_values=((values - encoder.mean) / encoder.std)[None]).last_hidden_state[0].float() + grid = (cropped[1] // encoder.patch_size, cropped[0] // encoder.patch_size) + return out[1:], out[0], grid + + +def top_mean(distance, mask): + """Mean of the largest 1% of foreground patch distances (the app's image score).""" + selected = distance[mask] + return float(selected.topk(max(1, math.ceil(len(selected) * 0.01))).values.mean()) + + +def knn_distance(patches, bank, chunk=32768): + """1 - highest cosine similarity to any bank patch; the bank is stored in half precision.""" + best = torch.full((len(patches),), -1.0, device=patches.device) + for part in bank.split(chunk): + best = torch.maximum(best, (patches @ part.float().T).amax(dim=1)) + return (1 - best).clamp_min(0) + + +def positional_distance(patches, stack, grid): + """Nearest normal patch at the same grid position or one step away; stack is [positions, images, features].""" + height, width = grid + device = patches.device + ys = torch.arange(height, device=device).repeat_interleave(width) + xs = torch.arange(width, device=device).repeat(height) + query = patches.half()[:, :, None] + best = torch.full((len(patches),), -1.0, device=device) + for dy, dx in OFFSETS: + y2, x2 = ys + dy, xs + dx + valid = (y2 >= 0) & (y2 < height) & (x2 >= 0) & (x2 < width) + index = y2.clamp(0, height - 1) * width + x2.clamp(0, width - 1) + similarity = torch.bmm(stack[index], query).squeeze(-1).amax(dim=1).float() + best = torch.where(valid, torch.maximum(best, similarity), best) + return (1 - best).clamp_min(0) + + +def open_image(relative): + return Image.open(VISA / relative).convert("RGB") + + +def run_category(category, encoder, smoke): + run = RUNS / category + split = json.loads((run / "split.json").read_text(encoding="utf-8")) + calibration = json.loads((run / "normal_calibration.json").read_text(encoding="utf-8")) + cached = {r["image"]: r["scores"][3] for r in json.loads((run / "test_progress.json").read_text(encoding="utf-8"))} + held_names = [p["image"] for p in calibration["predictions"]] + held_saved = {p["image"]: p["score"] for p in calibration["predictions"]} + skip = set(held_names) + fit_names = [r["image"] for r in split["train"] if r["image"] not in skip] + test_rows = split["test"] + if smoke: + fit_names = fit_names[:100] + held_names = held_names[:20] + test_rows = test_rows[:: max(1, len(test_rows) // 40)] + device = encoder.device + started = time.perf_counter() + + # Fit: encode every training normal at both scales and keep the features on the GPU. + fine, fine_fg, coarse, cls_rows, mean_rows, same_grid = [], [], [], [], [], [] + pos_grid = None + for name in fit_names: + image = open_image(name) + tokens, cls_token, grid = encode(encoder, image, 448) + mask = torch.as_tensor(foreground_mask(tokens, grid), device=device) + normal = F.normalize(tokens, dim=-1) + pos_grid = pos_grid or grid + fine.append(normal.half()) + fine_fg.append(normal[mask].half()) + cls_rows.append(F.normalize(cls_token, dim=-1)) + mean_rows.append(F.normalize(normal[mask].mean(0) if mask.any() else normal.mean(0), dim=-1)) + if grid == pos_grid: + same_grid.append(len(fine) - 1) + small, _, _ = encode(encoder, image, 224) + coarse.append(F.normalize(small, dim=-1).half()) + full_bank = torch.cat(fine) + fullfg_bank = torch.cat(fine_fg) + coarse_bank = torch.cat(coarse) + stack = torch.stack([fine[i] for i in same_grid]).permute(1, 0, 2).contiguous() + cls_bank, mean_bank = torch.stack(cls_rows), torch.stack(mean_rows) + del fine, fine_fg, coarse + with np.load(run / "bank_3.npz") as saved: + base_bank = F.normalize(torch.from_numpy(saved["patches"].astype("float32")).to(device), dim=-1) + fit_seconds = time.perf_counter() - started + + def score(name): + image = open_image(name) + tokens, cls_token, grid = encode(encoder, image, 448) + mask_np = foreground_mask(tokens, grid) + mask = torch.as_tensor(mask_np, device=device) + normal = F.normalize(tokens, dim=-1) + out = { + "base": top_mean(distances(normal, base_bank), mask), + "full": top_mean(knn_distance(normal, full_bank), mask), + "fullfg": top_mean(knn_distance(normal, fullfg_bank), mask), + "pos": top_mean(positional_distance(normal, stack, grid), mask) if grid == pos_grid else None, + "cls": float(1 - (cls_bank @ F.normalize(cls_token, dim=-1)).max()), + "meanpool": float(1 - (mean_bank @ F.normalize(normal[mask].mean(0), dim=-1)).max()) + if mask.any() + else None, + } + small, _, small_grid = encode(encoder, image, 224) + small_mask = torch.as_tensor(foreground_mask(small, small_grid), device=device) + out["coarse"] = top_mean(knn_distance(F.normalize(small, dim=-1), coarse_bank), small_mask) + return out + + held = {name: score(name) for name in held_names} + test = {row["image"]: score(row["image"]) for row in test_rows} + labels = {row["image"]: 0 if row["label"] == "normal" else 1 for row in test_rows} + differences = [abs(test[n]["base"] - cached[n]) for n in test] + held_differences = [abs(held[n]["base"] - held_saved[n]) for n in held] + record = { + "category": category, + "smoke": smoke, + "n_fit": len(fit_names), + "n_position_images": len(same_grid), + "grid": list(pos_grid), + "bank_patches": { + "base": len(base_bank), + "full": len(full_bank), + "fullfg": len(fullfg_bank), + "coarse": len(coarse_bank), + }, + "reproduction": { + "test_max_abs_difference": max(differences), + "test_mean_abs_difference": float(np.mean(differences)), + "heldout_max_abs_difference": max(held_differences), + }, + "seconds_fit": round(fit_seconds, 1), + "seconds_total": round(time.perf_counter() - started, 1), + "heldout": held, + "test": test, + "labels": labels, + } + return record + + +def summarise(record): + labels = record["labels"] + positive = [n for n, v in labels.items() if v == 1] + negative = [n for n, v in labels.items() if v == 0] + parts = [] + for name in CANDIDATES: + if any(record["test"][n][name] is None for n in labels): + parts.append(f"{name} n/a") + continue + value = auroc([record["test"][n][name] for n in positive], [record["test"][n][name] for n in negative]) + parts.append(f"{name} {value:.3f}") + return " ".join(parts) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--categories", nargs="+", choices=CATEGORIES, default=list(CATEGORIES)) + parser.add_argument("--smoke", action="store_true", help="100 fit images, 20 held-out, about 40 test images") + parser.add_argument("--force", action="store_true", help="recompute categories that already have a result file") + parser.add_argument( + "--weights", help="round 4: a fine-tuned encoder state dict; results go to dinov2_candidates_ft" + ) + parser.add_argument("--tag", default="ft", help="with --weights: results go to dinov2_candidates_") + args = parser.parse_args() + out = OUT.with_name(f"dinov2_candidates_{args.tag}") if args.weights else OUT + out.mkdir(parents=True, exist_ok=True) + encoder = HighResolutionEncoder(SOURCE) + if args.weights: + # The deployed "base" bank was built with the original encoder, so its score (and the reproduction check) no + # longer match the app with these weights; every other candidate is rebuilt from the fine-tuned features. + encoder.model.load_state_dict(torch.load(args.weights, map_location=encoder.device)) + for category in args.categories: + target = out / (f"{category}.smoke.json" if args.smoke else f"{category}.json") + if target.exists() and not args.force: + print(f"{category}: already done ({target.name})", flush=True) + continue + record = run_category(category, encoder, args.smoke) + torch.cuda.empty_cache() # the category's banks are freed when run_category returns + target.write_text(json.dumps(record), encoding="utf-8") + rep = record["reproduction"] + print( + f"{category}: {record['seconds_total']} s | reproduces the app: test max diff {rep['test_max_abs_difference']:.4f}, " + f"mean {rep['test_mean_abs_difference']:.4f}", + flush=True, + ) + print(" AUROC " + summarise(record), flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/encoder_candidates_report.py b/scripts/encoder_candidates_report.py new file mode 100644 index 0000000000000000000000000000000000000000..38fde99b83562d4e9df9d7464210b18c925541d9 --- /dev/null +++ b/scripts/encoder_candidates_report.py @@ -0,0 +1,198 @@ +"""Compare the detector candidates (step 2 of 2, CPU only; run scripts.encoder_candidates first). + + python -m scripts.encoder_candidates_report + +Rules fixed before any result was seen: +* Every candidate score is standardised with the mean and spread of the 90 held-out NORMAL images (no labels). +* Fusions are plain averages of those standardised scores; the list below is complete, nothing was added after looking. +* Each method is compared with the deployed one ("base") by a paired bootstrap of the AUROC difference + (images resampled with replacement within normals and within anomalies, 2,000 rounds, 95% interval). +* A method counts as an improvement only if the interval for the difference stays above zero. +* Thresholds come from the held-out normals only: q95 for every category (a like-for-like comparison) and the + deployed q80 for Macaroni1/2. +* The 200 test images per category were already seen during development, so this is descriptive, not a fresh test. +""" + +import argparse +import csv +import json + +import numpy as np + +from backend.config import ROOT +from scripts.diagnose_encoder import auroc + +RESULTS = ROOT / "experiments" / "dinov2_candidates" +VISA = ROOT / "VisA_20220922" +OUT = ROOT / "results" / "encoder_candidates.json" +SINGLES = ("base", "full", "fullfg", "pos", "cls", "meanpool", "coarse") +FUSIONS = { + "base+cls": ("base", "cls"), + "base+coarse": ("base", "coarse"), + "base+pos": ("base", "pos"), + "full+cls": ("full", "cls"), + "full+meanpool": ("full", "meanpool"), + "full+coarse": ("full", "coarse"), + "full+pos": ("full", "pos"), + "fullfg+coarse": ("fullfg", "coarse"), + "full+coarse+cls": ("full", "coarse", "cls"), + "full+coarse+pos": ("full", "coarse", "pos"), +} +HARD_TYPES = { + "macaroni1": "chip around edge and corner", + "macaroni2": "small chip around edge", + "pcb2": "missing", + "pcb3": "missing", + "candle": "weird candle wick", +} +DEPLOYED_QUANTILE = {"macaroni1": 0.80, "macaroni2": 0.80} +ROUNDS = 2000 + + +def standardised(record, parts): + """Average of the held-out-normal standardised scores of the named candidates, or None if unavailable.""" + held_names, test_names = sorted(record["heldout"]), sorted(record["test"]) + held = np.zeros(len(held_names)) + test = np.zeros(len(test_names)) + for part in parts: + h = [record["heldout"][n][part] for n in held_names] + t = [record["test"][n][part] for n in test_names] + if any(v is None for v in h + t): + return None + h, t = np.array(h, float), np.array(t, float) + spread = h.std() + if spread == 0: + return None + held += (h - h.mean()) / spread / len(parts) + test += (t - h.mean()) / spread / len(parts) + return held, test + + +def bootstrap_difference(labels, method, base, rng): + positive, negative = np.flatnonzero(labels == 1), np.flatnonzero(labels == 0) + differences = np.empty(ROUNDS) + for i in range(ROUNDS): + p = rng.choice(positive, len(positive)) + n = rng.choice(negative, len(negative)) + differences[i] = auroc(method[p], method[n]) - auroc(base[p], base[n]) + return np.percentile(differences, [2.5, 97.5]) + + +def anomaly_types(category, names): + rows = {r["image"]: r for r in csv.DictReader((VISA / category / "image_anno.csv").open(encoding="utf-8"))} + return {n: [t.strip() for t in rows[n]["label"].split(",")] for n in names} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--anchor", default="base", choices=SINGLES, help="method every difference is measured against") + anchor = parser.parse_args().anchor + rng = np.random.default_rng(2026) + records = { + p.stem: json.loads(p.read_text(encoding="utf-8")) + for p in sorted(RESULTS.glob("*.json")) + if ".smoke" not in p.name + } + methods = list(SINGLES) + list(FUSIONS) + report = {} + for category, record in records.items(): + names = sorted(record["test"]) + labels = np.array([record["labels"][n] for n in names]) + entry = {"reproduction_max_abs_difference": record["reproduction"]["test_max_abs_difference"], "methods": {}} + _, base_test = standardised(record, (anchor,)) + for name in methods: + parts = (name,) if name in SINGLES else FUSIONS[name] + got = standardised(record, parts) + if got is None: + continue + held, test = got + value = auroc(test[labels == 1], test[labels == 0]) + interval = None if name == anchor else bootstrap_difference(labels, test, base_test, rng).tolist() + result = {"auroc": value, "difference_vs_base_95": interval} + for label, quantile in (("q95", 0.95), ("deployed", DEPLOYED_QUANTILE.get(category, 0.95))): + threshold = np.quantile(held, quantile) + result[f"recall_{label}"] = float((test[labels == 1] >= threshold).mean()) + result[f"false_alarm_{label}"] = float((test[labels == 0] >= threshold).mean()) + if category in HARD_TYPES: + types = anomaly_types(category, names) + hard = np.array([HARD_TYPES[category] in types[n] for n in names]) + result["auroc_hard_type"] = auroc(test[hard & (labels == 1)], test[labels == 0]) + entry["methods"][name] = result + report[category] = entry + target = OUT if anchor == "base" else OUT.with_name(f"encoder_candidates_vs_{anchor}.json") + target.write_text(json.dumps(report, indent=2), encoding="utf-8") + + categories = list(report) + print( + f"Categories analysed: {len(categories)}. Harness reproduces the app: largest difference " + f"{max(e['reproduction_max_abs_difference'] for e in report.values()):.5f}\n" + ) + + def table(columns, title): + print(title) + print(f"{'category':<11}" + "".join(f"{c:>17}" for c in columns)) + for category in categories: + cells = [] + for c in columns: + m = report[category]["methods"].get(c) + if m is None: + cells.append(f"{'n/a':>17}") + continue + mark = "" + if m["difference_vs_base_95"] is not None: + low, high = m["difference_vs_base_95"] + mark = " ▲" if low > 0 else " ▼" if high < 0 else "" + cells.append(f"{m['auroc']:>15.3f}{mark:<2}") + print(f"{category:<11}" + "".join(cells)) + macro = [] + for c in columns: + values = [report[k]["methods"][c]["auroc"] for k in categories if c in report[k]["methods"]] + macro.append(f"{np.mean(values):>17.3f}" if len(values) == len(categories) else f"{'n/a':>17}") + print(f"{'MEAN':<11}" + "".join(macro) + "\n") + + print(f"AUROC per category. ▲ = better than '{anchor}' (95% interval above 0), ▼ = worse.\n") + table(SINGLES, "Single candidates") + table(list(FUSIONS)[:5], "Fusions (1/2)") + table(list(FUSIONS)[5:], "Fusions (2/2)") + + print("Hard defect types (AUROC of that type against all normals)") + print( + f"{'category / type':<40}" + + "".join(f"{c:>14}" for c in ("base", "full", "fullfg", "coarse", "full+coarse", "full+pos")) + ) + for category, kind in HARD_TYPES.items(): + if category not in report: + continue + cells = [ + report[category]["methods"].get(c, {}).get("auroc_hard_type") + for c in ("base", "full", "fullfg", "coarse", "full+coarse", "full+pos") + ] + print(f"{category + ' / ' + kind:<40}" + "".join(f"{'n/a':>14}" if v is None else f"{v:>14.3f}" for v in cells)) + + ranked = sorted( + (m for m in methods if m != "base" and all(m in report[k]["methods"] for k in categories)), + key=lambda m: -np.mean([report[k]["methods"][m]["auroc"] for k in categories]), + ) + print("\nOperating points for the three best methods by mean AUROC (thresholds from held-out normals only)") + print("q95 = same policy everywhere; deployed = q80 for macaroni1/2") + shown = ["base", "full"] + [m for m in ranked if m != "full"][:2] + print( + f"{'category':<11}{'method':<17}{'AUROC':>7}{'q95 recall':>12}{'q95 false':>11}{'dep. recall':>13}{'dep. false':>12}" + ) + for category in categories: + if category not in ("macaroni1", "macaroni2", "pcb2", "candle", "cashew"): + continue + for name in shown: + m = report[category]["methods"][name] + print( + f"{category:<11}{name:<17}{m['auroc']:>7.3f}{m['recall_q95']:>12.0%}{m['false_alarm_q95']:>11.0%}" + f"{m['recall_deployed']:>13.0%}{m['false_alarm_deployed']:>12.0%}" + ) + print( + "\nA method is an improvement only if the weak categories gain with an interval above 0 and no category is " + "significantly worse (▼). Written to results/encoder_candidates.json." + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/encoder_finetune.py b/scripts/encoder_finetune.py new file mode 100644 index 0000000000000000000000000000000000000000..41bc5fb32a0cccd56b77da07cccfa129bcd68efa --- /dev/null +++ b/scripts/encoder_finetune.py @@ -0,0 +1,338 @@ +"""Fine-tune the last blocks of DINOv2 with synthetic structural defects (round 4 of the detector study; needs the GPU). + + python -m scripts.encoder_finetune --cache # step 1: resize all training normals once (CPU, about 10 minutes) + python -m scripts.encoder_finetune --train # step 2: train (GPU, about 30 minutes) + +Why: round 1 found that the weak spots are structural defects (chipped edges, missing parts), where each small patch +can still look normal. This tests whether a DINOv2 whose last blocks have seen such defects separates them better. + +Fixed before any result (one configuration, nothing tuned on the test images): +* One shared model for all 12 categories. Training images: only the fit normals per category that the deployed banks use + (about 90% of the training normals: 810 for the larger categories, 405-487 for the others). The held-out normals and + the test images are never read here. +* Synthetic defects made from normal images only: cut-and-paste of a patch from another image, an "erased" region + filled with the local background (a missing part), and an edge region swapped with foreign content (a chip). One to + three per image; 20% of the images stay clean. +* Trained: the last 4 transformer blocks, the final layer norm and a linear patch head that predicts which patches + hold a synthetic defect. The first 8 blocks stay frozen. A consistency loss keeps the features of untouched patches + close to the original frozen model, so the strong categories should not drift. +* 2,500 steps, batch 8, AdamW (1e-5 backbone, 1e-3 head), cosine schedule, bf16. + +Evaluation (separate step): python -m scripts.encoder_candidates --weights experiments/dinov2_finetune/encoder_ft.pt +rebuilds every bank with the fine-tuned encoder and scores the same test images, compared with the frozen full bank. +""" + +import argparse +import json +import math +import time + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image, ImageDraw, ImageFilter +from transformers import AutoModel + +from backend.config import CATEGORIES, ROOT + +RUNS = ROOT / "experiments" / "dinov2_highres_v1" +VISA = ROOT / "VisA_20220922" +SOURCE = ROOT / "models" / "encoder_dinov2" +OUT = ROOT / "experiments" / "dinov2_finetune" +OUT_REALISTIC = ROOT / "experiments" / "dinov2_finetune_realistic" +SIZE = 448 +GRID = SIZE // 14 +STEPS = 2500 +BATCH = 8 +TRAINABLE_BLOCKS = 4 +CONSISTENCY = 2.0 +CLEAN_SHARE = 0.2 + + +def fit_names(category): + run = RUNS / category + split = json.loads((run / "split.json").read_text(encoding="utf-8")) + held = { + p["image"] for p in json.loads((run / "normal_calibration.json").read_text(encoding="utf-8"))["predictions"] + } + return [r["image"] for r in split["train"] if r["image"] not in held] + + +def build_cache(): + """Resize every fit normal to short edge 448, centre-crop 448 x 448 and store it as raw bytes on disk.""" + OUT.mkdir(parents=True, exist_ok=True) + entries = [(c, n) for c in CATEGORIES for n in fit_names(c)] + cache = np.lib.format.open_memmap( + OUT / "train_448.npy", mode="w+", dtype=np.uint8, shape=(len(entries), SIZE, SIZE, 3) + ) + for i, (_, name) in enumerate(entries): + with Image.open(VISA / name) as image: + image = image.convert("RGB") + factor = SIZE / min(image.size) + image = image.resize( + (max(SIZE, round(image.width * factor)), max(SIZE, round(image.height * factor))), + Image.Resampling.BICUBIC, + ) + left, top = (image.width - SIZE) // 2, (image.height - SIZE) // 2 + cache[i] = np.asarray(image.crop((left, top, left + SIZE, top + SIZE))) + if i % 1000 == 0: + print(f"cached {i}/{len(entries)}", flush=True) + cache.flush() + (OUT / "train_index.json").write_text(json.dumps(entries), encoding="utf-8") + print(f"cached {len(entries)} images", flush=True) + + +def rectangle(rng, height, width): + area = rng.uniform(0.004, 0.04) * height * width + ratio = rng.uniform(0.5, 2.0) + rh, rw = int(math.sqrt(area * ratio)), int(math.sqrt(area / ratio)) + rh, rw = max(8, min(rh, height // 3)), max(8, min(rw, width // 3)) + return rng.integers(0, height - rh), rng.integers(0, width - rw), rh, rw + + +def synthesise(image, other, rng): + """Return a copy of the image with 1-3 synthetic structural defects and the boolean mask of the changed pixels.""" + height, width, _ = image.shape + out, mask = image.copy(), np.zeros((height, width), bool) + gradient = np.hypot(*np.gradient(image.mean(2))) + edge_points = np.argwhere(gradient > np.quantile(gradient, 0.97)) + for _ in range(rng.integers(1, 4)): + kind = rng.choice(("cutpaste", "erase", "chip")) + if kind == "cutpaste": + y, x, rh, rw = rectangle(rng, height, width) + sy, sx = rng.integers(0, height - rh), rng.integers(0, width - rw) + piece = other[sy : sy + rh, sx : sx + rw].astype(np.float32) * rng.uniform(0.9, 1.1) + out[y : y + rh, x : x + rw] = np.clip(piece, 0, 255).astype(np.uint8) + mask[y : y + rh, x : x + rw] = True + elif kind == "erase": + y, x, rh, rw = rectangle(rng, height, width) + ring = np.concatenate( + [ + image[max(0, y - 6) : y, x : x + rw].reshape(-1, 3), + image[y + rh : y + rh + 6, x : x + rw].reshape(-1, 3), + ] + ) + fill = ring.mean(0) if len(ring) else image.reshape(-1, 3).mean(0) + out[y : y + rh, x : x + rw] = fill.astype(np.uint8) + mask[y : y + rh, x : x + rw] = True + elif len(edge_points): + cy, cx = edge_points[rng.integers(len(edge_points))] + radius = int(rng.integers(8, 28)) + yy, xx = np.ogrid[:height, :width] + disk = (yy - cy) ** 2 + (xx - cx) ** 2 <= radius**2 + sy, sx = rng.integers(0, height), rng.integers(0, width) + foreign = np.roll(other, (sy - cy, sx - cx), axis=(0, 1)) + out[disk] = foreign[disk] + mask |= disk + return out, mask + + +def smooth_noise(rng, scales=(3, 6, 12)): + """Low-frequency random field in [-1, 1] at SIZE x SIZE: a few octaves of coarse noise, upsampled.""" + total = np.zeros((SIZE, SIZE), np.float32) + for scale in scales: + grid = Image.fromarray(rng.random((scale, scale)).astype(np.float32)) + total += np.asarray(grid.resize((SIZE, SIZE), Image.Resampling.BICUBIC)) / len(scales) + total -= total.mean() + return total / (np.abs(total).max() + 1e-6) + + +def blob(rng, centre, radius, roughness=0.5): + """Irregular blob: a disk whose edge is pushed in and out by smooth noise.""" + yy, xx = np.ogrid[:SIZE, :SIZE] + distance = np.hypot(yy - centre[0], xx - centre[1]) / radius + return distance + roughness * smooth_noise(rng, (4, 8)) < 1 + + +def foreground_guess(image): + """Object pixels = colour far from the median of the image border (None if that does not separate anything).""" + border = np.concatenate([image[:12].reshape(-1, 3), image[-12:].reshape(-1, 3)]) + background = np.median(border, axis=0) + difference = np.linalg.norm(image.astype(np.float32) - background, axis=2) + mask = Image.fromarray(((difference > 28) * 255).astype(np.uint8)).filter(ImageFilter.MinFilter(5)) + mask = np.asarray(mask.filter(ImageFilter.MaxFilter(5))) > 0 + return (mask, background) if 0.04 < mask.mean() < 0.9 else (None, background) + + +def boundary_points(mask): + inner = np.asarray(Image.fromarray((mask * 255).astype(np.uint8)).filter(ImageFilter.MinFilter(5))) > 0 + return np.argwhere(mask & ~inner) + + +def scratch_mask(rng): + canvas = Image.new("L", (SIZE, SIZE), 0) + draw = ImageDraw.Draw(canvas) + y, x = rng.integers(40, SIZE - 40, 2).astype(float) + angle = rng.uniform(0, 2 * math.pi) + points = [(x, y)] + for _ in range(int(rng.integers(8, 20))): + angle += rng.normal(0, 0.35) + x, y = x + 9 * math.cos(angle), y + 9 * math.sin(angle) + points.append((x, y)) + draw.line(points, fill=255, width=int(rng.integers(2, 6))) + return np.asarray(canvas) > 0 + + +def synthesise_realistic(image, other, rng): + """1-3 more realistic defects: irregular chips that bite the object's edge, missing pieces, textured blotches + blended from another image, stains and scratches. Returns the edited copy and the mask of changed pixels.""" + out, mask = image.astype(np.float32), np.zeros((SIZE, SIZE), bool) + foreground, background = foreground_guess(image) + edge = boundary_points(foreground) if foreground is not None else np.empty((0, 2), int) + for _ in range(rng.integers(1, 4)): + kind = rng.choice(("chip", "chip", "missing", "texture", "stain", "scratch")) + if kind in ("chip", "missing") and len(edge): + centre = edge[rng.integers(len(edge))] + radius = rng.uniform(8, 26) if kind == "chip" else rng.uniform(18, 48) + region = blob(rng, centre, radius) & foreground + if region.sum() < 30: + continue + fill = background + rng.normal(0, 3, 3) + out[region] = fill + ring = np.asarray(Image.fromarray((region * 255).astype(np.uint8)).filter(ImageFilter.MaxFilter(7))) > 0 + out[ring & ~region & foreground] *= rng.uniform(0.75, 0.95) # darker fracture rim, as on a real break + mask |= ring + elif kind == "texture" or (kind in ("chip", "missing") and not len(edge)): + region = blob(rng, rng.integers(40, SIZE - 40, 2), rng.uniform(15, 50), roughness=0.7) + shift = (int(rng.integers(0, SIZE)), int(rng.integers(0, SIZE))) + alpha = rng.uniform(0.6, 1.0) + out[region] = (1 - alpha) * out[region] + alpha * np.roll(other, shift, axis=(0, 1))[region] + mask |= region + elif kind == "stain": + region = blob(rng, rng.integers(40, SIZE - 40, 2), rng.uniform(15, 45), roughness=0.7) + tint = rng.uniform(0.45, 0.85) if rng.random() < 0.6 else rng.uniform(1.15, 1.5) + out[region] = out[region] * tint + rng.normal(0, 10, 3) + mask |= region + else: + region = scratch_mask(rng) + out[region] = out[region] * (rng.uniform(0.4, 0.7) if rng.random() < 0.5 else rng.uniform(1.3, 1.7)) + mask |= region + return np.clip(out, 0, 255).astype(np.uint8), mask + + +def batch(cache, index, ranges, rng, synth=synthesise): + images, targets, clean = [], [], [] + for _ in range(BATCH): + i = int(rng.integers(len(cache))) + low, high = next(r for r in ranges if r[0] <= i < r[1]) + j = int(rng.integers(low, high)) + image, other = np.array(cache[i]), np.array(cache[j]) + if rng.random() < CLEAN_SHARE: + mask, keep = np.zeros((SIZE, SIZE), bool), True + else: + image, mask = synth(image, other, rng) + keep = False + if rng.random() < 0.5: + image, mask = image[:, ::-1], mask[:, ::-1] + if rng.random() < 0.5: + image, mask = image[::-1], mask[::-1] + images.append(np.ascontiguousarray(image)) + targets.append(mask.reshape(GRID, 14, GRID, 14).mean((1, 3))) + clean.append(keep) + return np.stack(images), np.stack(targets).astype(np.float32), clean + + +def train(realistic=False): + device = torch.device("cuda") + cache = np.load(OUT / "train_448.npy", mmap_mode="r") + entries = json.loads((OUT / "train_index.json").read_text(encoding="utf-8")) + ranges, start = [], 0 + for category in CATEGORIES: + count = sum(1 for c, _ in entries if c == category) + ranges.append((start, start + count)) + start += count + student = AutoModel.from_pretrained(str(SOURCE), local_files_only=True).to(device) + teacher = AutoModel.from_pretrained(str(SOURCE), local_files_only=True).to(device).eval() + teacher.requires_grad_(False) + student.requires_grad_(False) + parameters = [] + for block in student.encoder.layer[-TRAINABLE_BLOCKS:]: + block.requires_grad_(True) + parameters += list(block.parameters()) + student.layernorm.requires_grad_(True) + parameters += list(student.layernorm.parameters()) + head = torch.nn.Linear(student.config.hidden_size, 1).to(device) + optimiser = torch.optim.AdamW( + [{"params": parameters, "lr": 1e-5}, {"params": head.parameters(), "lr": 1e-3}], weight_decay=0.01 + ) + schedule = torch.optim.lr_scheduler.CosineAnnealingLR(optimiser, STEPS) + mean = torch.tensor([0.485, 0.456, 0.406], device=device)[None, :, None, None] + std = torch.tensor([0.229, 0.224, 0.225], device=device)[None, :, None, None] + rng = np.random.default_rng(2026) + started = time.perf_counter() + for step in range(1, STEPS + 1): + images, targets, _ = batch(cache, entries, ranges, rng, synthesise_realistic if realistic else synthesise) + pixels = (torch.from_numpy(images).to(device).permute(0, 3, 1, 2).float() / 255 - mean) / std + target = torch.from_numpy(targets).to(device).reshape(BATCH, -1) + with torch.autocast("cuda", dtype=torch.bfloat16): + tokens = student(pixel_values=pixels).last_hidden_state[:, 1:] + with torch.no_grad(): + original = teacher(pixel_values=pixels).last_hidden_state[:, 1:] + logits = head(tokens).squeeze(-1) + untouched = (target == 0).float() + similarity = F.cosine_similarity(tokens.float(), original.float(), dim=-1) + consistency = ((1 - similarity) * untouched).sum() / untouched.sum().clamp_min(1) + detection = F.binary_cross_entropy_with_logits(logits.float(), target.clamp(0, 1)) + loss = detection + CONSISTENCY * consistency + optimiser.zero_grad(set_to_none=True) + loss.backward() + torch.nn.utils.clip_grad_norm_(parameters + list(head.parameters()), 1.0) + optimiser.step() + schedule.step() + if step % 100 == 0 or step == 1: + hit = ((logits > 0).float() == (target > 0.2).float()).float().mean().item() + print( + f"step {step:4d}/{STEPS} loss {loss.item():.4f} detection {detection.item():.4f} " + f"consistency {consistency.item():.4f} patch accuracy {hit:.3f} {time.perf_counter() - started:.0f}s", + flush=True, + ) + state = {k: v.detach().half().cpu() for k, v in student.state_dict().items()} + target = OUT_REALISTIC if realistic else OUT + target.mkdir(parents=True, exist_ok=True) + torch.save(state, target / "encoder_ft.pt") + torch.save({k: v.detach().cpu() for k, v in head.state_dict().items()}, target / "head_ft.pt") + print(f"saved {target / 'encoder_ft.pt'} in {time.perf_counter() - started:.0f}s", flush=True) + + +def preview(): + """Write 12 images (one category each, original above, synthetic defects below) to check the defects look plausible.""" + cache = np.load(OUT / "train_448.npy", mmap_mode="r") + entries = json.loads((OUT / "train_index.json").read_text(encoding="utf-8")) + rng = np.random.default_rng(7) + tiles = [] + for category in CATEGORIES: + rows = [i for i, (c, _) in enumerate(entries) if c == category] + i, j = int(rng.choice(rows)), int(rng.choice(rows)) + original, other = np.array(cache[i]), np.array(cache[j]) + edited, mask = synthesise_realistic(original, other, rng) + outline = np.asarray(Image.fromarray((mask * 255).astype(np.uint8)).filter(ImageFilter.FIND_EDGES)) > 0 + marked = edited.copy() + marked[outline] = (255, 0, 0) + tiles.append(np.concatenate([original, edited, marked], axis=0)) + sheet = np.concatenate([np.concatenate(tiles[r * 6 : r * 6 + 6], axis=1) for r in range(2)], axis=0) + target = OUT_REALISTIC + target.mkdir(parents=True, exist_ok=True) + Image.fromarray(sheet).resize((sheet.shape[1] // 4, sheet.shape[0] // 4)).save(target / "preview.jpg", quality=90) + print(f"wrote {target / 'preview.jpg'}") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--cache", action="store_true") + parser.add_argument("--train", action="store_true") + parser.add_argument("--realistic", action="store_true", help="round 4b: more realistic synthetic defects") + parser.add_argument("--preview", action="store_true", help="save a picture of synthetic defects (CPU)") + args = parser.parse_args() + if args.preview: + preview() + return + if args.cache: + build_cache() + if args.train: + train(args.realistic) + if not (args.cache or args.train): + parser.error("choose --cache and/or --train") + + +if __name__ == "__main__": + main() diff --git a/scripts/encoder_finetune_report.py b/scripts/encoder_finetune_report.py new file mode 100644 index 0000000000000000000000000000000000000000..2d79cbed6e897cab86de6adf3e9b51985f9145a6 --- /dev/null +++ b/scripts/encoder_finetune_report.py @@ -0,0 +1,143 @@ +"""Report for round 4, the fine-tuned encoder (CPU only; run scripts.encoder_finetune and +scripts.encoder_candidates --weights first). + + python -m scripts.encoder_finetune_report + +Compares, on the same 200 test images per category, the frozen DINOv2 (experiments/dinov2_candidates) with the +fine-tuned one (experiments/dinov2_candidates_ft). The primary comparison, fixed before any result: the fine-tuned full +bank against the frozen full bank (same bank recipe, only the encoder differs). Same rules as +scripts.encoder_candidates_report: scores standardised with the 90 held-out normals only, paired bootstrap 95% intervals, +thresholds from held-out normals only (q95 for every category, and the deployed q80 for macaroni1/2 shown separately). +The "base" score in the fine-tuned files mixes the deployed bank (built with the frozen encoder) with fine-tuned +features and is not meaningful, so the deployed reference always comes from the frozen files. Descriptive only. +""" + +import argparse +import json + +import numpy as np + +from backend.config import ROOT +from scripts.diagnose_encoder import auroc +from scripts.encoder_candidates_report import ( + DEPLOYED_QUANTILE, + HARD_TYPES, + RESULTS, + anomaly_types, + bootstrap_difference, +) + +FROZEN = RESULTS +TUNED = ROOT / "experiments" / "dinov2_candidates_ft" +OUT = ROOT / "results" / "encoder_finetune.json" +METHODS = (("frozen base", "frozen", "base"), ("frozen full", "frozen", "full"), ("tuned full", "tuned", "full")) +EXTRA = (("tuned fullfg", "tuned", "fullfg"), ("tuned pos", "tuned", "pos"), ("frozen pos", "frozen", "pos")) + + +def scores(record, name, names): + return np.array([record["test"][n][name] for n in names], float) + + +def held(record, name): + return np.array([record["heldout"][n][name] for n in sorted(record["heldout"])], float) + + +def main(): + global TUNED, OUT + parser = argparse.ArgumentParser() + parser.add_argument("--tag", default="ft", help="read experiments/dinov2_candidates_") + args = parser.parse_args() + TUNED = ROOT / "experiments" / f"dinov2_candidates_{args.tag}" + OUT = ROOT / "results" / ("encoder_finetune.json" if args.tag == "ft" else f"encoder_finetune_{args.tag}.json") + rng = np.random.default_rng(2027) + report, categories = {}, sorted(p.stem for p in TUNED.glob("*.json") if ".smoke" not in p.name) + for category in categories: + records = { + "frozen": json.loads((FROZEN / f"{category}.json").read_text(encoding="utf-8")), + "tuned": json.loads((TUNED / f"{category}.json").read_text(encoding="utf-8")), + } + names = sorted(records["frozen"]["test"]) + assert names == sorted(records["tuned"]["test"]) + labels = np.array([records["frozen"]["labels"][n] for n in names]) + entry, cache = {}, {} + for label, source, name in METHODS + EXTRA: + h = held(records[source], name) + if any(v is None for v in h) or h.std() == 0: + continue + t = np.array([records[source]["test"][n][name] for n in names], float) + if np.isnan(t).any(): + continue + cache[label] = (h, t) + full_test = (cache["frozen full"][1] - cache["frozen full"][0].mean()) / cache["frozen full"][0].std() + for label, (h, t) in cache.items(): + z_held, z_test = (h - h.mean()) / h.std(), (t - h.mean()) / h.std() + result = {"auroc": auroc(z_test[labels == 1], z_test[labels == 0])} + if label != "frozen full": + result["vs_frozen_full"] = bootstrap_difference(labels, z_test, full_test, rng).tolist() + for tag, quantile in (("q95", 0.95), ("deployed", DEPLOYED_QUANTILE.get(category, 0.95))): + threshold = np.quantile(z_held, quantile) + result[f"recall_{tag}"] = float((z_test[labels == 1] >= threshold).mean()) + result[f"false_alarm_{tag}"] = float((z_test[labels == 0] >= threshold).mean()) + if category in HARD_TYPES: + kinds = anomaly_types(category, names) + hard = np.array([HARD_TYPES[category] in kinds[n] for n in names]) + result["auroc_hard_type"] = auroc(z_test[hard & (labels == 1)], z_test[labels == 0]) + entry[label] = result + report[category] = entry + OUT.write_text(json.dumps(report, indent=2), encoding="utf-8") + + def mark(m): + interval = m.get("vs_frozen_full") + if not interval: + return " " + return " ▲" if interval[0] > 0 else " ▼" if interval[1] < 0 else " " + + labels_all = [m[0] for m in METHODS + EXTRA] + print(f"Categories: {len(categories)} (▲/▼ = clearly better/worse than the FROZEN full bank)\n") + print(f"{'category':<11}" + "".join(f"{c:>15}" for c in labels_all)) + for category in categories: + row = "".join( + f"{report[category][c]['auroc']:>13.3f}{mark(report[category][c])}" + if c in report[category] + else f"{'n/a':>15}" + for c in labels_all + ) + print(f"{category:<11}{row}") + print( + f"{'MEAN':<11}" + + "".join( + f"{np.mean([report[k][c]['auroc'] for k in categories]):>15.3f}" + if all(c in report[k] for k in categories) + else f"{'n/a':>15}" + for c in labels_all + ) + ) + wins = sum(mark(report[k]["tuned full"]) == " ▲" for k in categories) + losses = sum(mark(report[k]["tuned full"]) == " ▼" for k in categories) + print(f"\ntuned full vs frozen full: clearly better in {wins}, clearly worse in {losses} of {len(categories)}\n") + + print("Hard defect types (AUROC of that type against all normals)") + print(f"{'category / type':<40}{'frozen base':>13}{'frozen full':>13}{'tuned full':>13}") + for category, kind in HARD_TYPES.items(): + if category in report: + cells = "".join( + f"{report[category][c]['auroc_hard_type']:>13.3f}" for c in ("frozen base", "frozen full", "tuned full") + ) + print(f"{category + ' / ' + kind:<40}{cells}") + + print("\nOperating points: q95 for every category; deployed = q80 for macaroni1/2") + print( + f"{'category':<11}{'method':<13}{'AUROC':>7}{'q95 recall':>12}{'q95 false':>11}{'dep. recall':>13}{'dep. false':>12}" + ) + for category in (c for c in ("macaroni1", "macaroni2", "pcb2", "candle", "cashew") if c in report): + for label in ("frozen base", "frozen full", "tuned full"): + m = report[category][label] + print( + f"{category:<11}{label:<13}{m['auroc']:>7.3f}{m['recall_q95']:>12.0%}{m['false_alarm_q95']:>11.0%}" + f"{m['recall_deployed']:>13.0%}{m['false_alarm_deployed']:>12.0%}" + ) + print(f"\nWritten to results/{OUT.name}. Descriptive only (test images already seen in development).") + + +if __name__ == "__main__": + main() diff --git a/scripts/encoder_tuned_coreset.py b/scripts/encoder_tuned_coreset.py new file mode 100644 index 0000000000000000000000000000000000000000..229c1dfa87687cd5e9e23a60c2f3d6d34c1184b6 --- /dev/null +++ b/scripts/encoder_tuned_coreset.py @@ -0,0 +1,106 @@ +"""Round 5: a deployable 32,768-patch coreset built from the fine-tuned (realistic-defect) encoder. Needs the GPU. + + python -m scripts.encoder_tuned_coreset # all 12 categories, about 40 minutes + python -m scripts.encoder_tuned_coreset --smoke --categories macaroni2 + +Fixed before any result: the encoder is experiments/dinov2_finetune_realistic/encoder_ft.pt (round 4b, the only +variant carried forward), the bank is a greedy farthest-point coreset of 32,768 patches taken from every patch of the +810 fit normals, exactly as in round 3 (scripts.encoder_banks), and scores use the same top-1% foreground rule. +Held-out normals and test images are only scored, never used to build anything. Compare with +scripts.encoder_tuned_coreset_report. Results go to experiments/dinov2_tuned_coreset/.json. +""" + +import argparse +import json +import time + +import torch +import torch.nn.functional as F + +from backend.config import CATEGORIES, ROOT +from backend.highres import HighResolutionEncoder, foreground_mask +from scripts.diagnose_encoder import auroc +from scripts.encoder_banks import greedy_coreset +from scripts.encoder_candidates import RUNS, SOURCE, encode, knn_distance, open_image, top_mean + +WEIGHTS = ROOT / "experiments" / "dinov2_finetune_realistic" / "encoder_ft.pt" +OUT = ROOT / "experiments" / "dinov2_tuned_coreset" +SIZE = 32768 + + +def run_category(category, encoder, smoke): + run = RUNS / category + split = json.loads((run / "split.json").read_text(encoding="utf-8")) + calibration = json.loads((run / "normal_calibration.json").read_text(encoding="utf-8")) + held_names = [p["image"] for p in calibration["predictions"]] + fit_names = [r["image"] for r in split["train"] if r["image"] not in set(held_names)] + test_rows = split["test"] + if smoke: + fit_names, held_names = fit_names[:100], held_names[:20] + test_rows = test_rows[:: max(1, len(test_rows) // 40)] + device = encoder.device + started = time.perf_counter() + parts = [] + for name in fit_names: + tokens, _, _ = encode(encoder, open_image(name), 448) + parts.append(F.normalize(tokens, dim=-1).half()) + everything = torch.cat(parts) + del parts + chosen = greedy_coreset(everything, SIZE, seed=42) + bank = everything[chosen].clone() + total = len(everything) + del everything + torch.cuda.empty_cache() + fit_seconds = time.perf_counter() - started + + def score(name): + tokens, _, grid = encode(encoder, open_image(name), 448) + mask = torch.as_tensor(foreground_mask(tokens, grid), device=device) + return top_mean(knn_distance(F.normalize(tokens, dim=-1), bank), mask) + + held = {n: {"core32k": score(n)} for n in held_names} + test = {r["image"]: {"core32k": score(r["image"])} for r in test_rows} + return { + "category": category, + "smoke": smoke, + "weights": str(WEIGHTS.relative_to(ROOT)), + "n_fit": len(fit_names), + "all_patches": total, + "bank_patches": len(bank), + "seconds_fit": round(fit_seconds, 1), + "seconds_total": round(time.perf_counter() - started, 1), + "heldout": held, + "test": test, + "labels": {r["image"]: 0 if r["label"] == "normal" else 1 for r in test_rows}, + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--categories", nargs="+", choices=CATEGORIES, default=list(CATEGORIES)) + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--force", action="store_true") + args = parser.parse_args() + OUT.mkdir(parents=True, exist_ok=True) + encoder = HighResolutionEncoder(SOURCE) + encoder.model.load_state_dict(torch.load(WEIGHTS, map_location=encoder.device)) + for category in args.categories: + target = OUT / (f"{category}.smoke.json" if args.smoke else f"{category}.json") + if target.exists() and not args.force: + print(f"{category}: already done", flush=True) + continue + record = run_category(category, encoder, args.smoke) + torch.cuda.empty_cache() + target.write_text(json.dumps(record), encoding="utf-8") + labels = record["labels"] + pos = [record["test"][n]["core32k"] for n, v in labels.items() if v == 1] + neg = [record["test"][n]["core32k"] for n, v in labels.items() if v == 0] + print( + f"{category}: {record['seconds_total']} s (fit {record['seconds_fit']} s) | tuned coreset 32k AUROC " + f"{auroc(pos, neg):.3f}", + flush=True, + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/encoder_tuned_coreset_report.py b/scripts/encoder_tuned_coreset_report.py new file mode 100644 index 0000000000000000000000000000000000000000..e4a6fcde11e419faad1197d133beb0b7ebbbf64f --- /dev/null +++ b/scripts/encoder_tuned_coreset_report.py @@ -0,0 +1,140 @@ +"""Report for round 5 (CPU only; run scripts.encoder_tuned_coreset first). + + python -m scripts.encoder_tuned_coreset_report + +Primary comparison, fixed before any result: the 32,768-patch coreset built from the fine-tuned (realistic-defect) +encoder against the 32,768-patch coreset built from the frozen encoder, the version that would be shipped otherwise. +Also shown: the deployed bank, the frozen full bank and the tuned full bank. Same rules as round 2/3: scores standardised +with the 90 held-out normals only, paired bootstrap 95% intervals, thresholds from held-out normals only (q95 for every +category, and the deployed q80 for macaroni1/2 shown separately). Descriptive only: the test images were already seen. +""" + +import json + +import numpy as np + +from backend.config import ROOT +from scripts.diagnose_encoder import auroc +from scripts.encoder_candidates_report import ( + DEPLOYED_QUANTILE, + HARD_TYPES, + RESULTS, + anomaly_types, + bootstrap_difference, +) + +EXPERIMENTS = ROOT / "experiments" +TUNED_CORESET = EXPERIMENTS / "dinov2_tuned_coreset" +OUT = ROOT / "results" / "encoder_tuned_coreset.json" +METHODS = ("frozen base", "frozen core32k", "frozen full", "tuned full", "tuned core32k") +REFERENCE = "frozen core32k" +WEAK = ("macaroni1", "macaroni2", "pcb2") + + +def read(path): + return json.loads(path.read_text(encoding="utf-8")) + + +def pick(category): + """(held-out, test) score arrays per method, in the order of the sorted test image names.""" + frozen = read(RESULTS / f"{category}.json") + banks = read(EXPERIMENTS / "dinov2_banks" / f"{category}.json") + tuned_full = read(EXPERIMENTS / "dinov2_candidates_realistic" / f"{category}.json") + tuned_core = read(TUNED_CORESET / f"{category}.json") + names = sorted(frozen["test"]) + held_names = sorted(frozen["heldout"]) + sources = { + "frozen base": (frozen, "base"), + "frozen core32k": (banks, "core32k"), + "frozen full": (frozen, "full"), + "tuned full": (tuned_full, "full"), + "tuned core32k": (tuned_core, "core32k"), + } + out = {} + for label, (record, key) in sources.items(): + out[label] = ( + np.array([record["heldout"][n][key] for n in held_names], float), + np.array([record["test"][n][key] for n in names], float), + ) + labels = np.array([frozen["labels"][n] for n in names]) + return out, labels, names + + +def main(): + rng = np.random.default_rng(2027) + categories = sorted(p.stem for p in TUNED_CORESET.glob("*.json") if ".smoke" not in p.name) + report = {} + for category in categories: + arrays, labels, names = pick(category) + standard = {k: ((h - h.mean()) / h.std(), (t - h.mean()) / h.std()) for k, (h, t) in arrays.items()} + reference = standard[REFERENCE][1] + entry = {} + for label, (z_held, z_test) in standard.items(): + result = {"auroc": auroc(z_test[labels == 1], z_test[labels == 0])} + if label != REFERENCE: + result["vs_frozen_core32k"] = bootstrap_difference(labels, z_test, reference, rng).tolist() + for tag, quantile in (("q95", 0.95), ("deployed", DEPLOYED_QUANTILE.get(category, 0.95))): + threshold = np.quantile(z_held, quantile) + result[f"recall_{tag}"] = float((z_test[labels == 1] >= threshold).mean()) + result[f"false_alarm_{tag}"] = float((z_test[labels == 0] >= threshold).mean()) + if category in HARD_TYPES: + kinds = anomaly_types(category, names) + hard = np.array([HARD_TYPES[category] in kinds[n] for n in names]) + result["auroc_hard_type"] = auroc(z_test[hard & (labels == 1)], z_test[labels == 0]) + entry[label] = result + report[category] = entry + OUT.write_text(json.dumps(report, indent=2), encoding="utf-8") + + def mark(m): + interval = m.get("vs_frozen_core32k") + if not interval: + return " " + return " ▲" if interval[0] > 0 else " ▼" if interval[1] < 0 else " " + + print(f"Categories: {len(categories)} (▲/▼ = clearly better/worse than the FROZEN 32k coreset)\n") + print(f"{'category':<11}" + "".join(f"{m:>16}" for m in METHODS)) + for category in categories: + print( + f"{category:<11}" + + "".join(f"{report[category][m]['auroc']:>14.3f}{mark(report[category][m])}" for m in METHODS) + ) + print(f"{'MEAN':<11}" + "".join(f"{np.mean([report[k][m]['auroc'] for k in categories]):>16.3f}" for m in METHODS)) + weak = [k for k in WEAK if k in report] + if weak: + print( + f"{'weak 3':<11}" + + "".join(f"{np.mean([report[k][m]['auroc'] for k in weak]):>16.3f}" for m in METHODS) + + f" (mean over {', '.join(weak)})" + ) + tuned = "tuned core32k" + better = sum(mark(report[k][tuned]) == " ▲" for k in categories) + worse = sum(mark(report[k][tuned]) == " ▼" for k in categories) + print( + f"\ntuned coreset vs frozen coreset: clearly better in {better}, clearly worse in {worse} of {len(categories)}" + ) + + print("\nHard defect types (AUROC of that type against all normals)") + print(f"{'category / type':<40}" + "".join(f"{m:>16}" for m in METHODS)) + for category, kind in HARD_TYPES.items(): + if category in report: + print( + f"{category + ' / ' + kind:<40}" + + "".join(f"{report[category][m]['auroc_hard_type']:>16.3f}" for m in METHODS) + ) + + print("\nOperating points: q95 for every category; deployed = q80 for macaroni1/2") + print( + f"{'category':<11}{'method':<16}{'AUROC':>7}{'q95 recall':>12}{'q95 false':>11}{'dep. recall':>13}{'dep. false':>12}" + ) + for category in (c for c in ("macaroni1", "macaroni2", "pcb2", "candle", "cashew") if c in report): + for label in ("frozen base", "frozen core32k", "tuned core32k"): + m = report[category][label] + print( + f"{category:<11}{label:<16}{m['auroc']:>7.3f}{m['recall_q95']:>12.0%}{m['false_alarm_q95']:>11.0%}" + f"{m['recall_deployed']:>13.0%}{m['false_alarm_deployed']:>12.0%}" + ) + print(f"\nWritten to results/{OUT.name}. Descriptive only (test images already seen in development).") + + +if __name__ == "__main__": + main() diff --git a/scripts/export_showcase.py b/scripts/export_showcase.py new file mode 100644 index 0000000000000000000000000000000000000000..659d81a01fdfa9fb00e757d93c0cf0cd1fd4e1cf --- /dev/null +++ b/scripts/export_showcase.py @@ -0,0 +1,127 @@ +"""Export only allowlisted, already measured VisA acceptance examples. + +Reads SQLite in read-only mode; never performs inference or publishes arbitrary uploads. +""" +import csv +import hashlib +import html +import io +import json +from pathlib import Path +import shutil +import sqlite3 + +ROOT = Path(__file__).resolve().parents[1] +OUTPUT = ROOT / 'frontend' / 'public' / 'showcase' + + +def export(output=OUTPUT): + acceptance = json.loads((ROOT / 'results/acceptance.json').read_text()) + examples = list(acceptance['real_images']) + if len(examples) != 6 or len({e['id'] for e in examples}) != 6: + raise ValueError('Expected six distinct verified acceptance examples') + scope = json.loads((ROOT / 'results/evidence_scope_verification.json').read_text()) + quality_path=ROOT/'results/assistant_quality_verification.json' + quality=json.loads(quality_path.read_text()) if quality_path.exists() else {} + if quality and quality.get('status')!='passed':raise ValueError('Finish assistant acceptance before exporting') + final_fingerprint = scope['answers'][0]['knowledge_fingerprint'] + examples.append({**scope['answers'][0]['observation'], 'truth': 1}) + extra_path=ROOT/'results/all_categories_acceptance.json' + extra=json.loads(extra_path.read_text())['real_images'] if extra_path.exists() else [] + examples.extend(extra) + extra_ids={e['id'] for e in extra} + output.mkdir(parents=True, exist_ok=True) + (output / 'images').mkdir(exist_ok=True) + (output / 'reports').mkdir(exist_ok=True) + records, samples, conversations = [], [], {} + fields = ['id', 'created_at', 'category', 'verdict', 'score', 'threshold', + 'uncertainty_margin', 'inference_ms', 'model_id'] + database = ROOT / 'runtime/inspection.sqlite3' + with sqlite3.connect(database.as_uri() + '?mode=ro', uri=True) as db: + for example in examples: + extra_db=sqlite3.connect((ROOT/'runtime/verification12/inspection.sqlite3').as_uri()+'?mode=ro',uri=True) if example['id'] in extra_ids else None + selected=extra_db or db + row = selected.execute('SELECT payload FROM inspections WHERE id=?', (example['id'],)).fetchone() + if not row: + raise ValueError('Saved measured example missing: ' + example['id']) + source = json.loads(row[0]) + record = {k: source[k] for k in fields if k in source} + if record['score'] != example['score'] or record['verdict'] != example['verdict']: + raise ValueError('Example differs from measured acceptance record') + identifier = record['id'] + record.update(batch='Verified VisA examples', filename='VisA example', + image_url=f'showcase/images/{identifier}.jpg', + heatmap_url=f'showcase/images/{identifier}_heatmap.jpg') + for suffix in ('.jpg', '_heatmap.jpg'): + artifacts=ROOT/('runtime/verification12/artifacts' if extra_db else 'runtime/artifacts') + shutil.copyfile(artifacts / (identifier + suffix), + output / 'images' / (identifier + suffix)) + name = record['category'] + ('_anomalous' if example['truth'] else '_good') + if identifier == scope['inspection_id']: + name += '_followup' + samples.append({'name': name, 'category': record['category'], 'record_id': identifier, + 'url': record['image_url'], 'attribution': 'VisA · Zou et al., ECCV 2022 · CC BY 4.0'}) + # Publish saved validated answers and abstentions; omit obsolete fallback diagnostics. + rows = selected.execute('SELECT role,payload FROM messages WHERE inspection_id=? ORDER BY id', (identifier,)).fetchall() + if extra_db:extra_db.close() + messages = [] + for previous, current in zip(rows, rows[1:]): + if previous[0] != 'user' or current[0] != 'assistant': + continue + answer = json.loads(current[1]) + if answer.get('mode') not in ('llm', 'abstained'): + continue + if answer.get('mode') == 'llm' and answer.get('knowledge_fingerprint') != final_fingerprint: + continue + messages.extend([{'role': 'user', 'question': json.loads(previous[1])['question']}, + {'role': 'assistant', **{k: answer[k] for k in ('answer', 'mode', 'evidence', 'trace') if k in answer}}]) + if identifier == scope['inspection_id']: + messages = [] + for answer in quality.get('answers',scope['answers']): + messages.extend([{'role': 'user', 'question': answer['question']}, + {'role': 'assistant', **{k: answer[k] for k in ('answer', 'mode', 'evidence', 'trace')}}]) + conversations[identifier] = messages + records.append(record) + esc = lambda value: html.escape(str(value)) + table = ''.join(f'{esc(k)}{esc(record.get(k, ""))}' for k in fields) + discussion = ''.join('

' + esc(m.get('question', m.get('answer', ''))) + '

' for m in messages) or '

No evidence conversation was recorded for this inspection.

' + sources = {s['chunk_id']: s for m in messages for s in m.get('evidence', [])} + discussion += '

Retrieved source passages

' + (''.join( + '

' + esc(k) + ' · ' + esc(s['title']) + '

' + esc(s['text']) + '

' + esc(s['url']) + '

' + for k, s in sources.items()) or '

No documentation was retrieved for this inspection.

') + (output / 'reports' / (identifier + '.html')).write_text( + '' + 'Saved DefectRAG example' + '

Saved inspection example

Previously measured VisA example. No live inference runs on this website.

' + '

VisA · Zou et al., ECCV 2022 · CC BY 4.0 · resized images and model overlay. ' + 'Dataset source

' + '' + table + '
' + f'

Image and measured heatmap

VisA sampleSaved heatmap' + '

Recorded evidence conversation

' + discussion + '', encoding='utf-8') + evaluation = json.loads((ROOT / 'results/evaluation.json').read_text()) + evaluation['serving_profile'] = json.loads((ROOT / 'results/serving_profile.json').read_text()) + # These files contain only evaluation metrics/configuration, not private runtime paths. + data = {'schema': 1, 'mode': 'saved_examples', 'records': records, 'samples': samples, + 'messages': conversations, 'evaluation': evaluation, + 'official_evaluation':json.loads((ROOT/'results/official_evaluation.json').read_text()), + 'attribution': 'VisA · Zou et al., ECCV 2022 · CC BY 4.0 · resized images and model overlays', + 'source': 'https://github.com/amazon-science/spot-diff'} + candidate=ROOT/'results/highres_evaluation.json' + if candidate.exists():data['official_evaluation']['candidate']=json.loads(candidate.read_text()) + text = json.dumps(data, indent=2) + if ':\\' in text or 'Users/' in text or 'localhost' in text or '127.0.0.1' in text: + raise ValueError('Local path or service address found in public snapshot') + (output / 'data.json').write_text(text, encoding='utf-8') + buffer = io.StringIO(newline='') + writer = csv.DictWriter(buffer, fieldnames=fields, extrasaction='ignore') + writer.writeheader(); writer.writerows(records) + (output / 'inspections.csv').write_text(buffer.getvalue(), encoding='utf-8') + hashes = {p.relative_to(output).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(output.rglob('*')) if p.is_file() and p.name != 'manifest.json'} + (output / 'manifest.json').write_text(json.dumps({'files': hashes, 'records': len(records), + 'provenance': 'allowlisted acceptance + all_categories_acceptance + passed assistant_quality receipts; original saved runtime artifacts; old experiments not repeated'}, indent=2)) + print(json.dumps({'status': 'passed', 'examples': len(records), 'files': len(hashes), 'output': str(output)})) + + +if __name__ == '__main__': + export() diff --git a/scripts/export_showcase_tuned.py b/scripts/export_showcase_tuned.py new file mode 100644 index 0000000000000000000000000000000000000000..cf89e50a392732cf5bee9550cc4d531dc6eff10a --- /dev/null +++ b/scripts/export_showcase_tuned.py @@ -0,0 +1,175 @@ +"""Rebuild the saved-example showcase from inspections made by the deployed tuned detector. + +Reads a finished inspection database and its artifacts in read-only mode. It never runs the model and never +publishes arbitrary uploads: only inspections whose file name is one of the 24 allowlisted VisA samples +(`_good.jpg` / `_anomalous.jpg`) are exported, with every result kept exactly as measured +(including the cases the detector got wrong). + + python -m scripts.export_showcase_tuned --source +""" + +import argparse +import csv +import hashlib +import html +import io +import json +import os +import shutil +import sqlite3 +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +OUTPUT = ROOT / "frontend" / "public" / "showcase" +FIELDS = [ + "id", + "created_at", + "category", + "verdict", + "score", + "threshold", + "uncertainty_margin", + "inference_ms", + "model_id", +] +CATEGORIES = [ + "candle", + "capsules", + "cashew", + "chewinggum", + "fryum", + "macaroni1", + "macaroni2", + "pcb1", + "pcb2", + "pcb3", + "pcb4", + "pipe_fryum", +] +ALLOWED = {f"{c}_{kind}.jpg": (c, kind) for c in CATEGORIES for kind in ("good", "anomalous")} +ATTRIBUTION = "VisA · Zou et al., ECCV 2022 · CC BY 4.0" + + +def read_json(relative): + return json.loads((ROOT / relative).read_text(encoding="utf-8")) + + +def load_inspections(source): + database = Path(source) / "inspection.sqlite3" + with sqlite3.connect(database.as_uri() + "?mode=ro", uri=True) as db: + payloads = [json.loads(row[0]) for row in db.execute("SELECT payload FROM inspections")] + chosen = {} + for payload in sorted(payloads, key=lambda p: p["created_at"]): + name = payload.get("filename") + if name in ALLOWED and payload["category"] == ALLOWED[name][0]: + chosen[name] = payload # the latest run of each sample wins + missing = sorted(set(ALLOWED) - set(chosen)) + if missing: + raise ValueError("Missing saved inspections for: " + ", ".join(missing)) + models = {p["model_id"].split("-")[0] + "-" + p["model_id"].split("-")[1] for p in chosen.values()} + if models != {"dinov2-tuned"}: + raise ValueError("Expected only inspections by the tuned detector, found: " + ", ".join(sorted(models))) + return [chosen[name] for name in sorted(chosen)] + + +def report_page(record, esc): + table = "".join(f"{esc(k)}{esc(record.get(k, ''))}" for k in FIELDS) + identifier = record["id"] + return ( + '' + "Saved DefectRAG example" + "

Saved inspection example

Previously measured VisA example. No live inference runs on this website.

" + f"

{ATTRIBUTION} · resized images and model overlay. " + 'Dataset source

' + '' + table + "
" + f'

Image and measured heatmap

VisA sample' + f'Saved heatmap' + "

Recorded evidence conversation

No evidence conversation was recorded for this inspection.

" + ) + + +def export(source, output=OUTPUT): + source = Path(source) + inspections = load_inspections(source) + for folder in ("images", "reports"): + shutil.rmtree(output / folder, ignore_errors=True) + (output / folder).mkdir(parents=True, exist_ok=True) + records, samples, conversations = [], [], {} + esc = lambda value: html.escape(str(value)) # noqa: E731 + for payload in inspections: + identifier = payload["id"] + record = {k: payload[k] for k in FIELDS if k in payload} + record.update( + batch="Verified VisA examples", + filename="VisA example", + image_url=f"showcase/images/{identifier}.jpg", + heatmap_url=f"showcase/images/{identifier}_heatmap.jpg", + ) + for suffix in (".jpg", "_heatmap.jpg"): + shutil.copyfile(source / "artifacts" / (identifier + suffix), output / "images" / (identifier + suffix)) + stem = Path(payload["filename"]).stem + samples.append( + { + "name": stem, + "category": record["category"], + "record_id": identifier, + "url": record["image_url"], + "attribution": ATTRIBUTION, + } + ) + conversations[identifier] = [] + records.append(record) + (output / "reports" / (identifier + ".html")).write_text(report_page(record, esc), encoding="utf-8") + evaluation = read_json("results/tuned_deployment_evaluation.json") + official = read_json("results/official_evaluation.json") + if (ROOT / "results/highres_evaluation.json").exists(): + official["candidate"] = read_json("results/highres_evaluation.json") + if (ROOT / "results/mvtec_summary.json").exists(): + official["mvtec"] = read_json("results/mvtec_summary.json") + data = { + "schema": 1, + "mode": "saved_examples", + "records": records, + "samples": samples, + "messages": conversations, + "evaluation": evaluation, + "official_evaluation": official, + "attribution": ATTRIBUTION + " · resized images and model overlays", + "source": "https://github.com/amazon-science/spot-diff", + } + text = json.dumps(data, indent=2) + if ":\\" in text or "Users/" in text or "localhost" in text or "127.0.0.1" in text: + raise ValueError("Local path or service address found in public snapshot") + (output / "data.json").write_text(text, encoding="utf-8") + buffer = io.StringIO(newline="") + writer = csv.DictWriter(buffer, fieldnames=FIELDS, extrasaction="ignore") + writer.writeheader() + writer.writerows(records) + (output / "inspections.csv").write_text(buffer.getvalue(), encoding="utf-8") + hashes = { + p.relative_to(output).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(output.rglob("*")) + if p.is_file() and p.name != "manifest.json" + } + (output / "manifest.json").write_text( + json.dumps( + { + "files": hashes, + "records": len(records), + "provenance": "24 inspections by the deployed tuned detector (dinov2_tuned_v1); results kept as measured, including misses; no assistant conversations", + }, + indent=2, + ) + ) + print(json.dumps({"status": "passed", "examples": len(records), "files": len(hashes), "output": str(output)})) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--source", + default=str(Path(os.environ.get("TEMP", ".")) / "defectrag-thumb-data"), + help="folder holding inspection.sqlite3 and artifacts/", + ) + export(parser.parse_args().source) diff --git a/scripts/fetch_public_assets.py b/scripts/fetch_public_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..65da9053632c506b65f6a96b949d8d26844ed165 --- /dev/null +++ b/scripts/fetch_public_assets.py @@ -0,0 +1,40 @@ +"""Explicit, optional asset download for a fresh source clone; never fit models.""" +import argparse +from pathlib import Path +from huggingface_hub import snapshot_download + +ROOT=Path(__file__).resolve().parents[1] +REPOSITORY='Wizzas/DefectRAG' +REVISION='bc6bc66c445388cce227bc3851bd602c88386741' +PATTERNS=['models/encoder_dinov2/*','models/highres/*','models/encoder_dinov2_tuned/*','models/highres_tuned/*','models/embedding/*', + 'models/BGE-LICENSE.txt','samples/*','results/*.json'] + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--list',action='store_true',help='List public asset groups; download nothing') + args=parser.parse_args() + print(f'Public Space assets: {REPOSITORY} @ {REVISION}') + print('Groups: '+', '.join(PATTERNS)) + if args.list: + return + # Only immutable public assets are downloaded; application code/config and + # private runtime are not part of this snapshot selection. + snapshot_download(REPOSITORY,repo_type='space',revision=REVISION, + allow_patterns=PATTERNS,local_dir=ROOT) + from backend.vision import sha256 + import json + cards=list((ROOT/'models/highres').glob('*.json')) + assert len(cards)==12,'All 12 category cards are required' + for path in cards: + card=json.loads(path.read_text()) + assert sha256(path.with_suffix('.npz'))==card['bank_sha256'] + tuned=list((ROOT/'models/highres_tuned').glob('[!P]*.json')) + assert len(tuned)==12,'All 12 fine-tuned category cards are required' + for path in tuned: + card=json.loads(path.read_text()) + assert sha256(path.with_suffix('.npz'))==card['bank_sha256'] + assert sha256(ROOT/'models/encoder_dinov2_tuned/model.safetensors')==card['encoder_sha256'] + print('All 12 bank checksums verified for both profiles (frozen and fine-tuned). No fitting, threshold change or GPU experiment.') + +if __name__=='__main__': + main() diff --git a/scripts/mvtec_eval.py b/scripts/mvtec_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..33feb2a68b2e9ede76a9ac677b622e1a4eec50b1 --- /dev/null +++ b/scripts/mvtec_eval.py @@ -0,0 +1,229 @@ +"""One-shot MVTec AD evaluation of three detector arms (needs the GPU). Protocol: docs/MVTEC_EVALUATION.md. + + python -m scripts.mvtec_eval --smoke --categories bottle # code check on a tiny subset; scores are discarded + python -m scripts.mvtec_eval # all 15 categories, one run, resumes finished ones + +Arms (fixed in the protocol before any MVTec score existed): + A original DINOv2 + random-sample bank (up to 48 foreground + 16 other patches per fit image, cap 32,768) + B original DINOv2 + 32,768-patch farthest-point coreset + C VisA-fine-tuned DINOv2 (models/encoder_dinov2_tuned) + the same coreset + +Nothing is trained or tuned here. Test images are used only for scoring. +""" + +import argparse +import hashlib +import json +import time + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image + +from backend.config import ROOT +from backend.highres import HighResolutionEncoder, foreground_mask, restore_map, score_tokens +from scripts.benchmark_official import pixel_metrics, rank_metrics +from scripts.encoder_banks import greedy_coreset + +DATA = ROOT / "MVTec_AD" +OUT = ROOT / "experiments" / "mvtec_eval" +PROTOCOL = ROOT / "docs" / "MVTEC_EVALUATION.md" +CATEGORIES = ( + "bottle", + "cable", + "capsule", + "carpet", + "grid", + "hazelnut", + "leather", + "metal_nut", + "pill", + "screw", + "tile", + "toothbrush", + "transistor", + "wood", + "zipper", +) +ARMS = ("A_random_frozen", "B_coreset_frozen", "C_coreset_tuned") +BANK_SIZE = 32768 +SEED = 42 + + +def sha256_file(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def listing(category): + base = DATA / category + train = sorted((base / "train" / "good").glob("*.png")) + rows = [ + {"image": p, "label": 0, "mask": None, "type": "good"} for p in sorted((base / "test" / "good").glob("*.png")) + ] + for p in sorted(base.glob("test/*/*.png")): + if p.parent.name != "good": + rows.append( + { + "image": p, + "label": 1, + "mask": base / "ground_truth" / p.parent.name / (p.stem + "_mask.png"), + "type": p.parent.name, + } + ) + return train, rows + + +def split_train(paths): + """The VisA rule: sort by content hash and hold out every tenth distinct hash for thresholds.""" + keyed = sorted(((sha256_file(p), p.name, p) for p in paths), key=lambda item: item[:2]) + held_hashes = set(sorted({k[0] for k in keyed})[::10]) + held = [k[2] for k in keyed if k[0] in held_hashes] + fit = sorted((k[2] for k in keyed if k[0] not in held_hashes), key=lambda p: p.name) + return fit, held + + +def encode(encoder, path): + with Image.open(path) as image: + tokens, geometry = encoder.encode(image) + return tokens, foreground_mask(tokens, geometry["grid"]), geometry + + +def random_bank(frozen, fit, rng): + """Arm A: up to 48 foreground + 16 other patches per fit image; subsample to the cap.""" + parts = [] + for path in fit: + tokens, mask, _ = encode(frozen, path) + features = F.normalize(tokens, dim=-1).half() + foreground, other = np.flatnonzero(mask), np.flatnonzero(~mask) + chosen = np.r_[ + rng.choice(foreground, min(48, len(foreground)), replace=False), + rng.choice(other, min(16, len(other)), replace=False), + ].astype(int) + parts.append(features[torch.as_tensor(chosen, device=features.device)]) + bank = torch.cat(parts) + if len(bank) > BANK_SIZE: + bank = bank[torch.as_tensor(rng.choice(len(bank), BANK_SIZE, replace=False), device=bank.device)] + return bank + + +def coreset_bank(encoder, fit): + """Arms B and C: greedy farthest-point coreset of every patch of every fit image.""" + parts = [F.normalize(encode(encoder, path)[0], dim=-1).half() for path in fit] + everything = torch.cat(parts) + del parts + chosen = greedy_coreset(everything, min(BANK_SIZE, len(everything)), seed=SEED) + bank = everything[chosen].clone() + del everything + torch.cuda.empty_cache() + return bank + + +def prepared(bank, device): + return F.normalize(bank.float().to(device), dim=-1) + + +def score_all(frozen, tuned, banks, path, want_maps): + """Scores (and 224x224 maps) of one image for the three arms.""" + out, maps = {}, {} + tokens, mask, geometry = encode(frozen, path) + for arm in ("A_random_frozen", "B_coreset_frozen"): + raw, score = score_tokens(tokens, banks[arm], mask) + out[arm] = score + if want_maps: + maps[arm] = restore_map(raw, geometry, (224, 224)).ravel().astype("float32") + tokens, mask, geometry = encode(tuned, path) + raw, score = score_tokens(tokens, banks["C_coreset_tuned"], mask) + out["C_coreset_tuned"] = score + if want_maps: + maps["C_coreset_tuned"] = restore_map(raw, geometry, (224, 224)).ravel().astype("float32") + return out, maps + + +def mask_array(row): + if row["mask"] is None: + return np.zeros(224 * 224, dtype=bool) + with Image.open(row["mask"]) as image: + return (np.asarray(image.convert("L").resize((224, 224), Image.Resampling.NEAREST)) > 0).ravel() + + +def run_category(category, frozen, tuned, smoke): + train, rows = listing(category) + fit, held = split_train(train) + if smoke: + fit, held, rows = fit[:20], held[:4], rows[:: max(1, len(rows) // 10)] + started = time.perf_counter() + rng = np.random.default_rng(SEED) + banks = { + "A_random_frozen": prepared(random_bank(frozen, fit, rng), frozen.device), + "B_coreset_frozen": prepared(coreset_bank(frozen, fit), frozen.device), + "C_coreset_tuned": prepared(coreset_bank(tuned, fit), frozen.device), + } + fit_seconds = time.perf_counter() - started + held_scores = [score_all(frozen, tuned, banks, path, False)[0] for path in held] + test_scores, pixel_maps = [], {arm: [] for arm in ARMS} + for row in rows: + scores, maps = score_all(frozen, tuned, banks, row["image"], True) + test_scores.append(scores) + for arm in ARMS: + pixel_maps[arm].append(maps[arm]) + truth = np.concatenate([mask_array(r) for r in rows]) + labels = [r["label"] for r in rows] + metrics = {} + for arm in ARMS: + values = [s[arm] for s in test_scores] + metrics[arm] = {**rank_metrics(labels, values)} + if truth.any(): + metrics[arm].update(pixel_metrics(truth, np.concatenate(pixel_maps[arm]))) + return { + "category": category, + "smoke": smoke, + "protocol_sha256": sha256_file(PROTOCOL), + "seed": SEED, + "n_fit": len(fit), + "n_heldout": len(held), + "n_test": len(rows), + "bank_patches": {arm: len(b) for arm, b in banks.items()}, + "seconds_fit": round(fit_seconds, 1), + "seconds_total": round(time.perf_counter() - started, 1), + "heldout": {p.name: s for p, s in zip(held, held_scores)}, + "test": {f"{r['type']}/{r['image'].name}": s for r, s in zip(rows, test_scores)}, + "labels": {f"{r['type']}/{r['image'].name}": r["label"] for r in rows}, + "metrics": None if smoke else metrics, + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--categories", nargs="+", choices=CATEGORIES, default=list(CATEGORIES)) + parser.add_argument("--smoke", action="store_true", help="tiny subset to check the code; metrics are not stored") + args = parser.parse_args() + OUT.mkdir(parents=True, exist_ok=True) + frozen = HighResolutionEncoder(ROOT / "models" / "encoder_dinov2") + tuned = HighResolutionEncoder(ROOT / "models" / "encoder_dinov2_tuned") + for category in args.categories: + target = OUT / (f"{category}.smoke.json" if args.smoke else f"{category}.json") + if target.exists() and not args.smoke: + print(f"{category}: already done", flush=True) + continue + record = run_category(category, frozen, tuned, args.smoke) + torch.cuda.empty_cache() + target.write_text(json.dumps(record), encoding="utf-8") + if args.smoke: + finite = all(np.isfinite(v) for s in record["test"].values() for v in s.values()) + print( + f"{category}: smoke run OK in {record['seconds_total']} s | {record['n_fit']} fit, {record['n_test']} test" + f" | banks {record['bank_patches']} | all scores finite: {finite} (scores discarded)", + flush=True, + ) + else: + m = record["metrics"] + print( + f"{category}: {record['seconds_total']} s | image AUROC " + + " ".join(f"{arm.split('_')[0]} {m[arm]['auroc']:.3f}" for arm in ARMS), + flush=True, + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/mvtec_report.py b/scripts/mvtec_report.py new file mode 100644 index 0000000000000000000000000000000000000000..1c3d098a9ebab04dcc0a56f45f5137de95415c34 --- /dev/null +++ b/scripts/mvtec_report.py @@ -0,0 +1,154 @@ +"""Report for the one-shot MVTec AD evaluation (CPU only; run scripts.mvtec_eval first). Protocol: docs/MVTEC_EVALUATION.md. + + python -m scripts.mvtec_report + +Image AUROC (primary), pixel AUROC and image average precision per category and macro mean, paired bootstrap 95% +intervals for the differences B-A, C-B and C-A, and descriptive operating points at the q95 threshold of the held-out +normals (same rule for every category). Results are written to results/mvtec_eval.json. +""" + +import json + +import numpy as np + +from backend.config import ROOT +from scripts.diagnose_encoder import auroc +from scripts.encoder_candidates_report import bootstrap_difference +from scripts.mvtec_eval import ARMS, CATEGORIES, OUT + +RESULT = ROOT / "results" / "mvtec_eval.json" +SUMMARY = ROOT / "results" / "mvtec_summary.json" +PROTOCOL_URL = "https://github.com/WAYTECHG/DefectRAG/blob/main/docs/MVTEC_EVALUATION.md" +LABELS = { + "A_random_frozen": "Random-sample memory", + "B_coreset_frozen": "Coreset memory", + "C_coreset_tuned": "Coreset + fine-tuned encoder", +} +PAIRS = ( + ("B_coreset_frozen", "A_random_frozen"), + ("C_coreset_tuned", "B_coreset_frozen"), + ("C_coreset_tuned", "A_random_frozen"), +) +SHORT = {"A_random_frozen": "A", "B_coreset_frozen": "B", "C_coreset_tuned": "C"} + + +def main(): + rng = np.random.default_rng(2027) + report = {} + for category in CATEGORIES: + path = OUT / f"{category}.json" + if not path.exists(): + continue + record = json.loads(path.read_text(encoding="utf-8")) + names = sorted(record["test"]) + labels = np.array([record["labels"][n] for n in names]) + scores = {arm: np.array([record["test"][n][arm] for n in names]) for arm in ARMS} + entry = { + "n_test": len(names), + "n_fit": record["n_fit"], + "n_heldout": record["n_heldout"], + "arms": {}, + "differences": {}, + } + for arm in ARMS: + held = np.array([s[arm] for s in record["heldout"].values()]) + threshold = float(np.quantile(held, 0.95)) + values = scores[arm] + metrics = record["metrics"][arm] + entry["arms"][arm] = { + "auroc": auroc(values[labels == 1], values[labels == 0]), + "pixel_auroc": metrics.get("pixel_auroc"), + "average_precision": metrics["average_precision"], + "recall_q95": float((values[labels == 1] >= threshold).mean()), + "false_alarm_q95": float((values[labels == 0] >= threshold).mean()), + } + for better, base in PAIRS: + low, high = bootstrap_difference(labels, scores[better], scores[base], rng) + entry["differences"][f"{SHORT[better]}-{SHORT[base]}"] = [float(low), float(high)] + report[category] = entry + categories = list(report) + RESULT.write_text(json.dumps(report, indent=2), encoding="utf-8") + write_summary(report, categories) + + def mark(interval): + return " ▲" if interval[0] > 0 else " ▼" if interval[1] < 0 else " " + + print( + f"Categories scored: {len(categories)} of {len(CATEGORIES)} (▲/▼ = clearly better/worse by paired bootstrap)\n" + ) + print( + 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" + ) + for category in categories: + a = report[category]["arms"] + d = report[category]["differences"] + pixel = " / ".join(f"{a[arm]['pixel_auroc']:.3f}" for arm in ARMS) + print( + f"{category:<11}" + + "".join( + f"{a[arm]['auroc']:>10.3f}" if i == 0 else f"{a[arm]['auroc']:>11.3f}" for i, arm in enumerate(ARMS) + ) + + f" {mark(d['B-A']):>5}{mark(d['C-B']):>5}{mark(d['C-A']):>5} {pixel}" + ) + + def macro(arm, key): + return float(np.mean([report[c]["arms"][arm][key] for c in categories])) + + print() + print( + f"{'MACRO MEAN':<11}" + + "".join( + f"{macro(arm, 'auroc'):>10.3f}" if i == 0 else f"{macro(arm, 'auroc'):>11.3f}" for i, arm in enumerate(ARMS) + ) + ) + print("macro pixel AUROC: " + " ".join(f"{SHORT[arm]} {macro(arm, 'pixel_auroc'):.3f}" for arm in ARMS)) + print("macro image AP: " + " ".join(f"{SHORT[arm]} {macro(arm, 'average_precision'):.3f}" for arm in ARMS)) + print( + "q95 recall / false alarms (macro): " + + " ".join( + f"{SHORT[arm]} {macro(arm, 'recall_q95'):.0%} / {macro(arm, 'false_alarm_q95'):.0%}" for arm in ARMS + ) + ) + for pair in ("B-A", "C-B", "C-A"): + better = sum(1 for c in categories if report[c]["differences"][pair][0] > 0) + worse = sum(1 for c in categories if report[c]["differences"][pair][1] < 0) + print(f"{pair}: clearly better in {better}, clearly worse in {worse} of {len(categories)} categories") + print( + "\nWritten to results/mvtec_eval.json. Descriptive; one run on a mirror copy of MVTec AD (docs/MVTEC_EVALUATION.md)." + ) + + +def write_summary(report, categories): + """A compact file for the dashboard's Official benchmark page (macro means, per-product AUROC, clear differences).""" + keys = ("auroc", "average_precision", "pixel_auroc", "recall_q95", "false_alarm_q95") + macro = {arm: {k: float(np.mean([report[c]["arms"][arm][k] for c in categories])) for k in keys} for arm in ARMS} + comparisons = { + pair: { + "better": sum(1 for c in categories if report[c]["differences"][pair][0] > 0), + "worse": sum(1 for c in categories if report[c]["differences"][pair][1] < 0), + } + for pair in ("B-A", "C-B", "C-A") + } + summary = { + "dataset": "MVTec AD", + "scope": ( + "One offline run on 15 products the detector was never built for. Each product's memory comes from its own " + "normal training photos; thresholds are the 95th percentile of held-out normal scores. These products are " + "not available for inspection in this app." + ), + "protocol_url": PROTOCOL_URL, + "arms": [{"key": arm, "label": LABELS[arm]} for arm in ARMS], + "products": len(categories), + "test_images": int(sum(report[c]["n_test"] for c in categories)), + "macro_mean": macro, + "comparisons": comparisons, + "categories": { + c: {"n_test": report[c]["n_test"], "arms": report[c]["arms"], "differences": report[c]["differences"]} + for c in categories + }, + } + SUMMARY.write_text(json.dumps(summary, indent=2), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/scripts/package_benchmark.py b/scripts/package_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..a12ed978c11b0bfca17114a9d211f7712fa84936 --- /dev/null +++ b/scripts/package_benchmark.py @@ -0,0 +1,41 @@ +"""Preserve completed official experiment assets, without rerunning a model.""" +import hashlib +import json +from pathlib import Path +import zipfile +import argparse +from backend.config import ROOT,CATEGORIES + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + +if __name__=='__main__': + parser=argparse.ArgumentParser() + parser.add_argument('--experiment',choices=['official_visa_v1','dinov2_highres_v1'],default='official_visa_v1') + parser.add_argument('--name',default='DefectRAG-official-benchmark-assets.zip') + args=parser.parse_args() + if Path(args.name).name!=args.name or not args.name.endswith('.zip'):raise ValueError('Use a ZIP basename') + source=ROOT/'experiments'/args.experiment + archive=ROOT.parent/args.name + if archive.exists():raise FileExistsError('Earlier archive preserved: '+str(archive)) + for category in CATEGORIES: + receipt=json.loads((source/category/'complete.json').read_text()) + assert receipt['status']=='passed' + for name,expected in receipt['files'].items(): + assert digest(source/category/name)==expected,(category,name) + paths=sorted(p for p in source.rglob('*') if p.is_file() and not set(p.relative_to(source).parts)&{'features','maps'}) + manifest={p.relative_to(source).as_posix():digest(p) for p in paths} + with zipfile.ZipFile(archive,'x',zipfile.ZIP_DEFLATED,compresslevel=3) as output: + for path in paths:output.write(path,'experiments/'+args.experiment+'/'+path.relative_to(source).as_posix()) + output.writestr('BENCHMARK_MANIFEST.json',json.dumps(manifest,indent=2)) + with zipfile.ZipFile(archive) as output: + assert output.testzip() is None + for name,expected in manifest.items(): + assert hashlib.sha256(output.read('experiments/'+args.experiment+'/'+name)).hexdigest()==expected + receipt={'status':'passed','archive':archive.name,'bytes':archive.stat().st_size,'sha256':digest(archive), + 'categories':len(CATEGORIES),'files':len(paths)+1,'crc_and_hashes':'passed', + 'restore':'Extract into project root; experiments/'+args.experiment+' appears. Do not overwrite newer experiments.', + 'intermediate_caches':'Feature caches/maps retained on the workstation; not duplicated in this artifact', + 'scope':'experimental banks, official split manifests, calibration, predictions, metrics; no source images or user history'} + archive.with_suffix('.receipt.json').write_text(json.dumps(receipt,indent=2)) + print(json.dumps(receipt,indent=2),flush=True) diff --git a/scripts/package_release.py b/scripts/package_release.py new file mode 100644 index 0000000000000000000000000000000000000000..b7b6625ebd5b295ceeab6fee17b347066a1cefea --- /dev/null +++ b/scripts/package_release.py @@ -0,0 +1,75 @@ +"""Build a clean release with file hashes, then verify and optionally extract it. +Never modifies model assets, datasets, earlier ZIPs or an existing extraction. +""" +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import zipfile + +ROOT=Path(__file__).resolve().parents[1] +EXCLUDED_PARTS={'node_modules','__pycache__','.pytest_cache','.git','runtime','development-support','.venv','.cache'} +HISTORICAL={'DEVELOPMENT_PROGRESS.previous.md','PAUSE_CHECKPOINT_20261016.md','acceptance_checkpoint.json', + 'rag_diagnostic.json','scope_diagnostic.json','pause_processes.json'} +ROOT_FILES={'README.md','LICENSE','DEVELOPMENT_PROGRESS.md','.env.example','.gitignore','.dockerignore', + 'requirements.txt','requirements-anomalib.txt','Start-DefectRAG.ps1','Start-DefectRAG.cmd','Dockerfile','compose.yaml','render.yaml'} +ROOT_DIRS={'backend','scripts','tests','knowledge','models','samples','results','docs','deployment','.vscode'} + +def digest(path): + h=hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda:stream.read(1024*1024),b''):h.update(block) + return h.hexdigest() + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument('--name',default='DefectRAG-v2.zip') + parser.add_argument('--extract',action='store_true') + args=parser.parse_args() + if Path(args.name).name!=args.name or not args.name.endswith('.zip'):raise ValueError('Use a ZIP basename') + archive=ROOT.parent/args.name + if archive.exists():raise FileExistsError('Earlier archive preserved: '+str(archive)) + paths=[] + for p in ROOT.rglob('*'): + if not p.is_file():continue + relative=p.relative_to(ROOT) + if set(relative.parts)&EXCLUDED_PARTS or p.name in HISTORICAL:continue + if p.name.startswith('.env') and p.name!='.env.example':continue + if p.suffix in {'.pyc','.zip','.bundle','.tar'} or '.sqlite' in p.name:continue + if len(relative.parts)==1: + include=p.name in ROOT_FILES + elif relative.parts[0]=='frontend': + include=relative.parts[1] in {'src','dist','dist-static','tests','public','package.json','package-lock.json','index.html','vite.config.js','vercel.json'} + else:include=relative.parts[0] in ROOT_DIRS + if include:paths.append(p) + required={'models/encoder/model.safetensors','models/embedding/model.safetensors','knowledge/index/index.npz', + 'frontend/dist/index.html','results/software-tests.xml','README.md','docs/VERIFICATION_REPORT.md'} + names={p.relative_to(ROOT).as_posix() for p in paths} + if not required<=names:raise RuntimeError('Missing required release files: '+str(required-names)) + manifest={'schema':1,'created_utc':datetime.now(timezone.utc).isoformat(), + 'git_commit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD'],text=True).strip(), + 'files':[{'path':p.relative_to(ROOT).as_posix(),'bytes':p.stat().st_size,'sha256':digest(p)} for p in sorted(paths)]} + manifest_path=ROOT/'RELEASE_MANIFEST.json';manifest_path.write_text(json.dumps(manifest,indent=2)) + with zipfile.ZipFile(archive,'x',zipfile.ZIP_DEFLATED,compresslevel=3) as zipped: + for p in paths+[manifest_path]:zipped.write(p,'DefectRAG-v2/'+p.relative_to(ROOT).as_posix()) + with zipfile.ZipFile(archive) as zipped: + assert zipped.testzip() is None + assert len(zipped.namelist())==len(set(zipped.namelist())) + for item in manifest['files']: + content=zipped.read('DefectRAG-v2/'+item['path']) + assert hashlib.sha256(content).hexdigest()==item['sha256'] + extraction=None + if args.extract: + extraction=ROOT.parent/('release-verification-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')) + extraction.mkdir(exist_ok=False) + for name in zipped.namelist(): + if not (extraction/name).resolve().is_relative_to(extraction.resolve()):raise ValueError('Unsafe archive entry') + zipped.extractall(extraction) + receipt={'archive':str(archive),'bytes':archive.stat().st_size,'sha256':digest(archive), + 'file_count':len(paths)+1,'crc_and_file_hashes':'passed','duplicate_entries':False, + 'git_commit':manifest['git_commit'],'extracted_project':str(extraction/'DefectRAG-v2') if extraction else None} + archive.with_suffix('.receipt.json').write_text(json.dumps(receipt,indent=2)) + print(json.dumps(receipt,indent=2),flush=True) +if __name__=='__main__':main() diff --git a/scripts/package_showcase.py b/scripts/package_showcase.py new file mode 100644 index 0000000000000000000000000000000000000000..ca985704c6b1ceec5e0c0c158e15822466c20c80 --- /dev/null +++ b/scripts/package_showcase.py @@ -0,0 +1,45 @@ +"""Package the already built static showcase; preserve every earlier archive.""" +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import zipfile + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--name', default='DefectRAG-v2-static.zip') + args = parser.parse_args() + if Path(args.name).name != args.name or not args.name.endswith('.zip'): + raise ValueError('Use a ZIP basename') + output = ROOT / 'frontend/dist-static' + if not (output / 'index.html').exists(): + raise RuntimeError('Run npm run build:showcase inside frontend first') + archive = ROOT.parent / args.name + if archive.exists(): + raise FileExistsError('Earlier archive preserved: ' + str(archive)) + shutil.copyfile(ROOT / 'deployment/STATIC_SPACE.md', output / 'README.md') + shutil.copyfile(ROOT / 'LICENSE', output / 'LICENSE') + shutil.copyfile(ROOT / 'docs/THIRD_PARTY_NOTICES.md', output / 'THIRD_PARTY_NOTICES.md') + paths = sorted(p for p in output.rglob('*') if p.is_file()) + with zipfile.ZipFile(archive, 'x', zipfile.ZIP_DEFLATED) as zipped: + for path in paths: + zipped.write(path, path.relative_to(output).as_posix()) + with zipfile.ZipFile(archive) as zipped: + if zipped.testzip() is not None: + raise RuntimeError('Archive CRC failure') + for path in paths: + if zipped.read(path.relative_to(output).as_posix()) != path.read_bytes(): + raise RuntimeError('Archived file mismatch') + receipt = {'status': 'passed', 'archive': str(archive), 'bytes': archive.stat().st_size, + 'sha256': hashlib.sha256(archive.read_bytes()).hexdigest(), 'files': len(paths), + 'mode': 'read-only saved real examples; no server, model download or secret required'} + archive.with_suffix('.receipt.json').write_text(json.dumps(receipt, indent=2)) + print(json.dumps(receipt, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/scripts/prepare_assets.py b/scripts/prepare_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e08bbd191f908ee646764d0d59dd5d434a7457 --- /dev/null +++ b/scripts/prepare_assets.py @@ -0,0 +1,28 @@ +"""Copy only existing, selected public model files; never copy credentials or history.""" +import argparse +import shutil +import json +from pathlib import Path +from backend.config import ROOT +from backend.vision import sha256 + +def copy_tree(source,destination,names): + destination.mkdir(parents=True,exist_ok=True) + for name in names: + path=source/name + if path.is_file(): shutil.copyfile(path,destination/name) + if (source/'1_Pooling'/'config.json').exists(): + (destination/'1_Pooling').mkdir(exist_ok=True) + shutil.copyfile(source/'1_Pooling'/'config.json',destination/'1_Pooling'/'config.json') + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument('--encoder',type=Path,required=True) + parser.add_argument('--embedding',type=Path,required=True) + args=parser.parse_args() + copy_tree(args.encoder,ROOT/'models'/'encoder',['config.json','preprocessor_config.json','model.safetensors']) + 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']) + checksums={str(p.relative_to(ROOT)).replace('\\','/'):sha256(p) for p in (ROOT/'models').rglob('*') if p.is_file()} + (ROOT/'models'/'checksums.json').write_text(json.dumps(checksums,indent=2)) + print('Copied cached public model assets, without modifying source files.') +if __name__=='__main__':main() diff --git a/scripts/prepare_dinov2.py b/scripts/prepare_dinov2.py new file mode 100644 index 0000000000000000000000000000000000000000..249af38d5202c921053e10168cfc69de29d3739b --- /dev/null +++ b/scripts/prepare_dinov2.py @@ -0,0 +1,27 @@ +"""Fetch only public DINOv2 tensor/config assets into a separate local directory.""" +import json +from urllib.request import urlopen +from huggingface_hub import HfApi,snapshot_download +from backend.config import ROOT +from backend.vision import sha256 + +if __name__=='__main__': + destination=ROOT/'models/encoder_dinov2' + destination.mkdir(parents=True,exist_ok=True) + license_path=destination/'LICENSE' + if not license_path.exists(): + with urlopen('https://raw.githubusercontent.com/facebookresearch/dinov2/main/LICENSE',timeout=30) as response: + license_path.write_bytes(response.read()) + receipt=destination/'ASSET_RECEIPT.json' + if receipt.exists(): + saved=json.loads(receipt.read_text()) + assert sha256(destination/'model.safetensors')==saved['model_sha256'] + print('Preserved existing verified DINOv2 asset.');raise SystemExit(0) + info=HfApi().model_info('facebook/dinov2-small') + snapshot_download('facebook/dinov2-small',revision=info.sha,local_dir=destination, + cache_dir=ROOT/'runtime/model-download-cache', + allow_patterns=['config.json','model.safetensors','preprocessor_config.json','README.md','LICENSE']) + receipt.write_text(json.dumps({'repo':'facebook/dinov2-small','revision':info.sha, + 'model_sha256':sha256(destination/'model.safetensors'),'license':'Apache-2.0', + 'source':'https://huggingface.co/facebook/dinov2-small','remote_code':False},indent=2)) + print(receipt.read_text(),flush=True) diff --git a/scripts/prepare_github_export.py b/scripts/prepare_github_export.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff280e0f9c83798f605db741e5068378952d0ad --- /dev/null +++ b/scripts/prepare_github_export.py @@ -0,0 +1,85 @@ +"""Build a small source-only GitHub upload folder; never copy private state/history.""" +import argparse +import json +import re +from pathlib import Path +import shutil +import subprocess + +ROOT=Path(__file__).resolve().parents[1] +DIRECTORIES=('backend/','scripts/','tests/','deployment/','knowledge/','frontend/src/', + 'frontend/tests/','frontend/public/') +PUBLIC_DOCS={ + 'docs/SETUP.md','docs/SECURITY.md','docs/ARCHITECTURE.md','docs/STAFF_QUICK_GUIDE.md', + 'docs/GUIDED_PRACTICE.md','docs/ACCURACY_AND_METRICS.md','docs/ACCURACY_RESULTS.md', + 'docs/TRAINING_AND_EVALUATION.md','docs/MACARONI_RECALL_UPDATE.md', + 'docs/SENSITIVITY_CALIBRATION.md','docs/THIRD_PARTY_NOTICES.md', + 'docs/FRONTEND_LICENSES.txt','docs/GITHUB_PUBLISHING.md', + 'docs/assets/hero.svg','docs/assets/dashboard.png','docs/assets/guided-practice.png', + 'docs/assets/macaroni-recall.png','docs/assets/recall-policy.png', +} +FILES={'README.md','LICENSE','.gitignore','.dockerignore','.env.example','requirements.txt', + 'requirements-anomalib.txt','Dockerfile','compose.yaml','render.yaml', + 'Start-DefectRAG.cmd','Start-DefectRAG.ps1','frontend/package.json', + 'frontend/package-lock.json','frontend/index.html','frontend/vite.config.js','frontend/localBuild.mjs', + 'results/evaluation.json','results/official_evaluation.json','results/highres_evaluation.json', + 'results/highres_deployment_evaluation.json','results/highres_comparison.json','results/highres_comparison.csv'} +FILES.update({'results/sensitive_deployment_evaluation.json','results/recall_threshold_audit.json', + 'results/macaroni_recall_deployment_evaluation.json'}) +FILES.update(PUBLIC_DOCS) +EXCLUDED=('knowledge/index/','frontend/public/config.js','docs/README_LEGACY.md', + 'docs/SUPABASE_QUERY_CATALOG.md','docs/QA_ACCOUNT_REMOVAL.md', + 'deployment/qa_account_backup_PRIVATE.sql','deployment/qa_account_cleanup_REVIEW_ONLY.sql', + 'deployment/qa_account_deletion_preflight.sql','deployment/email_pending_qa_verification.sql', + 'deployment/email_single_qa_verification.sql', + 'deployment/Update-GitHub.ps1', + 'deployment/corrective_actions_fresh_sink_result.sql', + 'deployment/corrective_actions_replacement_sink_result.sql', + 'deployment/corrective_actions_single_sink_metadata.sql', + 'deployment/corrective_actions_single_sink_result.sql', + 'deployment/email_qa_selection.sql','deployment/email_clock_where_fix_verification.sql', + 'deployment/email_no_send_live_preflight.sql', + 'scripts/checkpoint.py','scripts/package_release.py','scripts/sync_release.py', + 'scripts/verify_packaged.py','scripts/verify_highres_preservation.py', + 'scripts/verify_upgrade_preservation.py') + +def selected(name): + 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') + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output',type=Path,default=ROOT/'development-support/github-ready/DefectRAG') + args=parser.parse_args() + output=args.output.resolve() + assert output.is_relative_to(ROOT/'development-support'),'Keep exports under development-support.' + assert not output.exists(),'Choose a new empty export destination; existing exports are preserved.' + paths=subprocess.check_output(['git','ls-files','-z'],cwd=ROOT).decode().split('\0') + copied=[] + for name in filter(None,paths): + if not selected(name):continue + path=ROOT/name + if not path.is_file() or path.is_symlink():continue + if path.stat().st_size>15*1024*1024:raise ValueError('Unexpected large tracked file: '+name) + target=output/name + target.parent.mkdir(parents=True,exist_ok=True) + shutil.copy2(path,target) + copied.append(name) + config=output/'frontend/public/config.js' + config.parent.mkdir(parents=True,exist_ok=True) + config.write_text('window.DEFECTRAG_PUBLIC_CONFIG = {supabaseUrl:"",supabasePublishableKey:""};\n') + 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,}') + for path in output.rglob('*'): + 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'): + assert not credential.search(path.read_text(encoding='utf8',errors='replace')),'Credential-like value requires review: '+str(path.relative_to(output)) + assert not any((output/name).exists() for name in ('models','runtime','experiments','.venv','.git','.env','DEVELOPMENT_PROGRESS.md')) + manifest={'source_commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT).decode().strip(), + 'files':len(copied)+1,'public_config_blank':True, + 'excluded':'Git history, models, datasets, private runtime, environments, local evidence, secrets, build outputs'} + # Export receipts belong to the private preparation folder, not the public tree. + receipt=output.parent/(output.name+'.export.json') + assert not receipt.exists(),'Earlier export receipt preserved.' + receipt.write_text(json.dumps(manifest,indent=2)) + print(json.dumps({'folder':str(output),**manifest})) + +if __name__=='__main__': + main() diff --git a/scripts/prepare_knowledge.py b/scripts/prepare_knowledge.py new file mode 100644 index 0000000000000000000000000000000000000000..f9539ad02a3a8aac08dcee5b92818d12a199de56 --- /dev/null +++ b/scripts/prepare_knowledge.py @@ -0,0 +1,8 @@ +from backend.config import Settings +from backend.rag import KnowledgeIndex + +if __name__=='__main__': + settings=Settings() + index=KnowledgeIndex(settings.root,settings.root/'knowledge'/'index') + index.ensure() + print('Indexed',len(index.documents),'source-attributed passages') diff --git a/scripts/prepare_macaroni_recall.py b/scripts/prepare_macaroni_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..ca411bd77342e710f8d9618419527b1e5249b566 --- /dev/null +++ b/scripts/prepare_macaroni_recall.py @@ -0,0 +1,43 @@ +"""Macaroni-only q80 calibration from cached normal scores; no GPU or refitting.""" +from copy import deepcopy +import json +from scripts.audit_recall import ROOT, digest, metrics, quantile + + +def main(): + source=ROOT/'results/sensitive_deployment_evaluation.json' + baseline=json.loads(source.read_text()) + candidate=deepcopy(baseline) + candidate.update(decision_policy='macaroni-recall-v1', + 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.', + decision_policy_reason='User authorized focusing only on Macaroni1/2 recall, prioritizing anomaly detection with more false alarms and minimal compute.', + 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.', + previous_evaluation_sha256=digest(source)) + for category in ('macaroni1','macaroni2'): + directory=ROOT/'experiments/dinov2_highres_v1'/category + calibration=json.loads((directory/'normal_calibration.json').read_text()) + rows=json.loads((directory/'test_progress.json').read_text()) + scores=[p['score'] for p in calibration['predictions']] + card=candidate['categories'][category] + card.update(previous_threshold=card['threshold'], previous_model_id=card['model_id'], + threshold=quantile(scores,.8), model_id=card['model_id'].removesuffix('-q95-v1')+'-q80-v1', + decision_policy='normal-q80-v1') + threshold=card['threshold'];card['uncertainty_margin']=threshold*.05 + card['calibration'].update(method='Fixed linear 80th percentile of heldout normal scores; no anomalous calibration', + policy='normal-q80-v1',quantile=.8,calibration_above_threshold=sum(s>=threshold for s in scores)) + card['metrics'].update(metrics(rows,threshold), + uncertain_fraction=sum(abs(r['scores'][3]-threshold)<=threshold*.05 for r in rows)/len(rows)) + for category in set(baseline['categories'])-{'macaroni1','macaroni2'}: + assert candidate['categories'][category]==baseline['categories'][category] + candidate['macro_mean']={key:sum(c['metrics'][key] for c in candidate['categories'].values())/len(candidate['categories']) + for key in baseline['macro_mean']} + assert digest(source)==candidate['previous_evaluation_sha256'] + output=ROOT/'results/macaroni_recall_deployment_evaluation.json' + text=json.dumps(candidate,indent=2)+'\n' + if output.exists() and output.read_text()!=text:raise ValueError('Preserve differing existing version') + output.write_text(text,encoding='utf8') + print(json.dumps({'policy':candidate['decision_policy'],'macro_mean':candidate['macro_mean'], + 'categories':{c:candidate['categories'][c]['metrics'] for c in ('macaroni1','macaroni2')},'other_ten_unchanged':True},indent=2)) + + +if __name__=='__main__':main() diff --git a/scripts/prepare_sensitive_calibration.py b/scripts/prepare_sensitive_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..dccd15b9e82ab06b467e52e35f30fd183fce8b70 --- /dev/null +++ b/scripts/prepare_sensitive_calibration.py @@ -0,0 +1,58 @@ +"""Create a separate normal-only q95 policy, preserving every baseline artifact. + +This is a recall-oriented development policy, not new independent validation. +Test labels are used only to report its retrospective operating metrics. +""" +from copy import deepcopy +import json + +from scripts.audit_recall import ROOT, digest, metrics, quantile + + +def main(): + source = ROOT / 'results/highres_deployment_evaluation.json' + baseline_hash = digest(source) + baseline = json.loads(source.read_text()) + candidate = deepcopy(baseline) + candidate.update(decision_policy='normal-q95-v1', + 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.', + baseline_evaluation_sha256=baseline_hash, + validation_scope='Normal-only calibration and cached-score/software consistency checks; future recall and false-alarm rates are not guaranteed.', + decision_policy_reason='User requested prioritizing anomaly recall and accepts more false alarms.', + policy_selection_context='Policy adopted after viewing retrospective threshold-sensitivity results; not an independent or test-blind validation.', + source_sha256={}) + for category, card in candidate['categories'].items(): + directory = ROOT / 'experiments/dinov2_highres_v1' / category + calibration_path = directory / 'normal_calibration.json' + predictions_path = directory / 'test_progress.json' + calibration = json.loads(calibration_path.read_text()) + rows = json.loads(predictions_path.read_text()) + normal_scores = [row['score'] for row in calibration['predictions']] + assert max(normal_scores) == card['threshold'] + assert len(normal_scores) == card['calibration']['normal'] + # Threshold uses only normal calibration scores. Never optimize on test labels. + threshold = quantile(normal_scores, .95) + card.update(baseline_threshold=card['threshold'], threshold=threshold, + uncertainty_margin=threshold*.05, decision_policy='normal-q95-v1', + model_id=card['model_id']+'-q95-v1') + card['calibration'].update(method='Fixed linear 95th percentile of heldout normal scores; no anomalous calibration', + policy='normal-q95-v1', quantile=.95, + calibration_above_threshold=sum(s >= threshold for s in normal_scores), + future_false_positive_rate_guaranteed=False) + card['metrics'].update(metrics(rows, threshold), + uncertain_fraction=sum(abs(row['scores'][3]-threshold) <= threshold*.05 for row in rows)/len(rows)) + for path in (calibration_path, predictions_path): + candidate['source_sha256'][str(path.relative_to(ROOT))] = digest(path) + candidate['macro_mean'] = {key: sum(c['metrics'][key] for c in candidate['categories'].values()) / len(candidate['categories']) + for key in (*baseline['macro_mean'], 'false_positive_rate')} + assert digest(source) == baseline_hash + output = ROOT / 'results/sensitive_deployment_evaluation.json' + text = json.dumps(candidate, indent=2) + '\n' + if output.exists() and output.read_text() != text: + raise ValueError('Preserve differing existing calibration; use a new policy version') + output.write_text(text, encoding='utf-8') + print(json.dumps({'output':str(output),'baseline_preserved_sha256':baseline_hash,'macro_mean':candidate['macro_mean']}, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/scripts/profile_inference.py b/scripts/profile_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..bd4738de37dc74f8017b38f91f27b381b5c7897a --- /dev/null +++ b/scripts/profile_inference.py @@ -0,0 +1,49 @@ +"""One bounded serving profile of the existing models; no fitting or threshold changes.""" +import argparse +import json +import time +from pathlib import Path +import numpy as np +import torch +from PIL import Image +from backend.config import ROOT,Settings +from backend.vision import Detector + +def main(): + parser=argparse.ArgumentParser();parser.add_argument('--dataset',type=Path,required=True) + args=parser.parse_args() + detector=Detector(Settings()) + report={'method':'Existing calibrated models; 6 original held-out images, 5 warm repetitions each; no training', + 'categories':{},'python':__import__('platform').python_version(),'torch':torch.__version__} + if torch.cuda.is_available(): + free,total=torch.cuda.mem_get_info() + report['gpu']={'name':torch.cuda.get_device_name(),'free_mb_before':free/1024**2,'total_mb':total/1024**2} + for category in ('pcb1','capsules','cashew'): + rows=json.loads((ROOT/'results'/f'{category}_predictions.json').read_text())['test'] + chosen=[next(r for r in rows if r['label']==label) for label in (0,1)] + load=time.perf_counter();detector.load(category) + cold_load=(time.perf_counter()-load)*1000 + elapsed,core=[],[] + for iteration in range(6): + for row in chosen: + started=time.perf_counter() + with Image.open(args.dataset/row['image']) as im: + im.load();result,_=detector.predict(im,category) + assert abs(result['score']-row['score'])<1e-5 + if iteration: + elapsed.append((time.perf_counter()-started)*1000) + core.append(result['inference_ms']) + report['categories'][category]={'samples':len(elapsed),'core_median_ms':float(np.median(core)), + 'core_p95_ms':float(np.percentile(core,95)),'decoded_image_to_result_median_ms':float(np.median(elapsed)), + 'decoded_image_to_result_p95_ms':float(np.percentile(elapsed,95)),'category_load_ms':cold_load, + 'peak_torch_allocated_gpu_mb':result['peak_gpu_mb'],'device':result['device']} + # Verify the Docker default CPU path also executes actual weights. Small + # floating-point differences from calibrated CUDA/FP16 scores are expected. + cpu=Detector(Settings(device='cpu')) + with Image.open(args.dataset/chosen[0]['image']) as im: + started=time.perf_counter();result,_=cpu.predict(im,'cashew') + report['cpu_smoke']={'verdict':result['verdict'],'score':result['score'],'reference_cuda_score':chosen[0]['score'], + 'absolute_difference':abs(result['score']-chosen[0]['score']),'total_ms':(time.perf_counter()-started)*1000} + (ROOT/'results'/'serving_profile.json').write_text(json.dumps(report,indent=2)) + print(json.dumps(report,indent=2),flush=True) +if __name__=='__main__':main() diff --git a/scripts/qwen_after_training.py b/scripts/qwen_after_training.py new file mode 100644 index 0000000000000000000000000000000000000000..653b8f00030dd699d1f0d9815b2fe41c10877679 --- /dev/null +++ b/scripts/qwen_after_training.py @@ -0,0 +1,129 @@ +"""Run every measurement after training, one step at a time, and save a report. + + python -m scripts.qwen_after_training --wait-pid 12345 + +It waits for the training process to exit, checks that an adapter was saved, then runs: + 1. a check of my_questions.csv + 2. the short-question test (CPU only) + 3. the fine-tuned model on the 100 test questions and on my_questions.csv + 4. the same untouched base model through the same server, for a fair comparison + 5. the original Ollama model on my_questions.csv + 6. comparison tables +Only one heavy process runs at a time. Progress goes to experiments/qwen_lora_v1/pipeline.log. +""" + +import argparse +import os +import subprocess +import sys +import time +import urllib.request +from datetime import datetime + +from backend.config import ROOT + +OUT = ROOT / "experiments" / "qwen_lora_v1" +LOG = OUT / "pipeline.log" +BASE = OUT / "base_model" +ADAPTER = OUT / "adapter" +ENV = {**os.environ, "PYTHONUTF8": "1", "USE_TF": "0"} + + +def log(message): + line = f"{datetime.now():%H:%M:%S} {message}" + print(line, flush=True) + with LOG.open("a", encoding="utf-8") as stream: + stream.write(line + "\n") + + +def run(name, *args): + """Run one python module as a step. Returns True on success; never raises.""" + log(f"START {name}") + started = time.time() + with (OUT / f"step_{name}.log").open("w", encoding="utf-8") as stream: + code = subprocess.run( + [sys.executable, "-m", *args], cwd=ROOT, env=ENV, stdout=stream, stderr=subprocess.STDOUT + ).returncode + log(f"{'DONE ' if code == 0 else 'FAILED'} {name} (exit {code}, {(time.time() - started) / 60:.1f} min)") + return code == 0 + + +def serve(adapter, port=11500): + """Start the model server and wait until it answers. Returns the process or None.""" + stream = (OUT / f"server_{port}.log").open("w", encoding="utf-8") + proc = subprocess.Popen( + [sys.executable, "-m", "scripts.qwen_serve", "--adapter", adapter, "--base", str(BASE), "--port", str(port)], + cwd=ROOT, + env=ENV, + stdout=stream, + stderr=subprocess.STDOUT, + ) + for _ in range(120): + if proc.poll() is not None: + log(f"FAILED server exited early (exit {proc.returncode})") + return None + try: + urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=3).read() + log(f"server ready ({adapter})") + return proc + except OSError: + time.sleep(5) + proc.terminate() + log("FAILED server did not become ready in 10 minutes") + return None + + +def stop(proc): + proc.terminate() + try: + proc.wait(timeout=30) + except subprocess.TimeoutExpired: + proc.kill() + time.sleep(8) # let the GPU memory be released + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--wait-pid", type=int, default=0, help="process id of the training run to wait for") + args = parser.parse_args() + log("pipeline started") + if args.wait_pid: + import psutil + + while psutil.pid_exists(args.wait_pid): + time.sleep(15) + log("training process has ended") + if not (ADAPTER / "adapter_model.safetensors").exists(): + log("STOP: no adapter was saved, so training did not finish. See the training window.") + return + mine_ok = run("check_mine", "scripts.qwen_eval", "--split", "mine", "--check") + run("short_questions", "scripts.qwen_short_questions") + url = "http://127.0.0.1:11500" + for tag, adapter in (("lora", str(ADAPTER)), ("basehf", "none")): + proc = serve(adapter) + if proc is None: + continue + try: + run(f"eval_{tag}_test", "scripts.qwen_eval", "--split", "test", "--tag", tag, "--url", url) + if mine_ok: + run(f"eval_{tag}_mine", "scripts.qwen_eval", "--split", "mine", "--tag", tag, "--url", url) + finally: + stop(proc) + if mine_ok: + run("eval_ollama_mine", "scripts.qwen_eval", "--split", "mine", "--tag", "ollama") + with (OUT / "pipeline_report.txt").open("w", encoding="utf-8") as report: + for split, tags in (("test", ["gate50", "basehf", "lora"]), ("mine", ["ollama", "basehf", "lora"])): + report.write(f"\n===== {split} questions =====\n") + report.flush() + subprocess.run( + [sys.executable, "-m", "scripts.qwen_compare", "--split", split, *tags], + cwd=ROOT, + env=ENV, + stdout=report, + stderr=subprocess.STDOUT, + ) + log("ALL DONE: see pipeline_report.txt") + + +if __name__ == "__main__": + main() diff --git a/scripts/qwen_build_training_data.py b/scripts/qwen_build_training_data.py new file mode 100644 index 0000000000000000000000000000000000000000..26e3d462c52c950272368ef6f8a1c85342997891 --- /dev/null +++ b/scripts/qwen_build_training_data.py @@ -0,0 +1,191 @@ +"""Build the fine-tuning examples for the assistant's language model. + + python -m scripts.qwen_build_training_data # version 1 -> data/train.jsonl + python -m scripts.qwen_build_training_data --v2 # version 2 -> data/train_v2.jsonl + +Each example is the exact prompt the model sees in production (retrieved, numbered sentences) +and the answer we want back: + +* answerable question -> the sentence that really answers it and a short restatement. The restatement + is the base model's own answer when it passed the project's validator, otherwise the sentence itself. +* question the documents cannot answer -> {"claims": []} (the model must learn to say "nothing fits"). + +Version 1 uses the TRAIN wordings in scripts/qwen_eval.py. Version 2 keeps every version 1 example and adds +the questions in experiments/qwen_lora_v1/v2_questions.csv (every knowledge sentence, conversational wording). +Test questions are never used: version 2 refuses any new question that is (nearly) identical to one in the +test wordings, in my_questions.csv, or in the short-question test. +""" + +import argparse +import csv +import json +import random +import re +from collections import Counter + +from backend.config import ROOT, Settings +from backend.rag import EvidenceWorkflow, KnowledgeIndex +from scripts.qwen_eval import ( + MY_QUESTIONS, + OUT, + TOPICS, + UNANSWERABLE, + build_items, + knowledge_sentences, + load_cards, + make_inspection, +) + +NUMBER = r"\d+(?:\.\d+)?" +V2_QUESTIONS = OUT / "v2_questions.csv" + + +def prepare_state(workflow, item): + """Run the workflow up to the generation step. Returns None if the model would never be asked.""" + state = {"question": item["question"], "inspection": item["inspection"], "history": []} + state.update(workflow.route(state)) + if state["mode"] == "abstained": + return None + state.update(workflow.retrieve(state)) + state.update(workflow.validate_evidence(state)) + return state if state.get("evidence") else None + + +def base_restatements(workflow, state, quotes): + """Ask the base model once; keep restatements that pass the number check, keyed by quote_id.""" + produced = workflow.generate(dict(state)) + by_quote = {q["quote"]: qid for qid, q in quotes.items()} + good = {} + for claim in produced.get("raw_claims", []): + qid = by_quote.get(claim.get("quote")) + text = claim.get("text", "").strip() + if qid and text and set(re.findall(NUMBER, text)) <= set(re.findall(NUMBER, claim["quote"])): + good[qid] = text + return good + + +def words(text): + return set(re.findall(r"[a-z0-9]+", text.lower())) + + +def protected_questions(): + """Every question that belongs to a test set, so version 2 can be checked against them.""" + from scripts.qwen_short_questions import ONE_WORD, SHORT + + protected = [q for _, (_, _, _, test) in TOPICS.items() for q in test] + UNANSWERABLE["test"] + protected += [text for text, _ in SHORT + ONE_WORD] + lines = [line for line in MY_QUESTIONS.read_text(encoding="utf-8-sig").splitlines() if not line.startswith("#")] + protected += [row["question"].strip() for row in csv.DictReader(lines) if row["question"].strip()] + return protected + + +def too_similar(question, protected, threshold=0.7): + """True if the question is the same as, or a close rewording of, a protected test question.""" + a = words(question) + return any(a == words(p) or len(a & words(p)) / len(a | words(p)) >= threshold for p in protected) + + +def v2_items(rng): + """Items from v2_questions.csv: 1 inspection per answerable question, 2 per unanswerable one.""" + cards = load_cards() + sentences = knowledge_sentences() + protected = protected_questions() + lines = [line for line in V2_QUESTIONS.read_text(encoding="utf-8-sig").splitlines() if not line.startswith("#")] + items, dropped = [], [] + for number, row in enumerate(csv.DictReader(lines), start=1): + question, phrase = row["question"].strip(), row["answer_phrase"].strip() + if not question: + continue + if too_similar(question, protected): + dropped.append(f"too similar to a test question: {question}") + continue + hits = [s for s in sentences if phrase and phrase.lower() in s[2].lower()] + if phrase and not hits: + raise SystemExit(f"v2_questions.csv row {number}: phrase not found in any sentence: {phrase!r}") + sources = {h[0] for h in hits} + if sources == {"legacy-profile"}: + families = ["dinov3"] + elif sources == {"highres-profile"}: + families = ["dinov2"] + else: + families = ["dinov2", "dinov3"] + for _ in range(1 if phrase else 2): + items.append( + { + "id": f"v2-{len(items)}", + "kind": "answerable" if phrase else "unanswerable", + "topic": "v2" if phrase else "none", + "question": question, + "pattern": re.escape(phrase) if phrase else "", + "inspection": make_inspection(cards, rng.choice(families), rng), + } + ) + return items, dropped + + +def make_example(workflow, item, stats): + """One training example for an item, or None when the model would not be asked or the answer is missing.""" + state = prepare_state(workflow, item) + if state is None: + stats["skipped: model would not be asked (no evidence or prohibited topic)"] += 1 + return None + prompt, quotes = workflow.build_prompt(state) + if item["kind"] == "unanswerable": + claims = [] + else: + pattern = re.compile(item["pattern"], re.I) + wanted = [qid for qid, q in quotes.items() if pattern.search(q["quote"])][:2] + if not wanted: + stats["skipped: answer sentence not in retrieved evidence"] += 1 + return None + restated = base_restatements(workflow, state, quotes) + claims = [{"quote_id": qid, "text": restated.get(qid, quotes[qid]["quote"])} for qid in wanted] + stats["restatement from base model"] += sum(qid in restated for qid in wanted) + stats["restatement = the sentence itself"] += sum(qid not in restated for qid in wanted) + stats[f"example: {item['kind']}"] += 1 + return { + "id": item["id"], + "kind": item["kind"], + "topic": item["topic"], + "pattern": item["pattern"], + "prompt": prompt, + "completion": json.dumps({"claims": claims}), + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", default="qwen2.5:3b", help="Ollama model used for restatements") + parser.add_argument("--contexts", type=int, default=2, help="version 1: inspections per question") + parser.add_argument("--v2", action="store_true", help="add the version 2 questions to the version 1 examples") + args = parser.parse_args() + out_dir = OUT / "data" + out_dir.mkdir(parents=True, exist_ok=True) + stats = Counter() + if args.v2: + examples = [json.loads(line) for line in (out_dir / "train.jsonl").read_text(encoding="utf-8").splitlines()] + stats["example: version 1 kept as they are"] = len(examples) + workflow = EvidenceWorkflow(Settings(ollama_model=args.model), KnowledgeIndex(ROOT, OUT / "index")) + items, dropped = v2_items(random.Random("v2-7")) + for message in dropped: + print("dropped:", message) + examples += [e for e in (make_example(workflow, item, stats) for item in items) if e] + path = out_dir / "train_v2.jsonl" + else: + workflow = EvidenceWorkflow(Settings(ollama_model=args.model), KnowledgeIndex(ROOT, OUT / "index")) + examples = [ + e + for e in (make_example(workflow, item, stats) for item in build_items("train", contexts=args.contexts)) + if e + ] + path = out_dir / "train.jsonl" + path.write_text("\n".join(json.dumps(e) for e in examples) + "\n", encoding="utf-8") + print(f"wrote {len(examples)} examples to {path}") + for key, value in sorted(stats.items()): + print(f" {value:4d} {key}") + lengths = sorted(len(e["prompt"]) + len(e["completion"]) for e in examples) + print(f"characters per example: min {lengths[0]}, median {lengths[len(lengths) // 2]}, max {lengths[-1]}") + + +if __name__ == "__main__": + main() diff --git a/scripts/qwen_compare.py b/scripts/qwen_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..66dcdae90d8778dc9fdb836a87e1e7178f789b3c --- /dev/null +++ b/scripts/qwen_compare.py @@ -0,0 +1,46 @@ +"""Print saved evaluation runs side by side. + + python -m scripts.qwen_compare gate50 lora + +Each name is the --tag of a run made with scripts.qwen_eval on the test split. +""" + +import json +import sys + +from scripts.qwen_eval import OUT + +ROWS = [ + ("retrieval_hit", "right chunk retrieved", "higher"), + ("correct_all", "fully correct answers", "higher"), + ("wrong_source", "answered with a wrong sentence", "lower"), + ("no_answer_on_answerable", "no answer although one exists", "lower"), + ("false_answer_on_unanswerable", "answered an unanswerable question", "lower"), + ("generation_failed", "model output unusable (JSON/timeout)", "lower"), +] + + +def cell(v): + lo, hi = v["ci95"] + return f"{v['k']}/{v['n']} = {v['rate']:.0%} [{lo:.0%}-{hi:.0%}]" + + +def main(): + args = sys.argv[1:] + split = "test" + if "--split" in args: + split = args[args.index("--split") + 1] + del args[args.index("--split") : args.index("--split") + 2] + tags = args + if not tags: + sys.exit("usage: python -m scripts.qwen_compare [--split test|mine] TAG [TAG ...]") + data = {t: json.loads((OUT / f"summary_{t}_{split}.json").read_text()) for t in tags} + print(f"{'measure':38s}" + "".join(f"{t:30s}" for t in tags) + "better is") + for key, label, better in ROWS: + print(f"{label:38s}" + "".join(f"{cell(data[t][key]):30s}" for t in tags) + better) + print(f"{'seconds per generated answer':38s}" + "".join(f"{data[t]['mean_seconds_generated']!s:30s}" for t in tags)) + print("\n[...] is a 95% confidence interval. If two intervals overlap a lot, the difference may be noise.") + + +if __name__ == "__main__": + main() diff --git a/scripts/qwen_eval.py b/scripts/qwen_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..9d684c3b82d0182431f7d66f27c976f0ac7f5fe2 --- /dev/null +++ b/scripts/qwen_eval.py @@ -0,0 +1,614 @@ +"""Measure how well the assistant's language model picks and paraphrases evidence. + +Builds a labelled question set from the knowledge documents, runs the real answer workflow +(retrieve, validate, generate, validate) and scores it with the project's own validator. + + python -m scripts.qwen_eval --split test --model qwen2.5:3b --tag base + +Results are appended to experiments/qwen_lora_v1/runs/_.jsonl and can be resumed. +Only the language-model step changes between runs; retrieval and checks are identical. +""" + +import argparse +import json +import math +import random +import re +import time +import uuid + +from backend.config import CATEGORIES, ROOT, Settings +from backend.rag import EvidenceWorkflow, KnowledgeIndex + +OUT = ROOT / "experiments" / "qwen_lora_v1" + +# Each topic: which model family the inspection must have (evidence is filtered by family), +# regex patterns that identify a correct supporting sentence, and question wordings. +# Wordings in "test" are never used for training. +TOPICS = { + "score_meaning": ( + "any", + r"score is not a defect probability|larger anomaly score", + [ + "What does the anomaly score mean?", + "Is the score a probability that this part is defective?", + "How should I read the score number?", + "Does a higher score mean more defects?", + ], + ["Explain what this score tells me.", "Can I treat the score as the chance of a defect?"], + ), + "verdict_good": ( + "any", + r"Good means", + [ + "What does a Good verdict mean?", + "When is a result labelled Good?", + "How does the system decide something is Good?", + "What makes an inspection Good?", + ], + ["Explain the Good label.", "Under what condition do I get Good?"], + ), + "verdict_anomalous": ( + "any", + r"Anomalous means", + [ + "What does Anomalous mean?", + "When is an inspection flagged as Anomalous?", + "How does a result become Anomalous?", + "What is needed for an Anomalous verdict?", + ], + ["Explain the Anomalous label.", "Why would a result be called Anomalous?"], + ), + "verdict_uncertain": ( + "any", + r"Uncertain means|five-percent band", + [ + "What does Uncertain mean?", + "What is the Uncertain verdict?", + "How wide is the Uncertain zone?", + "When is a result Uncertain?", + ], + ["Explain the Uncertain label.", "How is the uncertain range defined?"], + ), + "review_band": ( + "any", + r"review band is an operational heuristic|five-percent band", + [ + "What is the review band?", + "Is the review band a statistical confidence interval?", + "How reliable is the review band?", + "What kind of measure is the five percent band?", + ], + ["Tell me about the review band.", "Is the review band calibrated?"], + ), + "good_not_proof": ( + "any", + r"not proof of factory acceptance", + [ + "Does Good mean the product is safe?", + "Can I ship a part just because it is Good?", + "Is a Good result proof of acceptance?", + "Does Good guarantee the part has no defects?", + ], + ["Is Good a guarantee of quality?", "Can I rely on Good as factory acceptance?"], + ), + "historical": ( + "any", + r"Historical inspections retain|newer active model does not change", + [ + "Will an old inspection change when a new model is installed?", + "Do past results keep their original model?", + "Does updating the model rewrite earlier verdicts?", + "What happens to historical inspections after a model update?", + ], + ["Are earlier verdicts recalculated with the newer model?", "Do old heatmaps change after an upgrade?"], + ), + "saved_fields": ( + "any", + r"saves its model ID", + [ + "What information is saved with each inspection?", + "Which details does an inspection record store?", + "What gets saved for every inspection?", + "Which fields are kept in a saved inspection?", + ], + ["What does the saved record contain?", "List what is stored for an inspection."], + ), + "heatmap": ( + "any", + r"heatmap shows cosine distance|Larger distances indicate", + [ + "What does the heatmap show?", + "How is the heatmap computed?", + "What do the brighter areas on the heatmap mean?", + "What is measured by the heatmap?", + ], + ["Explain this heatmap.", "How do I read the heatmap?"], + ), + "coarse_localization": ( + "any", + r"coarse localization|interpolation does not add", + [ + "Is the heatmap a precise defect outline?", + "Can the heatmap segment the exact defect?", + "How precise is the localization?", + "Does the heatmap name the defect?", + ], + ["Is localization exact?", "Does interpolation add detail to the heatmap?"], + ), + "product_scope": ( + "any", + r"wrong-product uploads|operator selects the product category", + [ + "What if I choose the wrong product category?", + "Can I upload any kind of photo?", + "Who selects the product category?", + "Are wrong-product uploads supported?", + ], + ["What happens with an unsupported kind of image?", "Does the system detect the product type itself?"], + ), + "alerts_errors": ( + "any", + r"create local review alerts|error event", + [ + "What happens when a model failure occurs?", + "When are review alerts created?", + "Do failed runs create inspections?", + "Which results trigger alerts?", + ], + ["What events create alerts?", "Is an error saved as a successful inspection?"], + ), + "visa": ( + "any", + r"VisA provides|official one-class split|PCB1, capsules|Image-level labels|Multiclass masks|Normal images have no stored", + [ + "What is the VisA dataset?", + "How does the official VisA split work?", + "What does VisA contain?", + "Which products does VisA include?", + ], + ["Tell me about VisA.", "Does VisA include anomaly masks?"], + ), + "visa_license": ( + "any", + r"CC BY 4\.0|SPot-the-Difference|Amazon Science", + [ + "What licence is the VisA dataset under?", + "Who should be credited for VisA?", + "Who released the VisA dataset?", + "How must VisA be attributed?", + ], + ["What is the VisA licence?", "Which paper introduced VisA?"], + ), + "legacy_profile": ( + "dinov3", + r"frozen DINOv3 ViT-S/16|224 by 224|64 normal images|Original DINOv3|identifies the original|maximizes validation F1|Calibration uses 32", + [ + "What is the original DINOv3 profile?", + "What number of normal images does the original profile fit per product?", + "What input size does the DINOv3 profile use?", + "How is the original profile calibrated?", + ], + ["Describe the legacy model profile.", "What patch grid does the original profile use?"], + ), + "highres_profile": ( + "dinov2", + r"frozen DINOv2 ViT-S/14|448-pixel|PCA-based foreground|averages the largest one percent|identifies the AnomalyDINO", + [ + "What is the DINOv2 high-resolution profile?", + "What image size does the high-resolution profile use?", + "How is the anomaly score computed in this profile?", + "What does the foreground heuristic do?", + ], + ["Describe the high-resolution model.", "Is the PCA foreground filter reliable?"], + ), + "calibration": ( + "dinov2", + r"maximum heldout normal score|ten-percent holdout|no anomalous images", + [ + "How is the decision threshold chosen?", + "Which images set the threshold?", + "Are anomalous images used to pick the threshold?", + "How is the operational threshold calibrated?", + ], + ["Explain how the threshold is calibrated.", "What is the threshold based on?"], + ), + "metrics": ( + "dinov2", + r"Image mAP is|Mean image AUROC|Pixel mAP|not bounding-box mAP", + [ + "What is image mAP?", + "How is mean image AUROC computed?", + "Is mAP here the same as YOLO box mAP?", + "Does DefectRAG predict bounding boxes?", + ], + ["Explain pixel mAP.", "Is this mAP measured at an IoU threshold?"], + ), + "retrospective": ( + "dinov2", + r"retrospective development evaluation|Earlier official test exposure", + [ + "Is the evaluation an untouched external test?", + "Was the model evaluated on unseen data?", + "How trustworthy is the reported accuracy?", + "Why is the evaluation called retrospective?", + ], + ["Is the benchmark independent?", "Does earlier test exposure affect the results?"], + ), + "dinomaly": ( + "any", + r"Dinomaly uses|compact nearest-normal fallback|does not establish|reconstruction|different method", + [ + "How does Dinomaly differ from this detector?", + "Does this app use Dinomaly reconstruction?", + "What is Dinomaly?", + "Can Dinomaly benchmark numbers describe this application?", + ], + ["Compare this model with Dinomaly.", "Is reconstruction used here?"], + ), +} + +# Questions the documents cannot answer. A good assistant returns no claim for these. +UNANSWERABLE = { + "train": [ + "What is the capital of France?", + "Give me a recipe for fried rice.", + "Write a short poem about spring.", + "What will the weather be tomorrow?", + "How do I sort a list in Python?", + "Who won the last football world cup?", + "Translate 'good morning' into Malay.", + "Tell me a joke.", + "Who funded the VisA dataset?", + "What is the total number of images in VisA?", + "Which GPU does the high-resolution profile need?", + "How long does one inspection take on a CPU?", + "Does the system work on metal screws?", + "What is the false alarm rate in production?", + "Which camera should I use for the photos?", + "What is the AUROC of the original profile on cashew?", + "Is this approved for medical device inspection?", + "Who wrote the DefectRAG project?", + ], + "test": [ + "What is the tallest mountain in the world?", + "Suggest a name for my cat.", + "How do I reverse a string in JavaScript?", + "What is 17 times 23?", + "Who paid for the VisA benchmark?", + "What resolution in megapixels should the photos have?", + "Does it work on bottle caps?", + "What is the precision on macaroni?", + "Which lighting setup is best?", + "Is the system certified for aerospace parts?", + ], +} + + +def load_cards(): + legacy = {c: json.loads((ROOT / "models" / f"{c}.json").read_text()) for c in CATEGORIES} + high = {c: json.loads((ROOT / "models" / "highres" / f"{c}.json").read_text()) for c in CATEGORIES} + return {"dinov3": legacy, "dinov2": high} + + +def make_inspection(cards, family, rng): + category = rng.choice(CATEGORIES) + card = cards[family][category] + threshold, margin = card["threshold"], card["uncertainty_margin"] + verdict = rng.choice(["Good", "Uncertain", "Anomalous"]) + if verdict == "Good": + score = threshold - margin * rng.uniform(1.5, 8) + elif verdict == "Anomalous": + score = threshold + margin * rng.uniform(1.5, 8) + else: + score = threshold + margin * rng.uniform(-0.9, 0.9) + return { + "id": uuid.UUID(int=rng.getrandbits(128)).hex, + "category": category, + "verdict": verdict, + "score": round(score, 5), + "threshold": round(threshold, 5), + "uncertainty_margin": round(margin, 5), + "model_id": card["model_id"], + "scope": "VisA benchmark appearance anomaly screening; category is user-selected and not verified by this model.", + "localization": card.get("localization", "patch distances, interpolated; not a defect segmentation classifier"), + "calibration": card.get("calibration"), + "profile": card.get("profile"), + } + + +MY_QUESTIONS = OUT / "my_questions.csv" + + +def knowledge_sentences(): + """Every sentence the assistant can quote, split exactly like rag.evidence_quotes does.""" + sources = json.loads((ROOT / "knowledge" / "sources.json").read_text(encoding="utf-8")) + found = [] + for source in sources: + text = (ROOT / "knowledge" / source["file"]).read_text(encoding="utf-8") + for sentence in re.split(r"(?<=[.!?])\s+|\n", text): + sentence = sentence.strip() + if len(sentence) >= 15 and not sentence.startswith("#"): + found.append((source["id"], source["file"], sentence)) + return found + + +def load_my_questions(cards, rng): + """Questions written by a person: columns 'question' and 'answer_phrase' (empty = unanswerable).""" + import csv + + if not MY_QUESTIONS.exists(): + raise SystemExit(f"{MY_QUESTIONS} does not exist yet.") + lines = [line for line in MY_QUESTIONS.read_text(encoding="utf-8-sig").splitlines() if not line.startswith("#")] + sentences = knowledge_sentences() + items = [] + problems = [] + for number, row in enumerate(csv.DictReader(lines), start=1): + question = (row.get("question") or "").strip() + phrase = (row.get("answer_phrase") or "").strip() + if not question: + continue + if not phrase: + family = rng.choice(["dinov2", "dinov3"]) + items.append(("unanswerable", "none", question, "", family)) + continue + hits = [s for s in sentences if phrase.lower() in s[2].lower()] + if not hits: + problems.append( + f"question {number} ({question[:50]!r}): answer_phrase {phrase!r} is not in any knowledge sentence" + ) + continue + sources = {h[0] for h in hits} + family = ( + "dinov3" + if sources == {"legacy-profile"} + else "dinov2" + if sources == {"highres-profile"} + else rng.choice(["dinov2", "dinov3"]) + ) + items.append(("answerable", "mine", question, re.escape(phrase), family)) + if problems: + raise SystemExit("Fix these rows in my_questions.csv:\n " + "\n ".join(problems)) + return [ + { + "id": f"mine-{index}", + "split": "mine", + "kind": kind, + "topic": topic, + "question": question, + "pattern": pattern, + "inspection": make_inspection(cards, family, rng), + } + for index, (kind, topic, question, pattern, family) in enumerate(items) + ] + + +def build_items(split, contexts=2, seed=7): + """Deterministic list of labelled items for 'train', 'test' or 'mine' (your own CSV).""" + rng = random.Random(f"{seed}-{split}") + cards = load_cards() + if split == "mine": + return load_my_questions(cards, rng) + items = [] + for topic, (family, pattern, train, test) in TOPICS.items(): + for question in train if split == "train" else test: + for _ in range(contexts): + fam = rng.choice(["dinov2", "dinov3"]) if family == "any" else family + items.append( + { + "id": f"{split}-{topic}-{len(items)}", + "split": split, + "kind": "answerable", + "topic": topic, + "question": question, + "pattern": pattern, + "inspection": make_inspection(cards, fam, rng), + } + ) + for question in UNANSWERABLE[split]: + for _ in range(contexts): + fam = rng.choice(["dinov2", "dinov3"]) + items.append( + { + "id": f"{split}-none-{len(items)}", + "split": split, + "kind": "unanswerable", + "topic": "none", + "question": question, + "pattern": "", + "inspection": make_inspection(cards, fam, rng), + } + ) + return items + + +def score_item(item, state, seconds): + """Turn one workflow result into measured outcomes.""" + claims = state.get("claims") or [] + raw = state.get("raw_claims") or [] + trace = state.get("trace") or [] + evidence = state.get("evidence") or [] + pattern = re.compile(item["pattern"], re.I) if item["pattern"] else None + row = { + "id": item["id"], + "kind": item["kind"], + "topic": item["topic"], + "question": item["question"], + "seconds": round(seconds, 2), + "mode": state.get("mode"), + "generated": "generate" in trace, + "generation_failed": "generation_fallback" in trace, + "n_raw": len(raw), + "n_valid": len(claims), + "claims": [{"text": c["text"], "source_id": c["source_id"], "quote": c["quote"]} for c in claims], + } + if item["kind"] == "answerable": + row["retrieval_hit"] = any(pattern.search(e["text"]) for e in evidence) + row["correct"] = bool(claims) and all(pattern.search(c["quote"]) for c in claims) + row["wrong_source"] = bool(claims) and not row["correct"] + else: + row["false_answer"] = bool(claims) + return row + + +def wilson(k, n, z=1.96): + if n == 0: + return (0.0, 0.0) + p = k / n + d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d + h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d + return (max(0.0, c - h), min(1.0, c + h)) + + +def summarize(rows): + ans = [r for r in rows if r["kind"] == "answerable"] + una = [r for r in rows if r["kind"] == "unanswerable"] + hit = [r for r in ans if r["retrieval_hit"]] + out = {"items": len(rows), "answerable": len(ans), "unanswerable": len(una)} + + def rate(name, k, n): + lo, hi = wilson(k, n) + out[name] = {"k": k, "n": n, "rate": round(k / n, 3) if n else None, "ci95": [round(lo, 3), round(hi, 3)]} + + rate("retrieval_hit", len(hit), len(ans)) + rate("correct_all", sum(r["correct"] for r in ans), len(ans)) + rate("correct_given_retrieval", sum(r["correct"] for r in hit), len(hit)) + rate("wrong_source", sum(r["wrong_source"] for r in ans), len(ans)) + rate("no_answer_on_answerable", sum(not r["n_valid"] for r in ans), len(ans)) + rate("false_answer_on_unanswerable", sum(r["false_answer"] for r in una), len(una)) + gen = [r for r in rows if r["generated"]] + reached = [r for r in rows if r["generated"] or r["generation_failed"]] + rate("generation_failed", sum(r["generation_failed"] for r in reached), len(reached)) + raw_total = sum(r["n_raw"] for r in gen) + out["validator_dropped_claims"] = {"raw": raw_total, "kept": sum(r["n_valid"] for r in gen)} + out["mean_seconds_generated"] = round(sum(r["seconds"] for r in gen) / len(gen), 2) if gen else None + return out + + +def require_server(url): + """Stop with a clear message if nothing answers at the model server address.""" + import urllib.request + + for path in ("/api/tags", "/"): + try: + urllib.request.urlopen(url.rstrip("/") + path, timeout=5).read() + return + except OSError: + continue + raise SystemExit( + f"No model server is answering at {url}. Start it first (scripts.qwen_serve, or Ollama) and retry." + ) + + +SPACE_SYSTEM = ( + "Follow the application instructions. Return only valid JSON matching the supplied schema. " + "No markdown fences or commentary." +) + + +def make_local_generator(model_dir, style): + """Generate the way the Hugging Face Space does: bf16 weights, greedy decoding, output format NOT forced. + + style "space": the Space's own wrapper (system message + 'JSON schema: ...' appended to the prompt). + style "plain": the prompt exactly as used in training. + Returns a function with the same (prompt, schema) -> {"json": text} contract as deployment/space/generation.py. + """ + import torch + from transformers import AutoModelForCausalLM, AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained(model_dir) + model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=torch.bfloat16, device_map="cuda").eval() + + @torch.inference_mode() + def generate(prompt, schema): + if style == "space": + messages = [ + {"role": "system", "content": SPACE_SYSTEM}, + {"role": "user", "content": prompt + "\nJSON schema: " + json.dumps(schema)}, + ] + else: + messages = [{"role": "user", "content": prompt}] + values = tokenizer.apply_chat_template( + messages, tokenize=True, add_generation_prompt=True, return_tensors="pt", return_dict=True + ) + if values["input_ids"].shape[-1] > 4096: + raise ValueError("Evidence request exceeds the bounded generation context") + values = {key: value.to("cuda") for key, value in values.items()} + output = model.generate(**values, max_new_tokens=384, do_sample=False, use_cache=True) + text = tokenizer.decode(output[0, values["input_ids"].shape[-1] :], skip_special_tokens=True).strip() + return {"json": text, "metadata": {}} + + return generate + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--local-model", default=None, help="folder of a merged model: run it in-process like the Space" + ) + parser.add_argument("--style", choices=["space", "plain"], default="space", help="with --local-model") + parser.add_argument("--split", choices=["train", "test", "mine"], default="test") + parser.add_argument("--model", default="qwen2.5:3b") + parser.add_argument("--tag", default="base") + parser.add_argument("--limit", type=int, default=0) + parser.add_argument("--url", default=None, help="Ollama-compatible server (default: your Ollama)") + parser.add_argument("--list-sentences", action="store_true", help="write the quotable sentences to a file and exit") + parser.add_argument("--check", action="store_true", help="with --split mine: only check the CSV, run nothing") + args = parser.parse_args() + if args.list_sentences: + path = OUT / "knowledge_sentences.txt" + rows = knowledge_sentences() + path.write_text("\n".join(f"[{source}] {sentence}" for source, _, sentence in rows) + "\n", encoding="utf-8") + print(f"wrote {len(rows)} sentences to {path}") + return + if args.check: + items = build_items("mine") + answerable = sum(i["kind"] == "answerable" for i in items) + print( + f"my_questions.csv is valid: {len(items)} questions ({answerable} answerable, {len(items) - answerable} unanswerable)" + ) + return + runs = OUT / "runs" + runs.mkdir(parents=True, exist_ok=True) + path = runs / f"{args.tag}_{args.split}.jsonl" + done = {json.loads(l)["id"]: json.loads(l) for l in path.read_text().splitlines()} if path.exists() else {} + settings = Settings(ollama_model=args.model) + if args.url: + settings.ollama_url = args.url + generator = None + if args.local_model: + generator = make_local_generator(args.local_model, args.style) + else: + require_server(settings.ollama_url) + workflow = EvidenceWorkflow(settings, KnowledgeIndex(ROOT, OUT / "index"), generator) + items = build_items(args.split) + if args.limit: + items = items[: args.limit] + failures_in_a_row = 0 + for n, item in enumerate(items, 1): + if item["id"] in done: + continue + start = time.perf_counter() + state = workflow.graph.invoke({"question": item["question"], "inspection": item["inspection"], "history": []}) + row = score_item(item, state, time.perf_counter() - start) + failures_in_a_row = failures_in_a_row + 1 if row["generation_failed"] else 0 + if failures_in_a_row >= 3: + raise SystemExit( + "STOPPED: the language model failed 3 times in a row, so these results would be meaningless. " + "Is the server still running? Nothing from the failed items was saved." + ) + done[item["id"]] = row + with path.open("a", encoding="utf-8") as stream: + stream.write(json.dumps(row) + "\n") + print( + f"{n}/{len(items)} {item['kind'][:3]} {row['mode']:<15} {row['seconds']:>5}s {item['question'][:60]}", + flush=True, + ) + summary = summarize([done[i["id"]] for i in items if i["id"] in done]) + (OUT / f"summary_{args.tag}_{args.split}.json").write_text(json.dumps(summary, indent=2)) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scripts/qwen_finetune.py b/scripts/qwen_finetune.py new file mode 100644 index 0000000000000000000000000000000000000000..c6dcf88572e28473c5d59d6b99fd4fcaa65009cb --- /dev/null +++ b/scripts/qwen_finetune.py @@ -0,0 +1,181 @@ +"""QLoRA fine-tuning of Qwen2.5-3B-Instruct on the evidence-selection examples. + +Run this in the SEPARATE training environment (defectrag-ft), not the app environment: + + python -m scripts.qwen_finetune + +What happens, in order: + 1. Load the base model in 4-bit (QLoRA): the big weights are frozen and compressed. + 2. Attach small trainable LoRA matrices to the attention and MLP layers (about 1% of the size). + 3. Turn each example into tokens. Loss is computed only on the ANSWER part, never on the prompt. + 4. Train for a few epochs with gradient accumulation (several small steps act like one big batch). + 5. Report training and validation loss each epoch, then save only the small adapter (tens of MB). +""" + +import argparse +import json +import math +import random +import time +from pathlib import Path + +import torch +from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig + +OUT = Path(__file__).resolve().parents[1] / "experiments" / "qwen_lora_v1" +BASE = "Qwen/Qwen2.5-3B-Instruct" + + +def encode(tokenizer, example, max_len): + """Tokens for one example; labels are -100 (ignored) for the prompt and real ids for the answer.""" + chat = [{"role": "user", "content": example["prompt"]}] + prompt_text = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True) + prompt_ids = tokenizer(prompt_text, add_special_tokens=False)["input_ids"] + answer_ids = tokenizer(example["completion"] + "<|im_end|>", add_special_tokens=False)["input_ids"] + ids = prompt_ids + answer_ids + if len(ids) > max_len: + return None + return {"input_ids": ids, "labels": [-100] * len(prompt_ids) + answer_ids} + + +def batch_loss(model, row, device): + ids = torch.tensor([row["input_ids"]], device=device) + labels = torch.tensor([row["labels"]], device=device) + return model(input_ids=ids, labels=labels).loss + + +@torch.no_grad() +def validation_loss(model, rows, device): + model.eval() + total = sum(batch_loss(model, r, device).item() for r in rows) + model.train() + return total / max(1, len(rows)) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", default=BASE) + parser.add_argument("--data", default=str(OUT / "data" / "train.jsonl")) + parser.add_argument("--out", default=str(OUT / "adapter")) + parser.add_argument("--epochs", type=int, default=3) + parser.add_argument("--lr", type=float, default=2e-4) + parser.add_argument("--accum", type=int, default=8, help="examples per optimizer step") + parser.add_argument("--rank", type=int, default=16) + parser.add_argument("--max-len", type=int, default=2048) + parser.add_argument("--max-steps", type=int, default=0, help="stop early (smoke test)") + parser.add_argument("--limit", type=int, default=0, help="use only the first N examples (smoke test)") + parser.add_argument("--seed", type=int, default=7) + args = parser.parse_args() + + random.seed(args.seed) + torch.manual_seed(args.seed) + device = "cuda" + print( + f"GPU: {torch.cuda.get_device_name(0)} free memory before loading: " + f"{torch.cuda.mem_get_info()[0] / 2**30:.1f} GiB", + flush=True, + ) + + tokenizer = AutoTokenizer.from_pretrained(args.model) + examples = [json.loads(line) for line in Path(args.data).read_text(encoding="utf-8").splitlines() if line.strip()] + if args.limit: + examples = examples[: args.limit] + random.shuffle(examples) + rows = [r for r in (encode(tokenizer, e, args.max_len) for e in examples) if r] + cut = max(1, len(rows) // 10) + val, train = rows[:cut], rows[cut:] + print( + f"examples: {len(train)} train, {len(val)} validation " + f"({len(examples) - len(rows)} dropped as too long); " + f"tokens per example: median {sorted(len(r['input_ids']) for r in rows)[len(rows) // 2]}", + flush=True, + ) + + quant = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_use_double_quant=True, + bnb_4bit_compute_dtype=torch.bfloat16, + ) + model = AutoModelForCausalLM.from_pretrained( + args.model, quantization_config=quant, device_map={"": 0}, dtype=torch.bfloat16 + ) + model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True) + lora = LoraConfig( + r=args.rank, + lora_alpha=2 * args.rank, + lora_dropout=0.05, + task_type="CAUSAL_LM", + target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"], + ) + model = get_peft_model(model, lora) + model.print_trainable_parameters() + model.train() + + params = [p for p in model.parameters() if p.requires_grad] + optimizer = torch.optim.AdamW(params, lr=args.lr, weight_decay=0.0) + steps_per_epoch = math.ceil(len(train) / args.accum) + total_steps = steps_per_epoch * args.epochs + if args.max_steps: + total_steps = min(total_steps, args.max_steps) + warmup = max(1, int(0.05 * total_steps)) + + def lr_at(step): # linear warm-up, then cosine decay to 10% + if step < warmup: + return args.lr * (step + 1) / warmup + progress = (step - warmup) / max(1, total_steps - warmup) + return args.lr * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * progress))) + + log = {"args": vars(args), "epochs": [], "steps": []} + step, started = 0, time.time() + val_before = validation_loss(model, val, device) + print(f"validation loss BEFORE training: {val_before:.4f}", flush=True) + log["validation_loss_before"] = val_before + for epoch in range(args.epochs): + random.shuffle(train) + running = [] + for start in range(0, len(train), args.accum): + group = train[start : start + args.accum] + for g in optimizer.param_groups: + g["lr"] = lr_at(step) + total = 0.0 + for row in group: + loss = batch_loss(model, row, device) / len(group) + loss.backward() + total += loss.item() + torch.nn.utils.clip_grad_norm_(params, 1.0) + optimizer.step() + optimizer.zero_grad(set_to_none=True) + step += 1 + running.append(total) + log["steps"].append({"step": step, "loss": total, "lr": lr_at(step - 1)}) + print( + f"epoch {epoch + 1}/{args.epochs} step {step}/{total_steps} loss {total:.4f} " + f"lr {lr_at(step - 1):.2e} {time.time() - started:.0f}s " + f"peak GPU {torch.cuda.max_memory_allocated() / 2**30:.1f} GiB", + flush=True, + ) + if args.max_steps and step >= args.max_steps: + break + val_loss = validation_loss(model, val, device) + log["epochs"].append( + {"epoch": epoch + 1, "train_loss": sum(running) / len(running), "validation_loss": val_loss} + ) + print( + f"== epoch {epoch + 1}: train loss {sum(running) / len(running):.4f}, validation loss {val_loss:.4f}", + flush=True, + ) + if args.max_steps and step >= args.max_steps: + break + + Path(args.out).mkdir(parents=True, exist_ok=True) + model.save_pretrained(args.out) + tokenizer.save_pretrained(args.out) + log["seconds"] = time.time() - started + (Path(args.out) / "training_log.json").write_text(json.dumps(log, indent=1), encoding="utf-8") + print(f"saved adapter to {args.out} (total {log['seconds'] / 60:.1f} minutes)", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/qwen_merge.py b/scripts/qwen_merge.py new file mode 100644 index 0000000000000000000000000000000000000000..e32148f7d064f48fb19e977c8b02a7e14ad8389c --- /dev/null +++ b/scripts/qwen_merge.py @@ -0,0 +1,42 @@ +"""Merge a trained LoRA adapter into the base model and save a plain model folder. + + python -m scripts.qwen_merge --adapter experiments/qwen_lora_v1/adapter_v2 --out experiments/qwen_lora_v1/merged_v2 + +The result is an ordinary Hugging Face model folder (no adapter needed), which Ollama can import. +The merge runs on the GPU so it needs very little system memory. Nothing in the app is touched. +""" + +import argparse +from pathlib import Path + +import torch +from peft import PeftModel +from transformers import AutoModelForCausalLM, AutoTokenizer + +from backend.config import ROOT + +BASE = ROOT / "experiments" / "qwen_lora_v1" / "base_model" + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--adapter", required=True) + parser.add_argument("--base", default=str(BASE)) + parser.add_argument("--out", required=True) + args = parser.parse_args() + out = Path(args.out) + if out.exists() and any(out.iterdir()): + raise SystemExit(f"{out} already has files; choose an empty folder so nothing is overwritten.") + device = "cuda" if torch.cuda.is_available() else "cpu" + # bf16 is the dtype the base model was published in; the adapter was trained on its 4-bit form. + model = AutoModelForCausalLM.from_pretrained(args.base, torch_dtype=torch.bfloat16, device_map=device) + model = PeftModel.from_pretrained(model, args.adapter) + merged = model.merge_and_unload() + out.mkdir(parents=True, exist_ok=True) + merged.save_pretrained(out, safe_serialization=True, max_shard_size="1GB") + AutoTokenizer.from_pretrained(args.base).save_pretrained(out) + print(f"saved merged model to {out}") + + +if __name__ == "__main__": + main() diff --git a/scripts/qwen_serve.py b/scripts/qwen_serve.py new file mode 100644 index 0000000000000000000000000000000000000000..61a75c03632fa83f8da62b2a9e90472d34df5776 --- /dev/null +++ b/scripts/qwen_serve.py @@ -0,0 +1,99 @@ +"""Serve Qwen (with or without the fine-tuned adapter) through an Ollama-compatible endpoint. + +Run in the training environment (defectrag-ft): + + python -m scripts.qwen_serve --adapter experiments/qwen_lora_v1/adapter # fine-tuned + python -m scripts.qwen_serve --adapter none --port 11501 # same base, no adapter + +It implements only POST /api/generate, which is all the assistant's workflow uses, so +`python -m scripts.qwen_eval --url http://127.0.0.1:11500` measures it with the same +questions, retrieval and checks as before. Decoding is greedy (temperature 0), and the output is +forced to follow the same JSON schema the assistant sends, as Ollama does. +""" + +import argparse +import json +import time +from http.server import BaseHTTPRequestHandler, HTTPServer + +import torch +from lmformatenforcer import JsonSchemaParser +from lmformatenforcer.integrations.transformers import build_transformers_prefix_allowed_tokens_fn +from peft import PeftModel +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig + +BASE = "Qwen/Qwen2.5-3B-Instruct" + + +def load(adapter, base=BASE): + tokenizer = AutoTokenizer.from_pretrained(base) + quant = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type="nf4", + bnb_4bit_use_double_quant=True, + bnb_4bit_compute_dtype=torch.bfloat16, + ) + model = AutoModelForCausalLM.from_pretrained( + base, quantization_config=quant, device_map={"": 0}, dtype=torch.bfloat16 + ) + if adapter != "none": + model = PeftModel.from_pretrained(model, adapter) + return tokenizer, model.eval() + + +def make_handler(tokenizer, model, label): + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): # keep the terminal readable + pass + + def _send(self, status, payload): + data = json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + self._send(200, {"status": "ok", "model": label}) + + def do_POST(self): + if self.path != "/api/generate": + return self._send(404, {"error": "only /api/generate is implemented"}) + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + chat = [{"role": "user", "content": body["prompt"]}] + text = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True) + inputs = tokenizer(text, return_tensors="pt", add_special_tokens=False).to(model.device) + kwargs = {} + if isinstance(body.get("format"), dict): + parser = JsonSchemaParser(body["format"]) + kwargs["prefix_allowed_tokens_fn"] = build_transformers_prefix_allowed_tokens_fn(tokenizer, parser) + start = time.perf_counter() + with torch.no_grad(): + out = model.generate( + **inputs, max_new_tokens=400, do_sample=False, pad_token_id=tokenizer.eos_token_id, **kwargs + ) + answer = tokenizer.decode(out[0][inputs["input_ids"].shape[1] :], skip_special_tokens=True) + print(f"{time.perf_counter() - start:5.1f}s {answer[:110]!r}", flush=True) + self._send(200, {"model": label, "response": answer, "done": True}) + + return Handler + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--adapter", default="experiments/qwen_lora_v1/adapter", help="folder, or 'none' for the base model" + ) + parser.add_argument("--port", type=int, default=11500) + parser.add_argument("--base", default=BASE, help="base model: Hugging Face id or a local folder") + args = parser.parse_args() + print("loading model ...", flush=True) + tokenizer, model = load(args.adapter, args.base) + label = "base" if args.adapter == "none" else "fine-tuned" + print(f"ready: {label} model at http://127.0.0.1:{args.port}", flush=True) + HTTPServer(("127.0.0.1", args.port), make_handler(tokenizer, model, label)).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/scripts/qwen_short_questions.py b/scripts/qwen_short_questions.py new file mode 100644 index 0000000000000000000000000000000000000000..1187ca6ea718363db44d75342d8b4b7aa32fdc12 --- /dev/null +++ b/scripts/qwen_short_questions.py @@ -0,0 +1,113 @@ +"""How do short or vague questions behave at different similarity cutoffs? (CPU only, no language model) + + python -m scripts.qwen_short_questions + +For every question this finds the 3 most similar document chunks and records the best similarity. +A question "succeeds" at a cutoff if a chunk containing the answer sentence is among the results with +similarity >= cutoff. An unrelated question "leaks" if any chunk passes (so the language model would be asked). +Output: experiments/qwen_lora_v1/short_question_report.json +""" + +import csv +import json + +import numpy as np + +from backend.config import ROOT +from backend.rag import KnowledgeIndex +from scripts.qwen_eval import MY_QUESTIONS, OUT, UNANSWERABLE + +CUTOFFS = [0.30, 0.35, 0.40, 0.45, 0.50] + +# (3 to 4 word version of the full question, phrase from the answering sentence) +SHORT = [ + ("anomaly score meaning", "not a defect probability"), + ("Uncertain result meaning", "within a fixed five-percent band around the threshold"), + ("Good result guarantee", "not proof of factory acceptance or product safety"), + ("heatmap colours meaning", "shows cosine distance between each image patch feature"), + ("warning what next", "Review source images and heatmaps before acting"), + ("detect defect type", "does not predict specific defect types"), + ("which model old result", "Consult that saved record"), + ("new model old results", "does not change a historical verdict or heatmap"), + ("analysis fails what happens", "Model failures create an error event"), + ("alerts when", "Anomaly and uncertain events create local review alerts"), + ("which products allowed", "wrong-product uploads are outside validated scope"), + ("what is VisA", "VisA provides normal and anomalous product images"), + ("sample photos source", "sample previews are resized JPEG derivatives"), + ("VisA licence", "released by Amazon Science under CC BY 4.0"), + ("trained on defects", "fits on normal images"), + ("original model image size", "a 224 by 224 input"), + ("background filtering", "PCA-based foreground heuristic filters background patches"), + ("how threshold chosen", "maximum heldout normal score"), + ("precision recall threshold", "use a frozen threshold"), + ("accuracy fair test", "not an untouched external test"), + ("copy of published method", "rather than an exact reproduction of AnomalyDINO"), + ("normal images masks", "Normal images have no stored anomaly mask"), + ("explanation about my photo", "must remain separate from saved image measurements"), +] +ONE_WORD = [ + ("heatmap", "shows cosine distance between each image patch feature"), + ("VisA", "VisA provides normal and anomalous product images"), + ("licence", "released by Amazon Science under CC BY 4.0"), + ("alerts", "Anomaly and uncertain events create local review alerts"), + ("Uncertain", "within a fixed five-percent band around the threshold"), + ("score", "not a defect probability"), + ("AnomalyDINO", "rather than an exact reproduction of AnomalyDINO"), + ("Good", "Good means the score lies below the decision threshold"), +] + + +def load_full(): + lines = [line for line in MY_QUESTIONS.read_text(encoding="utf-8-sig").splitlines() if not line.startswith("#")] + rows = list(csv.DictReader(lines)) + full = [(r["question"].strip(), r["answer_phrase"].strip()) for r in rows if r["answer_phrase"].strip()] + unrelated = [r["question"].strip() for r in rows if r["question"].strip() and not r["answer_phrase"].strip()] + return full, unrelated + + +def main(): + index = KnowledgeIndex(ROOT, OUT / "index") + index.ensure() + chunks = [d.page_content.lower() for d in index.documents] + + def probe(text): + vector = np.asarray(index.embeddings.embed_query(text), dtype="float32") + scores = index.matrix @ vector + order = [int(i) for i in np.argsort(scores)[::-1][:3]] + return [(i, float(scores[i])) for i in order] + + def success(phrase, hits, cutoff): + return any(score >= cutoff and phrase.lower() in chunks[i] for i, score in hits) + + full, unrelated = load_full() + groups = {"full question": full, "3-4 words": SHORT, "one word": ONE_WORD} + report = {"cutoffs": CUTOFFS, "on_topic": {}, "unrelated_leak": {}} + print(f"{'on-topic questions, right answer retrieved':44s}" + "".join(f"{c:>8.2f}" for c in CUTOFFS)) + for name, items in groups.items(): + probes = [(text, phrase, probe(text)) for text, phrase in items] + row = [sum(success(p, h, c) for _, p, h in probes) for c in CUTOFFS] + best = sorted(h[0][1] for _, _, h in probes) + report["on_topic"][name] = { + "n": len(items), + "retrieved_at_cutoff": row, + "lowest_best_similarity": round(best[0], 3), + "median_best_similarity": round(best[len(best) // 2], 3), + "below_050": [t for t, _, h in probes if h[0][1] < 0.50], + } + print( + f"{name + f' (n={len(items)})':44s}" + + "".join(f"{v:>8d}" for v in row) + + f" median best similarity {best[len(best) // 2]:.2f}, lowest {best[0]:.2f}" + ) + others = unrelated + UNANSWERABLE["train"] + UNANSWERABLE["test"] + probes = [(text, probe(text)) for text in others] + print(f"\n{'unrelated questions that still reach the model':44s}" + "".join(f"{c:>8.2f}" for c in CUTOFFS)) + row = [sum(any(score >= c for _, score in hits) for _, hits in probes) for c in CUTOFFS] + report["unrelated_leak"] = {"n": len(others), "reach_model_at_cutoff": row} + print(f"{f'unrelated (n={len(others)})':44s}" + "".join(f"{v:>8d}" for v in row)) + (OUT / "short_question_report.json").write_text(json.dumps(report, indent=1), encoding="utf-8") + print("\nsaved short_question_report.json") + + +if __name__ == "__main__": + main() diff --git a/scripts/space_dry_run.py b/scripts/space_dry_run.py new file mode 100644 index 0000000000000000000000000000000000000000..d4fc28b2e060fbe1dbd0b0914516589d639aa660 --- /dev/null +++ b/scripts/space_dry_run.py @@ -0,0 +1,62 @@ +"""Dry run of switching the Hugging Face Space to the fine-tuned model. + + python -m scripts.space_dry_run + +It copies deployment/space/generation.py into a temporary folder, applies the proposed change there, checks that the +result is valid Python and prints what would change. It never writes to deployment/ and uploads nothing. +""" + +import ast +import difflib +import tempfile +from pathlib import Path + +from backend.config import ROOT + +LIVE = ROOT / "deployment" / "space" / "generation.py" + +OLD = """MODEL_ID='Qwen/Qwen3-4B-Instruct-2507' +REVISION='cdbee75f17c01a7cc42f958dc650907174af0554' +TOKENIZER=None +MODEL=None +if os.getenv('SPACES_ZERO_GPU')=='1' and os.getenv('DEFECTRAG_LIVE_RAG')=='1': + # Download/cache in the Space only. Never place another 8 GB on the laptop. + TOKENIZER=AutoTokenizer.from_pretrained(MODEL_ID,revision=REVISION) + MODEL=AutoModelForCausalLM.from_pretrained(MODEL_ID,revision=REVISION, + dtype=torch.bfloat16,attn_implementation='sdpa').eval().to('cuda')""" + +NEW = """# Fine-tuned Qwen2.5-3B-Instruct (QLoRA adapter merged into the base weights, bf16, about 6 GB). +# Results: docs/QWEN_FINETUNING_RESULTS.md. Improved using Qwen (Qwen Research License, non-commercial). +MODEL_ID=os.getenv('DEFECTRAG_MODEL_ID','Wizzas/defectrag-qwen2.5-3b-evidence') +REVISION=os.getenv('DEFECTRAG_MODEL_REVISION','') # pin to the uploaded commit hash before going live +HF_TOKEN=os.getenv('HF_TOKEN') # Space secret; needed while the model repo is private +TOKENIZER=None +MODEL=None +if os.getenv('SPACES_ZERO_GPU')=='1' and os.getenv('DEFECTRAG_LIVE_RAG')=='1': + if not REVISION: + raise RuntimeError('Set DEFECTRAG_MODEL_REVISION to the pinned commit of the fine-tuned model') + # Download/cache in the Space only. Never place another 6 GB on the laptop. + TOKENIZER=AutoTokenizer.from_pretrained(MODEL_ID,revision=REVISION,token=HF_TOKEN) + MODEL=AutoModelForCausalLM.from_pretrained(MODEL_ID,revision=REVISION,token=HF_TOKEN, + dtype=torch.bfloat16,attn_implementation='sdpa').eval().to('cuda')""" + + +def main(): + original = LIVE.read_text(encoding="utf-8") + if OLD not in original: + raise SystemExit("The live file no longer contains the expected block, so the proposal needs updating.") + proposed = original.replace(OLD, NEW) + ast.parse(proposed) # raises if the result is not valid Python + with tempfile.TemporaryDirectory() as folder: + copy = Path(folder) / "generation.py" + copy.write_text(proposed, encoding="utf-8") + print(f"1. proposal written to a temporary copy ({copy.name}) and checked: valid Python") + print("2. live file left unchanged:", LIVE) + print("3. what would change:\n") + diff = difflib.unified_diff(original.splitlines(), proposed.splitlines(), "live", "proposed", lineterm="", n=1) + print("\n".join(diff)) + print("\nNothing was uploaded and nothing in deployment/ was modified.") + + +if __name__ == "__main__": + main() diff --git a/scripts/summarize_accuracy.py b/scripts/summarize_accuracy.py new file mode 100644 index 0000000000000000000000000000000000000000..042de2eb7ad8fc9e353b353b1f2863c37129b5cc --- /dev/null +++ b/scripts/summarize_accuracy.py @@ -0,0 +1,46 @@ +"""Compare saved official test predictions and reports, without model execution.""" +import csv,json +import numpy as np +from backend.config import ROOT,CATEGORIES +from scripts.benchmark_official import write + +if __name__=='__main__': + old=json.loads((ROOT/'results/official_evaluation.json').read_text()) + new=json.loads((ROOT/'results/highres_evaluation.json').read_text()) + assert set(new['categories'])==set(CATEGORIES) + rows=[] + for category in CATEGORIES: + a=json.loads((ROOT/'experiments/official_visa_v1'/category/'split.json').read_text()) + b=json.loads((ROOT/'experiments/dinov2_highres_v1'/category/'split.json').read_text()) + assert {r['image']:r['sha256'] for r in a['test']}=={r['image']:r['sha256'] for r in b['test']} + before=old['categories'][category]['benchmark_mean'];after=new['categories'][category]['benchmark_mean'] + rows.append({'category':category,'old_image_auroc':before['auroc'],'new_image_auroc':after['auroc'], + 'auroc_change_pp':(after['auroc']-before['auroc'])*100,'old_image_ap':before['average_precision'], + 'new_image_ap':after['average_precision'],'old_pixel_ap':before['pixel_average_precision'], + 'new_pixel_ap':after['pixel_average_precision']}) + for report in (old,new): + for metric in report['macro_mean']: + assert abs(report['macro_mean'][metric]-np.mean([c['benchmark_mean'][metric] for c in report['categories'].values()]))<1e-12 + result={'status':'passed','same_official_test_identities_and_content_hashes':True, + 'baseline_macro':old['macro_mean'],'candidate_macro':new['macro_mean'],'candidate_macro_std':new['macro_std'], + 'all_categories':rows,'image_auroc_regressions':[r['category'] for r in rows if r['auroc_change_pp']<0], + 'pixel_ap_regressions':[r['category'] for r in rows if r['new_pixel_ap']= threshold + return {'image_auroc':float(roc_auc_score(labels,scores)), 'average_precision':float(average_precision_score(labels,scores)), + 'precision':float(precision_score(labels,prediction,zero_division=0)), 'recall':float(recall_score(labels,prediction,zero_division=0)), + 'f1':float(f1_score(labels,prediction,zero_division=0)), 'confusion_matrix':confusion_matrix(labels,prediction,labels=[0,1]).tolist(), + 'n_images':len(labels)} + +def calibrate(labels, scores): + p,r,t = precision_recall_curve(labels,scores) + f = 2*p[:-1]*r[:-1]/np.maximum(p[:-1]+r[:-1],1e-12) + return float(t[int(np.argmax(f))]) + +def evaluate(encoder, bank, rows, dataset): + predictions, maps, masks = [], [], [] + for row in rows: + start = time.perf_counter() + with Image.open(dataset / row['image']) as im: + raw,score = map_and_score(encoder,bank,im) + elapsed = (time.perf_counter()-start)*1000 + label = int(row['label']!='normal') + predictions.append({'image':row['image'], 'sha256':sha256(dataset/row['image']), 'label':label, 'score':score, 'latency_ms':elapsed}) + # Explicitly report reduced-resolution pixel metrics including normal images. + maps.append(np.asarray(Image.fromarray(raw).resize((64,64),Image.Resampling.BILINEAR)).ravel()) + if label: + with Image.open(dataset/row['mask']) as mask: + masks.append((np.asarray(mask.convert('L').resize((64,64),Image.Resampling.NEAREST))>0).ravel()) + else: + masks.append(np.zeros(64*64,dtype=bool)) + return predictions,np.concatenate(maps),np.concatenate(masks) + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument('--dataset',type=Path,required=True) + parser.add_argument('--encoder',required=True) + parser.add_argument('--device',default='auto') + parser.add_argument('--train-count',type=int,default=64) + parser.add_argument('--categories',nargs='+',choices=CATEGORIES,default=list(CATEGORIES)) + parser.add_argument('--resume',action='store_true',help='Skip completed categories; preserve and extend existing evaluation') + args=parser.parse_args() + report_path=ROOT/'results'/'evaluation.json' + previous=json.loads(report_path.read_text()) if report_path.exists() else None + completed=[] + for category in args.categories: + files=[ROOT/'models'/f'{category}.npz',ROOT/'models'/f'{category}.json', + ROOT/'results'/f'{category}_splits.json',ROOT/'results'/f'{category}_predictions.json'] + if any(p.exists() for p in files): + if not (args.resume and all(p.exists() for p in files) and category in (previous or {}).get('categories',{})): + raise RuntimeError('Existing artifacts preserved; inspect category before continuing: '+category) + card=json.loads(files[1].read_text()) + if card['bank_sha256']!=sha256(files[0]) or card['train_normal_count']!=args.train_count: + raise RuntimeError('Saved category does not match requested configuration: '+category) + completed.append(category) + print('Preserved completed category: '+category,flush=True) + pending=[c for c in args.categories if c not in completed] + if not pending: + print('All requested categories already complete; no experiment repeated.',flush=True) + return + rows=list(csv.DictReader((args.dataset/'split_csv'/'1cls.csv').open(newline=''))) + # Profile one forward before fitting all categories. No gradient training here. + encoder=Encoder(args.encoder,args.device) + encoder_path=Path(args.encoder) + if not encoder_path.is_dir(): + from huggingface_hub import snapshot_download + encoder_path=Path(snapshot_download(args.encoder,local_files_only=True)) + fingerprint=sha256(encoder_path/'model.safetensors') + report={'method':'Frozen DINOv3 ViT-S/16 + cosine nearest-normal patch bank', + '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.', + 'platform':platform.platform(),'python':platform.python_version(),'torch':torch.__version__, + 'device':str(encoder.device),'encoder_sha256':fingerprint,'categories':{}} + if previous: + if previous['encoder_sha256']!=fingerprint: + raise RuntimeError('Encoder differs from existing evaluation; use a separate experiment') + report=previous + for category in pending: + start=time.perf_counter() + splits=make_split(rows,category,train_count=args.train_count) + hashes={name:{sha256(args.dataset/r['image']) for r in group} for name,group in splits.items()} + if any(hashes[a]&hashes[b] for a,b in [('train','validation'),('train','test'),('validation','test')]): + raise ValueError('Cross-split content overlap detected') + if encoder.device.type=='cuda': + torch.cuda.reset_peak_memory_stats() + features=[] + for row in splits['train']: + with Image.open(args.dataset/row['image']) as im: + features.append(encoder.patches(im)[0].cpu()) + bank=torch.cat(features) + indices=np.random.default_rng(42).choice(len(bank),min(8192,len(bank)),replace=False) + bank=bank[indices] + staging=ROOT/'runtime'/'training';staging.mkdir(parents=True,exist_ok=True) + bank_path=staging/f'{category}.npz' + np.savez_compressed(bank_path,patches=bank.numpy().astype('float16')) + # Use exactly the saved bank precision for calibration and test. + bank=F.normalize(torch.from_numpy(np.load(bank_path)['patches'].astype('float32')).to(encoder.device),dim=-1) + val,vmaps,vmasks=evaluate(encoder,bank,splits['validation'],args.dataset) + threshold=calibrate([x['label'] for x in val],[x['score'] for x in val]) + pixel_threshold=calibrate(vmasks,vmaps) + test,tmaps,tmasks=evaluate(encoder,bank,splits['test'],args.dataset) + metrics=binary_metrics([x['label'] for x in test],[x['score'] for x in test],threshold) + metrics.update({'pixel_auroc_64':float(roc_auc_score(tmasks,tmaps)), + 'pixel_average_precision_64':float(average_precision_score(tmasks,tmaps)), + 'pixel_f1_64':float(f1_score(tmasks,tmaps>=pixel_threshold,zero_division=0)), + 'pixel_threshold':pixel_threshold, + 'latency_median_ms':float(np.median([x['latency_ms'] for x in test])), + 'latency_p95_ms':float(np.percentile([x['latency_ms'] for x in test],95)), + 'peak_gpu_mb':torch.cuda.max_memory_allocated()/1024**2 if encoder.device.type=='cuda' else None}) + margin=threshold*.05 + metrics['uncertain_fraction']=float(np.mean([abs(x['score']-threshold)<=margin for x in test])) + card={'category':category,'available':True,'model_id':f'dinov3-normal-bank-{category}-v1','method':report['method'], + 'encoder_sha256':fingerprint,'bank_sha256':sha256(bank_path),'threshold':threshold,'uncertainty_margin':margin, + 'uncertainty_policy':'Fixed ±5% of validated threshold. Operational review band, not calibrated confidence.', + 'heatmap_scale':float(np.quantile(vmaps,.995)),'bank_size_bytes':bank_path.stat().st_size, + 'encoder_size_bytes':(encoder_path/'model.safetensors').stat().st_size, + 'calibration':{'method':'Max F1 on separate validation identities','normal':32,'anomalous':20,'seed':42}, + 'train_normal_count':len(splits['train']),'metrics':metrics,'fit_and_evaluation_seconds':time.perf_counter()-start} + manifest={name:[{**r,'sha256':sha256(args.dataset/r['image'])} for r in group] for name,group in splits.items()} + (ROOT/'results'/f'{category}_splits.json').write_text(json.dumps(manifest,indent=2)) + (ROOT/'results'/f'{category}_predictions.json').write_text(json.dumps({'validation':val,'test':test},indent=2)) + final_bank=ROOT/'models'/f'{category}.npz' + if final_bank.exists():raise RuntimeError('Refusing to overwrite an existing bank') + bank_path.replace(final_bank) + (ROOT/'models'/f'{category}.json').write_text(json.dumps(card,indent=2)) + report['categories'][category]=card + (ROOT/'results'/'evaluation.json').write_text(json.dumps(report,indent=2)) + print(category,json.dumps(metrics),flush=True) + for label,name in [('normal','good'),('anomaly','anomalous')]: + row=next(r for r in splits['test'] if (r['label']=='normal')==(label=='normal')) + with Image.open(args.dataset/row['image']) as im: + im=im.convert('RGB'); im.thumbnail((640,640)); im.save(ROOT/'samples'/f'{category}_{name}.jpg',quality=90) + print('Completed. Final metrics are frozen; do not tune against final-test labels.',flush=True) + +if __name__=='__main__': main() diff --git a/scripts/train_anomalib.py b/scripts/train_anomalib.py new file mode 100644 index 0000000000000000000000000000000000000000..225b69b135556e08ec2fed9df437d0b3e01d2c7b --- /dev/null +++ b/scripts/train_anomalib.py @@ -0,0 +1,46 @@ +"""Optional Anomalib Dinomaly experiment; unverified, never started automatically. + +Uses the same frozen identity manifest as the compact detector. DINOv3 is not +silently passed to a DINOv2-only interface. Export is deliberately separate from +the shipped memory-bank API until independently evaluated and integrated. +""" +import argparse +import json +from pathlib import Path +from backend.config import ROOT + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument('--dataset',type=Path,required=True) + parser.add_argument('--category',choices=['pcb1','capsules','cashew'],required=True) + parser.add_argument('--authorize-training',action='store_true') + parser.add_argument('--steps',type=int,default=500) + args=parser.parse_args() + if not args.authorize_training: parser.error('Requires approval via --authorize-training; may download a DINOv2 backbone') + from anomalib.models import Dinomaly + from anomalib.engine import Engine + from anomalib.data import Folder + import shutil + import torch + if not torch.cuda.is_available(): raise RuntimeError('This optional training path requires a compatible CUDA runtime') + free,total=torch.cuda.mem_get_info() + print(f'GPU memory before model: {free/1024**3:.2f} GiB free / {total/1024**3:.2f} GiB total') + if free<4*1024**3: raise RuntimeError('Less than 4 GiB free; stop and profile before training') + split=json.loads((ROOT/'results'/f'{args.category}_splits.json').read_text()) + staging=ROOT/'runtime'/'anomalib-data'/args.category + for partition,rows in split.items(): + for row in rows: + label='good' if row['label']=='normal' else 'bad' + destination=staging/partition/label/Path(row['image']).name + destination.parent.mkdir(parents=True,exist_ok=True) + if not destination.exists():shutil.copyfile(args.dataset/row['image'],destination) + # Folder automatic validation must not consume final test images: the + # manifest validation set is passed explicitly using validation directories. + 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) + model=Dinomaly(encoder_name='vit_small_patch14_dinov2',decoder_depth=4, + target_layers=[2,3,4,5],fuse_layer_encoder=[[0,1],[2,3]],fuse_layer_decoder=[[0,1],[2,3]]) + engine=Engine(default_root_dir=str(ROOT/'runtime'/'anomalib-training'),max_steps=args.steps,accelerator='gpu',devices=1) + engine.fit(model,datamodule=datamodule) + engine.trainer.save_checkpoint(str(ROOT/'runtime'/'anomalib-training'/f'{args.category}.ckpt')) + print('Experimental checkpoint saved. Final-test evaluation and API adapter remain required; do not replace calibrated production cards.') +if __name__=='__main__':main() diff --git a/scripts/verify_all_categories.py b/scripts/verify_all_categories.py new file mode 100644 index 0000000000000000000000000000000000000000..6b1e12a7b8c69007f304761aa39a9e940a5f6112 --- /dev/null +++ b/scripts/verify_all_categories.py @@ -0,0 +1,48 @@ +"""Verify new categories through the real API, preserving existing runtime history.""" +import json +from pathlib import Path +from fastapi.testclient import TestClient +from backend.main import create_app +from backend.config import ROOT, Settings, CATEGORIES +from backend.storage import SQLiteRepository + + +def main(): + dataset=Path(r'C:\Users\User\Downloads\VisA_20220922') + evaluation=json.loads((ROOT/'results/evaluation.json').read_text()) + assert set(evaluation['categories'])==set(CATEGORIES) + records=[] + # Separate persistent verification history; never replace the user's database. + data=ROOT/'runtime'/'verification12' + repo=SQLiteRepository(data/'inspection.sqlite3') + app=create_app(Settings(data=data)) + with TestClient(app) as client: + for category in CATEGORIES: + manifest=json.loads((ROOT/'results'/f'{category}_splits.json').read_text()) + hashes={k:{r['sha256'] for r in rows} for k,rows in manifest.items()} + assert all(not hashes[a]&hashes[b] for a,b in [('train','validation'),('train','test'),('validation','test')]) + if category in ('pcb1','capsules','cashew'):continue + predictions=json.loads((ROOT/'results'/f'{category}_predictions.json').read_text())['test'] + for truth in (0,1): + row=next(r for r in predictions if r['label']==truth) + existing=next((r for r in repo.list(category=category,limit=100) if r.get('filename')==Path(row['image']).name),None) + if existing:record=existing + else: + path=dataset/row['image'] + response=client.post('/api/inspect',data={'category':category,'batch':'All-category verification'}, + files={'file':(path.name,path.read_bytes(),'image/jpeg')}) + assert response.status_code==200,response.text + record=response.json()['data'] + assert abs(record['score']-row['score'])<1e-6 + assert client.get(record['heatmap_url']).status_code==200 + assert client.get('/api/inspections/'+record['id']+'/report').status_code==200 + records.append({'id':record['id'],'category':category,'truth':truth,'score':record['score'],'verdict':record['verdict']}) + print('API verified: '+category,flush=True) + receipt={'status':'passed','categories':list(CATEGORIES),'real_images':records, + 'data_directory':'runtime/verification12','new_records':len(records),'split_hash_checks':'passed', + 'scores_match_saved_evaluation':True,'original_three':'preserved; not repeated'} + (ROOT/'results/all_categories_acceptance.json').write_text(json.dumps(receipt,indent=2)) + print(json.dumps({'status':'passed','categories':12,'new_real_api_images':len(records)}),flush=True) + + +if __name__=='__main__':main() diff --git a/scripts/verify_assistant_quality.py b/scripts/verify_assistant_quality.py new file mode 100644 index 0000000000000000000000000000000000000000..2aca462649a94bd40980201dc784207aa66844fd --- /dev/null +++ b/scripts/verify_assistant_quality.py @@ -0,0 +1,37 @@ +"""Capture real upgraded answers against an isolated running inspection workspace.""" +import json +from pathlib import Path +import httpx + +ROOT=Path(__file__).resolve().parents[1] +IDENTIFIER='a6226ef392eb417e8991369e890d816b' +QUESTIONS=['So this product is anomaly right?','Does 0.09 mean 9% accurate?', + 'What does this inspection heatmap show?','How does that map relate to the anomaly score?', + 'What caused this defect?'] + +if __name__=='__main__': + path=ROOT/'results/assistant_quality_verification.json' + report=json.loads(path.read_text()) if path.exists() else {'status':'running','inspection_id':IDENTIFIER,'answers':[]} + with httpx.Client(base_url='http://127.0.0.1:8780',timeout=120,trust_env=False) as client: + record=client.get('/api/inspections/'+IDENTIFIER).json()['data'] + for question in QUESTIONS: + if any(a['question']==question for a in report['answers']):continue + response=client.post('/api/assistant',json={'inspection_id':IDENTIFIER,'question':question});response.raise_for_status() + answer=response.json()['data'] + assert f"{record['score']:.5f}" in answer['answer'] + report['answers'].append({'question':question,**answer}) + path.write_text(json.dumps(report,indent=2)) + print(question+' -> '+answer['mode'],flush=True) + assert report['answers'][0]['mode']=='measurement_only' and report['answers'][0]['answer'].startswith('Yes—') + assert report['answers'][1]['mode']=='measurement_only' and 'not an accuracy percentage' in report['answers'][1]['answer'] + assert all(a['mode']=='llm' for a in report['answers'][2:4]) + for answer in report['answers'][2:4]: + sources={s['chunk_id']:s for s in answer['evidence']} + assert answer['claims'] + assert all(c['quote'] in sources[c['source_id']]['text'] for c in answer['claims']) + assert report['answers'][4]['mode']=='abstained' + report.update(status='passed',checks={'saved_verdict_and_score':True,'score_not_accuracy':True, + 'real_local_qwen_explanations':2,'followup_with_quotes':True,'unsupported_root_cause_abstains':True, + 'scope':'five developer acceptance cases; not a general RAG accuracy benchmark'}) + path.write_text(json.dumps(report,indent=2)) + print(json.dumps(report['checks']),flush=True) diff --git a/scripts/verify_evidence_scope.py b/scripts/verify_evidence_scope.py new file mode 100644 index 0000000000000000000000000000000000000000..971baa5e7c7d67408408e6e653a48d5dd2437073 --- /dev/null +++ b/scripts/verify_evidence_scope.py @@ -0,0 +1,31 @@ +"""Real local RAG verification of the previously failing heatmap explanation.""" +import json +import time +import httpx +from backend.config import ROOT + +if __name__=='__main__': + report={'status':'running','answers':[]} + path=ROOT/'results'/'evidence_scope_verification.json' + try: + with httpx.Client(base_url='http://127.0.0.1:8766',timeout=120,trust_env=False) as client: + record=client.get('/api/inspections?category=pcb1').json()['data'][0] + report['inspection_id']=record['id'] + for question in ('What does this inspection heatmap show?','How does that map relate to anomaly scoring?'): + started=time.perf_counter() + response=client.post('/api/assistant',json={'inspection_id':record['id'],'question':question}) + response.raise_for_status();answer=response.json()['data'] + report['answers'].append({'question':question,'seconds':time.perf_counter()-started,**answer}) + path.write_text(json.dumps(report,indent=2)) + assert answer['mode']=='llm',answer + assert not any(d['id']=='dinomaly' for d in answer['evidence']) + assert any('cosine distance' in d['text'] for d in answer['evidence']) + for claim in answer['claims']: + source=next(d for d in answer['evidence'] if d['chunk_id']==claim['source_id']) + assert claim['quote'] in source['text'] + print(question,answer['answer'],flush=True) + report['status']='passed' + except Exception as exc: + report['status']='failed';report['failure']=str(exc) + raise + finally:path.write_text(json.dumps(report,indent=2)) diff --git a/scripts/verify_highres_application.py b/scripts/verify_highres_application.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf60682aab2d07d80702826584b0374c6e2baf5 --- /dev/null +++ b/scripts/verify_highres_application.py @@ -0,0 +1,62 @@ +"""Real isolated API/CPU/RAG acceptance of the installed high-resolution profile.""" +import json +from PIL import Image +from fastapi.testclient import TestClient +from backend.config import ROOT,CATEGORIES,Settings +from backend.main import create_app +from backend.highres import HighResolutionDetector +from backend.vision import sha256 +from scripts.benchmark_official import write + +if __name__=='__main__': + output=ROOT/'results/highres_application_verification.json' + report=json.loads(output.read_text()) if output.exists() else {'status':'running','examples':[],'answers':[]} + app=create_app(Settings(data=ROOT/'runtime/highres-acceptance',profile='dinov2_highres_v1')) + with TestClient(app) as client: + health=client.get('/api/health').json()['data'] + assert len(health['models'])==12 and all(c['model_id'].startswith('dinov2-highres-') for c in health['models']) + for category in CATEGORIES: + for label,truth in [('good',0),('anomalous',1)]: + if any(e['category']==category and e['truth']==truth for e in report['examples']):continue + sample=ROOT/'samples'/f'{category}_{label}.jpg' + response=client.post('/api/inspect',data={'category':category,'batch':'highres-acceptance'}, + files={'file':(sample.name,sample.read_bytes(),'image/jpeg')}) + response.raise_for_status();record=response.json()['data'] + assert record['model_id']==f'dinov2-highres-{category}-v1' + assert record['model_sha256']==sha256(ROOT/'models/highres'/f'{category}.npz') + assert record['calibration']['anomalous']==0 and 'PCA' in record['localization'] + for url in (record['image_url'],record['heatmap_url'],f"/api/inspections/{record['id']}/report"): + assert client.get(url).status_code==200 + actual=client.get('/api/inspections/'+record['id']).json()['data'] + assert actual['score']==record['score'] + 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')}}) + write(output,report);print(category+' '+label+' -> '+record['verdict']+' '+str(round(record['score'],5)),flush=True) + target=next(e for e in report['examples'] if e['category']=='macaroni2' and e['truth']==1) + questions=['Is this image anomalous?','Does the score mean accuracy?', + 'What does this saved inspection heatmap show?','How was this model threshold calibrated?', + 'What caused this defect?'] + for question in questions: + if any(a['question']==question for a in report['answers']):continue + response=client.post('/api/assistant',json={'inspection_id':target['id'],'question':question}) + response.raise_for_status();answer=response.json()['data'] + assert f"{target['score']:.5f}" in answer['answer'] + assert all(s.get('model_family')!='dinov3' for s in answer['evidence']) + report['answers'].append({'question':question,**answer});write(output,report) + print(question+' -> '+answer['mode'],flush=True) + assert all(a['mode']=='measurement_only' for a in report['answers'][:2]) + assert report['answers'][2]['mode']=='llm',report['answers'][2] + assert report['answers'][-1]['mode']=='abstained' + assert client.get('/api/evaluation').json()['data']['profile']=='dinov2_highres_v1' + official=client.get('/api/benchmark/official').json()['data'] + assert len(official['candidate']['categories'])==12 + assert target['id'] in client.get('/api/export.csv').text + if not report.get('cpu_smoke'): + cpu=HighResolutionDetector(Settings(device='cpu',profile='dinov2_highres_v1')) + with Image.open(ROOT/'samples/macaroni2_anomalous.jpg') as image:prediction,overlay=cpu.predict(image,'macaroni2') + assert prediction['device']=='cpu' and overlay.width>0 + report['cpu_smoke']={k:prediction[k] for k in ('model_id','score','verdict','inference_ms','device')} + report.update(status='passed',checks={'real_images':24,'all12_highres_profiles':True,'separate_normal_only_calibration':True, + 'images_reports_saved_records':True,'trusted_measurement_answers':2,'real_qwen_heatmap':True, + 'wrong_family_documents_excluded':True,'unsupported_cause_abstains':True,'cpu_smoke':True, + 'scope':'software/runtime acceptance on resized sample derivatives; not a new accuracy benchmark'}) + write(output,report);print(json.dumps(report['checks']),flush=True) diff --git a/scripts/verify_packaged.py b/scripts/verify_packaged.py new file mode 100644 index 0000000000000000000000000000000000000000..ac277a246b77548123fddbbbb8908134dfad2016 --- /dev/null +++ b/scripts/verify_packaged.py @@ -0,0 +1,58 @@ +"""Exercise an extracted archive's real API, weights and local RAG assets. +May be executed as a file from outside the extraction; imports are pinned to cwd. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import sys + +def main(): + parser=argparse.ArgumentParser();parser.add_argument('--output',type=Path,required=True) + args=parser.parse_args() + project=Path.cwd().resolve() + if not (project/'RELEASE_MANIFEST.json').exists():raise RuntimeError('Run inside a newly extracted release') + if (project/'runtime').exists():raise RuntimeError('Extraction already used; choose a fresh extraction') + os.environ['DEFECTRAG_ENCODER']=str(project/'models'/'encoder') + os.environ['DEFECTRAG_EMBEDDING']=str(project/'models'/'embedding') + os.environ['DEFECTRAG_DATA']=str(project/'runtime') + sys.path.insert(0,str(project)) + import backend.main as implementation + from backend.config import Settings + from fastapi.testclient import TestClient + assert Path(implementation.__file__).resolve().is_relative_to(project) + report={'status':'running','python':platform.python_version(),'loaded_from_extraction':True,'checks':{}} + try: + app=implementation.create_app(Settings(data=project/'runtime')) + with TestClient(app) as client: + report['checks']['dashboard']=client.get('/').status_code==200 + assert client.get('/api/inspections').json()['data']==[] + sample=project/'samples'/'pcb1_anomalous.jpg' + response=client.post('/api/inspect',data={'category':'pcb1','batch':'extracted-release'},files={'file':(sample.name,sample.read_bytes(),'image/jpeg')}) + response.raise_for_status();record=response.json()['data'] + expected='dinov2-tuned-' if (project/'models/highres_tuned/PROFILE.json').exists() else 'dinov2-highres-' if (project/'models/highres/PROFILE.json').exists() else 'dinov3-' + assert record['score']>=0 and record['model_id'].startswith(expected) + report['prediction']={k:record[k] for k in ('category','verdict','score','threshold','inference_ms','model_sha256')} + report['checks']['genuine_inference']=True + report['checks']['heatmap']=client.get(record['heatmap_url']).status_code==200 + report['checks']['saved_history']=client.get('/api/inspections').json()['data'][0]['id']==record['id'] + response=client.post('/api/assistant',json={'inspection_id':record['id'],'question':'What does this heatmap measure?'}) + response.raise_for_status();answer=response.json()['data'] + assert answer['mode']=='llm',answer + assert all(s['id']!='dinomaly' for s in answer['evidence']) + assert answer['claims'] + report['answer']=answer + report['checks']['bundled_retrieval_and_genuine_generation']=True + report['checks']['report']=client.get('/api/inspections/'+record['id']+'/report').status_code==200 + report['checks']['csv']=record['id'] in client.get('/api/export.csv').text + assert all(report['checks'].values()) + report['status']='passed' + print(json.dumps({'status':report['status'],'checks':report['checks'],'prediction':report['prediction']},indent=2),flush=True) + except Exception as exc: + report['status']='failed';report['error']=str(exc) + raise + finally: + args.output.parent.mkdir(parents=True,exist_ok=True) + args.output.write_text(json.dumps(report,indent=2)) +if __name__=='__main__':main() diff --git a/scripts/verify_showcase.py b/scripts/verify_showcase.py new file mode 100644 index 0000000000000000000000000000000000000000..d697e096b0433c5d93cedb86888a4cff1d9212fb --- /dev/null +++ b/scripts/verify_showcase.py @@ -0,0 +1,47 @@ +"""Verify snapshot provenance, privacy, asset closure and copied report resources.""" +import hashlib +import json +from pathlib import Path +import re + +ROOT = Path(__file__).resolve().parents[1] + + +def verify(): + output = ROOT / 'frontend/dist-static' + bundle = output / 'showcase' + manifest = json.loads((bundle / 'manifest.json').read_text()) + for name, expected in manifest['files'].items(): + path = (bundle / name).resolve() + assert path.is_relative_to(bundle.resolve()) + assert hashlib.sha256(path.read_bytes()).hexdigest() == expected, name + data = json.loads((bundle / 'data.json').read_text(encoding='utf-8')) + expected = {e['id']: e for e in json.loads((ROOT / 'results/acceptance.json').read_text())['real_images']} + scope = json.loads((ROOT / 'results/evidence_scope_verification.json').read_text()) + expected[scope['inspection_id']] = scope['answers'][0]['observation'] + extra=ROOT/'results/all_categories_acceptance.json' + if extra.exists():expected.update({e['id']:e for e in json.loads(extra.read_text())['real_images']}) + assert len(data['records']) == len(expected) + assert {r['id'] for r in data['records']} == set(expected) + for record in data['records']: + assert record['score'] == expected[record['id']]['score'] + assert record['verdict'] == expected[record['id']]['verdict'] + assert (output / record['image_url']).is_file() + assert (output / record['heatmap_url']).is_file() + report = bundle / 'reports' / (record['id'] + '.html') + for image in re.findall(r'src="([^"]+)"', report.read_text(encoding='utf-8')): + assert (report.parent / image).is_file() + text = (bundle / 'data.json').read_text(encoding='utf-8') + assert not re.search(r'localhost|127\.0\.0\.1|[A-Z]:\\\\|api[_-]?key|password|service_role', text, re.I) + for path in output.rglob('*'): + assert path.suffix not in {'.sqlite3', '.safetensors', '.pt', '.npz', '.env'} + assert any(m.get('mode') == 'llm' for messages in data['messages'].values() for m in messages) + receipt = {'status': 'passed', 'records': len(expected), 'snapshot_hashes': 'passed', + 'scores_match_saved_acceptance': True, 'report_images_exist': True, + 'saved_llm_conversation_present': True, 'no_private_paths_or_model_files': True} + (ROOT / 'results/static_verification.json').write_text(json.dumps(receipt, indent=2)) + print(json.dumps(receipt, indent=2)) + + +if __name__ == '__main__': + verify() diff --git a/scripts/verify_startup.py b/scripts/verify_startup.py new file mode 100644 index 0000000000000000000000000000000000000000..f544618bdff23e41f1572142c3e0e90b6a4888b7 --- /dev/null +++ b/scripts/verify_startup.py @@ -0,0 +1,18 @@ +import json +import platform +import importlib.metadata +from PIL import Image +from fastapi.testclient import TestClient +from backend.main import app + +if __name__=='__main__': + with TestClient(app) as client: + assert client.get('/api/health').status_code==200 + assert client.get('/').status_code==200 + sample=next((app.state.detector.settings.root/'samples').glob('*.jpg')) + result,_=app.state.detector.predict(Image.open(sample),sample.stem.rsplit('_',1)[0]) + assert result['score']>=0 + report={'startup':'passed','python':platform.python_version(),'torch':importlib.metadata.version('torch'), + 'transformers':importlib.metadata.version('transformers'),'real_model_prediction':result} + (app.state.detector.settings.root/'results'/'startup_verification.json').write_text(json.dumps(report,indent=2)) + print(json.dumps(report,indent=2)) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fd8eb07f2d71a09d34aebe2e3215c793313331fe --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""DefectRAG software and protocol checks.""" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..a1f25b5e5c9911b0890094896077e43c5a47386b --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,63 @@ +"""Shared pytest setup. + +A fresh GitHub clone (and the GitHub Actions CI run) has no model weights: they +are large and are downloaded separately with `python -m scripts.fetch_public_assets`. +Tests that build the full app need the local text-embedding model, so on such a +checkout they are skipped with a printed reason instead of failing. On a full +installation (models/embedding present) every test runs as before. +""" +from pathlib import Path +import os +import sys +import pytest + +# `import backend.main` normally builds the real application (detector and knowledge +# index) at import time. Tests build their own app with fakes through create_app(), +# so importing the module must not load model files. +os.environ.setdefault('DEFECTRAG_FACTORY_ONLY', '1') + +ROOT = Path(__file__).resolve().parents[1] +# DEFECTRAG_SIMULATE_CI=1 pretends the model files are absent, to reproduce the CI run locally. +HAS_MODELS = (ROOT / 'models' / 'embedding').is_dir() and os.getenv('DEFECTRAG_SIMULATE_CI') != '1' + +# Test files that create the whole application at import time. +NEEDS_MODELS = [] +# Single tests elsewhere that start the app. +NEEDS_MODELS_TESTS = { + 'test_calibration_policy.py::test_evaluation_endpoint_reports_the_active_policy', + 'test_macaroni_policy.py::test_public_evaluation_and_model_cards_agree_on_the_targeted_policy', +} + +collect_ignore = [] if HAS_MODELS else NEEDS_MODELS + + +@pytest.fixture +def client(tmp_path): + """A test client for an app that uses software fixtures instead of real models.""" + from fastapi.testclient import TestClient + from backend.config import Settings + from backend.main import create_app + from tests.test_application import SoftwareDetector, SoftwareWorkflow + app = create_app(Settings(data=tmp_path), SoftwareDetector(), SoftwareWorkflow()) + with TestClient(app) as test_client: + yield test_client + + +def pytest_report_header(config): + if not HAS_MODELS: + return 'models/embedding not found: %d app-level test files skipped (fresh clone / CI).' % len(NEEDS_MODELS) + + +# The Desktop sync script is a Windows operator tool (it defaults to a C:\ path). +WINDOWS_ONLY = {'test_desktop_sync.py'} + + +def pytest_collection_modifyitems(config, items): + no_models = pytest.mark.skip(reason='needs local model files (models/embedding); run on a full installation') + not_windows = pytest.mark.skip(reason='Windows-only Desktop sync tool') + for item in items: + name = item.nodeid.split('/')[-1] + if not HAS_MODELS and name in NEEDS_MODELS_TESTS: + item.add_marker(no_models) + if sys.platform != 'win32' and name.split('::')[0] in WINDOWS_ONLY: + item.add_marker(not_windows) diff --git a/tests/test_application.py b/tests/test_application.py new file mode 100644 index 0000000000000000000000000000000000000000..4a8d2ba8a3c5178587024ec535fa4e86c9bb01db --- /dev/null +++ b/tests/test_application.py @@ -0,0 +1,234 @@ +"""Isolated software tests. Fixtures below are NOT model-performance evidence.""" +from io import BytesIO +import json +import pytest +from PIL import Image +from fastapi.testclient import TestClient +from backend.main import create_app +from backend.config import Settings, ROOT +from backend.vision import ModelUnavailable +from backend.rag import EvidenceWorkflow + +def image_bytes(): + stream=BytesIO();Image.new('RGB',(100,80),'white').save(stream,format='PNG');return stream.getvalue() + +class SoftwareDetector: + def cards(self):return [] + def predict(self,image,category): + return {'category':category,'verdict':'Anomalous','score':.2,'threshold':.1,'uncertainty_margin':.005, + 'inference_ms':1,'model_id':'software-fixture','scope':'synthetic software fixture'},image +class SoftwareWorkflow: + def run(self,question,inspection,history=None): + return {'mode':'retrieval_only','answer':'Software fixture','evidence':[],'claims':[],'trace':['fixture']} + +def upload(client,**kwargs): + return client.post('/api/inspect',data={'category':'pcb1','batch':'LINE-A',**kwargs},files={'file':('input.png',image_bytes(),'image/png')}) + +def test_save_filter_alert_report_and_followup(client): + response=upload(client);assert response.status_code==200 + record=response.json()['data'];identifier=record['id'] + assert client.get('/api/inspections?batch=LINE-A').json()['data'][0]['id']==identifier + assert client.get('/api/inspections?batch=other').json()['data']==[] + assert client.get('/api/inspections?batch=%27%20OR%201=1--').json()['data']==[] + assert client.get(record['heatmap_url']).headers['content-type']=='image/jpeg' + assert 'score' in client.get(f'/api/inspections/{identifier}/report').text + alert=client.get('/api/alerts').json()['data'][0] + assert client.post(f"/api/alerts/{alert['id']}/acknowledge").status_code==200 + assert client.get('/api/alerts').json()['data'][0]['acknowledged']==1 + for question in ['Explain the result','What are its limits?']: + assert client.post('/api/assistant',json={'inspection_id':identifier,'question':question}).status_code==200 + assert len(client.get(f'/api/inspections/{identifier}/messages').json()['data'])==4 + assert client.get('/api/stats').json()['data']['total']==1 + assert identifier in client.get('/api/export.csv').text + +@pytest.mark.parametrize('category',['unknown','../pcb1','']) +def test_invalid_category(client,category): + assert upload(client,category=category).status_code==422 + assert client.get('/api/stats').json()['data']['total']==0 + +def test_invalid_image_and_no_persistence(client): + response=client.post('/api/inspect',data={'category':'pcb1'},files={'file':('bad.jpg',b'not an image','image/jpeg')}) + assert response.status_code==422 and 'error' in response.json() + assert client.get('/api/inspections').json()['data']==[] + +def test_model_failure_is_not_success(tmp_path): + class Failed(SoftwareDetector): + def predict(self,*args):raise ModelUnavailable('Missing model') + with TestClient(create_app(Settings(data=tmp_path),Failed(),SoftwareWorkflow())) as client: + assert upload(client).status_code==503 + assert client.get('/api/stats').json()['data']['failed_requests']==1 + assert client.get('/api/inspections').json()['data']==[] + assert client.get('/api/alerts').json()['data']==[] + +def test_upload_size_limit(client): + response=client.post('/api/inspect',data={'category':'pcb1'},files={'file':('big.png',b'x'*(10*1024*1024+1),'image/png')}) + assert response.status_code==413 + +def test_batch_partial_failure_and_filters(client): + response=client.post('/api/batch',data={'category':'pcb1','batch':'B-2'},files=[('files',('a.png',image_bytes(),'image/png')),('files',('b.jpg',b'bad','image/jpeg'))]) + result=response.json()['data'] + assert len(result['records'])==1 and len(result['errors'])==1 + assert len(client.get('/api/inspections?batch=B-2&verdict=Anomalous').json()['data'])==1 + +def test_report_escapes_metadata_and_csv_formula(client): + record=upload(client,batch='=HYPERLINK("bad")').json()['data'] + report=client.get(f"/api/inspections/{record['id']}/report").text + assert '' not in report + assert '<script>' in report + assert "'=HYPERLINK" in client.get('/api/export.csv').text + +def test_missing_record_and_path_traversal(client): + assert client.get('/api/inspections/'+'0'*32).status_code==404 + assert client.get('/api/samples/not-permitted.jpg').status_code==404 + +def test_persistence_across_application_restarts(tmp_path): + settings=Settings(data=tmp_path) + with TestClient(create_app(settings,SoftwareDetector(),SoftwareWorkflow())) as first: + identifier=upload(first).json()['data']['id'] + with TestClient(create_app(settings,SoftwareDetector(),SoftwareWorkflow())) as second: + assert second.get('/api/inspections/'+identifier).status_code==200 + +def test_graph_scope_gate_without_llm(): + class NeverRetrieve: + @property + def retriever(self):raise AssertionError('Unsupported intent must not call retrieval or generation') + workflow=EvidenceWorkflow(Settings(),NeverRetrieve()) + answer=workflow.run('What root cause caused this anomaly?',{'category':'pcb1'}) + assert answer['mode']=='abstained' and answer['trace']==['route','abstain'] + +def test_graph_rejects_fabricated_citation(): + workflow=EvidenceWorkflow(Settings(),None) + state={'mode':'llm','trace':[], 'raw_claims':[{'text':'invented','source_id':'missing','quote':'a made up quote'}], + 'evidence':[{'chunk_id':'real','text':'This is real supporting evidence.'}]} + result=workflow.validate_answer(state) + assert result['mode']=='retrieval_only' and result['claims']==[] + +def test_graph_accepts_traceable_claim(): + workflow=EvidenceWorkflow(Settings(),None) + text='The anomaly score is not a defect probability.' + result=workflow.validate_answer({'mode':'llm','trace':[],'evidence':[{'chunk_id':'real','text':text}], + 'raw_claims':[{'text':text,'source_id':'real','quote':text}]}) + assert result['mode']=='llm' and len(result['claims'])==1 + +def test_qwen_claim_schema_requires_supporting_quote(): + from backend.rag import GeneratedAnswer + from pydantic import ValidationError + with pytest.raises(ValidationError): + GeneratedAnswer.model_validate({'claims':[{'text':'A claim without evidence','source_id':'screening-2'}]}) + +@pytest.mark.parametrize('raw',['not-json','[]','{"claims": "invalid"}']) +def test_invalid_local_generation_returns_visible_fallback(monkeypatch,raw): + import httpx + import backend.rag as rag + class Client: + def __init__(self,**kwargs):pass + def __enter__(self):return self + def __exit__(self,*args):pass + def post(self,url,json): + assert isinstance(json['format'],dict) + return httpx.Response(200,json={'response':raw},request=httpx.Request('POST',url)) + monkeypatch.setattr(rag.httpx,'Client',Client) + workflow=EvidenceWorkflow(Settings(),None) + answer=workflow.generate({'inspection':{},'question':'Explain anomaly score','evidence':[{'chunk_id':'screening-2','text':'The anomaly score is not a probability.'}],'trace':[]}) + assert answer['mode']=='retrieval_only' and answer['error'] + +def test_missing_llm_keeps_retrieved_evidence(monkeypatch): + import httpx + import backend.rag as rag + class Client: + def __init__(self,**kwargs):pass + def __enter__(self):return self + def __exit__(self,*args):pass + def post(self,*args,**kwargs):raise httpx.ConnectError('Ollama offline') + monkeypatch.setattr(rag.httpx,'Client',Client) + workflow=EvidenceWorkflow(Settings(),None) + state={'inspection':{},'question':'Explain score','evidence':[{'chunk_id':'s','text':'The score is not a probability.'}],'trace':[]} + generated=workflow.generate(state) + answer=workflow.validate_answer({**state,**generated}) + assert answer['mode']=='retrieval_only' and answer['error'] + +def test_malformed_raw_claims_do_not_crash_validation(): + workflow=EvidenceWorkflow(Settings(),None) + answer=workflow.validate_answer({'mode':'llm','trace':[],'evidence':[],'raw_claims':{'unexpected':'object'}}) + assert answer['mode']=='retrieval_only' + +def test_quoted_passage_cannot_license_invented_number(): + workflow=EvidenceWorkflow(Settings(),None) + quote='Calibration uses 32 normal validation images.' + answer=workflow.validate_answer({'mode':'llm','trace':[],'evidence':[{'chunk_id':'real','text':quote}], + 'raw_claims':[{'quote':quote,'source_id':'real','text':'Calibration uses 500 images.'}]}) + assert answer['claims']==[] + +@pytest.mark.parametrize('question,expected',[ + ('What does this inspection heatmap show?', ['screening']), + ('Compare this detector with Dinomaly reconstruction.', ['dinomaly','screening'])]) +def test_evidence_must_apply_to_current_detector(question,expected): + workflow=EvidenceWorkflow(Settings(),None) + evidence=[{'id':identifier,'url':'project://test','license':'MIT','chunk_id':identifier+'-1','text':'Test passage'} for identifier in ('dinomaly','screening')] + result=workflow.validate_evidence({'question':question,'trace':[],'evidence':evidence}) + assert [d['id'] for d in result['evidence']]==expected + +def test_citation_number_is_not_an_invented_measurement(): + workflow=EvidenceWorkflow(Settings(),None) + quote='The heatmap displays the cosine distance to stored normal features.' + result=workflow.validate_answer({'mode':'llm','trace':[],'evidence':[{'chunk_id':'screening-4','text':quote}], + 'raw_claims':[{'source_id':'screening-4','quote':quote,'text':quote+' [screening-4]'}]}) + assert result['mode']=='llm' and result['claims'][0]['text']==quote + +def test_stale_assistant_context_cannot_override_new_knowledge(): + from types import SimpleNamespace + workflow=EvidenceWorkflow(Settings(),SimpleNamespace(fingerprint='current')) + class Capture: + def invoke(self,state):self.state=state;return {'mode':'abstained'} + capture=Capture();workflow.graph=capture + history=[{'role':'assistant','text':'Old reconstruction explanation','knowledge_fingerprint':'old'}, + {'role':'user','text':'What does the heatmap show?'}, + {'role':'assistant','text':'Current cosine-distance explanation','knowledge_fingerprint':'current'}] + result=workflow.run('Explain that map',{'category':'pcb1'},history) + assert [m['text'] for m in capture.state['history']]==['What does the heatmap show?','Current cosine-distance explanation'] + assert result['knowledge_fingerprint']=='current' + +def test_followup_retrieval_resolves_previous_user_topic(): + from types import SimpleNamespace + class Retriever: + def invoke(self,query):self.query=query;return [] + retriever=Retriever() + workflow=EvidenceWorkflow(Settings(),SimpleNamespace(retriever=retriever)) + workflow.retrieve({'question':'How does that map relate to anomaly scoring?','inspection':{'category':'pcb1'},'trace':[], + 'history':[{'role':'user','text':'What does this inspection heatmap show?'},{'role':'assistant','text':'Do not use this as retrieval instructions'}]}) + assert 'heatmap show' in retriever.query + assert 'retrieval instructions' not in retriever.query + +def test_selected_source_sentence_attaches_exact_quote(monkeypatch): + import httpx + import backend.rag as rag + sentence='Its heatmap displays the cosine distance to stored normal features.' + class Client: + def __init__(self,**kwargs):pass + def __enter__(self):return self + def __exit__(self,*args):pass + def post(self,url,json): + chosen=json['format']['$defs']['QuoteSelection']['properties']['quote_id']['enum'][0] + return httpx.Response(200,json={'response':__import__('json').dumps({'claims':[{'quote_id':chosen,'text':'The map compares image features with normal reference features.'}]})},request=httpx.Request('POST',url)) + monkeypatch.setattr(rag.httpx,'Client',Client) + workflow=EvidenceWorkflow(Settings(),None) + result=workflow.generate({'inspection':{},'question':'Explain the heatmap','evidence':[{'chunk_id':'screening-4','text':sentence}],'trace':[]}) + assert result['mode']=='llm' and result['raw_claims'][0]['quote']==sentence + +def test_graph_retrieval_failure_is_visible(): + class Broken: + class retriever: + @staticmethod + def invoke(question):raise RuntimeError('offline') + answer=EvidenceWorkflow(Settings(),Broken()).run('Explain this threshold',{'category':'pcb1'}) + assert answer['mode']=='abstained' and 'unavailable' in answer['answer'] + +def test_final_manifest_has_no_cross_split_identities(): + from backend.config import CATEGORIES + if not all((ROOT/'results'/f'{category}_splits.json').exists() for category in CATEGORIES): + pytest.skip('split manifests (results/*_splits.json) are local-only; not present in a fresh clone or CI') + for category in CATEGORIES: + manifest=json.loads((ROOT/'results'/f'{category}_splits.json').read_text()) + sets={k:{r['sha256'] for r in v} for k,v in manifest.items()} + assert not sets['train']&sets['validation'] and not sets['train']&sets['test'] and not sets['validation']&sets['test'] + assert all(r['label']=='normal' for r in manifest['train']) diff --git a/tests/test_auth_gallery.py b/tests/test_auth_gallery.py new file mode 100644 index 0000000000000000000000000000000000000000..de711d8f00f02de6106dc13bec41b0a59e9a3abf --- /dev/null +++ b/tests/test_auth_gallery.py @@ -0,0 +1,39 @@ +"""MFA-compatible public snapshots use authenticated bytes, never relative-URL fetches.""" +import pytest +from fastapi import HTTPException +from fastapi.testclient import TestClient +from backend.config import Settings +from backend.gallery import LocalGallery +from backend.main import create_app +from tests.test_application import SoftwareDetector,SoftwareWorkflow,image_bytes + + +class CloudFixture: + config={'auth_workflow_enabled':True} + cloud_config={'url':'https://fixture.invalid'} + staff={'role':'staff'} + user={'id':'fixture-owner'} + def __init__(self,owner='fixture-owner',denied=False):self.owner,self.denied,self.reads=owner,denied,[] + def current(self):return self + def get(self,identifier): + return {'id':identifier,'storage':'supabase_personal','owner_id':self.owner, + 'category':'pcb1','verdict':'Anomalous','score':.2,'threshold':.1, + 'image_url':'/api/inspections/'+identifier+'/image','heatmap_url':'/api/inspections/'+identifier+'/heatmap'} + def private_artifact(self,identifier,kind): + self.reads.append((identifier,kind)) + if self.denied:raise HTTPException(403,'Private artifact denied') + return image_bytes() + + +@pytest.mark.parametrize('owner,denied,expected',[('fixture-owner',False,200),('other-owner',False,403),('fixture-owner',True,403)]) +def test_authenticated_gallery_publication_preserves_owner_and_private_read_checks(tmp_path,owner,denied,expected): + repo=CloudFixture(owner,denied);gallery=LocalGallery(tmp_path/'gallery.sqlite3','a'*64) + app=create_app(Settings(data=tmp_path),SoftwareDetector(),SoftwareWorkflow(),repository=repo,gallery=gallery) + with TestClient(app) as client: + response=client.post('/api/inspections/'+'1'*32+'/publication',json={'consent':True}) + assert response.status_code==expected + if expected==200: + assert repo.reads==[('1'*32,'image'),('1'*32,'heatmap')] + item=client.get('/api/gallery/'+response.json()['data']['id']).json()['data'] + assert item['measurement']['score']==.2 and 'owner_id' not in item + else:assert gallery.read()==[] diff --git a/tests/test_auth_mfa.py b/tests/test_auth_mfa.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe64537c46cd96c4ec6748ead8e672cd37f0471 --- /dev/null +++ b/tests/test_auth_mfa.py @@ -0,0 +1,195 @@ +"""Offline boundary tests. No live Auth, email, SQL execution or model calls.""" +import ast +import re +from pathlib import Path +import pytest +from deployment.space.supabase_repository import StaffRepository, _staff_cache +from deployment.space.sessions import SessionRepository, identity + +CONFIG={'url':'https://fixture.invalid','key':'sb_publishable_fixture','auth_workflow_enabled':True} + +def posture(**overrides): + return dict(user_id='fixture-owner',role='staff',display_name='Staff fixture',approved=True, + revoked=False,authorized=True,mfa_required=True,aal2=True,**overrides) + + +def test_new_backend_flag_off_keeps_legacy_login_without_new_rpc(monkeypatch,tmp_path): + calls=[] + def request(self,method,path,**kwargs): + calls.append(path) + if path=='/auth/v1/user':return {'id':'legacy-staff-fixture'} + if path=='/rest/v1/staff_members':return [{'role':'staff','display_name':'Fixture'}] + raise AssertionError('Inactive features must not contact new RPCs') + monkeypatch.setattr(StaffRepository,'request',request) + repo=StaffRepository({**CONFIG,'auth_workflow_enabled':False},'legacy-test-unique',tmp_path) + assert repo.user['id']=='legacy-staff-fixture' + assert calls==['/auth/v1/user','/rest/v1/staff_members'] + + +@pytest.mark.parametrize('update',[ + {'approved':False}, {'revoked':True}, {'aal2':False}, {'authorized':False}, + {'role':'pending'}, {'role':None}, {'user_id':None}, {'mfa_required':None}, {'mfa_required':1}, +]) +def test_protected_accounts_fail_closed_for_bad_posture(monkeypatch,tmp_path,update): + monkeypatch.setattr(StaffRepository,'request',lambda *a,**k:{**posture(),**update}) + with pytest.raises(ValueError,match='authenticator'): + StaffRepository(CONFIG,'opaque-fixture',tmp_path) + + +def test_active_verified_account_passes_and_revocation_ignores_legacy_cache(monkeypatch,tmp_path): + state=posture();calls=[] + def request(self,method,path,**kwargs): + assert method=='POST' and path=='/rest/v1/rpc/defectrag_auth_status' and kwargs['json']=={} + calls.append(path);return state.copy() + monkeypatch.setattr(StaffRepository,'request',request) + token='revocation-software-fixture' + _staff_cache[token]=(10**15,{'id':'stale-user'},{'role':'developer'}) + try: + current=StaffRepository(CONFIG,token,tmp_path) + assert current.user['id']=='fixture-owner' and current.staff['role']=='staff' + state.update(approved=False,authorized=False,revoked=True) + with pytest.raises(ValueError):StaffRepository(CONFIG,token,tmp_path) + assert len(calls)==2 + finally:_staff_cache.pop(token,None) + + +def test_native_auth_outage_never_falls_through_to_guest(monkeypatch,tmp_path): + def fail(*args,**kwargs):raise RuntimeError('Supabase unavailable') + monkeypatch.setattr(StaffRepository,'request',fail) + repo=SessionRepository(tmp_path,CONFIG,tmp_path,personal_enabled=True) + with identity('a'*64,'expired-or-unavailable-fixture'): + with pytest.raises(RuntimeError,match='unavailable'):repo.current() + with identity('a'*64): + assert repo.list()==[] # explicit anonymous demo still works + + +def test_bootstrap_before_activation_accepts_approved_aal1_only_when_db_allows(monkeypatch,tmp_path): + monkeypatch.setattr(StaffRepository,'request',lambda *a,**k:{**posture(),'aal2':False,'mfa_required':False}) + assert StaffRepository(CONFIG,'bootstrap-fixture',tmp_path).staff['role']=='staff' + + +def test_private_images_generate_scoped_urls_not_signed_storage_links(tmp_path): + current=StaffRepository.__new__(StaffRepository);current.config=CONFIG + current.request=lambda *a,**k:pytest.fail('No signed URL request permitted') + row={'payload':{'id':'1'*32},'owner_id':'fixture-owner','image_path':'private/image','heatmap_path':'private/map'} + result=current.decorate(row) + assert result['image_url']=='/api/inspections/'+'1'*32+'/image' + assert result['heatmap_url'].endswith('/heatmap') and 'token=' not in str(result) + + +@pytest.mark.parametrize('status,length',[(403,7),(200,0),(200,10*1024*1024+1)],ids=['denied','empty','oversized']) +def test_private_artifact_denied_empty_and_oversized_response_rejected(monkeypatch,tmp_path,status,length): + content=b'x'*length + class Response: + is_success=status==200 + def __enter__(self):return self + def __exit__(self,*args):pass + def iter_bytes(self,**kwargs):yield content + class Client: + def __init__(self,**kwargs):pass + def __enter__(self):return self + def __exit__(self,*args):pass + def stream(self,*args,**kwargs):return Response() + monkeypatch.setattr('deployment.space.supabase_repository.httpx.Client',Client) + current=StaffRepository.__new__(StaffRepository);current.config=CONFIG;current.headers={} + current.raw=lambda identifier:{'image_path':'fixture-owner/id/image.jpg'} + with pytest.raises(ValueError):current.private_artifact('1'*32,'image') + + +def test_private_artifact_read_is_authenticated_under_correct_bucket(monkeypatch,tmp_path): + calls=[] + class Response: + is_success=True + def __enter__(self):return self + def __exit__(self,*args):pass + def iter_bytes(self,**kwargs):yield b'fixture-image' + class Client: + def __init__(self,**kwargs):pass + def __enter__(self):return self + def __exit__(self,*args):pass + def stream(self,*args,**kwargs):calls.append((args,kwargs));return Response() + monkeypatch.setattr('deployment.space.supabase_repository.httpx.Client',Client) + current=StaffRepository.__new__(StaffRepository);current.config=CONFIG;current.headers={'Authorization':'Bearer user-fixture'} + current.raw=lambda identifier:{'image_path':'fixture-owner/id/image.jpg'} + assert current.private_artifact('1'*32,'image')==b'fixture-image' + assert '/object/authenticated/team-inspections/' in calls[0][0][1] + assert calls[0][1]['headers']==current.headers + + +def sql_function(sql,name): + match=re.search(r'create (?:or replace )?function public\.'+name+r'\([^$]+?\$\$(.*?)\$\$;',sql,re.S|re.I) + assert match,name + return match.group(1) + + +def test_migration_inactive_and_privilege_matrix_is_explicit(): + sql=Path('deployment/supabase_auth_mfa.sql').read_text(encoding='utf8') + assert 'mfa_required boolean not null default false' in sql + assert 'registration_enabled boolean not null default false' in sql + assert not re.search(r'\b(delete|drop|truncate)\s',sql,re.I) + assert "auth.jwt()->>'aal'='aal2'" in sql and "f.factor_type='totp' and f.status='verified'" in sql + for name in ['defectrag_access_directory','defectrag_decide_access','defectrag_notification_status','defectrag_retry_notification']: + assert 'if not public.defectrag_can_manage_access()' in sql_function(sql,name) + for name in ['defectrag_claim_notifications','defectrag_finish_notification']: + assert "auth.role() is distinct from 'service_role'" in sql_function(sql,name) + configure=sql_function(sql,'defectrag_configure_auth') + assert 'Enroll and verify an active developer TOTP factor before enforcement' in configure + assert 'defectrag_configure_auth(boolean,boolean)' not in sql.split('grant execute on function')[-1] + for grant in re.findall(r'grant execute on function (.*?);',sql,re.S): + assert 'defectrag_configure_auth' not in grant + if 'defectrag_claim_notifications' in grant:assert grant.rstrip().endswith('to service_role') + assert 'create policy private_artifact_auth_guard on storage.objects as restrictive' in sql + assert "bucket_id not in ('team-inspections','personal-inspections')" in sql + assert 'defectrag_gallery_' not in sql + + +def test_sql_decisions_have_no_client_role_or_direct_browser_writes(): + sql=Path('deployment/supabase_auth_mfa.sql').read_text(encoding='utf8') + decide=sql_function(sql,'defectrag_decide_access') + assert "p_user_id=auth.uid()" in decide and 'p_version<>coalesce(r.version,0)' in decide + assert "pg_advisory_xact_lock(731902461)" in decide and "for update;" in decide + assert "values(p_user_id,r.display_name,'staff')" in decide + assert 'The last developer cannot be revoked' in decide + assert 'insert into public.staff_access_audit' in decide and 'insert into public.staff_notification_outbox' in decide + request=sql_function(sql,'defectrag_request_access') + assert 'email_confirmed_at is not null' in request and 'registration_enabled' in request + assert 'insert into public.staff_members' not in request + assert 'r.user_id is not null then return' in request + assert 'grant select on public.staff_access_requests,public.staff_access_audit to authenticated' in sql + assert not re.search(r'grant\s+(insert|update|delete|all)\b',sql,re.I) + + +def test_sql_outbox_claim_lease_retry_and_duplicate_constraints(): + sql=Path('deployment/supabase_auth_mfa.sql').read_text(encoding='utf8') + assert 'unique(subject_id,version,kind,recipient_id)' in sql + claim=sql_function(sql,'defectrag_claim_notifications') + assert 'for update skip locked' in claim and 'r.version=o.version' in claim + assert "status='superseded'" in claim and "status='dead'" in claim + assert 'lease_untilnow()' in finish + assert "when attempts>=8 then 'dead'" in finish and 'power(2,' in finish + + +def test_gradio_preflight_and_artifact_guards_remain_before_model_or_storage(): + # Parse source without importing the model-initializing host module. + source=Path('deployment/space/app.py').read_text(encoding='utf8');tree=ast.parse(source) + inspect=next(node for node in tree.body if isinstance(node,ast.FunctionDef) and node.name=='inspect') + body=ast.get_source_segment(source,inspect) + assert body.index('REPO.current()')alert(1)').json()['data'] + report=client.get(f'/api/inspections/{record["id"]}/report') + assert report.status_code==200 + for text in ('Inspection evidence report','Image and localization','Inspection measurements','Human review','Evidence conversation','Retrieved documentation','Print / save PDF','@media print','name="viewport"','not accuracy'): + assert text in report.text + assert '') + (dist/'assets/client.js').write_text('real compiled artifact fixture') + receipt={'schema':1,'protocol':1,'mode':'production', + 'sources':{n:hashlib.sha256((root/n).read_bytes()).hexdigest() for n in source_files(root)}, + 'files':{n:hashlib.sha256((dist/n).read_bytes()).hexdigest() for n in ('index.html','assets/client.js')}} + (dist/'local-ui-build.json').write_text(json.dumps(receipt)) + return dist + +def test_missing_or_stale_bundle_is_actionable_not_the_old_dashboard(tmp_path): + dist=tmp_path/'frontend/dist';app=FastAPI();mount_local_frontend(app,tmp_path,dist) + with TestClient(app) as client: + for endpoint in ('/','/index.html'): + result=client.get(endpoint) + assert result.status_code==503 and 'run_local.ps1' in result.text + assert result.headers['cache-control']=='no-store' + assert '/assets/' not in result.text + +def test_current_bundle_and_live_public_config_are_served(tmp_path): + dist=fixture_build(tmp_path);assert valid_local_build(tmp_path,dist) + app=FastAPI();mount_local_frontend(app,tmp_path,dist) + with TestClient(app) as client: + assert client.get('/').status_code==200 + config=client.get('/config.js') + assert 'authWorkflowEnabled = true' in config.text + assert config.headers['cache-control']=='no-store' + (tmp_path/'frontend/public/config.js').write_text('window.DEFECTRAG_PUBLIC_CONFIG={registrationEnabled:false};') + assert valid_local_build(tmp_path,dist),'public config is served live without a rebuild' + assert 'registrationEnabled:false' in client.get('/config.js').text + (tmp_path/'frontend/src/main.jsx').write_text('new incompatible source') + assert client.get('/').status_code==503 + +def test_modified_outputs_new_inputs_and_unsafe_receipts_fail_closed(tmp_path): + dist=fixture_build(tmp_path) + file=dist/'assets/client.js';before=file.read_bytes();file.write_text('stale compiled transport') + assert not valid_local_build(tmp_path,dist) + file.write_bytes(before);assert valid_local_build(tmp_path,dist) + receipt_file=dist/'local-ui-build.json';receipt=json.loads(receipt_file.read_text());receipt['mode']='showcase';receipt_file.write_text(json.dumps(receipt)) + assert not valid_local_build(tmp_path,dist),'a read-only showcase must not replace the inspection dashboard' + receipt['mode']='production';receipt_file.write_text(json.dumps(receipt)) + (tmp_path/'frontend/src/new.jsx').write_text('new source') + assert not valid_local_build(tmp_path,dist) + (tmp_path/'frontend/src/new.jsx').unlink() + receipt=json.loads((dist/'local-ui-build.json').read_text());receipt['files']['../outside.js']='a'*64 + (dist/'local-ui-build.json').write_text(json.dumps(receipt)) + assert not valid_local_build(tmp_path,dist) + receipt['sources']=sorted(receipt['sources']) + (dist/'local-ui-build.json').write_text(json.dumps(receipt)) + assert not valid_local_build(tmp_path,dist),'malformed receipt shows rebuild guidance, not a server error' diff --git a/tests/test_local_sync.py b/tests/test_local_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..24d7eb9a771e3c4d72dc7a8233586e9207ea1905 --- /dev/null +++ b/tests/test_local_sync.py @@ -0,0 +1,263 @@ +"""Software/transport fixtures only. No model, Supabase write or email calls.""" +import copy +import hashlib +import json +from pathlib import Path +import uuid +import pytest +from fastapi.testclient import TestClient +from backend.config import Settings +from backend.main import create_app +from backend.local_sync import LocalMirror,LocalSyncRepository,SyncEngine +from deployment.space.sessions import identity +from tests.test_application import SoftwareDetector,SoftwareWorkflow,image_bytes + +OWNER='11111111-1111-4111-8111-111111111111' +OTHER='22222222-2222-4222-8222-222222222222' + +def record(identifier='a'*32): + return {'id':identifier,'created_at':'2026-10-22T00:00:00+00:00','category':'pcb1','verdict':'Anomalous','batch':'SYNC-QA', + 'score':.2,'threshold':.1,'model_id':'software-fixture','request_fingerprint':'fixture-'+identifier} + +def mirror(tmp_path,owner=OWNER): + local=LocalMirror(tmp_path/owner/'inspection.sqlite3',owner,tmp_path/owner/'artifacts') + return local + +def save(local,identifier='a'*32): + for suffix in ('','_heatmap'):(local.artifacts/(identifier+suffix+'.jpg')).write_bytes(b'fixture-'+suffix.encode()) + return local.save(record(identifier)) + +class Cloud: + bucket='personal-inspections' + def __init__(self,owner=OWNER): + self.user={'id':owner};self.staff={'role':'staff','display_name':'QA owner'} + self.rows={};self.objects={};self.receipts={};self.calls=[];self.fail=False;self.lose_reply=False + def _upload(self,bucket,identifier,kind,path): + value=path.read_bytes();name=f'{self.user["id"]}/{identifier}/{kind}-{hashlib.sha256(value).hexdigest()}.jpg' + self.objects[name]=value;return name + def _read_private_image(self,path):return self.objects[path] + def request(self,method,path,**kwargs): + self.calls.append((method,path,kwargs)) + if self.fail:raise RuntimeError('Private fixture URL/token must not persist') + if path.endswith('defectrag_personal_sync_apply'): + p=kwargs['json'];op=p['p_operation'];identifier=p['p_id'];action=p['p_action'];data=p['p_data'] + if op in self.receipts:return self.receipts[op] + previous=self.rows.get(identifier) + if (action=='create' and previous) or (action!='create' and (not previous or previous['sync_version']!=p['p_base'])):return {'conflict':True} + if action=='create': + self.rows[identifier]={'id':identifier,'owner_id':self.user['id'],'created_at':data['record']['created_at'],'payload':data['record'], + 'image_path':data['image_path'],'heatmap_path':data['heatmap_path'],'conversation':[],'archived_at':None,'sync_version':1,'notes':[]} + else: + previous['sync_version']+=1 + if action=='conversation':previous['conversation'] += [{'role':'user','question':data['question']},{'role':'assistant',**data['answer']}] + if action=='acknowledge':previous['payload']['alert_acknowledged']=True + if action=='archive':previous['archived_at']='2026-10-22T01:00:00Z' + if action=='restore':previous['archived_at']=None + if action=='review':previous['notes'].append({'id':op,'inspection_id':identifier,'author_id':self.user['id'],'created_at':'2026-10-22T01:00:00Z','body':data['body']}) + answer={'version':self.rows[identifier]['sync_version']};self.receipts[op]=answer + if self.lose_reply:self.lose_reply=False;raise RuntimeError('Response lost after commit') + return answer + params=kwargs.get('params',{}) + if path.endswith('personal_inspections'): + assert params['owner_id']=='eq.'+self.user['id'] + values=list(self.rows.values()) + if 'id' in params: + operation,value=params['id'].split('.',1);values=[r for r in values if (r['id']==value if operation=='eq' else r['id']>value)] + return copy.deepcopy(sorted(values,key=lambda row:row['id'])[:int(params.get('limit',100))]) + if path.endswith('personal_notes'): + assert params['author_id']=='eq.'+self.user['id'] + offset=int(params.get('offset',0));limit=int(params.get('limit',1000)) + return copy.deepcopy(self.rows[params['inspection_id'][3:]]['notes'][offset:offset+limit]) + raise AssertionError('Unexpected/possibly shared-table request '+path) + +def due(local): + with local.connect() as db:db.execute("UPDATE sync_queue SET due=0 WHERE state='pending'") + +def test_local_write_and_queue_are_atomic_and_account_isolated(tmp_path): + a=mirror(tmp_path);b=mirror(tmp_path,OTHER);save(a) + assert a.get('a'*32)['owner_id']==OWNER and b.get('a'*32) is None + assert a.status()['pending']==1 and b.status()['pending']==0 + with a.connect() as db: + db.execute("CREATE TRIGGER deny_queue BEFORE INSERT ON sync_queue BEGIN SELECT RAISE(ABORT,'queue unavailable'); END") + with pytest.raises(Exception):save(a,'b'*32) + assert a.get('b'*32) is None + +def test_completed_local_inspection_uploads_privately_and_downloads_to_another_device(tmp_path): + a=mirror(tmp_path/'device-a');save(a);cloud=Cloud();first=SyncEngine(a,cloud).cycle() + b=mirror(tmp_path/'device-b');second=SyncEngine(b,cloud).cycle() + assert first['pending']==0 and second['state']=='synced' + assert b.get('a'*32)['score']==.2 and (b.artifacts/('a'*32+'.jpg')).read_bytes()==b'fixture-' + assert not any('shared_inspections' in path or 'team-inspections' in path for _,path,_ in cloud.calls) + assert b.status()['pending']==0,'Downloading must not enqueue its own upload' + +def test_response_loss_replays_operation_without_duplicate_cloud_records(tmp_path): + local=mirror(tmp_path);save(local);cloud=Cloud();cloud.lose_reply=True;engine=SyncEngine(local,cloud) + assert engine.cycle()['pending']==1 and len(cloud.rows)==1 + due(local);assert engine.cycle()['pending']==0 + assert len(cloud.receipts)==1 and len(cloud.rows)==1 + +def test_retry_backoff_survives_restart_and_never_records_credentials(tmp_path): + local=mirror(tmp_path);save(local);cloud=Cloud();cloud.fail=True + result=SyncEngine(local,cloud).cycle();assert result['pending']==1 + with local.connect() as db: + saved=dict(db.execute('SELECT * FROM sync_queue').fetchone()) + assert saved['attempts']==1 and saved['due']>0 and 'token' not in saved['error'] + reopened=mirror(tmp_path);assert reopened.status()['pending']==1 + before=len(cloud.calls);SyncEngine(reopened,cloud).cycle();assert len(cloud.calls)==before+1,'Only the pull may retry; queued operation is not due' + cloud.fail=False;due(reopened);assert SyncEngine(reopened,cloud).cycle()['pending']==0 + +def test_conversations_notes_alert_ack_archive_restore_replicate_without_echo(tmp_path): + local=mirror(tmp_path);save(local);cloud=Cloud();engine=SyncEngine(local,cloud);engine.cycle() + local.add_conversation('a'*32,'Explain the heatmap',{'answer':'Fixture answer'}) + local.add_review('a'*32,'Reviewed','Hold','QA note') + local.acknowledge('a'*32);local.archive();local.restore(['a'*32]) + for _ in range(6):engine.cycle() + assert local.status()['pending']==0 + remote=cloud.rows['a'*32] + assert len(remote['conversation'])==2 and len(remote['notes'])==1 and remote['archived_at'] is None + assert remote['payload']['alert_acknowledged'] is True + other=mirror(tmp_path/'second');SyncEngine(other,cloud).cycle() + assert other.messages('a'*32)[1]['answer']=='Fixture answer' + assert other.review_history('a'*32)[0]['decision']=='Hold' + assert other.alerts()[0]['acknowledged']==1 + remote['archived_at']='2026-10-22T02:00:00Z';remote['sync_version']+=1 + SyncEngine(other,cloud).cycle();assert other.get('a'*32) is None and len(other.list(archived=True))==1 + assert other.status()['pending']==0,'Remote archive never becomes a local restore operation' + +def test_conflict_retains_local_changes_until_explicit_resolution_with_backup(tmp_path): + local=mirror(tmp_path);save(local);cloud=Cloud();engine=SyncEngine(local,cloud);engine.cycle() + local.add_conversation('a'*32,'Keep this local question',{'answer':'Local draft'}) + cloud.rows['a'*32]['sync_version']+=1 + result=engine.cycle();assert result['state']=='conflict' + assert local.messages('a'*32)[0]['question']=='Keep this local question' + engine.resolve('a'*32,'cloud') + assert local.messages('a'*32)==[] and local.status()['conflicts']==[] + with local.connect() as db: + backup=json.loads(db.execute('SELECT snapshot FROM sync_conflict_backups').fetchone()[0]) + assert 'Local draft' in json.dumps(backup) + +def test_explicit_local_retry_can_rebase_but_cannot_replace_an_immutable_id_collision(tmp_path): + local=mirror(tmp_path);save(local);cloud=Cloud();engine=SyncEngine(local,cloud);engine.cycle() + local.add_conversation('a'*32,'Question after cloud edit',{'answer':'Kept'}) + cloud.rows['a'*32]['sync_version']+=1;engine.cycle();engine.resolve('a'*32,'retry_local');engine.cycle() + assert cloud.rows['a'*32]['conversation'][1]['answer']=='Kept' + fresh=mirror(tmp_path/'collision');save(fresh);collision=SyncEngine(fresh,cloud);collision.cycle() + with pytest.raises(ValueError,match='cannot be rebased'):collision.resolve('a'*32,'retry_local') + assert fresh.status()['conflicts'] + +def test_cloud_artifact_corruption_or_wrong_owner_never_enters_local_database(tmp_path): + first=mirror(tmp_path/'a');save(first);cloud=Cloud();SyncEngine(first,cloud).cycle() + cloud.objects[cloud.rows['a'*32]['image_path']]=b'corrupted' + other=mirror(tmp_path/'b');assert SyncEngine(other,cloud).cycle()['state']=='unavailable' + assert other.get('a'*32) is None + cloud.rows['a'*32]['owner_id']=OTHER + assert SyncEngine(other,cloud).cycle()['state']=='unavailable' and other.get('a'*32) is None + +def test_pagination_is_resumable_and_covers_more_than_one_page(tmp_path): + first=mirror(tmp_path/'a');cloud=Cloud();engine=SyncEngine(first,cloud) + for i in range(7):save(first,f'{i:032x}') + for _ in range(3):engine.cycle(maximum=3) + other=mirror(tmp_path/'b');pull=SyncEngine(other,cloud) + assert pull.cycle(maximum=3)['scan_in_progress'];assert len(other.list())==3 + pull.cycle(maximum=3);assert len(other.list())==6 + assert not pull.cycle(maximum=3)['scan_in_progress'];assert len(other.list())==7 + +def test_failing_earlier_record_does_not_starve_other_pending_inspections(tmp_path): + local=mirror(tmp_path);save(local);save(local,'b'*32);cloud=Cloud();cloud.fail=True + SyncEngine(local,cloud).cycle(maximum=1);cloud.fail=False + SyncEngine(local,cloud).cycle(maximum=1) + assert 'b'*32 in cloud.rows and 'a'*32 not in cloud.rows + +def test_live_auth_boundary_never_trusts_owner_from_browser_or_reuses_other_accounts(monkeypatch,tmp_path): + def authorize(self,config,token,artifacts): + if token in ('pending','aal1','revoked'):raise ValueError('Denied') + if token=='outage':raise RuntimeError('Account server unavailable') + self.user={'id':OWNER if token=='owner' else OTHER};self.staff={'role':'staff','display_name':'QA'} + monkeypatch.setattr('deployment.space.personal_repository.PersonalRepository.__init__',authorize) + repo=LocalSyncRepository(tmp_path,{'url':'https://fixture.invalid','key':'public','auth_workflow_enabled':True},tmp_path/'legacy-artifacts') + repo.artifacts.mkdir() + with identity('a'*64,'owner'),repo.bind(): + save(repo.current());assert len(repo.list())==1 + with identity('a'*64,'other'),repo.bind():assert repo.get('a'*32) is None + with identity('a'*64),repo.bind():assert repo.get('a'*32) is None,'No fallback from personal account to unassigned legacy history' + for token in ('pending','aal1','revoked','outage'): + with identity('a'*64,token),pytest.raises((ValueError,RuntimeError)): + with repo.bind():pytest.fail('Unauthorized repository exposed') + +def test_loopback_adapter_preserves_default_and_denies_untrusted_origins(monkeypatch,tmp_path): + monkeypatch.delenv('DEFECTRAG_LOCAL_SYNC',raising=False) + repo=LocalSyncRepository(tmp_path,{'url':'https://fixture.invalid','key':'public'},tmp_path/'artifacts') + with TestClient(create_app(Settings(data=tmp_path),SoftwareDetector(),SoftwareWorkflow(),repository=repo)) as client: + assert client.get('/api/health').json()['data']['local_sync_enabled'] is True + headers={'X-DefectRAG-Session':'a'*64,'Origin':'https://untrusted.invalid'} + assert client.post('/api/local-sync/run',headers=headers).status_code==403 + assert client.post('/api/local-sync/run',headers={'X-DefectRAG-Session':'a'*64}).status_code==403 + assert client.get('/api/stats').status_code==401 + assert client.get('/api/batch-name?name=QA').status_code==401 + assert client.get('/api/batch-name?name=QA',headers={'X-DefectRAG-Session':'a'*64,'X-DefectRAG-Workspace':'team'}).status_code==403 + assert client.get('/api/batch-name?name=QA',headers={'X-DefectRAG-Session':'a'*64}).json()['data']=={'available':True} + response=client.get('/api/stats',headers={'X-DefectRAG-Session':'a'*64}) + assert response.status_code==200 and response.headers['Cache-Control']=='private, no-store' + +def test_legacy_history_requires_explicit_import_and_preserves_unverified_review_provenance(monkeypatch,tmp_path): + def authorize(self,config,token,artifacts):self.user={'id':OWNER};self.staff={'role':'staff','display_name':'Owner'} + monkeypatch.setattr('deployment.space.personal_repository.PersonalRepository.__init__',authorize) + repo=LocalSyncRepository(tmp_path,{'url':'https://fixture.invalid'},tmp_path/'artifacts');repo.artifacts.mkdir() + for suffix in ('','_heatmap'):(repo.artifacts/('a'*32+suffix+'.jpg')).write_bytes(b'legacy-fixture') + repo.legacy.save(record());repo.legacy.add_conversation('a'*32,'Old local question',{'answer':'Old answer'}) + repo.legacy.add_review('a'*32,'Reviewed','Hold','Original operator unknown') + with identity('a'*64,'owner'),repo.bind(): + assert repo.get('a'*32) is None + assert repo.import_legacy(['a'*32])['imported']==1 + assert repo.import_legacy(['a'*32])['imported']==0 + assert repo.get('a'*32)['import_provenance'].startswith('Explicit import') + assert repo.messages('a'*32)[1]['answer']=='Old answer' + assert repo.review_history('a'*32)==[],'Do not turn an unverified imported review into an authenticated decision' + assert 'original identity unverified' in repo.review_notes('a'*32)[0]['body'] + assert repo.current().status()['pending']==3 + assert repo.legacy.get('a'*32) is not None + +def test_local_authenticated_api_inference_routes_artifacts_to_owner_folder(monkeypatch,tmp_path): + def authorize(self,config,token,artifacts): + if token!='approved':raise ValueError('MFA denied') + self.user={'id':OWNER};self.staff={'role':'staff','display_name':'Owner'} + monkeypatch.setattr('deployment.space.personal_repository.PersonalRepository.__init__',authorize) + repo=LocalSyncRepository(tmp_path,{'url':'https://fixture.invalid'},tmp_path/'artifacts') + headers={'X-DefectRAG-Session':'b'*64,'Authorization':'Bearer approved'} + with TestClient(create_app(Settings(data=tmp_path),SoftwareDetector(),SoftwareWorkflow(),repository=repo)) as client: + result=client.post('/api/inspect',headers=headers,data={'category':'pcb1'},files={'file':('fixture.png',image_bytes(),'image/png')}) + assert result.status_code==200 + row=result.json()['data'];assert row['owner_id']==OWNER and 'access=' in row['image_url'] + assert client.get(row['image_url']).status_code==200 + assert (tmp_path/'local-sync/accounts'/OWNER/'artifacts'/(row['id']+'.jpg')).exists() + assert client.get('/api/inspections',headers={'X-DefectRAG-Session':'c'*64}).json()['data']==[] + denied={**headers,'Authorization':'Bearer aal1'} + assert client.get('/api/inspections',headers=denied).status_code==403 + +def test_migration_is_additive_owner_mfa_checked_and_has_revision_idempotency(): + sql=Path('deployment/supabase_personal_sync.sql').read_text() + assert 'defectrag_is_staff()' in sql and 'auth.uid()' in sql and 'security definer set search_path' in sql + assert 'r.owner_id<>auth.uid()' in sql and 'r.sync_version<>p_base' in sql + assert 'request_hash<>fingerprint' in sql and 'pg_advisory_xact_lock' in sql + assert 'alter table public.personal_inspections add column' in sql + assert not any(value in sql.lower() for value in ('delete from','drop table','disable row level','shared_inspections','notification_automation')) + +def test_existing_cloud_factory_does_not_resolve_an_account_during_startup(monkeypatch,tmp_path): + from deployment.space.sessions import SessionRepository + monkeypatch.delenv('DEFECTRAG_LOCAL_SYNC',raising=False) + cloud=SessionRepository(tmp_path/'sessions',cloud_config={'url':'https://fixture.invalid'},artifacts=tmp_path/'artifacts',personal_enabled=True) + app=create_app(Settings(data=tmp_path),SoftwareDetector(),SoftwareWorkflow(),repository=cloud) + with TestClient(app) as client:assert client.get('/api/health').json()['data']['local_sync_enabled'] is False + +def test_personal_note_history_download_is_paginated_not_silently_truncated(tmp_path): + first=mirror(tmp_path/'a');save(first);cloud=Cloud();SyncEngine(first,cloud).cycle() + cloud.rows['a'*32]['notes']=[{'id':str(uuid.uuid4()),'inspection_id':'a'*32,'author_id':OWNER,'body':'Fixture note '+str(i),'created_at':'2026-10-22T00:00:00Z'} for i in range(201)] + other=mirror(tmp_path/'b');SyncEngine(other,cloud).cycle() + assert len(other.review_notes('a'*32))==201 + assert any(call[2].get('params',{}).get('offset')=='200' for call in cloud.calls) + +def test_opt_in_local_mirror_preserves_enabled_local_community_gallery(monkeypatch,tmp_path): + monkeypatch.setenv('DEFECTRAG_GALLERY_ENABLED','1') + repo=LocalSyncRepository(tmp_path,{'url':'https://fixture.invalid'},tmp_path/'artifacts') + with TestClient(create_app(Settings(data=tmp_path),SoftwareDetector(),SoftwareWorkflow(),repository=repo)) as client: + assert client.get('/api/gallery').json()['data']=={'enabled':True,'items':[]} diff --git a/tests/test_macaroni_policy.py b/tests/test_macaroni_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..71a0401b05d6267b5a985071f48a0ed4e9c70076 --- /dev/null +++ b/tests/test_macaroni_policy.py @@ -0,0 +1,83 @@ +"""Protect the two-product boundary and consistency of the shipped recall policy.""" +from copy import deepcopy +import json +from pathlib import Path +import pytest +from backend.calibration import active_evaluation, calibrated_card, MACARONI_FILENAME +from scripts.audit_recall import metrics, quantile + +ROOT=Path(__file__).resolve().parents[1] + + +@pytest.fixture +def manifests(tmp_path,monkeypatch): + monkeypatch.delenv('DEFECTRAG_CALIBRATION',raising=False) + (tmp_path/'results').mkdir() + names=['highres_deployment_evaluation.json','sensitive_deployment_evaluation.json',MACARONI_FILENAME] + values=[] + for name in names: + value=json.loads((ROOT/'results'/name).read_text());values.append(value) + (tmp_path/'results'/name).write_text(json.dumps(value)) + return tmp_path,*values + + +def test_default_changes_only_macaroni_cards_and_preserves_previous_manifest(manifests): + root,baseline,previous,candidate=manifests + before=deepcopy(previous) + result=active_evaluation(root,baseline) + assert result==candidate + for category,old in previous['categories'].items(): + card=calibrated_card(root,baseline['categories'][category]) + assert card==result['categories'][category] + if category in ('macaroni1','macaroni2'): + assert card['threshold']=(.85 if category=='macaroni1' else .8) + + +def test_public_evaluation_and_model_cards_agree_on_the_targeted_policy(manifests): + from backend.config import Settings + from backend.main import create_app + from fastapi.testclient import TestClient + root,baseline,_,candidate=manifests + class Metadata: + profile_name='dinov2_highres_v1' + def cards(self):return [calibrated_card(root,c) for c in baseline['categories'].values()] + with TestClient(create_app(Settings(root=root,data=root/'runtime'),detector=Metadata(),workflow=object())) as client: + assert client.get('/api/evaluation').json()['data']==candidate + cards={c['category']:c for c in client.get('/api/models').json()['data']} + assert cards==candidate['categories'] diff --git a/tests/test_official_protocol.py b/tests/test_official_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..89fb12e6dd1a20b048e9c6f9e0a1efd563cad6e4 --- /dev/null +++ b/tests/test_official_protocol.py @@ -0,0 +1,42 @@ +import json +from pathlib import Path +import numpy as np +from sklearn.metrics import auc +from scripts.benchmark_official import pixel_metrics + + +def test_vectorized_pixel_metric_matches_reference_threshold_scan_with_ties(): + truth=np.array([False,False,True,True,False,True,False]) + scores=np.array([.1,.2,.2,.8,.8,.9,.1],dtype=np.float32) + positive=scores[truth] + thresholds=np.sort(np.r_[np.percentile(positive,np.linspace(100,0,100)), + np.linspace(positive.max(),positive.min(),100),float(scores.min())-1e-8,float(scores.max())+1e-8])[::-1] + fpr=[];recall=[];precision=[] + for threshold in thresholds: + predicted=scores.astype(np.float64)>threshold + tp=np.sum(predicted&truth);fp=np.sum(predicted&~truth) + recall.append(tp/truth.sum());fpr.append(fp/(~truth).sum()) + precision.append(tp/(tp+fp) if tp+fp else 1) + actual=pixel_metrics(truth,scores) + assert abs(actual['pixel_auroc']-auc(fpr,recall))<1e-12 + assert abs(actual['pixel_au_pr']-auc(recall,precision))<1e-12 + + +def test_official_report_uses_all_official_identities_and_no_anomalous_calibration(): + root=Path(__file__).resolve().parents[1] + report=json.loads((root/'results/official_evaluation.json').read_text()) + assert len(report['categories'])==12 + for category,metrics in report['categories'].items(): + directory=root/'experiments/official_visa_v1'/category + if not directory.exists():continue # Banks/manifests are a separate optional experiment artifact. + split=json.loads((directory/'split.json').read_text()) + assert len(split['train'])==metrics['official_train_normals'] + assert len(split['test'])==metrics['official_test_images'] + assert all(r['split']=='train' and r['label']=='normal' for r in split['train']) + assert all(r['split']=='test' for r in split['test']) + assert sum(r['label']!='normal' for r in split['test'])==100 + assert [r['seed'] for r in metrics['benchmark_runs']]==[42,43,44] + holdout=json.loads((directory/'normal_calibration.json').read_text()) + assert holdout['threshold']==max(p['score'] for p in holdout['predictions']) + train_names={r['image'] for r in split['train']} + assert all(p['image'] in train_names for p in holdout['predictions']) diff --git a/tests/test_personal_workspace.py b/tests/test_personal_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..5174db32a5f2139ef8d6f576ba3c5ab6c7f3751e --- /dev/null +++ b/tests/test_personal_workspace.py @@ -0,0 +1,242 @@ +"""Repository and scope software tests; not evidence that live RLS passed.""" +import base64 +import json +import httpx +from pathlib import Path +import pytest +from deployment.space.sessions import identity,SessionRepository,WORKSPACE,capability,authorize_artifact,artifact_workspace +from deployment.space.supabase_repository import StaffRepository +from deployment.space.personal_repository import PersonalRepository + + +def record(): + return {'id':'1'*32,'created_at':'2026-10-19T00:00:00Z','category':'pcb1','batch':'SOFTWARE', + 'verdict':'Anomalous','score':.2,'threshold':.1,'request_fingerprint':'fixture-content-hash'} + + +def repository(tmp_path): + repo=PersonalRepository.__new__(PersonalRepository) + repo.config={'url':'https://example.invalid','key':'public-fixture'} + repo.user={'id':'owner-A'};repo.staff={'role':'staff','display_name':'Owner A'};repo.artifacts=tmp_path + for suffix in ('','_heatmap'):(tmp_path/('1'*32+suffix+'.jpg')).write_bytes(b'fixture-'+suffix.encode()) + calls=[];rows={} + def request(method,path,**kwargs): + calls.append((method,path,kwargs)) + if path=='/rest/v1/personal_inspections': + if method=='GET': + assert kwargs['params']['owner_id']=='eq.owner-A' + return [rows['1'*32]] if rows else [] + rows[kwargs['json']['id']]=kwargs['json'];return None + if '/object/sign/' in path:return {'signedURL':'/object/sign/private?token=fixture'} + return None + repo.request=request + return repo,calls,rows + + +def test_authenticated_default_personal_and_explicit_team_are_distinct(monkeypatch,tmp_path): + def initialize(self,*args):self.user={'id':'owner'};self.staff={'role':'staff'} + monkeypatch.setattr(StaffRepository,'__init__',initialize) + repo=SessionRepository(tmp_path,cloud_config={'url':'https://example.invalid','key':'public'},artifacts=tmp_path,personal_enabled=True) + with identity('a'*64,'valid-fixture-token'): + assert isinstance(repo.current(),PersonalRepository) + with identity('a'*64,'valid-fixture-token','team'): + current=repo.current();assert type(current) is StaffRepository and current.workspace_stats_enabled + with identity('a'*64,workspace='team'): + with pytest.raises(ValueError,match='Sign in'):repo.current() + + +def test_capability_cannot_be_reinterpreted_in_another_scope(): + with identity('a'*64,workspace='personal'): + token=capability('1'*32,'report') + assert artifact_workspace(token)=='personal' + raw=base64.urlsafe_b64decode(token+'='*(-len(token)%4)).decode().replace(':personal:',':team:') + tampered=base64.urlsafe_b64encode(raw.encode()).decode().rstrip('=') + with pytest.raises(ValueError):authorize_artifact(tampered,'1'*32,'report') + assert WORKSPACE.get()=='personal' + + +def test_personal_save_is_verified_private_and_replay_does_not_reupload(tmp_path): + repo,calls,rows=repository(tmp_path) + first=repo.save(record());uploads=[c for c in calls if '/object/personal-inspections/' in c[1]] + assert len(uploads)==2 and all(c[2]['ignore_conflict'] for c in uploads) + assert first['storage']=='supabase_personal' and first['owner_id']=='owner-A' + before=len(calls);second=repo.save(record()) + assert second['id']==first['id'] + assert not any('/object/personal-inspections/' in c[1] for c in calls[before:]) + assert len(rows)==1 + with pytest.raises(ValueError,match='different data'):repo.save({**record(),'request_fingerprint':'changed'}) + + +def test_personal_storage_failure_never_inserts_or_reports_success(tmp_path): + repo,calls,rows=repository(tmp_path);original=repo.request + def failing(method,path,**kwargs): + if '/storage/v1/object/personal-inspections/' in path:raise RuntimeError('Storage quota reached') + return original(method,path,**kwargs) + repo.request=failing + with pytest.raises(RuntimeError,match='quota'):repo.save(record()) + assert not rows + + +def test_archived_or_conflicting_record_never_silently_overwritten(tmp_path): + repo,_,rows=repository(tmp_path);repo.save(record());rows['1'*32]['archived_at']='2026-10-19T01:00:00Z' + with pytest.raises(ValueError,match='archived'):repo.save(record()) + + +def test_personal_conversations_and_ack_use_owner_action_rpc(tmp_path): + repo,calls,_=repository(tmp_path) + repo.add_conversation('1'*32,'Explain this result',{'answer':'software fixture'}) + repo.acknowledge('1'*32) + assert all(c[1]=='/rest/v1/rpc/defectrag_personal_action' for c in calls) + assert calls[0][2]['json']['p_action']=='conversation' and calls[1][2]['json']['p_action']=='acknowledge' + + +def test_personal_archive_restore_and_aggregate_stats_stay_in_scope(tmp_path): + repo,calls,_=repository(tmp_path);repo.raw_list=lambda *a,**k:[{'id':'1'*32}] + repo.archive();repo.restore(['1'*32]);repo.stats() + assert calls[0][2]['json']=={'p_ids':['1'*32],'p_restore':False} + assert calls[1][2]['json']['p_restore'] is True + assert calls[2][2]['json']=={'p_scope':'personal'} + + +def test_expired_account_never_falls_back_to_guest(monkeypatch,tmp_path): + def expired(*args):raise ValueError('Staff session expired') + monkeypatch.setattr(StaffRepository,'__init__',expired) + repo=SessionRepository(tmp_path,cloud_config={'url':'https://example.invalid'},artifacts=tmp_path,personal_enabled=True) + with identity('a'*64,'expired-token'): + with pytest.raises(ValueError,match='expired'):repo.current() + + +def test_owner_privacy_migration_has_no_developer_bypass_or_gallery_changes(): + sql=Path('deployment/supabase_personal_workspace.sql').read_text(encoding='utf-8') + assert 'owner_id=auth.uid()' in sql and 'personal-inspections' in sql + assert 'grant select,insert on public.personal_inspections' in sql + assert 'grant update' not in sql.lower() and 'drop ' not in sql.lower() + assert 'defectrag_gallery_' not in sql + assert 'for update;' in sql and 'defectrag_is_developer()' not in sql + assert "set search_path=''" in sql + + +@pytest.mark.parametrize('status,code,ignored',[(400,'Duplicate',True),(409,'23505',True),(400,'InvalidRequest',False),(403,'AccessDenied',False)]) +def test_only_real_duplicate_conflicts_are_safe_to_replay(monkeypatch,status,code,ignored): + class Reply: + is_success=False + status_code=status + def json(self):return {'code':code} + class Client: + def __init__(self,**kwargs):pass + def __enter__(self):return self + def __exit__(self,*args):pass + def request(self,*args,**kwargs):return Reply() + monkeypatch.setattr('deployment.space.supabase_repository.httpx.Client',Client) + repo=StaffRepository.__new__(StaffRepository);repo.headers={};repo.config={'url':'https://invalid.example'} + if ignored:assert repo.request('POST','/storage/v1/object/test',ignore_conflict=True) is None + else: + with pytest.raises((RuntimeError,ValueError)):repo.request('POST','/storage/v1/object/test',ignore_conflict=True) + + +def test_guest_save_is_explicit_and_preserves_review_provenance(monkeypatch,tmp_path): + saved={};notes=[];shares=[] + class Personal: + def __init__(self,*args):self.user={'id':'approved-owner'} + def raw(self,identifier):return saved.get(identifier) + def save(self,value,conversation=None):saved[value['id']]=value + def request(self,*args,**kwargs):notes.append(kwargs['json']) + def share(self,identifier,include):shares.append((identifier,include));return {'alreadyShared':False} + monkeypatch.setattr('deployment.space.personal_repository.PersonalRepository',Personal) + repo=SessionRepository(tmp_path,cloud_config={'url':'https://invalid.example'},artifacts=tmp_path,personal_enabled=True) + with identity('a'*64): + repo.save(record());repo.add_review('1'*32,'Reviewed','Hold','Guest review') + assert not saved and not shares + with identity('a'*64,'fixture-approved-token'): + assert repo.share('1'*32,personal_only=True)=={'saved':True} + assert not shares and notes[0]['author_id']=='approved-owner' + assert 'original identity unverified' in notes[0]['body'] and 'Hold' in notes[0]['body'] + repo.share('1'*32,personal_only=True);assert notes[0]['id']==notes[1]['id'] + repo.share('1'*32);assert shares==[('1'*32,False)] + assert repo.local().review_history('1'*32)[0]['decision']=='Hold' + + +def test_cloud_archive_cannot_resurface_through_old_guest_copy(tmp_path): + repo=SessionRepository(tmp_path,cloud_config={'url':'https://invalid.example'},artifacts=tmp_path,personal_enabled=True) + class ArchivedPersonal: + def raw(self,identifier):return None + def _raw_any(self,identifier):return {'id':identifier,'archived_at':'2026-10-19'} + def get(self,identifier):return None + with identity('a'*64):repo.save(record()) + with identity('a'*64,'valid-test-token'): + repo.current=lambda:ArchivedPersonal() + assert repo.get('1'*32) is None + + +def test_guest_conversation_import_limit_preserves_content_and_precedes_uploads(tmp_path): + repo,calls,rows=repository(tmp_path) + messages=[{'question':'a'*39982}] + assert len(json.dumps(messages).encode())==40000 + repo.save(record(),messages) + assert rows['1'*32]['conversation']==messages + calls.clear() + with pytest.raises(ValueError,match='too large'): + repo.save(record(),[{'question':'a'*39983}]) + assert calls==[] + + +@pytest.mark.parametrize('failure',['denied','empty','oversize','network','interrupted']) +def test_private_image_copy_failure_never_uploads_or_calls_share_rpc(monkeypatch,tmp_path,failure): + repo,calls,_=repository(tmp_path);repo.headers={'Authorization':'Bearer software-fixture'} + repo.raw=lambda identifier:{'image_path':'owner-A/source.jpg'} + class Reply: + is_success=failure!='denied' + def __enter__(self):return self + def __exit__(self,*args):pass + def iter_bytes(self,**kwargs): + if failure=='interrupted': + yield b'partial' + raise httpx.ReadError('sensitive upstream URL must not be returned') + if failure=='oversize':yield b'a'*(10*1024*1024+1) + class Client: + def __init__(self,**kwargs):assert kwargs['trust_env'] is False + def __enter__(self):return self + def __exit__(self,*args):pass + def stream(self,*args,**kwargs): + if failure=='network':raise httpx.ConnectError('sensitive upstream URL must not be returned') + return Reply() + monkeypatch.setattr('deployment.space.personal_repository.httpx.Client',Client) + with pytest.raises(RuntimeError) as error:repo.share('1'*32) + assert 'sensitive' not in str(error.value) + assert all(method=='GET' for method,_,_ in calls) + + +def test_explicit_team_copy_sends_only_authorized_bytes_and_conversation_choice(monkeypatch,tmp_path): + repo,calls,_=repository(tmp_path);repo.headers={'Authorization':'Bearer software-fixture'} + repo.raw=lambda identifier:{'image_path':'owner-A/image.jpg','heatmap_path':'owner-A/heatmap.jpg'} + reads=[] + class Reply: + is_success=True + def __enter__(self):return self + def __exit__(self,*args):pass + def iter_bytes(self,**kwargs):yield b'image';yield b'-bytes' + class Client: + def __init__(self,**kwargs):pass + def __enter__(self):return self + def __exit__(self,*args):pass + def stream(self,method,url,**kwargs): + assert kwargs['headers']==repo.headers + reads.append(url);return Reply() + monkeypatch.setattr('deployment.space.personal_repository.httpx.Client',Client) + repo.share('1'*32,include_conversation=True) + assert len(reads)==2 and all('/authenticated/personal-inspections/owner-A/' in url for url in reads) + uploads=[c for c in calls if '/object/team-inspections/' in c[1]] + assert len(uploads)==2 and all(c[2]['content']==b'image-bytes' and c[2]['ignore_conflict'] for c in uploads) + assert calls[-1][1]=='/rest/v1/rpc/defectrag_share_personal' + assert calls[-1][2]['json']['p_include_conversation'] is True + + +def test_already_shared_record_never_downloads_or_changes_team_copy(tmp_path): + repo,_,_=repository(tmp_path);repo.raw=lambda identifier:{'id':identifier} + calls=[] + def request(method,path,**kwargs): + calls.append((method,path));return [{'id':'1'*32,'owner_id':'owner-A'}] + repo.request=request + repo._read_private_image=lambda path:pytest.fail('A repeated share must not download images') + assert repo.share('1'*32)=={'alreadyShared':True} + assert calls==[('GET','/rest/v1/shared_inspections')] diff --git a/tests/test_publish_server_files.py b/tests/test_publish_server_files.py new file mode 100644 index 0000000000000000000000000000000000000000..09e6dab41fe3a9823da0858653bb988ba2606f19 --- /dev/null +++ b/tests/test_publish_server_files.py @@ -0,0 +1,74 @@ +"""Guards for `publish --server-files`: only reviewed server files, no hidden drift.""" +import subprocess +import sys +import types +from pathlib import Path + +import pytest + +from deployment.space import publish + +ROOT = Path(__file__).resolve().parents[1] +NAME = 'backend/rag.py' + + +def committed(name): + return subprocess.run(['git', 'show', 'HEAD:' + name], cwd=ROOT, capture_output=True, check=False).stdout + + +@pytest.fixture +def hub(tmp_path, monkeypatch): + """A fake Space whose files are set per test; records any commit.""" + state = {'files': {}, 'commits': []} + + class Api: + def space_info(self, repo): + return types.SimpleNamespace(sha='a' * 40) + + def list_repo_files(self, repo, repo_type, revision): + return list(state['files']) + + def create_commit(self, **kwargs): + state['commits'].append(kwargs) + return types.SimpleNamespace(oid='b' * 40) + + def download(repo, name, repo_type, revision): + path = tmp_path / name.replace('/', '_') + path.write_bytes(state['files'][name]) + return str(path) + + fake = types.SimpleNamespace(HfApi=Api, hf_hub_download=download, + CommitOperationAdd=lambda path_in_repo, path_or_fileobj: (path_in_repo, path_or_fileobj)) + monkeypatch.setitem(sys.modules, 'huggingface_hub', fake) + monkeypatch.setattr(publish, 'OUT', tmp_path / 'out') + return state + + +@pytest.mark.skipif(not committed(NAME), reason='needs the git history of backend/rag.py') +def test_live_equal_to_last_commit_is_accepted_and_only_that_file_is_sent(hub, capsys): + hub['files'] = {NAME: publish.unix_lines(committed(NAME))} + publish.publish_server_files([NAME], dry_run=True) + out = capsys.readouterr().out + assert '"server_files_only": true' in out and not hub['commits'] + local = publish.unix_lines((ROOT / NAME).read_bytes()) + assert ('"changed_files": ["backend/rag.py"]' in out) == (local != hub['files'][NAME]) + + +@pytest.mark.skipif(not committed(NAME), reason='needs the git history of backend/rag.py') +def test_unreviewed_live_drift_is_refused(hub): + hub['files'] = {NAME: b'# changed directly on the Space\n'} + with pytest.raises(SystemExit, match='differs from the last commit'): + publish.publish_server_files([NAME]) + assert not hub['commits'] + + +@pytest.mark.parametrize('name', ['models/x.py', 'backend/../.env', 'frontend/dist/index.html', 'backend/notes.txt']) +def test_only_server_python_files_are_allowed(hub, name): + with pytest.raises(SystemExit, match='only backend'): + publish.publish_server_files([name]) + + +def test_new_files_need_a_full_publish(hub): + hub['files'] = {} + with pytest.raises(SystemExit, match='not on the Space'): + publish.publish_server_files([NAME]) diff --git a/tests/test_rag_product_names.py b/tests/test_rag_product_names.py new file mode 100644 index 0000000000000000000000000000000000000000..f56c45aff2458ad27e886f53511d60b0ef6513d6 --- /dev/null +++ b/tests/test_rag_product_names.py @@ -0,0 +1,13 @@ +"""Assistant answers use the product names the dashboard shows, never internal keys.""" +import pytest + +from backend.rag import inspection_facts + + +@pytest.mark.parametrize('category,shown', [('pcb1', 'PCB 1'), ('macaroni2', 'Macaroni 2'), + ('pipe_fryum', 'pipe fryum'), ('chewinggum', 'chewing gum'), + ('new_item', 'new item'), (None, 'selected product')]) +def test_answer_names_the_product_like_the_dashboard(category, shown): + facts = inspection_facts('why is this result anomalous?', {'category': category, 'verdict': 'Anomalous', + 'score': 0.6, 'threshold': 0.5, 'uncertainty_margin': 0.01}) + assert f'flagged this {shown} image' in facts['text'] diff --git a/tests/test_references.py b/tests/test_references.py new file mode 100644 index 0000000000000000000000000000000000000000..4288ff6e5fa776c4699780187abc7c15ab564c0d --- /dev/null +++ b/tests/test_references.py @@ -0,0 +1,39 @@ +"""Nearest normal reference photos: ranking, missing index and independence from the verdict.""" + +import numpy as np +import torch + +from backend.references import ReferenceIndex, descriptor + + +def write_index(folder, vectors): + folder.mkdir(parents=True, exist_ok=True) + ids = np.array([f"pcb1/{i:02d}" for i in range(len(vectors))]) + np.savez_compressed(folder / "pcb1.npz", ids=ids, descriptors=np.asarray(vectors, dtype="float16")) + + +def test_the_descriptor_is_unit_length_and_uses_only_foreground_patches(): + tokens = torch.tensor([[1.0, 0.0], [0.0, 1.0], [0.0, 1.0]]) + value = descriptor(tokens, np.array([True, False, False])) + assert torch.allclose(value, torch.tensor([1.0, 0.0])) + assert torch.isclose(descriptor(tokens, np.array([False, False, False])).norm(), torch.tensor(1.0)) + + +def test_the_closest_references_come_first(tmp_path): + write_index(tmp_path, [[1, 0], [0, 1], [0.9, 0.1]]) + index = ReferenceIndex(tmp_path) + tokens = torch.tensor([[1.0, 0.05]] * 4) + found = index.nearest("pcb1", tokens, np.ones(4, dtype=bool), k=2) + assert [item["id"] for item in found] == ["pcb1/00", "pcb1/02"] + assert found[0]["similarity"] >= found[1]["similarity"] > 0.9 + + +def test_a_product_without_an_index_gives_no_references(tmp_path): + index = ReferenceIndex(tmp_path) + assert index.nearest("candle", torch.ones(3, 2), np.ones(3, dtype=bool)) == [] + + +def test_asking_for_more_than_exist_returns_all(tmp_path): + write_index(tmp_path, [[1, 0], [0, 1]]) + found = ReferenceIndex(tmp_path).nearest("pcb1", torch.tensor([[1.0, 1.0]]), np.ones(1, dtype=bool), k=5) + assert len(found) == 2 diff --git a/tests/test_release_preflight.py b/tests/test_release_preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..836b575214fda2cce08bd6ee76cc976d04648bb2 --- /dev/null +++ b/tests/test_release_preflight.py @@ -0,0 +1,48 @@ +"""Offline publisher/preflight checks: no migration, Supabase or HF call.""" +import json +from pathlib import Path +from types import SimpleNamespace +import pytest +from deployment.space import publish + + +def test_publisher_offline_frontend_check_does_not_import_huggingface(monkeypatch,capsys): + monkeypatch.setattr('sys.argv',['publish','--check-frontend']) + monkeypatch.setattr(publish,'checked_frontend',lambda:{'files':{'index.html':'fixture'},'source_fingerprint':'fixture-hash'}) + publish.main() + assert json.loads(capsys.readouterr().out)=={'verified':True,'files':1,'source_fingerprint':'fixture-hash'} + assert 'HfApi' not in vars(publish) + + +def test_invalid_frontend_blocks_before_publisher_can_contact_hf(monkeypatch): + monkeypatch.setattr('sys.argv',['publish','--phase','5']) + def fail():raise SystemExit('Frontend release blocked') + monkeypatch.setattr(publish,'checked_frontend',fail) + with pytest.raises(SystemExit,match='Frontend release blocked'):publish.main() + assert 'HfApi' not in vars(publish) + + +def test_frontend_validation_uses_offline_node_guard_not_remote_configuration(monkeypatch): + calls=[] + def run(command,**kwargs): + calls.append((command,kwargs));return SimpleNamespace(returncode=1,stderr='Source changed',stdout='') + monkeypatch.setattr(publish.subprocess,'run',run) + with pytest.raises(SystemExit,match='Source changed'):publish.checked_frontend() + assert calls[0][0][0]=='node' and calls[0][0][-2]=='check' + + +def test_preflight_contains_only_readonly_metadata_statements(): + import re + sql=Path('deployment/supabase_auth_preflight.sql').read_text(encoding='utf8') + clean=re.sub(r'--[^\n]*','',sql) + assert clean.strip().startswith('begin read only;') and clean.strip().endswith('rollback;') + assert not re.search(r'\b(create|alter|drop|insert|update|delete|grant|revoke|truncate|execute|call)\b',clean,re.I) + assert 'aclexplode(coalesce(p.proacl,acldefault(' in sql + assert "('auth.uid()'),('auth.jwt()'),('auth.role()')" in sql + assert 'from auth.users' not in clean and 'from auth.mfa_factors' not in clean + + +def test_reviewed_auth_migration_remains_exactly_the_same(): + import hashlib + normalized=Path('deployment/supabase_auth_mfa.sql').read_text(encoding='utf8').encode() + assert hashlib.sha256(normalized).hexdigest()=='cea1e451073fad9f47aca26292cb83a5d337854eef437d97f8c80b79c121e983' diff --git a/tests/test_space_batch.mjs b/tests/test_space_batch.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e9ce9cbb873ea1cec36dc3a3829116c6a429c336 --- /dev/null +++ b/tests/test_space_batch.mjs @@ -0,0 +1,21 @@ +import assert from 'node:assert/strict'; +import {runBatch} from '../deployment/space/batch_jobs.mjs'; +const files=['first.jpg','quota.jpg','pending.jpg','another.jpg'].map(name=>({name})); +let calls=0; +const limited=await runBatch(files,async file=>{ + calls++; + if(file.name==='quota.jpg')throw new Error('You have exceeded your ZeroGPU runs limit.'); + return {id:file.name}; +}); +assert.equal(calls,2,'No GPU calls may be attempted after quota rejection'); +assert.deepEqual(limited.records,[{id:'first.jpg'}]); +assert.equal(limited.errors.length,3); +assert.match(limited.errors[0].message,/Supabase staff login uses a separate account/); +assert.match(limited.errors[1].message,/Not submitted/); +const independent=await runBatch(files.slice(0,2),async file=>{ + if(file.name==='first.jpg')throw new Error('Invalid image'); + return {id:file.name}; +}); +assert.equal(independent.records.length,1,'Bad input must not discard later valid images'); +assert.equal(independent.errors.length,1); +console.log('PASS: quota stops pending GPU submissions; successes survive; input failures stay independent.'); diff --git a/tests/test_space_security.py b/tests/test_space_security.py new file mode 100644 index 0000000000000000000000000000000000000000..f0357f6e1cc6f2b10a696ef8f8fb6c349fe90e10 --- /dev/null +++ b/tests/test_space_security.py @@ -0,0 +1,113 @@ +"""Software security checks, separate from live Supabase/RLS acceptance tests.""" +import base64 +import json +import pytest +from deployment.space.sessions import identity,namespace,SessionRepository,capability,authorize_artifact +from deployment.space.supabase_repository import StaffRepository + + +def record(): + return {'id':'1'*32,'created_at':'2026-10-18T00:00:00+00:00','category':'pcb1', + 'verdict':'Anomalous','batch':'software-security-fixture','score':.2,'threshold':.1} + + +def test_foreign_workspace_cannot_read_record_or_messages(tmp_path): + repo=SessionRepository(tmp_path) + with identity('a'*64): + repo.save(record()) + repo.add_conversation('1'*32,'A question',{'answer':'Software fixture only'}) + assert repo.messages('1'*32) + with identity('b'*64): + assert repo.get('1'*32) is None + assert repo.list()==[] and repo.messages('1'*32)==[] + + +def test_artifact_capability_binds_owner_record_and_kind(): + with identity('a'*64): + token=capability('1'*32,'image') + assert authorize_artifact(token,'1'*32,'image')==namespace('a'*64) + with pytest.raises(ValueError): + authorize_artifact(token,'2'*32,'image') + with pytest.raises(ValueError): + authorize_artifact(token,'1'*32,'report') + raw=base64.urlsafe_b64decode(token+'='*(-len(token)%4)).decode().replace(':image:',':heatmap:') + tampered=base64.urlsafe_b64encode(raw.encode()).decode().rstrip('=') + with pytest.raises(ValueError): + authorize_artifact(tampered,'1'*32,'heatmap') + + +def test_old_capability_expires(monkeypatch): + with identity('a'*64): + token=capability('1'*32,'image') + import deployment.space.sessions as module + future=module.time.time()+3601 + monkeypatch.setattr(module.time,'time',lambda:future) + with pytest.raises(ValueError): + authorize_artifact(token,'1'*32,'image') + + +def test_missing_workspace_is_rejected(): + with pytest.raises(ValueError): + namespace('short') + + +def test_successful_auth_without_staff_membership_is_rejected(monkeypatch,tmp_path): + def request(self,method,path,**kwargs): + if path=='/auth/v1/user': + return {'id':'nonstaff-software-fixture'} + return [] + monkeypatch.setattr(StaffRepository,'request',request) + with pytest.raises(ValueError,match='staff allowlist'): + StaffRepository({'url':'https://example.invalid','key':'sb_publishable_fixture'},'nonstaff-unit-test-token',tmp_path) + + +def test_public_config_does_not_accept_service_role_key(tmp_path): + from deployment.space.supabase_repository import read_public_config + config=tmp_path/'config.js' + config.write_text('window.DEFECTRAG_PUBLIC_CONFIG='+json.dumps({'supabaseUrl':'https://example.invalid','supabasePublishableKey':'sb_secret_invalid'})) + with pytest.raises(ValueError): + read_public_config(config) + + +def test_staff_export_paginates_without_signing_every_image(): + repo=StaffRepository.__new__(StaffRepository) + calls=[] + def page(category,verdict,batch,limit,offset,archived): + calls.append((limit,offset,archived)) + return [{'payload':{'id':str(index)},'owner_id':'staff-fixture'} + for index in range(offset,min(offset+limit,1017))] + repo.raw_list=page + rows=repo.list(category='pcb1',limit=2000,offset=7) + assert len(rows)==1010 and rows[0]['id']=='7' and rows[-1]['id']=='1016' + assert calls==[(1000,7,False),(1000,1007,False)] + + +def test_ordinary_staff_archives_only_owned_visible_records(): + repo=StaffRepository.__new__(StaffRepository) + repo.staff={'role':'staff'} + repo.user={'id':'own-user'} + repo.raw_list=lambda *args,**kwargs:[{'id':'own-record','owner_id':'own-user'}, + {'id':'foreign-record','owner_id':'other-user'}] + calls=[] + def request(method,path,**kwargs): + calls.append((method,path,kwargs['json'])) + return 1 + repo.request=request + assert repo.archive()['archived']==1 + assert calls==[('POST','/rest/v1/rpc/archive_team_inspections',{'p_ids':['own-record']})] + + +def test_failed_upload_does_not_insert_record_or_report_success(tmp_path): + repo=StaffRepository.__new__(StaffRepository) + repo.user={'id':'staff-fixture'} + repo.artifacts=tmp_path + item=record() + (tmp_path/(item['id']+'.jpg')).write_bytes(b'fixture') + calls=[] + def request(method,path,**kwargs): + calls.append(path) + raise RuntimeError('Simulated storage unavailable') + repo.request=request + with pytest.raises(RuntimeError,match='storage unavailable'): + repo.save(item) + assert len(calls)==1 and calls[0].startswith('/storage/v1/object/') diff --git a/tests/test_tuned_profile.py b/tests/test_tuned_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..8518e1d37d6be0795915527cf517f23ca6f9b806 --- /dev/null +++ b/tests/test_tuned_profile.py @@ -0,0 +1,117 @@ +"""The fine-tuned DINOv2 profile: selection, rollback, manifest guards and the policy of its thresholds.""" + +import json +from copy import deepcopy + +import pytest + +from backend.calibration import TUNED_FILENAME, TUNED_POLICY, TUNED_QUANTILES, tuned_card +from backend.config import CATEGORIES, Settings +from backend.highres import PROFILES, HighResolutionDetector, TunedDetector +from backend.vision import Detector, ModelUnavailable, create_detector + + +def card(category, threshold=0.1): + quantile = TUNED_QUANTILES.get(category, 0.95) + return { + "category": category, + "model_id": f"dinov2-tuned-{category}-v1", + "profile": "dinov2_tuned_v1", + "encoder_sha256": "e" * 64, + "bank_sha256": "b" * 64, + "threshold": threshold, + "uncertainty_margin": threshold * 0.05, + "heatmap_scale": 0.12, + "calibration": {"normal": 90, "anomalous": 0, "policy": TUNED_POLICY, "quantile": quantile}, + } + + +@pytest.fixture +def installed(tmp_path): + (tmp_path / "results").mkdir() + manifest = {"decision_policy": TUNED_POLICY, "categories": {c: card(c) for c in CATEGORIES}} + (tmp_path / "results" / TUNED_FILENAME).write_text(json.dumps(manifest)) + return tmp_path, manifest + + +def marker(root, folder, status): + directory = root / "models" / folder + directory.mkdir(parents=True, exist_ok=True) + (directory / "PROFILE.json").write_text(json.dumps({"status": status})) + + +def test_auto_prefers_the_active_tuned_profile_and_legacy_stays_available(tmp_path): + marker(tmp_path, "highres", "active") + marker(tmp_path, "highres_tuned", "active") + assert isinstance(create_detector(Settings(root=tmp_path, profile="auto")), TunedDetector) + assert type(create_detector(Settings(root=tmp_path, profile="dinov2_highres_v1"))) is HighResolutionDetector + assert isinstance(create_detector(Settings(root=tmp_path, profile="legacy")), Detector) + + +def test_an_unvalidated_tuned_profile_never_replaces_the_working_one(tmp_path): + marker(tmp_path, "highres", "active") + marker(tmp_path, "highres_tuned", "pending") + assert type(create_detector(Settings(root=tmp_path, profile="auto"))) is HighResolutionDetector + with pytest.raises(ModelUnavailable, match="not validated"): + create_detector(Settings(root=tmp_path, profile="dinov2_tuned_v1")) + + +def test_asking_for_a_missing_tuned_profile_fails_closed(tmp_path): + with pytest.raises(ModelUnavailable, match="not installed"): + create_detector(Settings(root=tmp_path, profile="dinov2_tuned_v1")) + with pytest.raises(ModelUnavailable, match="Unknown"): + create_detector(Settings(root=tmp_path, profile="dinov2_tuned_v2")) + + +def test_profiles_use_separate_files_so_the_previous_profile_can_be_restored(): + assert PROFILES["dinov2_tuned_v1"]["directory"] != PROFILES["dinov2_highres_v1"]["directory"] + assert PROFILES["dinov2_tuned_v1"]["encoder"] != PROFILES["dinov2_highres_v1"]["encoder"] + assert TunedDetector.profile_name == "dinov2_tuned_v1" + + +def test_matching_card_and_manifest_are_accepted(installed): + root, _ = installed + assert tuned_card(root, card("pcb1"))["threshold"] == 0.1 + + +@pytest.mark.parametrize("key", ["threshold", "bank_sha256", "encoder_sha256", "model_id", "heatmap_scale"]) +def test_a_card_that_disagrees_with_the_manifest_is_rejected(installed, key): + root, _ = installed + changed = deepcopy(card("pcb1")) + changed[key] = "x" if isinstance(changed[key], str) else changed[key] * 2 + with pytest.raises(ValueError, match="disagree"): + tuned_card(root, changed) + + +def test_every_product_uses_the_same_q95_rule(installed): + root, manifest = installed + assert TUNED_QUANTILES == {} + wrong = deepcopy(manifest) + wrong["categories"]["macaroni2"]["calibration"]["quantile"] = 0.8 + (root / "results" / TUNED_FILENAME).write_text(json.dumps(wrong)) + with pytest.raises(ValueError, match="Invalid tuned threshold"): + tuned_card(root, wrong["categories"]["macaroni2"]) + + +def test_thresholds_must_be_finite_positive_and_use_no_anomalous_images(installed): + root, manifest = installed + for edit in ( + lambda c: c.update(threshold=0.0, uncertainty_margin=0.0), + lambda c: c["calibration"].update(anomalous=3), + lambda c: c.update(uncertainty_margin=0.5), + ): + broken = deepcopy(manifest) + edit(broken["categories"]["pcb1"]) + broken["categories"]["pcb1"]["calibration"].setdefault("policy", TUNED_POLICY) + original = deepcopy(broken["categories"]["pcb1"]) + (root / "results" / TUNED_FILENAME).write_text(json.dumps(broken)) + with pytest.raises(ValueError, match="Invalid tuned threshold"): + tuned_card(root, original) + + +def test_a_manifest_with_another_policy_is_rejected(installed): + root, manifest = installed + manifest["decision_policy"] = "something-else" + (root / "results" / TUNED_FILENAME).write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match="Invalid tuned calibration manifest"): + tuned_card(root, card("pcb1")) diff --git a/tests/test_workflow_fixes.py b/tests/test_workflow_fixes.py new file mode 100644 index 0000000000000000000000000000000000000000..8f76df187eba3fca42342b9a1c1c817f4d2dbce3 --- /dev/null +++ b/tests/test_workflow_fixes.py @@ -0,0 +1,66 @@ +"""Software integration checks; these fixtures do not measure model performance.""" +import pytest +from fastapi.testclient import TestClient +from backend.config import Settings +from backend.main import create_app +from backend.reviews import parse_review,review_body +from tests.test_application import SoftwareDetector,SoftwareWorkflow,image_bytes + +@pytest.fixture +def client(tmp_path): + with TestClient(create_app(Settings(data=tmp_path),SoftwareDetector(),SoftwareWorkflow())) as value: + yield value + +def upload(client,category='pcb1',batch='QA'): + return client.post('/api/inspect',data={'category':category,'batch':batch},files={'file':('input.png',image_bytes(),'image/png')}).json()['data'] + +def test_export_applies_all_filters_without_changing_all_export(client): + first=upload(client);second=upload(client,'candle','OTHER') + assert first['id'] in client.get('/api/export.csv?category=pcb1&batch=QA&verdict=Anomalous').text + assert second['id'] not in client.get('/api/export.csv?category=pcb1').text + assert first['id'] not in client.get('/api/export.csv?verdict=Good').text + assert second['id'] in client.get('/api/export.csv').text + +def test_review_audit_does_not_change_model_and_survives_report(client): + original=upload(client);identifier=original['id'] + for status,decision in [('In review','Pending'),('Reviewed','Hold')]: + response=client.post(f'/api/inspections/{identifier}/review',json={'status':status,'decision':decision,'note':''}) + assert response.status_code==200 and response.json()['data']['created_at'] + reviews=client.get(f'/api/inspections/{identifier}/reviews').json()['data'] + assert len(reviews)==2 and reviews[-1]['decision']=='Hold' + assert client.get(f'/api/inspections/{identifier}').json()['data']==original + report=client.get(f'/api/inspections/{identifier}/report').text + assert 'Human review' in report and 'Hold' in report and '<script>' in report + assert '' not in report + +def test_invalid_review_and_archived_target_cannot_create_decision(client): + identifier=upload(client)['id'] + assert client.post(f'/api/inspections/{identifier}/review',json={'status':'Reviewed','decision':'Pending'}).status_code==422 + client.post('/api/history/archive',json={'confirmation':'ARCHIVE'}) + assert client.post(f'/api/inspections/{identifier}/review',json={'status':'Reviewed','decision':'Hold'}).status_code==404 + +def test_report_does_not_render_internal_urls_or_owner_as_measurements(client): + record=upload(client) + # Report uses an explicit scalar-field allowlist; image URLs still belong in img attributes. + report=client.get(f"/api/inspections/{record['id']}/report").text + assert 'image url' not in report and 'owner id' not in report + assert 'report url' not in report and '