Shared detector engine
Every detector port under detectors/<id>/ is a thin package built around four files: detector.yaml, pyproject.toml, model.py, and inference.py. Aside from bespoke exceptions such as RECCE's decoder-audit entrypoint, inference.py delegates entirely to detectors/common/engine.py:
from common.engine import run_detector
from model import build_model
run_detector(build_model, Path(__file__).with_name("detector.yaml"))Centralizing media decoding, face detection, deterministic frame sampling, normalization, auxiliary tensor extraction, Grad-CAM/attention rendering, and result.json serialization in detectors/common/ ensures two critical forensic invariants: (1) all 58 detector ports apply identical sampling and coordinate conventions, and (2) raw upstream logit ordering quirks (e.g. RawNet2 / XLS-R+SLS putting spoof at index 0) are normalized in each model.py so index 1 always means fake before hitting the engine.
Specification loading
detectors/common/spec.py loads each detector's detector.yaml into a DetectorSpec dataclass defaulting to the DeepfakeBench image baseline (256x256 RGB, mean/std (0.5, 0.5, 0.5)). load_spec() honors:
input_mode(face_crop,face_clip,full_frame,full_clip,audio, orav_clip, inferringface_clipwhenvideo_mode: trueif omitted);face_margin(for detectors trained on expanded face boxes such as SBI and LAA-Net, which require a 25% total box margin);resize_shortandcenter_crop(whole-frame preprocessing);cam(defaultTrue; when explicitlyFalse, pixel-space Grad-CAM fallback is disabled by design — used for waveform audio models, wavelet-spacesafe, distance-basedaeroblade, frozen feature probeunivfd, and temporal transformerstimesformer,videomae,xclip,tallwhose inputs/heads lack meaningful spatial Grad-CAM surfaces);region_analysis(defaults toTrueonly forface_crop/face_clipwhencamis enabled);max_frames(overridable viaVERITY_MAX_FRAMES, where0disables the cap);caveat(prepended verbatim toconfidence_factorswhenever known limitations exist, such asm2f2_det's omitted bridge adapter blocks oraasist's ASVspoof2019 generalization boundary).
Determinism and bounded memory
Before loading or running any model, detectors/common/engine.py fixes:
SEED = 0xC0FFEE
torch.manual_seed(SEED)
np.random.seed(SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = FalseVideo decoding uses VideoReader (detectors/common/sampling.py), which plans the evenly spaced target frame positions (and neighboring clip_size windows in clip mode) up front via _plan(), then performs a single sequential cv2.VideoCapture pass retaining only needed frames in memory. Avoiding random seeks prevents decoder keyframe-drift from shifting frame selection across runs, while keeping only sampled frames avoids exhausting RAM on long 1080p videos.
Input modes
DetectorSpec.input_mode controls what run_detector extracts, scores, and names as its unit:
input_mode | Consumed input | Scored unit | Key behavior |
|---|---|---|---|
face_crop | Face crops per sampled frame | face | MTCNN FaceDetector (min_face filter) + _expand_box(face_margin) |
face_clip | clip_size consecutive face crops | face | VideoReader.clip + crop_rgb stacked as (1, 3, T, H, W) |
full_frame | Whole image or evenly sampled frames | frame | Calls optional model.preprocess(pil) else resize/center-crop/normalize |
full_clip | clip_size consecutive whole frames | clip | Stacked (1, 3, T, H, W) without face cropping |
audio | 16 kHz mono waveform windows | window | Prefers extracted artifacts/audio/audio.wav, else ffmpeg; tiles short audio |
av_clip | clip_size frames + matching audio span | window | Streams frame ranges once; passes window dict to model.forward_detailed |
If mode is audio or av_clip and no decodable soundtrack exists, AudioUnavailable is caught cleanly so result.json records the audio gap instead of crashing the examination.
Native attention, Grad-CAM, and auxiliary signals
After scoring via model.forward_detailed(x):
- Native vs Grad-CAM (
_cam_for): The engine inspectsout.get("attention_map")first. If present and spatially non-constant (std > 1e-6), it min-max normalizes the native map (for example LAA-Net's 96x96 boundary heatmap, Forensics Adapter / VLAForge / DF40 ViT patch attention, SRM spatial attention, or ProDet's gated attention mask). Otherwise, ifspec.camisTrue, it invokesgrad_cam(model, x)using thefeattensor returned byforward_detailed. - Region-energy attribution: When MediaPipe
FaceMeshsucceeds andspec.region_analysisisTrue, attention energy is projected onto six facial regions (left_eye,right_eye,nose,mouth,jaw,forehead) and stored inper_face[*].region_energyandregion_aggregate. - Auxiliary sub-scores (
_extract_aux&aggregate_aux): Models that compute interpretable secondary measurements return them inout["aux"](or per-windowout["info"]in AV mode) — for example ProDet's blend/identity heads, VLAForge's query vs VLA-gated scores, AEROBLADE's per-VAE LPIPS distances (SD1.1, SD2.1, Kandinsky), or SyncNet's AV offset and LSE-C confidence. The engine rounds each scalar toper_face[*].aux, aggregates dataset-wide means intoaux_aggregate, and surfaces them inconfidence_factorsviabuild_reasoning.
RECCE honest-degradation audit
detectors/recce/inference.py exemplifies how Verity handles checkpoints with dead or untrained sub-modules. The official DeepfakeBench v1.0.1 recce_best.pth checkpoint leaves the reconstruction decoder untrained (producing near-constant ~0 tensors). At model load time, audit_reconstruction(model) runs a synthetic gradient probe and checks whether the reconstruction tensor varies (std > 1e-4 and min < max). When decoder_alive is False, RECCE explicitly omits reconstructions/*_recon.png, drops reconstruction residual claims from region_energy, records the audit telemetry in tensor_audit, and explains in reasoning and confidence_factors that the verdict rests solely on classifier logits and guided attention maps.
Aggregation, reasoning, and result.json
detectors/common/reasoning.py computes deterministic panel statistics across all scored units in per_face:
aggregatecomputesmean_p,confidence = 1.0 - min(std_p * 2.0, 0.9)(so cross-frame/cross-face variance lowers confidence automatically), andstatscoveringmean,min,max,std,median,count,threshold,above_threshold,below_threshold,high_confidence_fake(> 0.7), andhigh_confidence_real(< 0.3).build_reasoningformats an explicitFAKE(> 0.7),REAL(< 0.3), orUNCERTAIN(0.30–0.70) summary plus itemizedconfidence_factorscovering weight provenance, CAM availability, top region energy,aux_aggregate, unit count, and execution device.
run_detector writes:
result.jsonwithprediction,confidence,reasoning,confidence_factors,stats,weights,timing_seconds,device,model,unit,input_mode,per_face,audio,total_video_frames,sampling,region_aggregate,aux_aggregate, andexecution_context;per_face_results.jsonmirroringper_face;- Explainability images (
faces/,frames/,attention_maps/,full_frames/, andtimeline.png).
Related pages
- Detector runtime and isolation — how
DetectorRunnerlaunches and parses the engine's outputs. - Detector catalog (all 58 ports) — per-detector input modes, CAM flags, auxiliary signals, and caveats.
- Explainability artifacts and on-disk formats — full file layout and evidence contract.