How facenox/face-antispoof-onnx works
1. Repository purpose
- This is a face anti-spoofing project with two main operating modes: training a lightweight classifier and running low-latency inference on images/webcam frames.
- The production path is centered on MiniFASNet V2 SE with ONNX/quantized ONNX deployment.
2. Top-level architecture
- The repo is split into four functional areas:
- src/detection/: face localization
- src/inference/: runtime preprocessing and model execution
- src/minifasv2/: active training implementation
- scripts/: dataset preparation, checkpoint cleanup, export, quantization, training entrypoints
- src/mobilenetv4/ is a legacy training branch kept for reference, not the main deployment path.
3. Inference data flow
- demo.py is the user-facing entrypoint.
- Input comes from either a webcam frame or a single image.
- The frame/image is passed through face detection, then face cropping/resizing, then anti-spoof classification.
- The classifier returns a real vs spoof decision that is rendered as a color-coded bounding box in the demo.
4. Detection boundary
- src/detection/face.py is the face detection subsystem.
- Its job is to isolate a face region before classification; this keeps the spoof model focused on face texture rather than the whole scene.
- This is a clear architectural boundary: detector first, anti-spoof model second.
5. Inference/runtime boundary
- src/inference/ contains the runtime pieces that glue detection to model execution:
- loader.py for model loading
- preprocess.py for resizing/normalization and input shaping
- inference.py for prediction orchestration
- system.py for higher-level runtime coordination
- The runtime is designed around PyTorch for training artifacts and ONNX Runtime for deployment artifacts.
6. Model and deployment formats
- Trained weights are stored in models/ in multiple forms:
- .pth for PyTorch training/fine-tuning
- .onnx for general inference
- quantized .onnx for smaller production deployment
- The repo includes both full and quantized exported models, showing a clear separation between training-time artifacts and inference-time artifacts.
7. Training pipeline
- scripts/train.py drives training using the active implementation in src/minifasv2/.
- Training outputs checkpoints and logs into an experiment directory under MINIFAS/.
- Checkpoints are preserved at many epochs plus checkpoint_best.pth and checkpoint_latest.pth, indicating a standard long-running training workflow with resumability.
8. Dataset preparation flow
- scripts/prepare_data.py is the data ingestion/preprocessing boundary.
- It expects face images plus matching bounding-box files and train/test label metadata.
- The script crops faces, applies padding via a configurable expansion factor, resizes to the model input size, and organizes the result into train/test folders.
- This preprocessing step is important because the downstream model expects fixed-size face crops, not raw full images.
9. MiniFAS model-specific training components
- src/minifasv2/ contains the active model/config/data definitions for MiniFASNet V2 SE.
- The README notes a Fourier Transform auxiliary loss and SE blocks, which are part of the training-time design to improve spoof-vs-real discrimination.
- Architecturally, this is the core learning subsystem that produces the final classifier used by inference/export.
10. Model cleanup and export pipeline
- scripts/prepare_best_model.py extracts a clean inference-ready PyTorch model from a training checkpoint by stripping optimizer/training-only state.
- scripts/export_onnx.py converts the model to ONNX.
- scripts/quantize_onnx.py produces the INT8 quantized ONNX version.
- This creates a clear lifecycle: checkpoint → cleaned weights → ONNX → quantized deployment artifact.
11. Legacy experimentation path
- src/mobilenetv4/ contains an older MobileNetV4-based training stack with its own data, labels, sampling, checkpointing, and fine-tuning utilities.
- It is explicitly described as reference/experimental code retained for future work, while current production training uses MiniFAS.
- For an architecture diagram, this should be shown as a side branch rather than the main line.
12. Results, metrics, and documentation
- assets/results/ and models/best/ capture historical best runs and metric snapshots.
- docs/ contains architecture notes, data preparation rationale, metric definitions, previous results, and limitations.
- These are supporting artifacts rather than runtime components, but they document the system’s performance characteristics and constraints.
13. Tests and verification
- tests/ covers detection, preprocessing, and inference.
- The test boundary aligns with the runtime path: verify face detection behavior, preprocessing correctness, and inference integration.
- This suggests the project treats preprocessing and model-loading as critical correctness points, not just the model itself.
14. Operational constraint
- The deployed model is intentionally small and CPU-friendly, with quantized ONNX emphasized for production use.
- The system is optimized for low-spec hardware and well-lit frontal faces, which is a practical limitation that should be reflected in any architecture diagram or deployment note.
Main entry points: main.py MiniFAS main · face.py Face detect · test_inference.py Tests · system.py System
Components 21
Runtime
Demo and low-latency inference path
- Demo · User-facing image/webcam entrypoint
demo.py - Face detect · Locates and isolates the face region
src/detection/face.py - Preprocess · Resizes, normalizes, and shapes face crops
src/inference/preprocess.py - Loader · Loads deployment artifacts for execution
src/inference/loader.py - Predict · Runs classification and returns real/spoof output
src/inference/inference.py - System · Coordinates detection and inference flow
src/inference/system.py
Training
Active MiniFASV2 training and export pipeline
- Prep data · Builds cropped train/test face datasets
scripts/prepare_data.py - Train · Starts active MiniFASV2 training
scripts/train.py - Clean ckpt · Strips training-only state from checkpoints
scripts/prepare_best_model.py - Export ONNX · Converts cleaned weights to ONNX
scripts/export_onnx.py - Quantize · Produces INT8 ONNX for production
scripts/quantize_onnx.py - MiniFAS cfg · Active model and training configuration
src/minifasv2/config.py - MiniFAS data · MiniFASV2 data definitions and loaders
src/minifasv2/data.py - MiniFASNet · MiniFASNet V2 SE model definition
src/minifasv2/model.py - MiniFAS main · Active training loop and optimization
src/minifasv2/main.py
Legacy
Older MobileNetV4 training branch kept for reference
- Legacy train · Older MobileNetV4 training stack
src/mobilenetv4/training.py - Legacy net · MobileNetV4 fine-tuning and model code
src/mobilenetv4/ft_net.py
Support
Artifacts, docs, and verification
- Deploy model · Production ONNX classifier artifact
models/best/98.20/best_model_quantized.onnx - Detector model · Face detector ONNX artifact
models/detector_quantized.onnx - Tests · Covers detection, preprocessing, and inference
tests/test_inference.py - Docs · Architecture, data prep, metrics, and limitations
docs/ARCHITECTURE.md
Connections 21
- Demo → System: run · User input enters the runtime coordinator
- System → Face detect: detect · Find the face before classification
- Face detect → Preprocess: crop · Face region is resized and normalized
- Preprocess → Loader: shape input · Prepared tensors are passed to the model loader/runtime
- Loader → Predict: execute · Loaded ONNX/PyTorch artifact is used for prediction
- Predict → Demo: render result · Real/spoof decision is shown in the UI
- Train → MiniFAS main: start · Script launches the active training loop
- MiniFAS main → MiniFASNet: build · Training uses the MiniFASNet V2 SE model
- MiniFAS main → MiniFAS data: load · Training consumes MiniFAS-specific data pipeline
- MiniFAS main → MiniFAS cfg: configure · Model and run settings come from config
- Prep data → MiniFAS data: prepare · Raw face assets are converted into model-ready datasets
- Clean ckpt → Export ONNX: clean · Training checkpoint is converted to inference-ready weights
- Export ONNX → Quantize: convert · ONNX export feeds quantization
- Quantize → Deploy model: publish · Quantized ONNX becomes the deployment artifact
- Face detect → Detector model: uses · Detection subsystem relies on detector ONNX
- System → Deploy model: uses · Runtime classifier loads the deployed model
- Legacy train → Legacy net: build · Legacy branch trains its own MobileNetV4 stack
- Tests → Face detect: verify · Checks detection behavior
- Tests → Preprocess: verify · Checks preprocessing correctness
- Tests → Predict: verify · Checks inference integration
- Docs → Prep data: describe · Documents data preparation assumptions and limits