Optional reference: Classical ML¶
Compact Review of ML Algorithms in Production¶
This compact reference shows how production ML code turns mathematical assumptions into shapes, invariants, numerical policies, and measurable failure behavior. It emphasizes implementation contracts rather than surveying each algorithm exhaustively.
Vectorized logistic regression¶
For examples X, labels y, and weights w, logits are z = Xw. Binary cross entropy should use a stable logits form rather than computing log(sigmoid(z)) directly.
Example status: Illustrative Python excerpt; not standalone.
def logistic_loss_and_grad(X, y, w, l2=0.0):
z = X @ w
# softplus(z) - y*z is stable binary cross entropy from logits.
loss = mean(softplus(z) - y * z) + 0.5 * l2 * dot(w, w)
p = sigmoid(z)
grad = (X.T @ (p - y)) / X.shape[0] + l2 * w
return loss, grad
Production implementations must specify sparse-feature handling, class weighting, calibration, distributed reduction, feature normalization, leakage controls, and stopping criteria. The sparse matrix-vector product and update cost O(nnz(X)) per pass.
K-means¶
Lloyd's algorithm alternates nearest-centroid assignment and centroid recomputation. Complexity is O(n k d) per iteration. Initialization strongly affects the local optimum; k-means++ spreads initial centers.
For large data, mini-batch k-means updates centroids from samples. Distributed implementations compute local counts and sums, then reduce. Empty clusters require a policy: reinitialize to a far point, split a large cluster, or retain the old centroid.
The Euclidean objective assumes roughly spherical clusters and comparable feature scales. If those assumptions fail, changing the optimizer will not fix the model.
Decision trees¶
A tree searches splits that reduce impurity. For classification, Gini or entropy is common; for regression, squared error. Efficient continuous-feature search sorts values or uses histograms. Missing values and categorical features require explicit routing.
Depth, minimum leaf size, feature subsampling, and pruning trade fit against variance. Distributed histogram methods reduce candidate statistics instead of shipping examples. Production code also handles monotonic constraints, stable serialization, and feature schema evolution.
Attention from primitives¶
Example status: Illustrative Python excerpt; not standalone.
def attention(q, k, v, mask=None):
scale = 1.0 / sqrt(q.shape[-1])
scores = q @ swapaxes(k, -1, -2) * scale
if mask is not None:
scores = where(mask, scores, -inf)
probs = softmax(scores, axis=-1)
return probs @ v
Follow-ups include causal masks, padding, batched heads, mixed precision, stable softmax, dropout, KV caching, GQA, and memory-efficient attention. The concise code is a semantic reference, not a performant long-context implementation. It assumes at least one permitted key per query: a fully masked row otherwise feeds all negative infinities to softmax. The runnable single-head reference in examples/attention.py defines that case as a zero vector and tests dense versus chunked reduction. A production API may reject that input instead; the caller and kernel must agree.
Beam search¶
Beam search keeps the best partial sequences by cumulative log probability. Length normalization can reduce the preference for short outputs, but changes the ranking objective. Finished beams must remain candidates without being expanded. Per-step top-k can be taken over beam * vocabulary scores.
Beam search is not sampling. It searches high-probability sequences under the model and may reduce diversity. Diverse beam variants, constraints, or stochastic beams modify the objective.
Example status: Illustrative Python excerpt; not standalone.
for step in range(max_steps):
active, finished = partition_by_finished(beams)
if not active:
break
logits, next_state = model.step(active.tokens, active.state)
scores = active.scores[:, None] + log_softmax(logits, axis=-1)
# Each candidate retains its parent ID and proposed token.
expanded = candidates_with_parent_ids(active, scores, next_state)
# Finished sequences retain score, length, and state unchanged.
selected = select_best(finished + expanded, beam_width)
beams = materialize_selected_sequences_and_parent_states(selected)
if beams.all_finished():
break
return rank_with_length_penalty(beams)
The helpers above are schematic, not library APIs. Candidate materialization appends a token only for an expanded candidate, marks EOS as finished, and gathers every layer's cache from the same parent. Final length-penalty reranking does not make the intermediate raw-score pruning exact for the normalized objective.
Nearest-neighbor search¶
Exact search computes all distances. Approximate methods reduce query work through graphs, inverted files, product quantization, or trees. The design must specify recall target, latency, update rate, filtering, memory, and metric.
Embedding normalization makes cosine similarity equivalent to inner product ranking. Product quantization compresses vectors and uses lookup tables for approximate distance, trading recall for capacity and bandwidth. Metadata filters can destroy index efficiency if applied after retrieval; integrate filters or route to partitions.
From classifier scores to routing decisions¶
The logistic and tree examples also apply to model routing: predict whether a cheaper path will satisfy the task contract, then escalate difficult cases. A similarity score, softmax maximum, or fluent self-assessment is not automatically a calibrated probability of success. Train and evaluate against the actual outcome definition, including unsupported answers and unavailable evidence.
Use a held-out calibration split to choose a threshold, then freeze it before acceptance testing. Report coverage (the fraction sent to the cheap path), conditional failure among accepted requests, total cost, and latency by task slice. A router can look accurate by escalating nearly everything. A changed generator, retriever, prompt, or user population can invalidate calibration even when the router weights stay fixed.
In an original cost example, the cheap path costs one unit and escalation costs ten additional units. If 60% of requests stop after the cheap path, mean cost is 1 + 0.40 * 10 = 5 units. If accepted answers are correct 95% of the time and escalated answers 99%, overall correctness is 0.60 * 0.95 + 0.40 * 0.99 = 96.6%. This misses a hypothetical 98% requirement despite the savings. Direct routing to the expensive path has a different cost formula because it need not pay for the initial cheap attempt.
Small tests also leave uncertainty. Zero failures among 100 independently sampled accepted cases gives a one-sided 95% binomial upper failure bound of 1 - 0.05^(1/100) ~= 2.95%. It does not establish a failure rate below 1%. Correlated cases, threshold tuning on the same set, or distribution shift invalidate that simple interpretation. If evidence is insufficient, gather more representative cases or reduce coverage; changing a confidence label does not improve reliability.
Worked check: after replacing the retriever, can the old threshold ship unchanged because the classifier code is identical? Only after revalidation. Its target is the complete pipeline's outcome, which has changed.
Design Exercises¶
- Derive stable logistic loss from logits.
- How do you distribute k-means updates?
- Implement beam search state gathering correctly.
- Explain why the reference attention code is memory-heavy.
- Choose an ANN index for high update rate and metadata filtering.
Worked answer criteria¶
- Use
max(z, 0) - y*z + log1p(exp(-abs(z)))for binary cross entropy from logits, then average consistently with the gradient. Test large positive and negative logits and reject incompatible shapes. - Reduce each cluster's count and vector sum across workers; divide only after the global reduction. Workers must share a centroid revision and an empty-cluster policy. Averaging local centroids without weighting their counts is wrong.
- Test two winning candidates from one parent, an EOS candidate, a retained finished beam, and reordered parents. Tokens, scores, lengths, and every layer's KV cache must follow the same ancestry.
- The dense reference materializes a query-by-key score matrix and usually probabilities of the same size. Chunked attention retains online normalization state instead; compare against the dense result within the declared dtype tolerance.
- Benchmark the actual update/delete workload and filtered recall, not only unfiltered search throughput. Keep an exact-search oracle for small partitions and test selective ACLs before committing to an ANN layout.