Skip to content

About

Intelligent model optimization toolkit for edge and on-device AI, providing graph-aware quantization, mixed-precision optimization, compression, benchmarking, and hardware-aware deployment support.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

7 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SnapQuant AI — Intelligent Model Optimization for Edge and On-Device AI

Test Suite Python Version Frontend Stack Hardware Targets Accuracy Safety License


1. Project Overview

SnapQuant AI is an autonomous, accuracy-aware, and hardware-aware neural network optimization engine designed to compress, quantize, and package deep learning vision models for edge accelerators, microcontrollers, and modern PC platforms—including Qualcomm Snapdragon X Elite and Snapdragon X Plus Copilot+ PCs.

SnapQuant AI replaces manual, ad-hoc quantization scripts with an automated multi-candidate exploration pipeline. It characterizes computation DAGs, evaluates competing precision candidates (FP16, per-channel INT8 QDQ, and sensitivity-aware Mixed Precision), enforces hard accuracy safety gates against held-out validation data, and generates self-contained deployment packages complete with hardware-specific operator compatibility manifests.


2. Problem

Deploying deep learning models to on-device edge environments introduces severe engineering challenges:

  1. Memory Bandwidth & Storage Footprint: Unquantized 32-bit floating-point (FP32) models consume excessive memory bandwidth and storage, exceeding strict thermal and energy budgets on edge devices.
  2. Catastrophic Accuracy Collapse: Blind single-pass post-training quantization often causes severe accuracy degradation—especially on delicate vision transformer attention blocks and normalized layers—without automated recovery mechanisms.
  3. Hardware & Accelerator Fragmentation: Edge AI accelerators and neural processing units (NPUs) impose strict constraints on operator sets, tensor dimensions, and quantization parameter alignments that generic export frameworks fail to validate prior to deployment.

3. Solution

SnapQuant AI solves these bottlenecks through an integrated, autonomous pipeline:

  • Topology-Driven Graph Characterization: Inspects actual neural computation DAGs to classify architectures (CNN, Vision Transformer, Hybrid) and identify sensitive subgraphs (attention heads, normalization layers, residual connections).
  • Multi-Candidate Exploration Space: Generates competing, isolated optimization candidates tailored to the model architecture and target hardware profile.
  • Empirical Accuracy Safety Gate: Automatically evaluates candidates against validation data, classifying accuracy retention and immediately vetoing degraded candidates to safely preserve the FP32 baseline.
  • Hardware-Aware Packaging: Analyzes operator support, inspects dynamic axes, and generates complete, auditable deployment manifests for target runtimes.

4. Architecture

SnapQuant AI is engineered with clean modularity between model ingestion, structural analysis, optimization engines, and hardware deployment adapters:

 ┌──────────────────────────────────────────────────────────────┐
 │                     Model Ingestion Layer                    │
 │         ONNX • PyTorch • TensorFlow Lite • SafeTensors       │
 └──────────────────────────────┬───────────────────────────────┘
                                │
                                ▼
 ┌──────────────────────────────────────────────────────────────┐
 │              Graph Characterization Engine                   │
 │   - Topology Pattern Recognition (CNN / Transformer / Hybrid)│
 │   - Attention Detection (Q*K^T -> Softmax -> *V)             │
 │   - Normalization & Dynamic Axis Categorization              │
 └──────────────────────────────┬───────────────────────────────┘
                                │
                                ▼
 ┌──────────────────────────────────────────────────────────────┐
 │                Architecture-Specific Routers                 │
 │   ┌───────────────────┬───────────────────┬──────────────┐   │
 │   │    CNN Engine     │Transformer Engine │ Hybrid Engine│   │
 │   └─────────┬─────────┴─────────┬─────────┴──────┬───────┘   │
 └─────────────┼───────────────────┼────────────────┼───────────┘
               │                   │                │
               ▼                   ▼                ▼
 ┌──────────────────────────────────────────────────────────────┐
 │             Autonomous Candidate Search Space                │
 │       FP16 • Per-Channel INT8 QDQ • Mixed Precision          │
 └──────────────────────────────┬───────────────────────────────┘
                                │
                                ▼
 ┌──────────────────────────────────────────────────────────────┐
 │               Validation & Safety Policy Gate                │
 │   - Empirical Ground-Truth Accuracy Evaluation               │
 │   - Quality Thresholds: EXCELLENT (≤1.0 pp) / ACCEPTABLE     │
 │   - Unverified Metric Fail-Safe Retaining FP32 Baseline      │
 └──────────────────────────────┬───────────────────────────────┘
                                │
                                ▼
 ┌──────────────────────────────────────────────────────────────┐
 │          Hardware Target Packaging & Deployment              │
 │   - Snapdragon X Elite / X Plus (QNN Static HTP Manifest)    │
 │   - Raspberry Pi 5 • NVIDIA Jetson • STM32 Cortex-M4         │
 │   - Self-Contained Deployable .uaqe Package Generation       │
 └──────────────────────────────────────────────────────────────┘

The underlying Python engine resides in src/uaqe/, accompanied by an interactive TypeScript/React cockpit in frontend/.


5. Optimization Pipeline

The core optimization workflow executes through six automated phases:

  1. Ingestion & Inspection: Ingests the model, computes cryptographic SHA256 checksums, inspects tensor inputs/outputs, and generates structural metadata.
  2. Empirical Baseline Evaluation: Benchmarks the original FP32 model on validation data to establish verified reference accuracy and host latency baselines.
  3. Candidate Synthesis:
    • FP16 Candidate: Converts weights to 16-bit half-precision floating point.
    • INT8 QDQ Candidate: Inserts paired QuantizeLinear and DequantizeLinear operators with per-channel scaling.
    • Mixed Precision Candidate: Protects noise-sensitive layers (boundary encoder blocks, attention Softmax, LayerNorm) in native FP32 while quantizing feed-forward networks to INT8.
  4. Accuracy & Metric Validation: Runs all candidates through held-out evaluation samples using identical preprocessing.
  5. Safety Gate & Pareto Ranking: Applies the AccuracySafetyPolicy to verify quality, filtering candidates that exceed allowed loss thresholds and ranking survivors across accuracy, size, and latency.
  6. Hardware Packaging: Bundles the winning artifact into a standardized .uaqe container with target deployment manifests.

6. Supported Model Types

SnapQuant AI characterizes and optimizes three primary neural network families:

A. Convolutional Neural Networks (CNN)

  • Supported Models: MobileNetV2, MobileNetV3 (Small/Large), ResNet-18, ResNet-50, custom ConvNet classifiers.
  • Strategies: Post-Training Quantization (PTQ INT8), Quantization-Aware Training (QAT), Structured Sensitivity Pruning, XNNPACK CPU acceleration.

B. Vision Transformers (ViT / DeiT)

  • Supported Models: Data-efficient Image Transformers (DeiT-Tiny, DeiT-Small), Vision Transformers (ViT-Base, ViT-Large).
  • Strategies: Attention head preservation, decomposed LayerNorm/RMSNorm protection, FP16 half-precision, per-channel INT8 QDQ, and boundary-protected Mixed Precision.

C. Hybrid Vision Models

  • Supported Models: Architectures combining convolutional stems with self-attention transformer blocks (e.g., MobileViT style).
  • Strategies: Multi-stage partition analysis, stage-aware quantization policies, protected transition layers.

7. Supported Hardware Targets

SnapQuant AI implements dedicated hardware target profiles in src/uaqe/orchestration/hardware_target_registry.py:

Hardware Target Compute Architecture Preferred Runtime Target Precision Deployment Deliverable
Snapdragon X Elite / X Plus Qualcomm Hexagon NPU / Oryon CPU ONNX Runtime QNN Execution Provider (onnxruntime-qnn) INT8 QDQ, Mixed Precision, FP16 snapdragon_deployment_manifest.json, ONNX model, QNN build script
Raspberry Pi 5 Quad-core ARM Cortex-A76 TensorFlow Lite with XNNPACK Delegate Per-channel / per-tensor INT8 Optimized .tflite, benchmark script
NVIDIA Jetson (Nano / Orin) NVIDIA Ampere / Maxwell GPU TensorRT / ONNX Runtime CUDA FP16, INT8 QDQ ONNX model, TensorRT build recipe
STM32 Cortex-M4 ARM Cortex-M4 Microcontroller CMSIS-NN / STM32Cube.AI Per-channel symmetric INT8 Quantized FlatBuffer, memory budget audit

8. Accuracy Safety Mechanism

To prevent deployment of degraded models, SnapQuant AI enforces an uncompromising Accuracy Safety Policy (AccuracySafetyPolicy):

$$\Delta_{\text{pp}} = \text{Candidate Accuracy} - \text{FP32 Baseline Accuracy}$$ $$\text{Loss}_{\text{pp}} = \text{FP32 Baseline Accuracy} - \text{Candidate Accuracy}$$

Hard Quality Thresholds:

  • EXCELLENT: $\text{Loss}_{\text{pp}} \le 1.0\text{ percentage point}$ (Eligible for all profiles, including accuracy_first).
  • ACCEPTABLE: $1.0\text{ pp} < \text{Loss}_{\text{pp}} \le 4.0\text{ percentage points}$ (Eligible for balanced and size_first profiles).
  • CRITICAL: $\text{Loss}_{\text{pp}} > 4.0\text{ percentage points}$ (Automatically vetoed and rejected).

Fail-Safe Metric Unavailability Invariant:

If an evaluation dataset is missing, malformed, or inaccessible, the candidate is flagged UNVERIFIED_METRIC_UNAVAILABLE. An unverified candidate cannot satisfy accuracy constraints or become the winning deployment model; the system safely retains the reference FP32 baseline.


9. Real-Model Results

Empirical validation results on real neural network architectures:

Real CNN: MNIST Classifier

  • Baseline FP32 Accuracy: 98.80%
  • Quantized INT8 Accuracy: 98.70% (Loss: $+0.10\text{ pp}$)
  • Compression Ratio: 4.0× model size reduction
  • Safety Status: EXCELLENT (Passed)

Real CNN: MobileNetV3 Semiconductor Wafer Defect Classifier

  • Task: 9-class industrial wafer defect inspection (SEM imagery).
  • Baseline Size: 6.84 MiB (FP32).
  • Optimized Size: 1.77 MiB (INT8 QAT / XNNPACK).
  • Hardware Acceleration: 204/204 operators delegated to XNNPACK CPU runtime (0 fallbacks).

10. Transformer Validation

Empirical end-to-end validation was conducted on the genuine facebook/deit-tiny-patch16-224 Vision Transformer:

  • Parameters: 5,717,416 float32 parameters
  • Architecture: 12 Transformer encoder blocks, 3 attention heads, embedding dimension 192, patch size 16×16
  • Export: ONNX opset 14 with dynamic batch axis (pixel_values: [batch_size, 3, 224, 224])
  • Numerical Verification: Max logit difference PyTorch vs. ONNX Runtime CPU = $4.05 \times 10^{-6}$ (zero NaNs, zero Infs)

Multi-Strategy Artifact Audit:

Variant Artifact Path Size (MiB) Size Reduction Total Nodes QDQ Nodes SHA256 Checksum
FP32 Baseline models/deit_tiny_patch16_224.onnx 22.00 MiB Baseline (1.0×) 1,266 0 dcfb6110b7d71814...
FP16 models/deit_tiny_fp16.onnx 11.18 MiB 49.18% (1.97× smaller) 1,269 0 7aedc2f3a881d97f...
INT8 QDQ models/deit_tiny_int8_qdq.onnx 6.35 MiB 71.15% (3.47× smaller) 2,671 1,405 7773252af5557cfb...
Mixed Precision models/deit_tiny_mixed_precision.onnx 8.79 MiB 60.03% (2.50× smaller) 2,445 1,179 d57aa17231ab809a...

Structural Boundary Protection:

Mixed Precision preserves 226 additional operations in native Float32 compared to pure INT8 QDQ. Both boundary blocks (Layer 0 and Layer 11) and all LayerNorms and Softmax operations remain completely unquantized (0 QDQ nodes inside boundary blocks).

Ground-Truth Accuracy on Web-Hosted Validation Subset:

DeiT-Tiny accuracy was measured on a genuine 1,000-image ImageNet-1k validation subset (ronanhansel/imagenet-1k-validation-subsets, split validation_1k) across all four precision variants using identical preprocessing (BICUBIC resize to 224×224, ImageNet normalization):

Model Variant Top-1 Accuracy Top-5 Accuracy Correct (Top-1) Accuracy Delta vs FP32 Safety Decision
FP32 Baseline 67.10% 88.80% 671 / 1,000 — Reference Baseline (VALID)
FP16 67.10% 88.80% 671 / 1,000 $\mathbf{+0.00\text{ pp}}$ EXCELLENT (Satisfied)
INT8 QDQ 67.40% 88.70% 674 / 1,000 $\mathbf{+0.30\text{ pp}}$ EXCELLENT (Satisfied)
Mixed Precision 66.90% 88.50% 669 / 1,000 $\mathbf{-0.20\text{ pp}}$ EXCELLENT (Satisfied)

Evaluation Manifest Hash: ce98944d89836df97acecda428bf8346648c78ff472e622516dc132c76f451fa (SHA256 across all 1,000 evaluation rows). Calibration was conducted using 184 genuine SEM defect images, honestly documented as calibration_domain = OUT_OF_DOMAIN.


11. Snapdragon Deployment Analysis

SnapQuant AI implements a dedicated Snapdragon target workflow designed for Copilot+ PCs powered by Snapdragon X Elite and Snapdragon X Plus processors:

1. Hardware-Aware Optimization

Prepares models for execution with the ONNX Runtime QNN Execution Provider (onnxruntime-qnn), optimizing graph structures to leverage Qualcomm Hexagon NPU capabilities.

2. Operator Compatibility Analysis

Cross-references every node in the model graph against Qualcomm QNN HTP specifications:

  • For DeiT-Tiny, 320/320 operators (100.0% operator coverage) are verified compatible with QNN HTP primitives.

3. Dynamic-Shape Analysis & Readiness

Qualcomm Hexagon HTP offline graph compilation requires static tensor dimensions. SnapQuant AI inspects all input and intermediate tensors, classifying dynamic axes into semantic categories (batch, sequence, spatial, kv_cache). If dynamic shapes exist, the packager issues:

"deployment_readiness": "REQUIRES_STATIC_SHAPE_FIX"

and provides static shape override scripts to prepare the graph for offline context binary generation.

4. Deployment Package Generation

Emits a compliant, self-contained deployment directory and .uaqe archive containing:

  • The optimized ONNX model artifact.
  • snapdragon_deployment_manifest.json recording operator support, dynamic shape classifications, candidate roles (OPTIMIZED_CANDIDATE vs SOURCE_MODEL), and SHA256 checksums.
  • Standalone execution scripts for ONNX Runtime with Qualcomm QNN Execution Provider.

12. Installation

Prerequisites

  • Python 3.10, 3.11, 3.12, or 3.13
  • Node.js 18+ and npm (for frontend cockpit)
  • Git

Setup Steps

# 1. Clone the repository
git clone https://github.com/SachinSB06/SnapQuant-AI.git
cd SnapQuant-AI

# 2. Create and activate a Python virtual environment
python -m venv .venv
# On Windows:
.venv\Scripts\activate
# On Linux/macOS:
source .venv/bin/activate

# 3. Install Python dependencies
pip install -r requirements.txt

# 4. Build frontend production assets
cd frontend
npm install
npm run build
cd ..

13. Quick Start

A. Launch the Web Cockpit

# Start the backend API server
python uaqe.py serve --host 127.0.0.1 --port 8000

In a separate terminal, launch the frontend dev server or serve the compiled bundle:

cd frontend
npm run dev

Navigate to http://localhost:5173 to explore the Model Registry, configure optimization jobs, and inspect generated deployment manifests.

B. Command-Line Interface (CLI)

# Inspect a model graph
python uaqe.py inspect-model --model models/mobilenetv3_sem_9class_qat_int8.tflite

# Plan optimization for Snapdragon target
python uaqe.py plan \
  --model models/deit_tiny_patch16_224.onnx \
  --target snapdragon_x_elite \
  --profile balanced

14. Testing

SnapQuant AI includes a rigorous test suite covering graph characterization, routing, transformer quantization, hybrid partitioning, Snapdragon packaging, and accuracy safety:

# Run the complete test suite (658 tests: 654 passing, 4 skipped)
python pytest.py

# Run dedicated Vision Transformer validation suites (38 tests)
python pytest.py \
  tests/test_real_transformer_validation.py \
  tests/test_deit_numerical_fidelity.py \
  tests/test_deit_web_accuracy_validation.py

# Run CNN regression tests
python pytest.py \
  src/uaqe/tests/test_accuracy_pipeline_and_baseline_guard.py \
  src/uaqe/tests/test_phase_r1_resnet50_int8_ptq.py \
  src/uaqe/tests/test_phase_e2_cifar10_resnet50.py

Note on Skipped Tests (4): The four skipped tests in the repository suite verify graceful fallback behavior when the Qualcomm QNN SDK / physical hardware silicon is absent on the host.


15. Reproducibility

Step-by-step reproduction instructions for all published experiments:

  1. Export Pretrained DeiT-Tiny:

    python scripts/export_deit_tiny.py

    Exports facebook/deit-tiny-patch16-224 to models/deit_tiny_patch16_224.onnx (opset 14) and validates numerical fidelity against PyTorch ($< 1.0 \times 10^{-4}$ max diff).

  2. Run Real Web Accuracy Validation:

    python scripts/run_deit_accuracy_validation.py

    Evaluates all 1,000 samples of ronanhansel/imagenet-1k-validation-subsets (validation_1k) across FP32, FP16, INT8 QDQ, and Mixed Precision variants.

  3. Run Canonical Host Latency Benchmark:

    python scripts/run_canonical_benchmark.py

    Executes CanonicalBenchmark.benchmark_onnx (10 warmup runs, 100 timed runs, 2 threads) on host CPU.


16. Limitations

In alignment with strict engineering transparency:

  1. Validation Subset Scope: Task accuracy for DeiT-Tiny was measured on a genuine 1,000-image ImageNet-1k validation subset, not the full 50,000-image official ImageNet validation set.
  2. Host-Measured Benchmark Timings: All reported latency and throughput figures represent host development CPU execution via ONNX Runtime. Target NPU throughput (TOPS) and on-device power consumption require profiling on physical Snapdragon silicon or Qualcomm AI Hub.
  3. Static Shape Requirements for NPU: Qualcomm QNN HTP graph compilation requires static input dimensions. Models containing dynamic batch axes require static overrides before offline binary compilation.

17. Future Work

Future engineering milestones for SnapQuant AI focus on advanced algorithmic exploration and automated tuning:

  • Adaptive Layer-Wise Precision Selection: Automatic per-layer integer bit-width allocation (INT4 / INT8 / FP16) based on second-order Hessian trace approximations.
  • Hardware-Aware Auto-Tuning Search: Closed-loop Bayesian search for optimal operator kernel configurations and tile sizes.
  • Multimodal & Large Transformer Quantization: Extending topology characterization to autoregressive transformer decoders (LLaMA, Mistral) and vision-language architectures.
  • Quantization-Aware Training (QAT) with Learned Step Sizes: Integrating automated QAT pipelines with learned step-size quantization (LSQ) for sub-4-bit weights.
  • Structured Sparsity & Advanced Clustering: Combining structured 2:4 sparsity with weight clustering for maximum compression on supported hardware.
  • Automated Cloud-to-Edge Deployment CI/CD: Cloud-orchestrated compilation connecting directly to Qualcomm AI Hub device farms for automated on-device hardware profiling.

18. License

SnapQuant AI is licensed under the Apache License, Version 2.0. See the LICENSE file for complete terms, conditions, and third-party model acknowledgments.


19. Author

SACHIN SB
Department of Electronics and Communication Engineering (ECE)
Chennai Institute of Technology, Chennai, India
GitHub: @SachinSB06

About

Intelligent model optimization toolkit for edge and on-device AI, providing graph-aware quantization, mixed-precision optimization, compression, benchmarking, and hardware-aware deployment support.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages