ML0183 DNN vs KNN Inference Time

If you have a million data points, would you use a DNN or KNN? What is the difference in inference time and memory at prediction?

Three-panel scenario card with dashed borders. Panel one, the data: 1,000,000 labeled points, 256 float32 features per point, 10 classes with about 20k new points per day. Panel two, the serving budget: 2,000 predictions per second, p99 latency at most 10 ms, one CPU replica with 4 GB RAM and about 50 GB/s memory bandwidth. Panel three, the open choice: option A is KNN with k equal to 10 over all stored points, option B is a DNN, an MLP with layers 256-512-256-10, and an open box asks about inference time, memory at prediction, and which one ships.

The Problem: A classifier built on 1,000,000 points of 256 float32 features must serve 2,000 predictions per second at a 10 ms p99 from a 4 GB CPU replica. Option A is KNN with k = 10 over every stored point, option B is a 256-512-256-10 MLP, and nobody has yet priced either one at prediction time.

Answer

At a million points with any real query volume, use a DNN (or a learned embedding served through an approximate nearest-neighbor index), not brute-force KNN. KNN is a lazy learner. Training is free because it only stores the data, but every prediction scans all N stored points, so a query costs O(Nd) time and the model occupies O(Nd) memory. A DNN pays up front in training and then predicts in O(P) time and memory, where the parameter count P does not grow with the dataset. With 256 float32 features, brute-force KNN holds 1.02 GB and spends 2.56 \times 10^8 multiply-adds per query. A 265k-parameter MLP holds 1.06 MB and spends about 2.6 \times 10^5, a gap of roughly 1,000x on both axes. KNN stays competitive only behind an ANN index such as HNSW or IVF-PQ, or when the data changes faster than you can retrain.

(1) Lazy Versus Eager Learning: KNN defers all computation to prediction time, while a DNN compresses the training set into P weights once. The choice is really about where the cost lands: training or every single query.
(2) Inference Time: Brute-force KNN computes N distances of d multiply-adds each, plus an O(N \log k) top-k selection. A DNN forward pass costs O(P) regardless of N, so at one million points the MLP finishes in tens of microseconds while KNN is memory-bandwidth bound at about 20 ms.
(3) Memory At Prediction: KNN must keep every training vector resident, N d b bytes, and the footprint grows linearly as data arrives. The DNN keeps only its weights, so ten times more training data leaves its serving footprint unchanged.
(4) ANN Indexes Change The Math: HNSW visits roughly 1,500 nodes and reaches recall@10 near 0.95 in under a millisecond, but its graph links push memory to about 1.28 GB. IVF-PQ compresses each vector to 32 bytes (about 44 MB in total) at the price of approximate distances.
(5) Distance Quality: In 256 raw dimensions, distances concentrate and KD-trees degrade to brute force beyond roughly 20 dimensions. Raw Euclidean distance also weights every feature equally, while a DNN learns which features matter.
(6) When Lazy Learning Wins: Tiny query volume, data that must count the moment it arrives, a need for instance-level explanations, or cases where the neighbors themselves are the product, such as similar-item retrieval.

Mathematical Formulation:
\hat y(x) = \mathrm{mode}\{ y_i : i \in \mathcal{N}_k(x) \}
T_{\mathrm{knn}} = N d
M_{\mathrm{knn}} = N d b
T_{\mathrm{dnn}} = \sum_{l=1}^{L} h_{l-1} h_l
M_{\mathrm{dnn}} = P b
C_{\mathrm{train}} = 3 E N T_{\mathrm{dnn}}
Q^{*} = \frac{C_{\mathrm{train}}}{T_{\mathrm{knn}} - T_{\mathrm{dnn}}}

Where:

  • \hat y(x) is the prediction for query x, y_i is the stored label of training point i, and \mathcal{N}_k(x) holds the indices of the k stored points closest to x; regression replaces the mode with a mean.
  • T_{\mathrm{knn}} is the number of multiply-adds per query for brute-force KNN over N stored points of dimension d; top-k selection adds O(N \log k) comparisons on top.
  • M_{\mathrm{knn}} is the resident memory at prediction, with b bytes per number (b = 4 for float32).
  • T_{\mathrm{dnn}} sums h_{l-1} h_l over L dense layers of widths h_l, with h_0 = d, and M_{\mathrm{dnn}} stores P parameters. Neither depends on N.
  • C_{\mathrm{train}} is DNN training compute over E epochs; the factor 3 counts one forward pass plus a backward pass that costs about twice the forward.
  • Q^{*} is the break-even number of predictions after which the DNN has spent less total compute than KNN, training included.

The formulas make the asymmetry explicit. N appears in both of KNN’s inference terms, but for the DNN it appears only inside C_{\mathrm{train}}, a one-time cost. So the question “DNN or KNN?” is really “how many predictions will this model serve before the data changes?” Any service answering more than Q^{*} queries per model version favors the DNN, and Q^{*} is usually tiny compared with production traffic.

Worked Example:
Use the scenario’s numbers: N = 10^6, d = 256, float32 so b = 4, and an MLP with layers 256-512-256-10. Brute-force KNN holds 10^6 \times 256 \times 4 = 1.024 \times 10^9 bytes and spends 2.56 \times 10^8 MACs per query. The MLP spends 131{,}072 + 131{,}072 + 2{,}560 = 264{,}704 MACs and stores 265,482 parameters, or 1.06 MB. Training it for E = 20 epochs costs 3 \times 20 \times 10^6 \times 264{,}704 \approx 1.59 \times 10^{13} MACs, and each prediction then saves about 2.56 \times 10^8 MACs, so Q^{*} \approx \frac{1.59 \times 10^{13}}{2.56 \times 10^{8}} \approx 62{,}000. At 2,000 queries per second the DNN repays its whole training run in 31 seconds of traffic. Latency tells the same story: one unbatched KNN query streams 1.02 GB, about 20 ms at 50 GB/s, and 2,000 such queries per second would need about 2 TB/s of memory bandwidth, forty times what the replica has.

Three-panel chart. Panel a, log-log plot of multiply-adds per query against dataset size from ten thousand to one hundred million: brute-force KNN rises linearly and reaches 2.6 times ten to the eighth at one million points, about 970 times the DNN; KNN with an HNSW index rises slowly with log N; the DNN with 265k parameters is a flat line. Panel b, log-log plot of memory held at prediction in megabytes: brute-force KNN and HNSW grow linearly and cross a 4 GB replica RAM line at a few million points, IVF-PQ grows at 40 bytes per vector, and the DNN stays flat at 1.06 MB. Panel c, cumulative compute against predictions served at one million points: KNN starts at zero and rises steeply, the DNN starts at 1.6 times ten to the thirteenth multiply-adds of training and rises slowly, and the lines cross at about 62,000 predictions, which is 31 seconds of traffic at 2,000 queries per second.

Figure 1: (a) Per-query multiply-adds against dataset size: brute-force KNN grows linearly, HNSW grows roughly with \log N (schematic model of about 75 \log_2 N visited nodes), and the DNN is flat. (b) Memory held at prediction: at N = 10^6 brute force needs 1.02 GB, HNSW 1.28 GB, IVF-PQ about 44 MB, and the DNN 1.06 MB regardless of N. (c) Total compute including training: the DNN’s training bill of 1.6 \times 10^{13} MACs is repaid after about 62,000 predictions.

Panel (a) hides one subtlety that the table makes explicit. HNSW spends only slightly more multiply-adds per query than the MLP, yet it is still around ten times slower in wall-clock time, because graph traversal makes random memory accesses across a 1.28 GB structure while the MLP’s 1 MB of weights stays in CPU cache.

Property (N = 1M, d = 256)DNN (MLP 256-512-256-10)Brute-force KNNKNN + HNSW index
Training costAbout 1.6 x 10^13 MACs for 20 epochs; minutes on a GPUStore the data; effectively zeroGraph build; a few minutes on a multi-core CPU
Memory at prediction1.06 MB of weights, independent of N1.02 GB, linear in NAbout 1.28 GB (vectors plus 64 links per node)
Compute per query264,704 MACs2.56 x 10^8 MACs plus top-k selectionAbout 1,500 distance evaluations, roughly 4 x 10^5 MACs
Single-query latency (CPU)Tens of microseconds, weights stay in cacheAbout 20 ms, bound by memory bandwidthAbout 0.2 to 1 ms at recall@10 near 0.95
Adding a new data pointWaits for the next retrain or fine-tuneAppend one row; usable immediatelyOnline insert; deletes become tombstones
Fails whenData drifts faster than the retraining cadenceQuery volume, latency budget, or RAM is tightExact recall or heavy metadata filtering is required

Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *