EmbeddingGemma-2 Edge ONNX INT8 (Multimodal Β· Zero PyTorch Β· Zero Vocab Pruning)

A universal, CPU-accessible ONNX Runtime INT8 optimization of Google DeepMind's google/embeddinggemma-2 covering Text/Code, Images, and Spoken Audio in a single unified 768D Matryoshka (768 / 512 / 256 / 128D) vector space β€” running with zero PyTorch or Transformers dependency at runtime, zero vocabulary pruning (all 262,144 multilingual tokens intact), and strictly <= 3.0% quality drop across every modality.

Highlights (measured on consumer Apple M1 8-core CPU vs PyTorch MPS BF16 baseline):

  • 39.2Γ— faster cold startup: 0.30 s to first text embedding (1.12 s for all 3 towers) vs 11.85 s PyTorch.
  • 2.1×–5.9Γ— faster throughput on pure CPU: 40.5–95.9 queries/s, 13.3 docs(128t)/s, 3.91 images/s (5.9Γ— vs PyTorch 280 tok), and 5.75 audios/s (1.42Γ— vs PyTorch).
  • 2.28Γ— smaller on disk, 3.7×–8.4Γ— lower RAM: 672.6 MB total for all 3 towers (308.7 MB text-only); 402 MB peak RSS for text (926 MB for all 3 towers).
  • 100% Apache 2.0 with standalone zero-PyTorch runtime (eg2_edge/) bundled directly in this repository.

Architecture & Optimizations

This release combines lossless graph-level ONNX optimizations with outlier-aware mixed-precision INT8 quantization and zero-backpropagation structural pruning:

  1. Zero-Copy Memory-Mapped Full Vocabulary (0 tokens pruned):
    • The 262,144 Γ— 512 multilingual embedding matrix is stored as a per-row symmetric INT8 table (embed_tokens_int8.npy + embed_tokens_scale.npy, 128.5 MB) loaded via np.load(..., mmap_mode="r") (~5 ms load, <2 MB active RSS for queries).
    • Uses the native binary SentencePiece model (tokenizer.model, 4.5 MB, 14.1Γ— faster to load than tokenizer.json, 100% bit-identical token IDs across 100+ languages).
  2. Modular Lazy Tower Loading:
    • Loads only backbone_int8.onnx (175.7 MB) at startup; vision_int8.onnx (127.0 MB) and audio_int8.onnx (236.9 MB) load lazily on first image/audio call and can be unloaded at any time to reclaim RAM.
  3. Exact Graph-Level CPU Fusions (0.00% mathematical drift):
    • Fused qkv_proj (3Γ— -> 1Γ— DynamicQuantizeLinear per layer) and fused gate_up_proj (2Γ— -> 1Γ— wider GEMM).
    • Replaced 1,842 slow transcendental torch.pow ops in RMSNorm (pow(x, 2), pow(ms, -0.5)) and GeGLU tanh (pow(x, 3)) with pure x * x and rsqrt.
    • Dynamic Vision patch trimming strips unused padding patches per batch (630 -> 486–576), saving 15–26% $O(P^2)$ vision attention FLOPs with zero quality loss.
    • Pre-optimized offline using portable ORT_ENABLE_EXTENDED graph passes so inference sessions start in ~180 ms without rewriting the graph on every launch.
  4. Outlier-Aware Selective INT8 Protection:
    • Activation profiling of google/embeddinggemma-2 revealed extreme GeGLU activation spikes (112×–312Γ— max/rms) entering mlp.down_proj in layers L5, L6, L18–L23.
    • Keeping just 10 of 194 backbone MatMul nodes in FP32 (embedding_projection, per_layer_model_projection, and those top-8 high-kurtosis down_proj layers) reduces quantization cosine error by 60% (0.9824 -> 0.9935) while preserving 40+ q/s CPU speed.
  5. Zero-Backpropagation Multi-Gap Residual Ridge Layer Pruning:
    • Vision Tower (16L -> 12L, -25% layers, max_soft_tokens=70): Removed layers [1, 2, 4, 6] and healed the resulting gaps analytically via closed-form internal ResidualRidgeSeamLayer bridges (h -> h + h @ W_res + b_res, seam cosine 0.999–1.000, 0.00% OOS drop).
    • Audio Tower (12L -> 10L, -17% layers): Removed layers [1, 2] with an analytical internal Residual Ridge seam (cos = 0.996), preserving full multilingual speech retrieval.
    • Text Backbone (24L full depth): Kept intact to preserve Per-Layer Embeddings (PLE) fidelity within the strict <= 3.0% benchmark budget.
  6. Multi-Worker GIL-Free Media Pools & 1-Bit -> INT8 SQLite Index:
    • Bundled eg2_edge runtime includes parallel ONNX session pools (media_workers=4) and a single-file SQLite 1-Bit Binary -> INT8 multimodal file index (91.6 MB / 1M files @ 768D with 100.0% retention; 30.5 MB / 1M files @ 256D).

Benchmarks

All timings were measured solo (no contention) on an Apple M1 (8-core CPU, 16 GB unified memory) with all 262,144 tokens intact.

Metric google/embeddinggemma-2 PyTorch MPS BF16 This Model: Universal CPU ONNX INT8
Runtime Dependencies torch, transformers, accelerate onnxruntime, sentencepiece, numpy, pillow
Hardware Support MPS / CUDA / ROCm Any CPU (Windows, Linux, macOS, Docker, ARM64/x86)
Cold Startup (1st Text Embedding) 11.85 s 0.30 s (39.2Γ— faster)
Cold Startup (All 3 Towers Loaded) 11.85 s 1.12 s (10.6Γ— faster)
Disk Footprint (All 3 / Text-only) 1,530 MB 672.6 MB (308.7 MB text-only)
Peak RSS Memory (Text / All 3) ~3,400 MB 402 MB / 926 MB
Throughput: Text Queries 16.3 q/s (bs=1) 40.5 q/s (SciFact) / 95.9 q/s (NFCorpus) (bs=1: 33.6 q/s)
Throughput: Text Docs (128 / 256 tok) β€” / 7.8 doc/s (bs=32) 13.3 doc/s / 5.0–5.2 doc/s (pure CPU)
Throughput: Images (max_soft_tokens=70) 0.66 img/s (280 tok) 3.91 img/s (4w, 1w: 3.21 img/s, 5.9Γ— faster)
Throughput: Audio (16 kHz WAV) 4.04 aud/s (bs=1) 5.75 aud/s (4w, 1w: 4.63 aud/s, 1.42Γ— faster)
Quality: PIRB SciFact-PL (nDCG@10, 300q) 68.61% (full 5.1k: 66.17%) 67.28% (-1.94%, q_cos = 0.9935)
Quality: PIRB NFCorpus-PL (nDCG@10, 323q) 31.77% (full 3.6k: 31.38%) 30.97% (-2.51%, q_cos = 0.9932)
Quality: 24 Hard Confusable Images OOS 100.0% R@1 / 100.0% MRR 100.0% R@1 / 100.0% MRR (0.00% drop, cos = 0.9750)
Quality: 18 Bilingual PL+EN Spoken Audio OOS 94.4% R@1 / 96.3% MRR 100.0% R@1 / 100.0% MRR (+3.7 pkt, cos = 0.9672)
Unified 58-File Cross-Modal SQLite (768D 1b→8b) 93.1% R@1 / 96.0% MRR (FP32) 93.1% R@1 / 96.0% MRR (100.0% retention, 91.6 MB/1M)

Repository Contents

File Size Description
backbone_int8.onnx 175.7 MB Shared 24L bidirectional text/multimodal transformer (fused QKV/MLP, outlier-protected INT8)
embed_tokens_int8.npy + embed_tokens_scale.npy 128.5 MB Zero-copy mmap per-row symmetric INT8 table for all 262,144 tokens
tokenizer.model (+ tokenizer.json) 4.5 MB Binary SentencePiece tokenizer (fast load; HF JSON included as fallback)
vision_int8.onnx 127.0 MB Lazy 12L pruned + Residual Ridge healed vision encoder (max_soft_tokens=70, dynamic patch trim)
audio_int8.onnx 236.9 MB Lazy 10L pruned + Residual Ridge healed Conformer audio encoder (16 kHz mono WAV)
manifest.json <1 KB Model metadata, special token IDs, and runtime flags
eg2_edge/ <25 KB Standalone zero-PyTorch Python runtime (engine.py, preprocessors.py, index.py)
LICENSE / NOTICE β€” Apache 2.0 license and upstream attribution

Quick Start (Zero PyTorch)

Install only the lightweight runtime dependencies:

pip install onnxruntime sentencepiece numpy pillow huggingface_hub

Download and run Text, Image, and Audio embeddings in 10 lines of Python:

import sys
from huggingface_hub import snapshot_download

# Download full repo (or pass ignore_patterns=["vision_int8.onnx", "audio_int8.onnx"] for text-only!)
model_dir = snapshot_download("Damaon/embeddinggemma-2-edge-onnx-int8")
sys.path.insert(0, model_dir)

from eg2_edge import UniversalEdgeEmbeddingGemma2, MultimodalEdgeIndex

engine = UniversalEdgeEmbeddingGemma2(model_dir, num_threads=4, media_workers=4)

# 1. Text & Code embeddings (Matryoshka: dim=768, 512, 256, or 128)
q_vec = engine.encode_texts("invoice for cloud GPU servers", prompt="query")
d_vecs = engine.encode_texts(["Server invoice PDF 2026", "Quarterly revenue chart"], prompt="document")
print("Text cosine similarities:", d_vecs @ q_vec)

# 2. Image embeddings (lazy-loads vision_int8.onnx; default 70 soft tokens)
img_vec = engine.encode_images("diagram.png")
print("Image-to-query similarity:", float(img_vec @ q_vec))

# 3. Audio embeddings (16 kHz PCM WAV; lazy-loads audio_int8.onnx)
aud_vec = engine.encode_audios("voice_note.wav")
print("Audio-to-query similarity:", float(aud_vec @ q_vec))

# 4. Single-file SQLite 1-Bit -> INT8 Multimodal File Organizer (91.6 MB / 1M files @ 768D)
idx = MultimodalEdgeIndex("my_files.sqlite", engine=engine, dim=768)
idx.index_directory("./my_documents")
for hit in idx.search_text("cloud server invoice or deployment voice memo", top_k=5):
    print(f"[{hit.modality}] {hit.score:.3f} | {hit.path}")
idx.close()

Supported Text Task Prompts

Pass prompt= to encode_texts(...) using either a built-in key or a custom prefix string:

  • "query" β†’ "task: search result | query: "
  • "document" β†’ "title: none | text: "
  • "code" β†’ "task: code retrieval | query: "
  • "clustering" β†’ "task: clustering | query: "
  • "classification" β†’ "task: classification | query: "
  • "similarity" β†’ "task: sentence similarity | query: "
  • "fact" β†’ "task: fact checking | query: "

Limitations & Notes

  • Vision soft-token budget: vision_int8.onnx is exported for max_soft_tokens=70 (up to 630 patches, dynamically trimmed per batch). This delivers a 4.9×–5.9Γ— speedup with negligible quality loss for general photo, screenshot, diagram, and chart retrieval; dense small-font OCR documents may benefit from higher soft-token budgets using the upstream checkpoint.
  • Audio input format: The bundled pure-NumPy preprocessor natively reads uncompressed 16-bit PCM .wav files (automatically mono-mixing and resampling to 16 kHz). For MP3/M4A/OGG, decode to a float32 16 kHz NumPy array first and pass it directly to encode_audios([waveform]).
  • Precision: Never cast activations to float16 (EmbeddingGemma 2 relies on full FP32/BF16 dynamic range in RMSNorm and PLE). The ONNX graphs keep all activations in FP32 with INT8 weights (QInt8).
  • Inherited limitations: As a quantized/pruned derivative of google/embeddinggemma-2, this model inherits its training-data coverage and bias characteristics. Please review the upstream EmbeddingGemma 2 Model Card and Gemma Prohibited Use Policy.

License & Citation

Released under the Apache License 2.0 (see LICENSE and NOTICE), matching the upstream google/embeddinggemma-2 release by Google DeepMind.

If you use this model, please cite the upstream EmbeddingGemma 2 technical report:

@misc{embeddinggemma2_2026,
    title={EmbeddingGemma 2: Unified and Efficient Multimodal Representations},
    author={Schechter Vera, Henrique and Dua, Sahil and Team, EmbeddingGemma},
    year={2026},
    eprint={2610.37364},
    archivePrefix={arXiv},
    primaryClass={cs.LG},
    url={https://arxiv.org/abs/2610.37364}
}
Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Model tree for Damaon/embeddinggemma-2-edge-onnx-int8

Quantized
(154)
this model

Paper for Damaon/embeddinggemma-2-edge-onnx-int8