- Detect spam in emails and SMS (binary classification)
- Run on browsers & edge devices (no external APIs)
- Comply with Internxt's privacy principles
- Use modern NLP AI techniques
Key technologies: Byte Pair Encoding (BPE) · BERT/RoBERTa · ONNX · XAI layer
| Constraint | Requirement | Reason |
|---|---|---|
| Inference time | < 100 ms | Smooth XUI |
| Model size | < 20 MB | Fast browser loading |
| Execution | CPU only (no GPU) | User devices |
| Accuracy | ≥ 95% | Accurate detection |
| Environment | Internext's mail | Platform constraint |
Byte Pair Encoding (BPE) algorithm:
- Build initial vocabulary from characters
- Iteratively merge most frequent adjacent pairs
- Assign unique token IDs to each vocabulary entry
- Apply learned merge rules at inference time
Special tokens: [CLS], [SEP], [UNK], [PAD], [MASK]
Discarded options
- HuggingFace RoBERTa tokenizer (50k tokens → large model, external API)
- Python tokenizer (not easily portable to browser)
Chosen solution
- C++ implementation (faster training & inference)
- Exported via Emscripten → WebAssembly (WASM)
- No external dependencies at runtime
- Python’s Wikipedia package allows us to scrap wikipedia
- Training corpus: spam + Wikipedia articles (English + Spanish) datasets
- Topics scrapped from wikipedia: companies, finance, politics, geography and science terms. Chosen heuristically
- English only: 8k tokens, 1M chars from the 29.5M scrapped
- Bilingual (EN + ES): 18k tokens; 2M chars from the 46.4M scrapped
- UTF-8 encoding supports non-ASCII (Greek, Cyrillic, Hiragana)
- We catch look-alike characters used for spammers to trick users (e.g.
ρinstead ofp)
- Uses the encoder side of the Transformer only
- Output: probability over 2 labels (spam / ham)
- Classification head: Mean Pool → Feed Forward (GeLU) → Softmax
- Custom PyTorch implementation (flexibility for ONNX export, RoPE, ALiBi, etc.)
Tunable hyperparameters: token length · hidden dimension · # attention layers · # attention heads · positional embedding method
**Goal:**compute pm for each m-token to indicate which tokens drive the prediction.
$p_m \in [0,1]$ - Model is more clear, not just a black-box
- Model can be audited
Advantage vs. LIME / SHAP / GRAD-CAM: No extra model, no extra passes, no backprop.
ONNX
- Cross-platform ML format
- Runs in browser via CPU
- Requires static forward graph (no dynamic loops/ifs)
Quantization (ONNX)
- Float32 → Int8 (int16 / int4 also available)
- Smaller size + faster inference
- Static calibration used (data is private)
- Drawback: accuracy drop notable for small models
Optimizer
- ADAM, lr ≈ 5×10⁻⁵
- Cosine LR scheduler
- Warm-up: first 10% of steps
Loss function
L = - sum p(x)\log q(x) + λ||W||_2
- Cross-entropy for classification
- L2 penalty on XAI weights
$W$ - λ is the penalty impact
Public datasets
- Enron (2002): 27,716 msgs link
- TREC 2007 (2007): 75,419 msgs link
- SpamAssassin (2003): 5,797 msgs link
- Ling-Spam (-): 2,893 msgs[link](http://www.aueb.gr/users/ion/data/lingspam public.tar.gz)
- Spam Email Dataset (-): 5695 msgs link
- Twitter SMS Spam Hunter (2018-2022): 25,890 msgs link
- UTKML SMS Contest(-): 12416 msgs link
- SMS Phishing Dataset(-): 5971 msgs link
Synthetic / distilled data
- GPT-5 generated: 20,720 ham + 18,320 spam (EN)
- LLAMA 3.2 generated: EN + ES with emojis & special chars
- ES: 4,355 ham / 4,575 spam
- EN: 4,555 ham / 5,200 spam
| Split | Ham | Spam | Total |
|---|---|---|---|
| Training | 104,811 | 104,813 | 209,624 |
| Testing | 22,460 | 22,460 | 44,920 |
| Validation | 22,461 | 22,461 | 44,922 |
| Total | 149,482 | 149,984 | 299,466 |
- Balanced: 50.1% spam / 49.9% ham
- Messages from 2000–2025 (email + SMS)
- Filtered: < 8 words or containing HTML/JS tags removed
| HuggingFace | Our Model | 2nd option | |
|---|---|---|---|
| Size | 490 MB | 72 MB (!) | 6 MB |
| Vocabulary | 50k | 18k | 18k |
| Testing accuracy | 99% | 98% | 95% |
| Inference time | 4318 ms | 58 ms | 15 ms |
| XAI? | ✗ | ✓ | ✓ |
| Browser-Ready | ✗ | ✓ | ✓ |
- Privacy-first: fully on-device, no external API calls
- Custom BPE tokenizer in C++/WASM — 18k tokens, bilingual (EN/ES)
- Custom BERT encoder in PyTorch → exported to ONNX
- XAI layer provides token-level explanations in a single forward pass
- Accuracy 98%, 58 ms inference, 72 MB model size
- Trained on ~300k balanced messages spanning 2000–2025
Core modules (Python/PyTorch)
models.py— Transformer architectureattention.py— Attention layersloss.py— Custom loss functionsdataset.py— Batch managementtokenizer.py— BPE tokenizertrainers.py— Train & test routines
Tooling
cli.py— CLI (train, test, export)onnxquant.py— Quantization- Poetry for dependency management
- TensorBoard + tqdm for monitoring
- pytest + coverage for testing
pip install poetry && poetry install
poetry run cli --helpKey commands:
buildfolders— parse datasets into ham/spam folders + CSVstrain— train model from JSON configtest— evaluate modelexportonnx— export to ONNX formatbuildbow— build vocabulary & merge rulesbuildwiki— generate Wikipedia training corpus
Goal: Reduce kbps required to transmit a video stream while preserving resolution.
Bandwidth saving:
%saving = 100(1 - y/x)
where
- Resolution must be preserved — trivial pixel-dropping is forbidden
- Quality enforced via SSIM ≥ 0.95 (SSIM is the structural similarity index, 1 → images are equal, 0 → nothing alike)
| Constraint | Requirement | Rationale |
|---|---|---|
| Inference time | < 50 ms (P2P, 20 fps) | Real-time operation |
| Model size | < 20 MB | Fast browser loading |
| Execution | CPU only (no GPU) | User devices |
| Bandwidth saving | ≥ 50% | Meaningful improvement |
| SSIM | ≥ 0.95 | Perceived quality |
| Environment | Jitsi Meet (WebRTC) | Platform constraint |
Codec priority by device
- Desktop: AV1 > VP9 > VP8 > H264
- Phone: H264 > VP8 > VP9 > AV1
- P2P: VP8 > VP9 > H264 > AV1
Bandwidth per codec at HIGH (720p)
| Codec | kbps |
|---|---|
| AV1 | 1000 |
| VP9 | 1200 |
| VP8 | 1500 |
| H264 | 2000 |
AV1: best compression, high CPU cost — H264: low CPU cost, larger files
Multicasting (VP8, H264)
- Multiple resolution streams sent to bridge
- Bridge selects stream per participant
K-SVC (AV1, VP9)
- Layered encoding: up to 3 resolutions (L) × 3 fps (T)
- KEY: layers are independent (can discard freely)
Downsampling rids (standard)
| rid | Factor |
|---|---|
| 1 | 4.0× |
| 2 | 2.0× |
| 3 | 1.0× |
Higher factors apply for FULLHD/ULTRAHD cameras.
Goal: Recover brightness lost during compression.
Gamma formula:
M' = 255 (M/255)^γ
Brightness metric (RGB):
B(M) = 0.2126M_R + 0.7152M_G + 0.0722M_B
- Target brightness: 100 (scale 0–255)
- Max correction: ±20 brightness units (prevents over-correction)
- Network input always resized to 16×16 for constant shape
Dataset — VGGFace2
- 198k face images, 2.32 GB
- Wide variation: pose, age, lighting, ethnicity
- In-the-wild captures
Loss functions
- Image quality: SSIM-based : L = |1 - SSIM(x, y)|
- Brightness correction: MSE on gamma : L = MSE(γ_x, γ_y)
Optimizer: ADAM, lr = 10⁻³
Architecture: Convolutional encoder–decoder + variational sampler + brightness corrector
- Theoretical bandwidth reduction: 98.4%, SSIM: 0.95
- Outside Jitsi: encoder 40 ms, decoder 70 ms ✓
- Inside Jitsi (parallel processes): encoder 120 ms, decoder 210 ms ✗
- 6× over the 50 ms limit → rejected
Changes from v1: removed VAE sampler, reduced layers & hidden dims, dropped brightness corrector.
| Metric | Value (720p) | Target |
|---|---|---|
| SSIM | 0.99 | > 0.95 |
| Theoretic BW reduction | 75% | > 50% |
| Encoder inference | 5 ms | < 50 ms |
| Decoder inference | 44 ms | < 50 ms |
- Results looked promising, deployed to production
- Problem: with 3+ participants, decoder runs per incoming track → severe lag
- Rejected and disabled post-deployment
Key insight: Remove the Internxt encoder entirely — put all workload on the decoder.
- Jitsi encoder sends stream at half resolution (downsampled)
- Internxt decoder on receiver side:
- Bilinear upsampling (×2 in rows and columns)
- Gamma correction network (16×16 input → brightness fix)
Theoretical bandwidth reduction:
100(1 - 1/4) = 75%
(half resolution in each dimension = quarter the pixels)
| Property | Value (720p) | Target | Met? |
|---|---|---|---|
| SSIM | 0.98 | > 0.95 | ✓ |
| Theoretic BW reduction | 75% | > 50% | ✓ |
| Empiric BW reduction | 67% | > 50% | ✓ |
| Inference time | 28 ms | < 50 ms | ✓ |
| ONNX model size | 336.4 kB | < 20 MB | ✓ |
- Empiric vs. theoretic gap (67% vs. 75%) due to codecs without K-SVC (VP8, H264)
- Applied only to resolutions < 240p in production → mean inference 8 ms
- Real-time, CPU-only bandwidth reduction for Internxt Meet (Jitsi-based)
- Final approach: bilinear upsampling + lightweight gamma correction network
- All constraints met: SSIM 0.98, 67% empiric BW saving, 28 ms inference, 336 kB model
- Two prior architectures (VAE, pruned CNN) discarded due to multi-participant lag
- Deployed for streams < 240p; mean inference time 8 ms in production
- Single ONNX session — one session for all participants, not one per track
- Dimension order: ONNX/Python use
[C,H,W]; JS uses[H,W,C]— translation required - Dynamic resolution: codec rids can change resolution abruptly — dispose
ImageBitMapbefore its reference, not after - Tensor reuse: tensors should be reused; on dimension change, release content manually to avoid orphan tensors and memory leaks