File size: 6,335 Bytes
cfc7a54 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | """Inference script: run trained SIFQ on a dataset and save per-image scores.
Output JSON format (one line per image):
{"image_path": ..., "q_score": 73.2, "concepts": [0.8, 0.6, ...],
"identity_id": "00002401", "finger_id": "F07", "sensor_id": "U_500_roll"}
Usage:
python scripts/run_infer.py --checkpoint checkpoints/v16/last.pt \\
--root-302b dataset/302b/images/baseline \\
--output /tmp/sifq_scores.jsonl
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
import torch
ROOT = Path(__file__).resolve().parents[1]
SRC_ROOT = ROOT / "src"
if str(SRC_ROOT) not in sys.path:
sys.path.insert(0, str(SRC_ROOT))
from data.nist302_loader import NIST302Loader, NIST302Paths
from models.aggregator import ScoreAggregator
from models.backbone import SIFQBackbone
from models.concept_head import ConceptHead, SpatialConceptHead
from models.sensor_discriminator import SensorDiscriminator
from models.sifq import SIFQ
def load_model(checkpoint_path: str, device: torch.device, num_sensors: int = 10) -> SIFQ:
ckpt = torch.load(checkpoint_path, map_location=device, weights_only=False)
# Infer num_sensors from checkpoint metrics ("n_sensors" key saved by train_sifq.py)
num_sensors = ckpt.get("metrics", {}).get("n_sensors", num_sensors)
backbone = SIFQBackbone(model_name="tiny_vit_5m_224.dist_in22k", pretrained=False)
# Detect architecture from saved config — spatial head was introduced in v27
_use_spatial = ckpt.get("config", {}).get("spatial_concept_head", False)
if _use_spatial:
concept_head = SpatialConceptHead(in_dim=backbone.feature_dim)
else:
concept_head = ConceptHead(in_dim=backbone.feature_dim)
aggregator = ScoreAggregator(k=6)
sensor_disc = SensorDiscriminator(in_dim=backbone.feature_dim, num_sensors=num_sensors)
model = SIFQ(backbone, concept_head, aggregator, sensor_disc)
model.load_state_dict(ckpt["model"], strict=True)
model.to(device).eval()
return model
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="SIFQ inference — generate quality scores")
p.add_argument("--checkpoint", type=str, required=True,
help="Path to trained SIFQ checkpoint (last.pt or best.pt)")
p.add_argument("--root-302a", type=str, default="",
help="Root for NIST SD302-A challengers (optional)")
p.add_argument("--root-302b", type=str,
default="/home/aiserver/works/fingerprint/dataset/302b/images/baseline",
help="Root for NIST SD302-B baseline")
p.add_argument("--root-302d", type=str,
default="/home/aiserver/works/fingerprint/dataset/nist_302d/images/auxiliary",
help="Root for NIST SD302-D auxiliary")
p.add_argument("--image-size", type=int, default=224)
p.add_argument("--batch-size", type=int, default=32)
p.add_argument("--num-workers", type=int, default=2)
p.add_argument("--output", type=str, default="/tmp/sifq_scores.jsonl",
help="Output JSONL file path")
p.add_argument("--max-samples", type=int, default=-1,
help="Cap number of images for quick eval; -1 means all")
p.add_argument("--exclude-sensor", type=str, default="",
help="Comma-separated sensor_ids to skip inference on. "
"E.g. 'R_1000_slap,R_500_slap,S_500_slap'")
return p.parse_args()
@torch.no_grad()
def main() -> None:
args = parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# --- Load model ---
print(f"Loading checkpoint: {args.checkpoint}")
model = load_model(args.checkpoint, device)
print(f"Model loaded. Device: {device}")
# --- Discover records ---
paths = NIST302Paths(
root_302a=args.root_302a or "",
root_302b=args.root_302b,
root_302d=args.root_302d,
)
loader = NIST302Loader(image_size=args.image_size)
records = loader.discover(paths)
if args.exclude_sensor:
excluded = {s.strip() for s in args.exclude_sensor.split(",") if s.strip()}
records = [r for r in records if r["sensor_id"] not in excluded]
print(f"After excluding sensors {excluded}: {len(records)} records remain")
if args.max_samples > 0:
records = records[:args.max_samples]
print(f"Discovered {len(records)} records")
# --- Batch inference ---
output_path = Path(args.output)
output_path.parent.mkdir(parents=True, exist_ok=True)
batch_records: list[dict] = []
batch_tensors: list[torch.Tensor] = []
def flush_batch() -> None:
if not batch_tensors:
return
images = torch.stack(batch_tensors, dim=0).to(device)
outputs = model(images)
scores = outputs["score"].squeeze(-1).cpu().tolist()
concepts_batch = outputs["concepts"].cpu().tolist()
for rec, q, conc in zip(batch_records, scores, concepts_batch):
row = {
"image_path": rec["image_path"],
"identity_id": rec["identity_id"],
"finger_id": rec["finger_id"],
"sensor_id": rec["sensor_id"],
"dataset": rec["dataset"],
"q_score": round(float(q), 3),
"concepts": [round(float(c), 4) for c in conc],
}
with open(output_path, "a", encoding="utf-8") as f:
f.write(json.dumps(row) + "\n")
batch_records.clear()
batch_tensors.clear()
# Clear output file
output_path.write_text("")
n_done = 0
for sample in loader.iter_samples(records):
batch_records.append({
"image_path": sample["image_path"],
"identity_id": sample["identity_id"],
"finger_id": sample["finger_id"],
"sensor_id": sample["sensor_id"],
"dataset": sample["dataset"],
})
batch_tensors.append(sample["image"])
if len(batch_tensors) >= args.batch_size:
flush_batch()
n_done += args.batch_size
if n_done % 500 == 0:
print(f" {n_done}/{len(records)} done")
flush_batch()
print(f"Done. Scores saved to: {output_path}")
if __name__ == "__main__":
main()
|