On-Device Embeddings

Search 40,000 photos without sending one. Store 132 bytes a photo instead of 2,048: the index falls from 82 MB to 5.3 MB, and the top ten barely move.

Pick a way to store each vector. Watch the index size against a phone’s memory, and the top ten against the exact search. Then we build it piece by piece: the budget, the small encoder, the cut vector, the plain index, the listener, the anomaly score and the leak.

You need what an embedding is (a list of numbers whose distances mean something) and a little Python. We build the rest from zero.

Shrink the index, keep the answers

Sizes are for 40,000 photos. The results come from a live toy: 1,500 synthetic 512-number vectors whose early numbers carry the most, and 40 test queries, checked against the exact float search. The 30 MB line is an illustrative memory allowance.

Chapter 0

Search Without Sending

Price the two places a photo search can run, and list what the phone must do to win

You want one photo: your dog on the beach at sunset. It is somewhere in 40,000 pictures, and you do not know the date. You want to type the sentence and get the picture.

That is semantic search: a match on meaning, not on file names or tags. An embedding makes it work. A network turns each photo into a fixed list of numbers, a vector. A second network turns your sentence into a vector in the same space. Search returns the photos whose vectors lie closest to the query vector.

DesignWhat movesWhat it costs
A. Send it upEvery photo goes to a server, which embeds and searches120 GB of upload before the first answer
B. Keep it downThe phone embeds, stores and searches; nothing leavesA model, an index and a battery budget on the phone

Count design A. At 3 MB a photo, 40,000 photos are 120 GB. A 20 Mbit/s upload moves that in 13.3 hours. Design B stores vectors instead. At 512 numbers of 4 bytes each, that is 2,048 bytes a photo and 81.9 MB in total. Chapter 3 cuts it to 132 bytes a photo, 5.28 MB, about 23,000 times less than the photos.

Grow the library, compare the bills

Warm is the upload design A needs. Purple is what design B keeps on the phone, at full and at cut size. Drag the library size.

40,000

Assumes 3 MB a photo and 20 Mbit/s of upload. The bars use a log scale; a straight scale would hide the cut index.

A phone is not a small server. It has three hard walls, each with its own enforcer:

WallWho enforces itWhat you see
LatencyThe userSearch feels broken above about 100 ms
MemoryThe operating systemThe OS kills a background task that holds too much
EnergyThe battery screenThe user finds your app at the top and deletes it

Failure. The symptom: one pipeline serves both the query and the first indexing sweep, and it is either slow to answer or hot during the sweep. Measure each path on its own. Fix: give the query path a small, warm model, and give the sweep a batched job that runs while the phone charges.

The road

  1. The budget: which wall binds, and the test for compute against memory.
  2. Shrinking the encoder: architecture, distillation and quantization.
  3. Cut the vector: fewer numbers, fewer bits. This is the hero’s selector.
  4. The index on the phone: why a plain loop beats a graph.
  5. Always on: a wake word, where power rules.
  6. Distance to normal: anomaly scores with an alarm budget.
  7. What leaves the device: an embedding is not anonymous.
  8. Where to cut: the budget board, the showcase.
  9. Field guide: numbers, checklist, code and links.
Why can a phone not reuse one pipeline for both answering a query and building the index?

Chapter 1

The Budget

Name the regime, then test whether a model waits on arithmetic or on memory

"It has to run in 30 ms." Which 30 ms? A phone model works in one of three regimes, and each has its own budget.

RegimeBudgetWhere it comes from
Interactive queryabout 100 ms, end to endBelow it, a response feels instant
Live camera33.3 ms a frame at 30 fps1 / 30 s, shared with the preview
Background sweepno deadlineLimited by energy and heat instead

Spend the 100 ms of a query. Tokenizing takes about 0.2 ms, the text encoder 2 ms and the index scan 3 ms of it. Loading 50 thumbnails takes 40 ms, and drawing the screen takes 15 ms of it. The network is 2 ms of 60. These splits are illustrative, but the pattern holds: the thumbnails are the bill.

Arithmetic or memory?

A multiply-add (MAC) is one multiply and one add. A chip can do many per second, but it must also read every weight from memory. Which one sets the time? Call the multiply-adds per call C and the bytes of weights read W. Their ratio is the arithmetic intensity, I.

Say it aloud

I equals C divided by W.

I
I the arithmetic intensity: multiply-adds done for each byte read.
C
C the multiply-adds in one call of the model.
W
W the bytes of weights the call reads; at int8, one byte per weight.
In plain words

Divide the work C by the bytes W. Compare I with the chip’s own ratio B. If I is larger, arithmetic sets the time. If I is smaller, the chip waits on memory.

With numbers

MobileCLIP’s MCi0 image tower: C = 2.4 billion, W = 11.4 MB at int8. I = 2.4e9 / 11.4e6 = 211. An assumed chip with B = 16 is far below it, so MCi0 is compute-bound.

The chip has its own ratio, the machine balance B. Take its peak rate R (1e12 multiply-adds a second, sold as 2 TOPS), times the share u it reaches (0.4). Divide by its memory speed β (25 GB/s). All three are assumptions for a mid-range phone.

B = (R × u) / β = (1e12 × 0.4) / 25e9 = 16 multiply-adds per byte

Find the wall a workload hits

Pick a workload. Blue is the time for the arithmetic, purple is the time to read the weights. Drag the chip’s speed and memory speed.

40%
25

MCi0: 2.4 G (the paper’s FLOPs column, read as multiply-adds) and 11.4 M weights (MobileCLIP, Vasu et al. 2024). The two layers are 512 to 512 channel 1×1 convolutions on an 8×8 grid and on one position. The chip, 1e12 multiply-adds a second peak, is illustrative.

The model predicts 6.0 ms for MCi0. The paper measures 1.5 ms on an iPhone 12 Pro Max, so that chip is faster than our guess. The estimate still names the right wall. A 1×1 layer on a single position has I = 1: it waits on memory, so cutting its multiply-adds saves nothing.

The energy bill

Per photoEnergyNote
Decode a 12 MP JPEG30 mJassumed; measure yours
Resize and normalize0.6 mJassumed
MCi0 forward pass2.4 mJ4.8 G operations at an assumed 2e12 per joule
Total, 40,000 photos1,320 J2.16% of a 4,400 mAh, 3.85 V battery (60,984 J)

Failure. The symptom: you halve the model and the sweep’s battery cost barely moves. Measure the whole pipeline: here the decoder is 91% of the bill and the model 7%. Fix: embed the library’s small thumbnails instead of the full photos. At an assumed 1.5 mJ a decode, the sweep falls to 0.26% of a charge.

A layer has I = 4 multiply-adds per byte on a chip with B = 16. You halve its multiply-adds. What happens to its time?

Chapter 2

Shrinking the Encoder

Use three separate knobs to make a model small, and see why one outlier ruins int8

The image encoder must run 40,000 times on a phone and still find the dog. Three knobs make an encoder smaller. They do different things, and they stack.

KnobWhat changesWhat it costs
ArchitectureThe shape: layers, channels, resolutionA full retrain
DistillationWhat the weights know; a big teacher trains the small studentA teacher and a training run, paid once
QuantizationHow you store each number: 8 bits, not 32A calibration pass

MobileCLIP (Vasu et al., 2024) is a worked case. Its smallest model, S0, pairs the MCi0 image tower (11.4 M parameters, 1.5 ms) with the MCt text tower (42.4 M, 1.6 ms). The paper times both on an iPhone 12 Pro Max with Core ML. S0 reaches 67.8% zero-shot on ImageNet.

Image towerLatencyImageNet top-1Change
MCi01.5 ms82.2%base
MCi12.5 ms83.8%twice as deep: 1.6 points per ms
MCi23.6 ms84.5%25% wider: 0.64 points per ms

Distillation buys more. MobileCLIP stores a captioning model’s captions and two big CLIP teachers’ embeddings in the dataset once, so training reads them from disk. On the same 12 M images, four small encoders gain 10.6 to 13.7 points of zero-shot accuracy. The student costs nothing extra at inference.

Quantization, and the outlier

Store each weight w as a small integer q from −127 to 127, plus one shared scale s: the real size of one integer step.

Say it aloud

s equals the largest absolute w, divided by 127. Then q equals w over s, rounded.

s
s the scale: one shared number for the whole group.
max|w|
the largest absolute w the biggest weight in the group, sign ignored.
q
q the stored integer, one byte, from −127 to 127.
round
round to the nearest whole number; this step is where error enters.
w
w one real weight. The rebuilt weight is q times s.
In plain words

Find the biggest weight and make it 127 steps. Divide every weight w by that step s and round to get q. The step size is the same for every weight in the group.

With numbers

Weights 0.12, −0.05, 0.31, 0.02, −0.28 and an outlier 2.40. s = 2.40 / 127 = 0.0189, so 0.12 becomes q = 6 and returns as 0.113. The five small weights lose 0.0051 on average.

Let one outlier set the step

Teal bars are five ordinary weights; the faint lines are the int8 grid. Drag the outlier, then give it its own group.

2.40

An illustrative group of six weights, rounded exactly as the equation says.

Put the outlier in its own group, and the five get s = 0.31 / 127. Their error falls to 0.00055, 9.3 times less. The scales differ by 2.40 / 0.31 = 7.7, and log₂ 7.7 = 2.95: the outlier costs every neighbour about three bits. A scale for each output channel of 512 weights adds 0.06 bits a weight.

Failure. The symptom: the int8 model works on your test set and gives nonsense on 0.3% of real photos. Measure activation ranges on the failing inputs. If they pass the range you calibrated on, the values clip. Fix: calibrate on a wider set, or compute that tensor’s range per call.

One weight in an int8 group is 8 times larger than the rest. What happens to the others?

Chapter 3

Cut the Vector

Keep fewer numbers and fewer bits in each vector, and measure what the search loses

The index stays in memory all the time, so it is what gets an app killed. Call the photo count N, the kept numbers d, the bits per number b, and the fixed extra bytes per photo c.

Say it aloud

M equals N times the sum of d times b over 8, plus c.

M
M the index size in bytes.
N
N the number of photos: 40,000.
d
d the numbers kept in each vector, out of 512.
b / 8
b over 8 bits per number, turned into bytes: 32, 8 or 1 bit.
c
c extra bytes per photo: here a 2-byte scale and a 2-byte length.
In plain words

One vector costs d numbers of b bits, plus c bytes of extras. Multiply by N photos. d and b multiply, so cutting both pays twice.

With numbers

Full: d = 512, b = 32, c = 0 gives 2,048 bytes and 81.9 MB. Cut: d = 128, b = 8, c = 4 gives 132 bytes and 5.28 MB. That is 15.5 times smaller.

Fewer numbers: Matryoshka

An ordinary embedding spreads its meaning over all 512 numbers, so the first 128 are a random sample. Matryoshka Representation Learning (Kusupati et al., 2022) applies the loss to prefixes of 8, 16, 32 numbers and up. Early numbers sit in every term, so they learn to carry the most. The paper reports vectors up to 14 times smaller at equal ImageNet accuracy.

A cut prefix has length below 1. Call the vector z and the kept count m.

Say it aloud

z-prime equals z from 1 to m, divided by the length of z from 1 to m.

z′
z-prime the cut vector, stretched back to length 1.
z1..m
z from 1 to m the first m numbers of the length-1 vector z.
‖·‖
the length of the square root of the sum of squares.
In plain words

Keep the first m numbers of z. Measure their length. Divide each kept number by that length, so every photo’s z-prime has length 1 again.

With numbers

With made-up numbers: z = (0.715, 0.477, 0.358, 0.239, …), eight numbers. The first four keep 0.924 of the squared length, so the length is 0.961. z′ = (0.744, 0.496, 0.372, 0.248).

Fewer bits

Int8 on a length-1 vector of 128 numbers is almost free. A step of 0.25 / 127 leaves an error of length 0.0064: cosine 0.99998 to the truth. No later layer multiplies it, unlike a weight’s error. One bit per number keeps the sign: 16 bytes. Two codes differ in h bits, the Hamming distance.

angle ≈ π × h / d = 3.1416 × 20 / 128 = 0.49 rad = 28°, cosine 0.88

128 bits give only 129 distances, so many photos tie. Use bits as a first pass, then rescore the best 100 with int8.

Cut, then count what survives

Pick the numbers kept and the bits. Switch the training off to cut an ordinary embedding.

Live toy: 1,500 synthetic vectors, 40 queries, recall@10 against exact float search on all 512 numbers. The ordinary model is the same data after a random rotation. Sizes are for 40,000 photos.

Failure. The symptom: some photos rank high for no reason. Measure stored lengths after the cut; if they differ, the renormalize is missing. A photo keeping 92.4% of its squared length beats one keeping 80% by √(0.924 / 0.80) = 1.075. Fix: renormalize every cut vector.

You cut a Matryoshka embedding to 128 numbers but skip the renormalize step. What goes wrong?

Chapter 4

The Index on the Phone

Price a plain scan against a graph index, and see why locality decides on a phone

A query arrives. You hold 100,000 vectors of 128 int8 numbers. Server habit says: build an HNSW graph (a layered graph of near neighbours that search walks greedily). On a phone, the plain loop usually wins.

A flat scan compares the query with every stored vector. It reads each byte once, in order. So its time is the bytes divided by the speed of a streaming read, β. Take an assumed β of 8 GB/s for one core.

time = 100,000 × 128 bytes / 8e9 bytes per second = 1.6 ms

HNSW stores links. At the usual M = 16, a node keeps up to 2M = 32 links on the bottom layer. Upper layers add about M / 15 more, at 4 bytes a link.

links ≈ 2M + M / (M − 1) = 32 + 1.07 = 33.07;   × 4 bytes = 132 bytes per node
100,000 vectorsFlat scanHNSW, M = 16
Query timeabout 1.6 ms, one corea fraction of a millisecond
Extra memorynone13.2 MB: it doubles the index
Recallexactbelow 1, set by knobs you must tune
Add or delete a photoappend or remove 132 bytesa graph edit; deletes need a rebuild later

Race a scan against a graph

Blue bars are query time, purple bars are memory held. The pink line is the memory allowance. Drag the library size, then read the index from flash.

100,000

Illustrative constants: 8 GB/s streaming, 1.5 GB/s flash, 100 µs per random flash page, 25 MB allowance. HNSW time models about 1,000 distance checks with a cache miss each; cold, about 300 page faults.

Flat search breaks on memory before time. A million vectors take 132 MB and 16 ms. Shrink the vectors first (Chapter 3): 64 bits each brings a million down to 8 MB. Then split by something the user knows. Say 80% of searches hit the last three years, 12,000 of 40,000 photos. The average scan is 0.8 × 12,000 + 0.2 × 40,000 = 17,600 vectors: 2.3 times less, still exact.

Failure. The symptom: the graph is fast in a benchmark and slow in the app. Measure page faults during a query. A memory-mapped graph jumps around flash: 300 hops at 100 µs add up to 30 ms of waiting. A flat scan streams 5.28 MB in 3.5 ms instead. Fix: keep the scan sequential, and store the 8-byte sign codes in their own array.

On a phone with 100,000 int8 vectors of 128 numbers, why is HNSW usually the wrong first choice?

Chapter 5

Always On

Turn energy per call into power, stream the work, and count false alarms per day

A wake word listener never stops. It embeds the last second of sound, compares it with a stored keyword vector, and does this 50 times a second, all day. The photo app cared about one call. This one cares about every call. Call the energy of one call E and the calls per second f.

Say it aloud

P equals E times f.

P
P the power: joules spent each second, in watts.
E
E the energy of one call, in joules.
f
f the calls per second.
In plain words

Take the energy E of one call. Multiply by the calls f in each second. That is the drain P, and a day is P times 86,400 seconds.

With numbers

The MCi0 call from Chapter 1: E = 2.4 mJ, f = 50. P = 120 mW. A day is 10,368 J, 17% of a 60,984 J battery. Fine for 40,000 photos once; fatal as a listener.

A keyword spotter uses a much smaller model. Its input is 49 frames of 40 numbers: 40 ms windows every 20 ms, covering one second (Zhang et al., 2017). Each new call shares 48 of its 49 frames with the last. A stack of stride-1 convolutions can cache what it computed for those frames and work out only the new column. That cuts the work 49 times, with the same output.

Design (20 M multiply-adds a call)PowerBattery a day
Rerun the whole second each call20 mW2.83%
Stream: compute only the new frame0.41 mW0.058%

The table assumes an audio chip doing 100 G operations per joule. The cache costs about 512 bytes. A layer that looks at the whole window at once, like full attention, cannot use this cache.

False alarms

50 checks a second is 4,320,000 checks a day. A false-accept rate of 0.5% per check gives 21,600 false wakes a day, one every four seconds. For one a day, you need 1 in 4.32 million. The fix is a rule, not a model: wake only after k checks in a row pass.

Demand k checks in a row

The warm line is a detector’s score on ordinary sound. Checks above the pink threshold are false accepts. Raise k and compare the two counts.

0.5%
1

The score is noise from a simulation. Neighbouring checks move together, as overlapping one-second windows do. “Simulated” counts runs in 2.4 hours of it, scaled to a day.

Failure. The symptom: the listener wakes during television. Measure run lengths of passing checks on hours of real audio. Two neighbouring windows share 980 of 1,000 ms, so their errors move together, and the rate pk is far too hopeful. Fix: choose k and the threshold from the measured runs.

A detector checks 50 times a second with a 0.5% false-accept rate per check. What is the problem and the usual fix?

Chapter 6

Distance to Normal

Score how far a window is from normal, and set the alarm line from an alarm budget

A factory pump has run for four years. A vibration sensor on it feeds a microcontroller with 256 kB of memory. You want a warning before the bearing fails. You have no failures to learn from, only four years of normal.

So ask a different question: how far is this window from everything normal? A tiny encoder turns each second of vibration into an embedding. Keep the mean μ of the normal embeddings and their covariance Σ, which says how much each direction usually varies. Call the new embedding t.

Say it aloud

D squared equals t minus mu, transposed, times Sigma inverse, times t minus mu.

D2
D squared the squared Mahalanobis distance: the anomaly score.
(t − μ)T
t minus mu, transposed the gap from normal, laid on its side for the product.
Σ−1
Sigma inverse divides each direction by how much it usually varies.
(t − μ)
t minus mu the gap between the new embedding t and the normal mean mu.
In plain words

Subtract the mean mu from t. Measure that gap in units of normal spread, so a wide direction counts less. Square and add. That is D squared.

With numbers

With made-up 2-D numbers: normal points (1,4), (2,5), (3,4), (2,3), (2,4). They give μ = (2, 4) and a variance of 0.5 per axis. For t = (3.5, 6): D² = 1.5² / 0.5 + 2² / 0.5 = 12.5.

Is 12.5 an alarm? Only an alarm budget can say. If normal embeddings are Gaussian in 2-D, D² passes a line τ with chance e−τ/2. Call the tolerated false-alarm chance per window P.

Say it aloud

Tau equals minus 2 times the natural log of P.

τ
tau the alarm line for D squared.
−2
minus 2 undoes the −τ/2 in the 2-D tail.
ln
the natural log the power of e that gives P.
P
P the false-alarm chance you accept for one window.
In plain words

Decide how often a normal window may raise an alarm: that is P. Take its natural log and multiply by minus 2. Alarm when D squared passes tau.

With numbers

P = 1%: τ = 9.21, and 12.5 alarms, but at one window a second that is 864 false alarms a day. One a day, P = 1 / 86,400: τ = 22.73, and 12.5 is quiet.

Draw the alarm line

Teal dots are normal windows; warm dots are a fault drifting away. Red marks a false alarm. Move the pink line and require k windows in a row.

3.03
1

Illustrative 2-D toy, one window a second. False alarms per day use the Gaussian tail e−D²/2 and treat windows as independent, which is hopeful.

The quiet line costs sensitivity. √22.73 / √9.21 = 1.57: a fault must move 57% further before the detector sees it. Demanding 3 windows in a row at the 1% line gives 86,400 × 0.01³ = 0.086 false alarms a day, if windows were independent.

Failure. The symptom: the pump fails and the detector never alarmed. Measure how fast the mean adapts. A moving average with α = 0.001 at 1 Hz forgets in about 17 minutes, so a fault that grows over weeks becomes normal. Fix: freeze adaptation while the score is high.

You check one window a second and accept one false alarm a day. In 2-D, what is the alarm line τ?

Chapter 7

What Leaves the Device

See why an embedding is a description of the content, and test the usual fixes with numbers

A planning meeting asks: "Can we sync the embeddings, so search works on the laptop too?" The index is 5.28 MB, about two photos’ worth. It sounds harmless, because a 3 MB photo became 132 bytes.

That reasoning mixes up compression with secrecy. The encoder throws away what does not matter for meaning and keeps the meaning, which is the private part. Morris et al. (2023) rebuilt 92% of 32-token texts exactly from their embeddings, by guessing a text, embedding it, and correcting it again and again. And the attacker has your encoder: it ships inside your app.

What crosses the networkWhat you can say truthfully
Nothing goes up“Your photos never leave your device.” A packet capture can check it.
Embeddings go up“We do not upload your photos.” True, and much weaker than it sounds.
Photos go upWhatever your privacy policy says.

Two attacks follow from a leaked index. Matching: embed a photo the attacker already has and scan the 40,000 vectors; in milliseconds they learn if it was in your library. Reconstruction: train a decoder from vectors back to content; it costs more, and gets cheaper every year.

Does noise help?

Cutting and int8 keep the meaning, so they hide nothing. A secret rotation keeps every dot product, so it keeps everything matching needs. Noise is the one fix that trades. Add random noise of size σ to each of the d numbers of a length-1 vector.

Say it aloud

cos is about 1 over the square root of 1 plus d sigma squared.

cos
cos the cosine between the true vector and its noisy copy.
√
the square root of turns the squared length back into a length.
d
d the numbers in the vector: 128.
σ2
sigma squared the noise power added to each number.
In plain words

The noise adds d times sigma squared to the squared length. The true part stays 1. So the copy points away from the truth by that much.

With numbers

d = 128. σ = 0.005 gives 0.998: no harm to search, no help against an attacker. σ = 0.05 gives 0.87, while good matches differ by a few hundredths.

Add noise, watch the ranking

Each tick is a photo, placed by its true similarity to a query. The lower row is the order after noise. Green tops kept their place; red ones did not.

0.020

Illustrative: random 128-number vectors, 20 candidates with true similarity 0.80 to 0.92, top 5 averaged over 200 trials.

Failure. The symptom: a design note says "we only send embeddings, so the data is anonymous." Measure it: embed a few known photos and match them against the synced file. Fix: do not send the vectors. Sync them end-to-end encrypted with a key the server never holds, or build the laptop’s own index from its own photos.

Training across phones has the same rule. Federated averaging (McMahan et al., 2017) sends weight updates, not photos, but one phone’s update can still reveal its data. Secure aggregation hides each update inside a sum; differential privacy clips and adds noise.

The team says: a 3 MB photo became 132 bytes, so syncing embeddings is private. What is wrong?

Chapter 8

Where to Cut

Turn the four dials on one board, and learn the order to reach for them

Here is a brief with numbers. 40,000 photos and a 100 ms query. At most 30 MB of index in memory and 60 MB of model download. At most 3% of a charge for the first sweep.

Fit the photo app on a phone

Each bar is one budget; the pink tick is its ceiling. Turn the dials and read which bar fails first. The read-out names the next dial to try.

40,000

Encoder sizes, times and multiply-adds are MobileCLIP’s (S0, S1, S2), both towers at int8. Fixed costs (0.2 ms tokenize, 40 ms thumbnails, 15 ms render, 1.5 mJ a thumbnail decode, 8 GB/s scans, 8-byte photo ids) are illustrative. The old phone has 4 GB/s and a 25 MB allowance. There is no quality bar: measure recall.

Start at 512 floats. The index needs 82 MB plus ids. Now follow the order:

  1. Precision first. Int8 is almost free on an embedding, and it cuts memory and scan time 4 times.
  2. Dimension next. Free if the model is Matryoshka. 512 to 128 is 4 times more.
  3. Split by something the user knows: year, album, place.
  4. Only then an index. It is the one dial that adds memory.
  5. Last, a new encoder. It costs weeks and reopens every other choice.

Design one: S0, 128 int8 numbers, flat scan. 148 bytes a photo with id and sign code is 5.92 MB. The query is 0.2 + 1.6 + 0.04 + 0.3 + 40 + 15 = 57 ms in total. The sweep from thumbnails is 40,000 × 3.9 mJ = 156 J, 0.26% of a charge. All four pass with room, so spend the room on quality: try 256 numbers.

Design two fails: 500,000 photos on an old phone with 4 GB/s and 25 MB. At 128 int8 numbers the index is 70 MB. Precision and dimension are spent. The next move is arrangement: keep only 16-byte sign codes and ids in memory (12 MB), read int8 vectors from flash for the best 200. That costs 2 ms to scan plus 20 ms of reads: 78.8 ms in total. Toggle the old phone above and build it.

Failure. The symptom: results are on topic but oddly ordered. Measure recall@1 and recall@50 against your own exact float search. If recall@50 is good and recall@1 is poor, the cut is too coarse: widen the rescore. If recall@50 is poor, the information is gone: keep more numbers or change the encoder.

Your on-device search is over its memory budget. Which dial first?

Chapter 9

Field Guide

Keep the numbers, the checklist and the code in one place

Compute a vector on the device, compare it with something stored on the device, and let the distance be the product. Photo search, a wake word and a pump monitor share that shape; only the binding wall changes.

TermRule or numberUse it for
Arithmetic intensityI = C / W; compare with B = R × u / βCut multiply-adds if I > B, bytes if I < B
Multiply-add1 MAC = 2 operations; halve a TOPS figureReading vendor numbers
Int8 scales = max|w| / 127; an outlier r times larger costs log₂ r bitsPer-channel scales on weights
Index sizeM = N × (d × b / 8 + c); 132 B for 128 int8Fitting the memory wall
Matryoshka cutKeep z1..m, divide by its lengthOnly on models trained for it
Binary codeangle ≈ π h / dA first pass, then rescore
Flat scanbytes / β; 1.6 ms for 100k × 128 at 8 GB/sThe default below a few hundred thousand
HNSW linksabout 2M + M/(M−1) links of 4 B; 132 B at M = 16Pricing an index before you build it
PowerP = E × f; 50 checks a second is 4.32 M a dayAlways-on models
Alarm line, 2-Dτ = −2 ln PTurning an alarm budget into a threshold
Noisecos ≈ 1 / √(1 + dσ²)Seeing what noise costs search

Measure before you ship

  1. End-to-end query time on the oldest phone you support, against 100 ms.
  2. Peak memory during the sweep and during a query, against the background allowance.
  3. Recall@1 and recall@50 of the shipped pipeline, against your own exact float search on the same phone.
  4. Total energy of a full sweep, against 3% of a charge.
  5. Throughput after 20 minutes, against the first minute: heat can halve it.
python# budget.py: run in CI; fail the build when a change breaks a budget
BETA, ETA, CHARGE = 8e9, 2e12, 60984   # B/s measured on the oldest phone; ops/J; J

def budget(N, d, bits, model_mb, txt_ms, macs_g, pre_mj=1.5):
    rec = d * bits / 8 + 4 + 8                 # vector + scale/length + photo id
    scan_ms = N * d * bits / 8 / BETA * 1e3
    joules = N * (pre_mj + 2 * macs_g * 1e9 / ETA * 1e3) / 1e3
    return {"app_mb": model_mb, "index_mb": N * rec / 1e6,
            "query_ms": 0.2 + txt_ms + scan_ms + 40 + 15,
            "charge_pct": joules / CHARGE * 100}

CAPS = {"app_mb": 60, "index_mb": 30, "query_ms": 100, "charge_pct": 3}

def test_photo_app_fits():                        # MobileCLIP-S0, 128 int8, flat scan
    b = budget(N=40_000, d=128, bits=8, model_mb=53.8, txt_ms=1.6, macs_g=2.4)
    for k, cap in CAPS.items():
        assert b[k] <= cap, f"{k} = {b[k]:.2f} exceeds {cap}"

Runtimes

RuntimeWhat its docs say
Core MLSplits the network graph into parts for the Neural Engine, the GPU and the CPU. The GPU and Neural Engine compute in float16, the CPU in float32. MobileCLIP’s timings use Core ML Tools 7.0.
ONNX RuntimeGives each node to the first execution provider in your priority list that can run it, such as Core ML, NNAPI or XNNPACK. The CPU provider is the fallback.

So a model that takes 1.5 ms in a paper can run slower in your app if some operators fall back to the CPU. Profile where each layer runs.

Keep going

LessonWhat it adds
Vector EmbeddingsWhere the vectors come from
Vector DatabasesThe server side, where the answers flip
Matryoshka Representation LearningThe paper behind Chapter 3
Contrastive Learning and CLIPHow text and image land in one space
TinyML 05: QuantizationChapter 2’s int8, in depth
TinyML 09: Knowledge DistillationThe teacher and student in general form
TinyML 10: MCUNetThe pump monitor’s world: kilobytes
Audio RepresentationsThe MFCC front end of Chapter 5
Embedding SecurityChapter 7’s attacks, in depth
Embedding BenchmarksKnowing whether a smaller vector is worse

Sources

Vasu et al., MobileCLIP: Fast Image-Text Models through Multi-Modal Reinforced Training (CVPR 2024). Kusupati et al., Matryoshka Representation Learning (NeurIPS 2022). Malkov and Yashunin, HNSW (2016). Zhang et al., Hello Edge: Keyword Spotting on Microcontrollers (2017). Morris et al., Text Embeddings Reveal (Almost) As Much As Text (EMNLP 2023). McMahan et al., Communication-Efficient Learning of Deep Networks from Decentralized Data (AISTATS 2017). Docs: Core ML Tools, typed execution; ONNX Runtime execution providers.

The takeaway. Before you write code, write M = N × (d × b / 8 + c) and the other budgets. Within an hour you know whether the feature can live on the phone.
What one idea joins the photo search, the wake word and the pump monitor?

Now press Present or Teach. Explain from memory which wall binds and why int8 is free on a vector but not on a weight. Then explain the renormalize, the plain scan and the leak. Then go back to the selector and say why 1 bit alone loses half the top ten.

On-Device Embeddings
Back to Gleams