Veritas-AI / implementation_plan.md
Aditya-Jadhav150
feat: implement AEGIS-AI v4 MSCVN 5-stream engine & UI/UX modular overhaul
f5125ca
|
Raw History Blame Contribute Delete
32.1 kB

AEGIS-AI v4: Custom Multi-Stream Consistency Verification Network

Goal

Replace the current HuggingFace model wrapper pipeline with a fully custom-trained neural network that detects deepfakes by verifying whether forensic signals across multiple independent streams are mutually consistent with reality β€” rather than memorizing what specific fakes look like.

This is a ground-up rebuild of the detection engine. The Flask API and web frontend remain untouched.


What Makes This Genuinely Novel

Existing Detectors Our System (MSCVN)
Binary classifier trained on known fakes Learns what reality looks like β†’ detects anomalies
Single CNN/ViT backbone 5 independent forensic streams cross-checked for consistency
Amplitude spectrum only Phase spectrum analysis (where deepfake artifacts actually hide)
Global heart rate detection (defeated in 2025) Localized blood flow pattern analysis per facial region
Fixed SRM preprocessing filters Learnable SRM filters that adapt during training
Confidence score with no explanation Per-stream evidence breakdown + spatial heatmaps

Hardware Constraints

Environment GPU VRAM Usage
Local Development RTX 3050 4 GB Training (FP16), inference, debugging
Cloud Training Google Colab / Kaggle 16 GB (T4/P100) Heavy training sessions
Production (HF Spaces) T4 (paid tier) 16 GB Inference serving

Model Budget: ~55–65M total parameters β†’ ~130MB FP32 / ~65MB FP16 β†’ fits in 2–3GB VRAM with batch data.


Architecture: Multi-Stream Consistency Verification Network (MSCVN)

                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                         β”‚         Input Media              β”‚
                         β”‚   (Image / Video Frame / Audio)  β”‚
                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                    β”‚
                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                 β”‚                  β”‚                       β”‚
                 β–Ό                  β–Ό                       β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚  Preprocessing  β”‚  β”‚  Preprocessing    β”‚  β”‚   Preprocessing    β”‚
    β”‚  SRM Filters    β”‚  β”‚  2D FFT (cuFFT)   β”‚  β”‚   ELA + Local Var  β”‚
    β”‚  (30 learnable  β”‚  β”‚  + DCT Transform  β”‚  β”‚   + Entropy Maps   β”‚
    β”‚   high-pass)    β”‚  β”‚                    β”‚  β”‚                    β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
            β”‚                    β”‚                          β”‚
            β–Ό                    β–Ό                          β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚   STREAM 1      β”‚  β”‚    STREAM 2       β”‚  β”‚    STREAM 3        β”‚
    β”‚  NoiseResNet    β”‚  β”‚  SpectralCNN      β”‚  β”‚  ForensicCNN       β”‚
    β”‚  (~10M params)  β”‚  β”‚  (~10M params)    β”‚  β”‚  (~8M params)      β”‚
    β”‚                 β”‚  β”‚                    β”‚  β”‚                    β”‚
    β”‚  Learns camera  β”‚  β”‚  Detects GAN       β”‚  β”‚  ELA anomalies,    β”‚
    β”‚  sensor noise   β”‚  β”‚  spectral peaks,   β”‚  β”‚  local statistics, β”‚
    β”‚  vs synthetic   β”‚  β”‚  diffusion noise   β”‚  β”‚  JPEG artifacts    β”‚
    β”‚  noise patterns β”‚  β”‚  scheduling traces β”‚  β”‚                    β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
            β”‚                    β”‚                          β”‚
            β”‚  256-d             β”‚  256-d                   β”‚  256-d
            β”‚                    β”‚                          β”‚
            β–Ό                    β–Ό                          β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚                                                                β”‚
    β”‚              STREAM 4: BiologicalTemporalStream                β”‚
    β”‚              (Video only β€” ~12M params)                        β”‚
    β”‚                                                                β”‚
    β”‚  β€’ rPPG: Localized blood flow extraction per face region       β”‚
    β”‚  β€’ Blink rate & micro-expression temporal coherence            β”‚
    β”‚  β€’ Corneal reflection consistency across frames                β”‚
    β”‚  β€’ Temporal confidence drift analysis                          β”‚
    β”‚                                                                β”‚
    β”‚  Output: 256-d temporal evidence vector                        β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚                  β”‚                       β”‚
            β–Ό                  β–Ό                       β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚                                                                β”‚
    β”‚              STREAM 5: SemanticBackbone                        β”‚
    β”‚              (Lightweight EfficientNet-B0 β€” ~5M params)        β”‚
    β”‚                                                                β”‚
    β”‚  β€’ High-level content understanding                            β”‚
    β”‚  β€’ Face vs scene vs object awareness                           β”‚
    β”‚  β€’ Texture coherence at semantic level                         β”‚
    β”‚                                                                β”‚
    β”‚  Output: 256-d semantic feature vector                         β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚
                               β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚                                                                β”‚
    β”‚         CROSS-ATTENTION CONSISTENCY FUSION MODULE               β”‚
    β”‚         (~5M params β€” 4 transformer layers)                    β”‚
    β”‚                                                                β”‚
    β”‚  Input: [S1_256, S2_256, S3_256, S4_256, S5_256]               β”‚
    β”‚         = 5 tokens Γ— 256-d = 1280-d sequence                   β”‚
    β”‚                                                                β”‚
    β”‚  β€’ Multi-head cross-attention (8 heads)                        β”‚
    β”‚  β€’ Each stream attends to ALL other streams                    β”‚
    β”‚  β€’ Consistency check: do streams agree or conflict?            β”‚
    β”‚  β€’ Adaptive weight normalization for missing streams           β”‚
    β”‚    (image-only: S4 masked; audio-only: S1-S3 masked)          β”‚
    β”‚                                                                β”‚
    β”‚  Output:                                                       β”‚
    β”‚    β”œβ”€β”€ final_score: float (0.0 = definitely real, 1.0 = fake)  β”‚
    β”‚    β”œβ”€β”€ per_stream_scores: [s1, s2, s3, s4, s5]                 β”‚
    β”‚    β”œβ”€β”€ consistency_matrix: 5Γ—5 agreement scores                β”‚
    β”‚    └── risk_level: HIGH / MEDIUM / LOW                         β”‚
    β”‚                                                                β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Total: ~50–55M parameters


Stream Architecture Details

Stream 1: NoiseResNet (Noise Residual Extraction)

Purpose: Extract and classify the noise fingerprint β€” camera sensor PRNU noise vs synthetic generation noise.

# Architecture
class NoiseResNet(nn.Module):
    # Layer 0: 30 Learnable SRM High-Pass Filters (3β†’30 channels, 5Γ—5 kernels)
    #          Initialized with classic SRM filter bank, then fine-tuned
    # Layer 1-4: ResNet-style blocks (30β†’64β†’128β†’256β†’256 channels)
    #            Each block: Conv3x3 β†’ BN β†’ ReLU β†’ Conv3x3 β†’ BN + Skip
    # Global Average Pooling β†’ FC(256) β†’ 256-d output vector
  • Input: RGB image (224Γ—224)
  • Preprocessing: Learnable SRM filters suppress image content, amplify noise residuals
  • Key innovation: SRM filters are initialized with classical steganalysis weights but fine-tuned during training β€” adapts to modern generator noise patterns
  • Parameters: ~10M
  • VRAM: ~400MB with batch=8 FP16

Stream 2: SpectralCNN (Frequency Domain Forensics)

Purpose: Detect periodic GAN artifacts and diffusion noise scheduling traces in the frequency domain.

# Architecture
class SpectralCNN(nn.Module):
    # Preprocessing (no learnable params):
    #   1. 2D FFT via torch.fft.fft2 (backed by NVIDIA cuFFT)
    #   2. Split into: log-amplitude spectrum + phase spectrum
    #   3. Concatenate: 2-channel input (amp + phase)
    #
    # Backbone: 5-layer CNN
    #   Conv(2β†’32) β†’ Conv(32β†’64) β†’ Conv(64β†’128) β†’ Conv(128β†’256) β†’ Conv(256β†’256)
    #   Each: Conv3x3 β†’ BN β†’ GELU β†’ MaxPool2x2
    #
    # Dual-head output:
    #   Head A: Radial band energy analyzer (concentric ring features)
    #   Head B: Angular sector analyzer (directional artifact features)
    #   Concat β†’ FC(512β†’256) β†’ 256-d output vector
  • Input: RGB image (224Γ—224)
  • Preprocessing: torch.fft.fft2 β†’ log-amplitude + phase spectrum (phase is where deepfake traces hide β€” this is our key differentiator)
  • Key innovation: Most detectors only analyze amplitude. We analyze both amplitude AND phase, plus use radial band + angular sector decomposition for direction-aware artifact detection
  • NVIDIA: cuFFT accelerates 2D FFT computation on GPU
  • Parameters: ~10M

Stream 3: ForensicCNN (Pixel-Level Artifact Localization)

Purpose: Detect compression artifacts, ELA anomalies, and local statistical inconsistencies.

# Architecture
class ForensicCNN(nn.Module):
    # Preprocessing (partially learnable):
    #   1. ELA map: JPEG recompress at Q=95, abs difference Γ— 20
    #   2. Local variance map: sliding 7Γ—7 window variance
    #   3. Laplacian edge map: cv2.Laplacian
    #   4. Stack: 3-channel forensic input
    #
    # Backbone: Compact ResNet (3β†’32β†’64β†’128β†’256)
    # Spatial Attention Module: learns WHERE manipulation occurred
    # Global Average Pooling β†’ FC(256) β†’ 256-d output + spatial heatmap
  • Input: RGB image (224Γ—224)
  • Output: 256-d feature vector + spatial anomaly heatmap (for explainability)
  • Key innovation: Instead of ELA as a separate post-hoc step, ELA/variance/edge maps are first-class input channels to a learned network
  • Parameters: ~8M

Stream 4: BiologicalTemporalStream (Video Only)

Purpose: Analyze biological signals (rPPG blood flow), temporal consistency, and face identity coherence across frames.

# Architecture
class BiologicalTemporalStream(nn.Module):
    # Sub-module A: rPPG Extractor
    #   - ROI extraction: forehead, left cheek, right cheek, nose
    #   - Per-region color channel tracking across frames
    #   - 1D CNN on temporal signal β†’ pulse frequency estimation
    #   - Cross-region coherence scoring (all regions should show same pulse)
    #
    # Sub-module B: Temporal Consistency Analyzer
    #   - Per-frame Stream 1-3 features β†’ LSTM/GRU sequence
    #   - Detect sudden forensic score jumps (splice boundaries)
    #   - Confidence drift analysis
    #
    # Sub-module C: Face Identity Tracker
    #   - Face embedding extraction (lightweight MobileFaceNet)
    #   - Cosine similarity across frames
    #   - Identity swap detection
    #
    # Fusion: Concat β†’ FC(768β†’256) β†’ 256-d temporal evidence vector
  • Input: Sequence of video frames (N frames Γ— 224Γ—224)
  • Key innovation: Localized rPPG β€” we don't just check "does this person have a heartbeat?" (modern deepfakes pass this test). We check "does the blood flow pattern in the left cheek agree with the right cheek and forehead?" β€” a consistency check that generators can't fake
  • Parameters: ~12M
  • Masked when input is a single image (fusion module handles this)

2025 research (Fraunhofer HHI) showed deepfakes can "inherit" global pulse signals from source videos. Our localized cross-region coherence approach addresses this directly.


Stream 5: SemanticBackbone (High-Level Content Understanding)

Purpose: Provide semantic context β€” what type of content is this? Face? Scene? Object? This helps the fusion module weight other streams appropriately.

# Architecture
class SemanticBackbone(nn.Module):
    # EfficientNet-B0 backbone (pre-trained on ImageNet, fine-tuned)
    # Remove classification head
    # Add: AdaptiveAvgPool β†’ FC(1280β†’256) β†’ 256-d semantic feature
  • Input: RGB image (224Γ—224)
  • Pre-trained: ImageNet weights (transfer learning β€” this is the ONE stream where we leverage pre-training)
  • Parameters: ~5.3M (EfficientNet-B0 is naturally efficient)
  • Role in fusion: Provides semantic context so the fusion module knows how to weight forensic streams (e.g., for a landscape with no faces, biological stream gets zero weight)

Cross-Attention Consistency Fusion Module

Purpose: The brain of the system β€” checks whether all streams agree with each other.

# Architecture
class ConsistencyFusion(nn.Module):
    # Input: 5 stream vectors Γ— 256-d β†’ treated as 5-token sequence
    #
    # 4 Transformer Encoder Layers:
    #   - Multi-Head Attention (8 heads, d_model=256)
    #   - Feed-Forward Network (256β†’512β†’256)
    #   - Layer Norm + Residual connections
    #
    # Stream availability mask:
    #   - Image input:  [S1βœ“, S2βœ“, S3βœ“, S4βœ—, S5βœ“] β†’ mask S4
    #   - Video input:  [S1βœ“, S2βœ“, S3βœ“, S4βœ“, S5βœ“] β†’ all active
    #   - Audio input:  [S1βœ—, S2βœ—, S3βœ—, S4βœ—, S5βœ—] β†’ separate audio path
    #
    # Output heads:
    #   Head 1: Binary classification (real vs fake) β€” BCE loss
    #   Head 2: Per-stream anomaly scores β€” per-stream supervision
    #   Head 3: Consistency matrix (5Γ—5) β€” do streams agree?
    #   Head 4: Risk level classification (HIGH/MEDIUM/LOW)
  • Key innovation: The cross-attention lets each stream "look at" every other stream. If Stream 1 (noise) says "fake" but Stream 5 (semantic) says "real face photo", the attention mechanism learns to detect this inconsistency β€” which is itself strong evidence of manipulation
  • Missing stream handling: Uses attention masking (like masked language models) β€” missing streams are zeroed and masked from attention computation, remaining weights auto-normalize
  • Parameters: ~5M

Audio Detection (Separate Path)

Audio uses a different architecture since it's a 1D signal:

class AudioForensicNet(nn.Module):
    # Input: 16kHz mono waveform (5-second segments)
    #
    # Frontend: Learnable mel-filterbank (replaces fixed librosa mel)
    #   1D Conv(1β†’40, kernel=401, stride=160) β†’ log compression
    #
    # Backbone: 1D ResNet (40β†’64β†’128β†’256)
    #   4 ResNet blocks with 1D convolutions
    #
    # Temporal pooling: Attention-weighted average across time
    #
    # Output: fake_probability, voice_consistency_score
  • Parameters: ~5M
  • Training data: ASVspoof 2021/2024, In-the-Wild audio deepfakes
  • Segments: 5s windows with 2.5s overlap (same as current system)

Training Strategy

Phase A: Contrastive Pre-Training on Real Media (2–3 days on Colab)

This is the core innovation. We train the network to understand what reality looks like BEFORE showing it any fakes.

Objective: SimCLR-style contrastive loss
  - Positive pairs: Two augmented views of the SAME real image
  - Negative pairs: Different real images in the batch
  - The network learns: "real images have consistent noise patterns,
    consistent frequency spectra, consistent ELA responses"

Dataset: 50K–100K real images
  - FFHQ (70K high-quality face images)
  - LSUN subsets (bedrooms, churches β€” non-face content)
  - COCO subset (diverse real-world scenes)

Augmentations (forensic-preserving):
  - Random crop + resize (preserves noise structure)
  - Horizontal flip
  - JPEG compression at random quality (60–95)
  - Gaussian noise injection (simulates sensor noise variation)
  - DO NOT use color jitter or heavy geometric transforms
    (these destroy the forensic signals we need to learn)

Phase B: Supervised Fine-Tuning with Fake Data (3–5 days on Colab)

Datasets (mixed):
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚ Dataset                  β”‚ Real   β”‚ Fake      β”‚ Manipulation Types  β”‚
  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  β”‚ FaceForensics++ (C23)    β”‚ 1,000  β”‚ 4,000     β”‚ DF, F2F, FS, NT    β”‚
  β”‚ Celeb-DF v2              β”‚ 890    β”‚ 5,639     β”‚ Face swap           β”‚
  β”‚ DFDC (Kaggle subset)     β”‚ 1,000  β”‚ 4,000     β”‚ Various             β”‚
  β”‚ Self-generated (SDXL)    β”‚ β€”      β”‚ 5,000     β”‚ Text-to-image       β”‚
  β”‚ Self-generated (Flux)    β”‚ β€”      β”‚ 3,000     β”‚ Text-to-image       β”‚
  β”‚ WildDeepfake             β”‚ 3,805  β”‚ 3,509     β”‚ Real-world          β”‚
  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  β”‚ TOTAL                    β”‚ ~6,700 β”‚ ~25,000   β”‚ 8+ methods          β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Loss function (multi-task):
  L = Ξ»1 Β· BCE(final_pred, label)           # Binary classification
    + Ξ»2 Β· Ξ£ BCE(stream_i_pred, label)       # Per-stream supervision
    + Ξ»3 Β· ConsistencyLoss(stream_vectors)   # Streams should agree
    + Ξ»4 Β· ContrastiveLoss(embeddings)       # Maintain pre-trained representations

  Ξ»1=1.0, Ξ»2=0.3, Ξ»3=0.2, Ξ»4=0.1

Phase C: Adversarial Robustness Training (1–2 days)

Attack the model with common real-world degradations:
  - JPEG compression (quality 30–70)
  - Resolution downscaling (0.25x–0.75x + upscale)
  - Social media simulation (screenshot β†’ re-upload pipeline)
  - Gaussian noise injection
  - H.264 video compression at CRF 23–35

Training approach: For each batch, randomly apply 1–3 degradations
to both real and fake samples. The model must maintain accuracy
despite degradation.

Training Hyperparameters

Optimizer:       AdamW (lr=3e-4, weight_decay=0.01)
Scheduler:       Cosine annealing with warmup (500 steps)
Batch size:      8 (RTX 3050) / 32 (Colab T4)
Precision:       FP16 mixed precision (torch.cuda.amp)
Epochs:          Phase A: 50 / Phase B: 30 / Phase C: 10
Image size:      224Γ—224 (all streams)
Gradient accum:  4 steps (effective batch = 32 on RTX 3050)

NVIDIA Stack Integration

Library Where Used How
cuFFT Stream 2 (SpectralCNN) torch.fft.fft2() β†’ cuFFT backend for GPU-accelerated 2D FFT
cuDNN All streams torch.backends.cudnn.benchmark = True for auto-tuned convolutions
TensorRT Production inference Export trained model β†’ ONNX β†’ TensorRT INT8 engine. Target: <30ms/image
DALI Training data pipeline GPU-decoded JPEG/H.264 loading, replaces CPU-bound torchvision.transforms

All NVIDIA libraries will be credited in README.md and documentation as required.


Project File Structure

d:\ANTIGRAVITY\
β”‚
β”œβ”€β”€ aegis/                              # NEW: Custom detection engine
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ config.py                       # Architecture hyperparameters
β”‚   β”‚
β”‚   β”œβ”€β”€ streams/                        # 5 forensic streams
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ noise_stream.py             # Stream 1: NoiseResNet (learnable SRM)
β”‚   β”‚   β”œβ”€β”€ spectral_stream.py          # Stream 2: SpectralCNN (FFT + phase)
β”‚   β”‚   β”œβ”€β”€ forensic_stream.py          # Stream 3: ForensicCNN (ELA + stats)
β”‚   β”‚   β”œβ”€β”€ biological_stream.py        # Stream 4: BiologicalTemporalStream
β”‚   β”‚   └── semantic_stream.py          # Stream 5: EfficientNet-B0 backbone
β”‚   β”‚
β”‚   β”œβ”€β”€ fusion/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ cross_attention.py          # Multi-head cross-attention fusion
β”‚   β”‚   └── consistency.py              # Consistency verification logic
β”‚   β”‚
β”‚   β”œβ”€β”€ preprocessing/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ srm_filters.py              # SRM filter bank (30 kernels)
β”‚   β”‚   β”œβ”€β”€ frequency.py                # 2D FFT + DCT + phase extraction
β”‚   β”‚   β”œβ”€β”€ ela.py                      # Error Level Analysis computation
β”‚   β”‚   └── rppg.py                     # Remote photoplethysmography
β”‚   β”‚
β”‚   β”œβ”€β”€ audio/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── audio_net.py                # AudioForensicNet (1D ResNet)
β”‚   β”‚
β”‚   β”œβ”€β”€ training/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ datasets.py                 # Custom PyTorch Dataset classes
β”‚   β”‚   β”œβ”€β”€ contrastive.py              # SimCLR contrastive pre-training
β”‚   β”‚   β”œβ”€β”€ train_streams.py            # Individual stream training script
β”‚   β”‚   β”œβ”€β”€ train_fusion.py             # End-to-end fusion training
β”‚   β”‚   β”œβ”€β”€ train_audio.py              # Audio network training
β”‚   β”‚   └── augmentations.py            # Forensic-preserving augmentations
β”‚   β”‚
β”‚   β”œβ”€β”€ inference/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ predictor.py                # Unified inference class (replaces old pipeline)
β”‚   β”‚   └── tensorrt_export.py          # ONNX β†’ TensorRT conversion
β”‚   β”‚
β”‚   └── evaluation/
β”‚       β”œβ”€β”€ __init__.py
β”‚       β”œβ”€β”€ benchmark.py                # Cross-dataset accuracy evaluation
β”‚       └── robustness.py               # Compression attack robustness tests
β”‚
β”œβ”€β”€ core/                               # KEEP: Existing adapter layer
β”‚   β”œβ”€β”€ media_validator.py              # KEEP: Magic-byte validation
β”‚   β”œβ”€β”€ metadata_forensics.py           # KEEP: EXIF/C2PA analysis
β”‚   β”œβ”€β”€ alignment.py                    # KEEP: RetinaFace alignment
β”‚   β”œβ”€β”€ adapter.py                      # NEW: Bridge old API β†’ new aegis engine
β”‚   └── ...                             # Others deprecated but not deleted
β”‚
β”œβ”€β”€ app.py                              # KEEP: Flask routes (minimal changes)
β”œβ”€β”€ requirements.txt                    # UPDATE: Add new dependencies
β”œβ”€β”€ Dockerfile                          # UPDATE: GPU support option
└── README.md                           # UPDATE: NVIDIA credits + new architecture docs

API Compatibility Layer

The frontend expects a specific JSON contract from /api/predict. We create an adapter that translates MSCVN output to the existing format:

# core/adapter.py β€” Maps new engine output to existing API contract

class MSCVNAdapter:
    """Translates MSCVN predictions to the JSON format expected by index.html"""

    def format_response(self, mscvn_output, media_path, media_type):
        return {
            "success": True,
            "verdict": {
                "final_prediction": "FAKE" if mscvn_output.score > 0.5 else "REAL",
                "final_confidence": mscvn_output.score * 100,
                "final_fake_prob": mscvn_output.score * 100,
                "risk_level": self._risk_level(mscvn_output.score),
            },
            "ensemble": {
                "primary_score": mscvn_output.stream_scores['noise'] * 100,
                "secondary_score": mscvn_output.stream_scores['spectral'] * 100,
                "fused_score": mscvn_output.score * 100,
            },
            "artifact_localization": {
                "ela_url": mscvn_output.heatmaps.get('ela'),
                "freq_url": mscvn_output.heatmaps.get('frequency'),
                "attention_url": mscvn_output.heatmaps.get('consistency'),
            },
            # ... map remaining fields
            "confidence_breakdown": {
                "noise_forensics": mscvn_output.stream_scores['noise'] * 100,
                "spectral_analysis": mscvn_output.stream_scores['spectral'] * 100,
                "pixel_forensics": mscvn_output.stream_scores['forensic'] * 100,
                "metadata": mscvn_output.metadata_score * 100,
            },
            "consistency_matrix": mscvn_output.consistency_matrix.tolist(),
        }

The adapter ensures zero frontend changes. The web UI continues to work exactly as before β€” it just gets better predictions.


Phased Build Order

Phase 1 β€” Foundation & Infrastructure (Week 1)

  • Create aegis/ package structure
  • aegis/config.py β€” all hyperparameters centralized
  • aegis/preprocessing/srm_filters.py β€” SRM filter bank initialization
  • aegis/preprocessing/frequency.py β€” FFT + phase extraction utilities
  • aegis/preprocessing/ela.py β€” ELA computation
  • aegis/training/datasets.py β€” PyTorch Dataset classes for all data sources
  • aegis/training/augmentations.py β€” forensic-preserving augmentations
  • Download & organize training datasets

Phase 2 β€” Core Streams (Week 2–3)

  • aegis/streams/noise_stream.py β€” NoiseResNet with learnable SRM
  • aegis/streams/spectral_stream.py β€” SpectralCNN with dual-head (radial + angular)
  • aegis/streams/forensic_stream.py β€” ForensicCNN with spatial attention
  • aegis/streams/semantic_stream.py β€” EfficientNet-B0 backbone
  • aegis/training/train_streams.py β€” individual stream training script
  • Train each stream independently (verify each stream learns useful features)

Phase 3 β€” Contrastive Pre-Training (Week 3–4)

  • aegis/training/contrastive.py β€” SimCLR contrastive loss implementation
  • Collect real-media dataset (FFHQ + LSUN + COCO subsets)
  • Pre-train Streams 1–3 on real media only (Colab/Kaggle)
  • Evaluate: does the model cluster real images in embedding space?

Phase 4 β€” Fusion & End-to-End Training (Week 4–5)

  • aegis/fusion/cross_attention.py β€” transformer cross-attention fusion
  • aegis/fusion/consistency.py β€” consistency verification + stream masking
  • aegis/training/train_fusion.py β€” end-to-end multi-task training
  • Train full MSCVN on FaceForensics++ / Celeb-DF / DFDC / self-generated
  • Adversarial robustness training (compression attacks)

Phase 5 β€” Video & Audio (Week 5–6)

  • aegis/streams/biological_stream.py β€” rPPG + temporal consistency
  • aegis/preprocessing/rppg.py β€” blood flow signal extraction
  • aegis/audio/audio_net.py β€” AudioForensicNet
  • aegis/training/train_audio.py β€” audio training on ASVspoof
  • Integrate video pipeline (frame sampling + per-frame MSCVN + temporal fusion)

Phase 6 β€” Integration & Deployment (Week 6–7)

  • aegis/inference/predictor.py β€” unified inference class
  • core/adapter.py β€” API compatibility adapter
  • aegis/inference/tensorrt_export.py β€” TensorRT optimization
  • Update app.py β€” swap old pipeline for new MSCVN engine
  • Update requirements.txt and Dockerfile
  • Update README.md β€” NVIDIA credits, new architecture docs
  • aegis/evaluation/benchmark.py β€” cross-dataset accuracy evaluation
  • aegis/evaluation/robustness.py β€” compression robustness tests
  • Deploy to HF Spaces with GPU

Verification Plan

Automated Tests

# Per-stream unit tests
python -m pytest aegis/tests/test_noise_stream.py -v
python -m pytest aegis/tests/test_spectral_stream.py -v
python -m pytest aegis/tests/test_fusion.py -v

# Full pipeline integration test
python aegis/evaluation/benchmark.py --dataset faceforensics --split test

# Robustness test
python aegis/evaluation/robustness.py --attacks jpeg,resize,noise --dataset celeb_df

Accuracy Targets

Benchmark Current AEGIS-AI Target (MSCVN)
FaceForensics++ (C23) ~55% (guessing) >92%
Celeb-DF v2 ~50% (guessing) >88%
Self-generated (Flux/SDXL) ~50% (fails) >85%
JPEG compressed (Q=40) ~50% (fails) >80%
Cross-dataset (train on FF++, test on CelebDF) ~50% >82%

Manual Verification

  • Test with known real photos from personal camera
  • Test with known AI-generated images from Midjourney, Flux, DALL-E 3
  • Test with deepfake videos from public examples
  • Test with screenshots / social media re-uploads (robustness)
  • Verify frontend displays results correctly (no JSON contract breaks)

Open Questions

Dataset Access: FaceForensics++ requires an official request to TUM (Technical University of Munich). We should submit the request form ASAP β€” it can take 1–3 days to get access. In the meantime, we can start with Kaggle subsets and self-generated data.

Training Compute: Heavy training (contrastive pre-training + full fine-tuning) will need ~10–15 hours on a T4 GPU. Do you have access to Google Colab Pro ($10/month) or are we using free-tier Colab (4hr session limit)?

Self-Generated Fakes: To make the model robust against current generators, we should generate our own fake training data using Stable Diffusion XL, Flux, and potentially Midjourney. Do you have access to any of these generators, or should we use only the open-source ones (SDXL, Flux)?