Skip to content
internxtPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

133 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mail Spam Detector & Bandwidth Reduction


Table of Contents

  1. Mail Spam Detector
  2. Bandwidth Reduction

Mail Spam Detector

Project goals in mail

Project Goals

  • 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


Constraints Summary

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

Tokenizer

BPE Tokenizer — Overview

Byte Pair Encoding (BPE) algorithm:

  1. Build initial vocabulary from characters
  2. Iteratively merge most frequent adjacent pairs
  3. Assign unique token IDs to each vocabulary entry
  4. Apply learned merge rules at inference time

Special tokens: [CLS], [SEP], [UNK], [PAD], [MASK]


Tokenizer Implementation Choices

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

Tokenizer — Vocabulary & Data

  • 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 of p)

Model Architecture

BERT/RoBERTa Encoder

  • 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


XAI Layer

**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 & Quantization

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

Training

Training Details

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

Datasets

Data Sources

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

Dataset Summary

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

Results and summary {#summary-spam}

Model's Results

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 ✗ ✓ ✓

Summary

  • 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

Infrastructure

Codebase Structure

Core modules (Python/PyTorch)

  • models.py — Transformer architecture
  • attention.py — Attention layers
  • loss.py — Custom loss functions
  • dataset.py — Batch management
  • tokenizer.py — BPE tokenizer
  • trainers.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

CLI Quick Reference

pip install poetry && poetry install
poetry run cli --help

Key commands:

  • buildfolders — parse datasets into ham/spam folders + CSVs
  • train — train model from JSON config
  • test — evaluate model
  • exportonnx — export to ONNX format
  • buildbow — build vocabulary & merge rules
  • buildwiki — generate Wikipedia training corpus


Bandwidth Reduction for Internxt Meet

AI-Powered Video Quality Enhancement


Project goals in BW

Problem Definition

Goal: Reduce kbps required to transmit a video stream while preserving resolution.

Bandwidth saving:

%saving = 100(1 - y/x)

where $x$ = original kbps, $y$ = reduced kbps.

  • 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)

Constraints Summary

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

Jitsi Meet Environment

Codec Preferences

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


Jitsi Scalability: K-SVC & Multicasting

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.


Models & Tools


Gamma Correction

Goal: Recover brightness lost during compression.

Gamma formula:

M' = 255 (M/255)^γ

$γ&gt; 1$: brighter; $γ &lt; 1$: darker

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 & Loss Functions

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⁻³

Development & Iterations

Iteration 1 — CNN + VAE (Discarded)

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

Iteration 2 — Pruned CNN (Discarded)

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

Final Solution

Final Pipeline

Key insight: Remove the Internxt encoder entirely — put all workload on the decoder.

  1. Jitsi encoder sends stream at half resolution (downsampled)
  2. 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)


Final Results

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

Summary bandwidth

  • 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

Implementation Notes (Browser / ONNX)

  • 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 ImageBitMap before its reference, not after
  • Tensor reuse: tensors should be reused; on dimension change, release content manually to avoid orphan tensors and memory leaks

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages