Trit
How it works

Networks with three possible weights, answering in milliseconds.

Trit runs two models directly in your browser. A six-layer language model sorts email, with every one of its 10,616,832 layer weights set to −1, 0 or +1: the heavy math becomes additions and subtractions, the whole model is 14.4 MB, and it reads an email in a few milliseconds on a consumer GPU, 50–90× faster than a round trip to a cloud model, without your mail leaving the browser. A ternary image model does the same for photos of water samples, spotting microplastics.

Part one · Email triage
1.58
bits per weight
log₂ 3 — three possible values
16×
smaller than FP32
2.5 MB vs 40.5 MB for the 36 layer matrices
~6 ms
per email
one email at a time, WebGPU on an RX 6650 XT
418/s
batched
32 emails packed per GPU submission
Part two · Microplastics
A ternary ConvNeXt that says none, a few or a lot, from a photo of a water sample
93% on 100 test images~9 ms / photo2.8 MB
00 · Overview

The big picture

How Trit classifies an emailThe inbox sends each email to a Web Worker that tokenizes the text, runs six ternary transformer layers on WebGPU with weights cached in OPFS, pools the result through the decision head and routes it, returning the decision in milliseconds. The email never leaves the browser. Offline, labelled datasets retrain the model, DeepEval verifies it locally, and it is served as a static file the browser downloads once.Your browserTrit server · Next.js on VercelOffline training · ml/Inbox UImain threadWeb Worker · on-device1TokenizeWordPiece26 layersternary · GPU3Pool+head4+1 scores4RoutethresholdsOPFS cache14 MB model on local diskload weightsemaildecision · ~6 ms/api/v1/modelsstatic manifest + weightsdownload on changeTraining dataCEAS_08 · teacher · synthDistill MiniLM → ternaryteacher → 1.58-bit studentPack & calibrate16 weights per u32Verify · DeepEvallocal · no LLM judgeship if no regressionOn-device decisionOffline / background
Every decision is made on-device in milliseconds. The server only hands out the model files; retraining and verification happen offline. Hover or tap a box to see what it does.
01 · Weights

Why “1.58 bits”, not 1

A normal network stores each weight as a 16- or 32-bit number. This one allows only three values: −1, 0 and +1. Three choices carry log₂ 3 ≈ 1.58 bits of information, hence the name. (A true 1-bit model would only have −1 and +1; the extra 0 lets the model switch an input off, which matters a lot for accuracy.)

We start from MiniLM, a small pretrained language model that has already read billions of words, and first fine-tune it at full precision on email triage (the teacher). Then a copy (the student) rounds every layer weight to ternary on each forward pass, using the average magnitude γ of each weight row:

γrow = mean(|Wrow|)  ·  Wternary = clamp(round(W / γrow), −1, +1)

Gradients flow through the rounding with a straight-through estimator, and the student learns to reproduce the teacher's answers and its internal states layer by layer (distillation). After training only the ternary values and one γ per row (20,736 numbers in total) are kept.

02 · Storage

16 weights in one 32-bit word

Each weight is stored in 2 bits: 01 for +1, 10 for −1 and 00 for 0. Sixteen of them fit in a single unsigned 32-bit integer, the native word size of a GPU.

+10−10+1+10−100+1−10+10−1
16 weights → 1 × u320x84908521

All 36 layer matrices (10,616,832 weights) pack into 2.5 MB, compared with 40.5 MB in FP32. The rest of the file is the word vocabulary's embeddings, stored as 8-bit integers.

03 · Compute

Matrix math without multiplying

Multiplying by +1 is a copy, by −1 a negation, by 0 nothing at all. So each output of the ternary layer is just a sum of some inputs minus a sum of others, scaled once at the end:

y = γ · ( Σ xi where wi = +1  −  Σ xi where wi = −1 )
input x0.8-1.20.52.0-0.31.10.7-0.9
weight w+10−1+10−1+10
operation+0.8skip−0.5+2.0skip−1.1+0.7skip
result before scaling1.9

On the GPU each thread owns one output row. It reads one 32-bit word, extracts sixteen 2-bit codes with shifts and masks, turns each into +1, −1 or 0 without branching, and applies it to 16 tokens at once from shared memory. Up to 32 emails are packed into one sequence, and embedding, all six layers and the mean-pool run on the GPU, so a whole batch costs 44 GPU dispatches, uploads only token ids and reads back one 384-number vector per email.

One honest detail: on the GPU, applying the ±1 is still a float multiply-add (acc += s · x), because a GPU does that as fast as an add and it avoids branching. The result is identical to adding and subtracting. The win on a GPU is memory: 16× less weight data to move. The CPU fallback really does only additions and subtractions.

04 · Precision

What exactly is 1.58-bit

Paper · V1 foundationarXiv:2402.17764 ↗
Shuming Ma, Hongyu Wang, Lingxiao Ma, Lei Wang, Wenhui Wang, Shaohan Huang, Li Dong, Ruiping Wang, Jilong Xue, Furu Wei · Microsoft Research · Feb 2024

Introduces BitNet b1.58: absmean ternary quantization into {−1, 0, +1} trained with a straight-through estimator. Trit V1 adapts this to per-row/per-channel scales γ and distills from pretrained teachers in W1.58 A32 rather than training from scratch in W1.58 A8.

“A 1.58-bit model” is easy to over-claim, so here is the exact breakdown, measured from the model file the browser downloads, not from the training code.

Ternary: all 36 weight matrices in the six transformer layers, where almost all of the arithmetic happens. Every one of those weights is −1, 0 or +1.

Not ternary: the word-embedding table is 8-bit. It is a lookup table, so it costs no arithmetic, and ternary embeddings would blur the meaning of 30,522 word pieces. Position vectors, LayerNorms, the per-row scales γ, biases and the 5-output decision head stay 32-bit. They are tiny.

Activations stay 32-bit. The numbers flowing between layers are full-precision floats. BitNet b1.58 also squeezes those to 8 bits, which pays off on chips with fast 8-bit math; a GPU running WebGPU gains little from it. In the usual notation this model is W1.58 A32, not BitNet’s W1.58 A8.

Where the bits go
File sizetrit.bin, 14.4 MB
2.5 MB · 18%11.2 MB · 78%712 KB · 4.8%
Parameters22.5 M numbers
10.6 M · 47%11.7 M · 52%182 K · 0.8%
Math per emailmultiply-adds for a 191-token email (the test-set average)
2.03 B · 92%168.1 M · 7.7%

The int8 embedding table is the largest part of the file but does no math: each token just looks up its row. Nearly all of the arithmetic runs through ternary weights.

Precision at every stepthe numbers flowing between steps are float32
Ternary · 1.58-bitint8 · 8-bitfloat32 · 32-bitActivations × activations · float32
Word embedding
30,522 × 384 lookup
+
Position
256 × 384
LayerNorm
transformer layer · ×6
Q · K · V
3 × 384→384
Attention
Q·Kᵀ, softmax, ·V
Output
384→384
Add & LayerNorm
Feed-forward up
384→1536 + GELU
Feed-forward down
1536→384
Add & LayerNorm
Every ternary matrix also has one float32 scale γ per output row and a float32 bias.
Mean pool
Decision head
384→5
Calibrate & route
All 10,616,832 layer weights, decoded from the file1.584 bits/weight · max log₂3 = 1.585
−134%
032%
+134%

No other value appears anywhere in the packed weights. The three values are used almost equally, so each weight carries close to the full 1.58 bits; it is stored in 2 bits because 1.58 bits doesn’t pack evenly.

Every weight matrix in the six transformer layers is ternary (−1, 0, +1): 1.58 bits per weight, stored in 2. Embeddings are int8; activations are float32.

That sentence is the accurate one-line description. “A 1-bit model” or “the whole model is 1.58-bit” would not be: most of the file is the 8-bit embedding table.

05 · Pipeline

From email to decision

  1. 1
    TokenizeCPU · worker

    Sender, subject and body become WordPiece tokens from a 30,522-entry vocabulary: common words stay whole, rare ones split into pieces, so nothing is out of vocabulary. Up to 256 tokens.

  2. 2
    EmbedCPU · worker

    Each token looks up a 384-number vector (stored as int8) and adds a position vector, so the model knows word order. Then LayerNorm.

  3. 3
    Six transformer layersWebGPU · trit_matmul / trit_attention / trit_add_ln.wgsl

    Each layer lets every token look at every other token (12 attention heads), then passes each token through a feed-forward network. All six weight matrices per layer — query, key, value, output, and the two feed-forward layers — are ternary.

  4. 4
    PoolCPU · worker

    The 384-number vectors of all tokens are averaged into one vector that represents the whole email.

  5. 5
    Decision headCPU · worker

    A small layer turns that vector into 4 intent scores (request, spam, notification, newsletter) and 1 lead score.

  6. 6
    Calibrate & routeCPU · worker

    Temperature-scaled softmax and sigmoid turn scores into honest probabilities; thresholds tuned on held-out mail pick Priority, Newsletter, Review or Likely spam.

Intent temperature
1.2
Lead temperature
1.05
Spam suggestion ≥
80%
Priority lead ≥
60%
06 · Input

What the model reads

Speed also comes from a hard budget on input. Per email the on-device model reads:

Fields
Sender and subject, plus the plain-text body
Other headers, HTML layout, images and attachments are ignored
Body
First 6,000 characters
Trimmed before tokenizing
Tokens
Up to 256 WordPiece tokens
Roughly the first 150 words of normal English; 54% of CEAS emails are longer and get cut
Vocabulary
30,522 word pieces
Unknown words are split into known pieces instead of being dropped

Most routing signals sit in the sender, subject and opening lines, so long forwarded threads are where the window matters. It can be raised to 512 tokens at roughly twice the compute.

07 · Speed

Why it’s this fast

  • It decides, it doesn’t write. A chat model generates its answer one token at a time, running the whole network again for each one. This model does a single forward pass and outputs five probabilities.

  • It’s small. Six layers and 10.6 million ternary weights, against billions of 16-bit weights in a chat model. A typical email is about two billion additions, which a consumer GPU finishes in a few milliseconds.

  • Ternary math is cheap math. The weight layers need no real multiplications, move 16× less weight data than FP32, and reuse each decoded weight for 16 tokens.

  • Batches share the trip. Every GPU submission has a fixed cost of about 2 ms in the browser. Packing 32 emails into one sequence spreads it out: 418 emails per second instead of about 170.

  • It never leaves the browser. No network round trip. The model runs in a Web Worker, so the page stays responsive even while classifying 1,000 emails.

  • Weights load from local disk. The first visit downloads the model into the browser’s private file system (OPFS). After that it loads with synchronous file reads in tens of milliseconds, and refreshes automatically when the model changes.

Time to classify one email
Trit, one email, WebGPU~6 ms
Trit, batched, per email~2.4 ms
Cloud LLM API, over the network~300–550 ms

Measured in Chrome on an AMD RX 6650 XT over 1,000 CEAS emails (mean 191 tokens), tokenization included; p99 for a single email is 8.9 ms. The CPU fallback takes about 1 s per email. Rerun it at /bench.

08 · Results

How it compares

Every test below is data the model never trained on. Spam is scored against the Kaggle labels; leads against emails whose answer we know. The old model is the earlier single-layer bag-of-words design.

CEAS test (rows 0-999, Kaggle labels)
ModelSpam accuracy %Spam flaggedLegit wrongly flagged
Trit transformer99.8593/5980
Old bag-of-hashes98.7584/5983
Random 100 (rows 6500+, Kaggle labels)
ModelSpam accuracy %Spam flaggedLegit wrongly flagged
Trit transformer9742/460
Old bag-of-hashes9440/460
Hand-written (12 leads + 10 legit)
ModelSpam accuracy %Spam flaggedLegit wrongly flaggedLeads caughtFalse leads
Trit transformer81.81/138/121
Old bag-of-hashes54.51/180/120
Synthetic, unseen industries
ModelSpam accuracy %Spam flaggedLegit wrongly flaggedLeads caughtFalse leads
Trit transformer9932/320104/1050
Old bag-of-hashes98.132/32281/1050

Hand-written modern mail is the weak spot: some genuine leads are missed and some legitimate mail is suggested as spam. The honest referee is a gold set labelled from your own inbox, and every run is tracked over time by ml.eval_deepeval.

09 · Trade-offs

What it can’t do (yet)

Speed comes from simplicity, and simplicity has costs. We’d rather you know them:

  • It reads the start of each email. 256 tokens is roughly 150 words. A lead buried at the bottom of a long forwarded thread can be missed.

  • Not everything is ternary. The 36 layer matrices are 1.58-bit. Word embeddings (most of the file) are 8-bit, and activations, attention scores, LayerNorm and the small decision head stay in 32-bit floats. See “What exactly is 1.58-bit” above.

  • It still learned mostly from 2008 mail. Training data is the CEAS spam corpus, labels distilled from a larger teacher model and synthetic leads. On modern business mail it still mistakes some genuine inquiries (an enterprise licence request, a salon asking for Instagram help) and receipts for spam, so it never junks anything on its own.

That's why Trit only ever suggests spam and leaves the final call to you.

Part two

The same trick for images: spotting microplastics in a photo.

The Microplastics tab runs a second ternary network, a ConvNeXt that looks at a photo of a water sample and answers no microplastics, a few or a lot, and shows where it saw them. It is 2.8 MB, and takes about 9 ms per photo, JPEG decoding included.

10 · Task

None, a few, or a lot

The model gives one of three answers for a photo of water in a glass dish: no microplastics, a few (1 to 9 particles) or a lot (10 or more). It also estimates how many particles there are and where.

It learned from the Kaggle Microplastic Dataset for Computer Vision (public domain): 781 photos of plastic fragments, films and fibres in water, from 6 photo sessions with different plastics and backgrounds, with 7,126 hand-drawn boxes around particles, 1 to 52 per photo.

The catch: every photo contains plastic. The export kept only images with at least one box, so there was no clean water to learn the most important answer from.

11 · Data

Making clean water out of dirty photos

The photo · 7 particles
The photo · 7 particles
Clean plate · inpainted
Clean plate · inpainted
Rebuilt · 3 particles
Rebuilt · 3 particles
Rebuilt · 16 particles
Rebuilt · 16 particles

Clean plates. LaMa, an inpainting network (Suvorov et al., 2021), paints out every boxed particle and fills the hole with what the dish behind it would look like, rim and reflections included. That leaves the same dish with no plastic in it.

Rebuilt dishes. Each training example rebuilds a dish from its clean plate with a chosen number of real particles: some of its own, or more cut from other photos with a similar background (a particle's outline is wherever the photo and its clean plate differ). The same dish is seen with none, a few and a lot, so the model has to count particles instead of recognising dishes. Every example is also flipped, turned, zoomed (the label is recounted from the particles left in view), re-lit, blurred, noised and re-compressed like a camera JPEG.

Particles the annotators missed. Some particles have no box, so a clean plate can still hold plastic and a photo labelled “a few” can really have fifteen. Two models, each trained on half the photos, searched the other half's clean plates, where anything they find must be a missed particle: 239 more particles on 145 plates were painted out and added to the counts. In the two photo sessions full of unboxed fibres, only “a lot” is ever used as a label.

Rendered water samples. All the photos show one setup, a petri dish in a dark bowl, so a clear glass of water on a green cutting mat once came out as “a lot”: the grid lines bent by the glass looked like fibres. Blender now renders 650 more scenes with physically based glass, each once clean and once with plastic fragments, films and fibres in the water: tumblers (some fluted), bowls, beakers and dishes on cutting mats, wood, cloth, tiles and plain surfaces, under random lights (domain randomisation; Tobin et al., 2017). Refraction moves what is seen through water, so each particle is found where it actually appears, as the difference from the clean render, and its reflections in the glass are not counted. Lint and crumbs on the table appear in both renders: only what is in the water counts.

Real clean water. 223 distinct photos of clean water (S. Bonillas, MIT licence) cover the setups the model used to get wrong: glasses and bowls on red, white and dark cloth and on a cutting mat, as well as dishes in the bowl. Near-identical shots are grouped, so a burst of one scene never lands on both sides; 57 are held out, and particles from other photos are pasted into the rest to make “a few” and “a lot” on those backgrounds too.

A test set checked by eye. The 100 test images are held-out photos: 34 clean plates, 33 with a few particles and 33 with a lot. A missing box can only make a count too low, so every “a lot” label is safe. Every clean plate and “a few” photo was looked at: 19 photos were swapped out and 9 clean plates had leftover particles boxed by hand and painted out.

12 · Model

A ConvNeXt with three possible weights

The network is ConvNeXt-pico, a 9-million-weight image model pretrained on ImageNet, reading the photo at 320 × 320. It works on the image at 1/4, 1/8, 1/16 and 1/32 scale, and most of its arithmetic is 1 × 1 convolutions, which are the same matrix multiplications the email model runs, with pixels in place of tokens.

Every 1 × 1 convolution and every stride-2 downsampling convolution is ternary: 8,355,840 of 8,580,484 weights (97.4%), with the email model's recipe:

γchannel = mean(|Wchannel|)  ·  Wternary = clamp(round(W / γ), −1, +1)

Not ternary: the first 4 × 4 layer (3 K weights; the first layer is the most fragile), the 7 × 7 depthwise filters (147 K; 49 weights per channel are too few to share one scale), LayerNorms, scales and biases (71 K) and the two heads. Activations stay float32, so this is W1.58 A32 like the email model.

Weightsmeasured from the 2.8 MB model file
8.4 M ternary · 97%225 K float32 · 2.6%
Multiply-adds per photo320 × 320 input
2.67 B ternary · 96%115 M float32 · 4.1%

Of the ternary weights, 33% are 0, 33% +1 and 34% −1: 1.58 bits of information per weight, stored in 2.

Two heads. One reads the averaged final features and answers none, a few or a lot. The other estimates how many particles sit in each 16 × 16-pixel cell of the input; the cells add up to a count and draw the heatmap in the Microplastics tab.

Knowing when it doesn't know. A model shown a photo unlike anything it learned from still gives a confident answer: before the renders and clean-water photos, a clear glass on a green cutting mat came out as “a lot”, because the grid lines bent by the glass look like fibres. So the app also measures how far a photo's final features are from those of the training photos (Mahalanobis distance in their 64 main directions plus whatever lies outside them; Lee et al., 2018). Above 23.2 (1.5 × the least familiar validation photo), it says “Can't tell” instead of guessing. None of the 100 test images is flagged.

Teacher and student. As for email, a full-precision copy is fine-tuned first. The ternary student starts as that copy and learns to match its answers, its density map and its features at every stage, as well as the labels. Temperature scaling (T = 0.75) makes the probabilities honest.

13 · On the GPU

From photo to answer

  1. 1
    DecodeCPU · worker

    The JPEG becomes pixels with createImageBitmap and no colour management, so they match what Pillow decoded in training.

  2. 2
    Resize and stemWebGPU · vision_stem.wgsl

    The pixels go to the GPU as a texture. Pillow's antialiased bilinear filter shrinks the photo to 320 × 320 (its taps are worked out once on the CPU), then a 4 × 4, stride-4 convolution and LayerNorm turn it into an 80 × 80 grid of 64-number pixels.

  3. 3
    Twelve ConvNeXt blocksWebGPU · vision_dwln / vision_matmul.wgsl

    Each block mixes neighbouring pixels with a 7 × 7 depthwise filter and LayerNorm (one kernel), then runs every pixel through two ternary 1 × 1 convolutions. The second adds its result straight into the running sum, so there is no extra pass.

  4. 4
    Three downsamplesWebGPU · vision_lnds / vision_matmul.wgsl

    Between stages a LayerNorm folds each 2 × 2 patch into one pixel with four times the channels (space-to-depth), and a ternary 2 × 2 stride-2 convolution becomes one matrix multiplication over those patches.

  5. 5
    Density map and poolWebGPU · vision_head.wgsl

    A density head reads the 20 × 20 stage-3 grid: how many particles in each 16 × 16-pixel cell. The last stage is averaged into one 512-number vector. Only those 912 numbers per photo come back from the GPU.

  6. 6
    DecideCPU · worker

    LayerNorm and a 3-way linear layer give none / a few / a lot; a temperature-scaled softmax turns that into calibrated probabilities. The density cells add up to the particle count. A familiarity check on the same features decides whether to answer at all.

Up to 32 photos share one GPU submission: one resize-and-stem dispatch per photo, then 44 for the whole batch. The wide ternary layers give each GPU thread four output channels, so every input it reads from fast shared memory is used four times. The GPU result is checked against an exact CPU implementation of the same network (largest logit difference about 10−6), which in turn matches NumPy and PyTorch.

Most of the time is not the network. The GPU needs about 2.4 ms for one photo and 1.2 ms per photo in a batch; decoding the JPEG, copying its pixels to the GPU and the browser's round trip for each submission make up the rest.

Time per photo
One photo at a time, WebGPU~9 ms
Batched, per photo~3.1 ms (325/s)
CPU fallback (JavaScript)~1.7 s

Measured in Chrome on an AMD RX 6650 XT over the 100 test photos, one after another, JPEG decode included (about 1.5 ms of it). A lone photo after the GPU has been idle takes about 15 ms, because the GPU first has to clock back up. Rerun it at /bench/microplastics.

14 · Results

How well it does

On the 100 held-out test images the ternary model gets 93% of the three-way answers right (the full-precision teacher: 94%). Telling plastic from no plastic is the easier part: 99% right, with 0 of 66 contaminated photos called clean and 1 of 34 clean dishes flagged.

Test set · 100 images · expected → predicted
ExpectedNo microplasticsA fewA lotRight
No microplastics331097.1%
A few0330100%
A lot062781.8%

Most mistakes are photos with a lot of particles called “a few”. In those photos the annotators also boxed dust-sized specks that are left unboxed elsewhere in the data, and the model, like most of the labels, does not count specks; its estimate is off by 1.37 particles per test image on average, clean dishes included. On the held-out validation photos it gets 90.8%. Run it yourself with Test accuracy on all 100 in the Microplastics tab.

15 · Trade-offs

What the microplastics model can't do (yet)

  • Few real clean samples. “No microplastics” is learned mostly from photos with the particles painted out and from renders, plus 223 real clean-water photos. 56 of the 57 held out read “no microplastics”, but they come from the same few setups as the rest.

  • It knows a few kinds of photo. Glass dishes, bowls and tumblers of water shot from above, on dark cloth, coloured or white surfaces and cutting mats. Filters, microscopes or field photos are outside what it has seen; the familiarity check catches most of them and answers “Can’t tell”, but it is a heuristic, not a guarantee. Every photo with plastic in it shows the original dark-bowl setup, so counts on other setups rest on pasted and rendered particles.

  • The line at 10 is fuzzy. Near 10 particles both the labels and the model are uncertain; read the count and the probabilities, not just the label.

  • Specks are not counted. Annotators skipped dust-sized specks and so does the model, so very small particles can go unreported.

  • It screens, it doesn't analyse. Telling plastic from sand, fibre or a bubble for certain, and naming the polymer, needs a microscope and spectroscopy in a lab.