"The purpose of computing is insight, not numbers."
Richard Hamming · Original printed motto
Phase 2 ended with a small inference server and a first look inside vLLM. I could run a model, use a KV cache, and recognise online softmax in an attention kernel. But recognising the pieces was different from understanding what happened when memory became tight, or how a few packed bytes became a useful dot product.
Phase 3 started closing that gap. I worked on ARM SIMD on my Mac, built a block allocator and cache manager, implemented grouped-query attention, read llama.cpp's quantization code, instrumented vLLM's scheduler, and wrote my own explanation of speculative decoding. The final exercise brought the CPU work together: packed 4-bit weights, dequantization, and a SIMD matrix-vector product.
This covers the late-March lead-in and the core exercises on April 2-8, 2026. The last conversation continued into Phase 4; I am stopping at the completed quantized SIMD exercise. The snippets are excerpts or clearly labelled adaptations, not a complete library. Numbers are the results I recorded then, not fresh benchmarks or production claims.

1. SIMD: four lanes are not a whole block
My first question was simple: if SIMD processes four floats at a time, how does it work on a quantization block containing many more values?
I had to separate two meanings of "block". A quantization block is the set of weights sharing a scale and offset. A SIMD register is a fixed-width set of lanes that processes part of it. On my ARM NEON path, a 128-bit register holds four 32-bit floats. A 32-float block still needs several iterations. SIMD changes the work inside the loop, not the length of the entire array.
For the unsigned 8-bit block quantizer I had built earlier, the transformation was:
scale = (block_max - block_min) / 255
q = round((weight - block_min) / scale)
recovered_weight = q * scale + block_min
I broadcast the minimum and scale, loaded four weights, subtracted, divided, rounded, and narrowed the results to bytes. The arithmetic core looked like this:
// Adapted excerpt of my NEON quantizer.
// Assumes four valid floats and a nonzero scale.
float32x4_t vmin = vdupq_n_f32(blockMin);
float32x4_t vscale = vdupq_n_f32(blockScale);
float32x4_t w = vld1q_f32(&weights[j]);
float32x4_t shifted = vsubq_f32(w, vmin);
float32x4_t scaled = vdivq_f32(shifted, vscale);
int32x4_t rounded = vcvtnq_s32_f32(scaled);
That is only the arithmetic excerpt. A general implementation still needs defined behaviour for constant blocks, safe narrowing and storage, and a tail when the length is not divisible by four.
My first version compiled but produced a block mean error of 5.237320, against 0.085305 for the per-tensor version. The problem was indexing: I restarted the inner loop at zero for each block instead of at the block's start. I kept revisiting earlier weights using the wrong block parameters.
After fixing the loop, block mean error fell to 0.013018, about 6.6 times lower than per-tensor error on that outlier test. That improvement came from block-local ranges, not SIMD. Block quantization changed the representation; vectorization changed the execution speed.
The final recorded 10-million-weight run was:
C++ scalar: 27.32 ms
C++ SIMD: 5.08 ms
Speedup: 5.37x
I also had NumPy and Triton figures in my notes, but I do not want to turn unlike execution environments into a universal CPU-versus-GPU headline. The narrow result is that my NEON path was about 5.4x faster than my scalar C++ version in that local test, with the recorded block error unchanged.
2. Euclidean distance, and a benchmark that almost measured nothing
I returned to a familiar HNSW operation: sqrt(sum((a[i] - b[i])^2)). The SIMD path loads four coordinates from each vector, subtracts them, squares the differences, and accumulates them.
I initially mixed up an index in the full array with a lane index in the register. A four-lane vector has lanes 0-3. It does not have lanes 128-131 because the outer loop has reached array offset 128.
A cleaned-up teaching version is:
// Adapted version, with a scalar tail.
float distanceSIMD(const float* a, const float* b, int d) {
float32x4_t acc = vdupq_n_f32(0.0f);
int i = 0;
for (; i + 4 <= d; i += 4) {
float32x4_t av = vld1q_f32(a + i);
float32x4_t bv = vld1q_f32(b + i);
float32x4_t diff = vsubq_f32(av, bv);
acc = vaddq_f32(acc, vmulq_f32(diff, diff));
}
float sum = vaddvq_f32(acc);
for (; i < d; ++i) {
float diff = a[i] - b[i];
sum += diff * diff;
}
return std::sqrt(sum);
}
Different reduction orders can change floating-point rounding. One matching printed result is a test, not a proof for every input.
The more interesting failure was in the benchmark. Scalar printed as 0.0 ns per call, while SIMD took measurable time. That was a reason to inspect the measurement, not evidence of impossibly fast scalar arithmetic. Repeated work on unchanged inputs can be removed or moved out of the loop. An optimising compiler can also auto-vectorize a function I have labelled "scalar".
We changed the workload and examined compiler settings. After the discussion about disabling automatic vectorization, I recorded:
| Experiment | Scalar | SIMD | Speedup |
|---|---|---|---|
| 128 dimensions, 1 million calls | 542.0 ns/call | 273.4 ns/call | 1.98x |
| 768 dimensions, 100,000 calls | 3,681.8 ns/call | 1,620.4 ns/call | 2.27x |
| 768 dimensions, 1 million calls | 36,022.1 ns/call | 37,061.0 ns/call | 0.97x |
The last run reversed the win. A larger working set and more data movement were plausible explanations, but timings alone did not prove the cause. I did not collect hardware counters in that session.
I had started with "SIMD should be faster" and ended with "what is this benchmark measuring?" Four lanes do not guarantee a 4x speedup. The baseline, compiler flags, input reuse and memory behaviour are all part of the result.
3. A BlockAllocator small enough to understand
Reading vLLM's BlockPool had left me with a gap: I understood reusable blocks conceptually, but not the pointer arithmetic underneath them.
I built a C++ allocator with one preallocated float array, divided into equal-sized blocks, and a free list of block indices. Allocation pops an index and returns the corresponding address. Freeing converts the address back into an index.
// Corrected excerpts from my small BlockAllocator.
float* allocate() {
if (free_list.empty()) return nullptr;
int index = free_list.back();
free_list.pop_back();
return pool + index * block_size;
}
void free_block(float* ptr) {
int index = (ptr - pool) / block_size;
free_list.push_back(index);
}
My original free method multiplied the pointer difference by block_size; it should divide. Subtracting pointers into the same float array gives a distance in float elements, not bytes and not blocks.
Eight blocks of 64 floats occupied 2,048 bytes. The free count went from eight to seven after allocation and back to eight after freeing. A reuse check printed b2 == b3? 1: the freed address could be allocated again.
The first free-count check alone had been too weak. A bad index can still increase the length of a free list. Checking the address made the test more meaningful.
This was a learning allocator, not a production one. It lacked ownership checks, double-free protection, thread safety and safe copy semantics. A raw new float[...] is also a finite allocation, not unlimited memory. The point was to make the relationship between the storage pool and its metadata concrete.
4. From blocks to sequences: KVCacheManager
The next layer associated sequence IDs with their blocks. I used an unordered_map<int, vector<float*>> around the allocator.
// Excerpts from my exercise, not a production cache manager.
float* allocate_block(int seq_id) {
float* ptr = allocator.allocate();
if (ptr == nullptr) return nullptr;
block_table[seq_id].push_back(ptr);
return ptr;
}
void free_sequence(int seq_id) {
auto ptrs = block_table[seq_id];
for (float* ptr : ptrs) {
if (ptr) allocator.free_block(ptr);
}
block_table.erase(seq_id);
}
Three blocks went to sequence 0 and two to sequence 1, leaving three free. Releasing sequence 0 brought the free count to six. Allocating one block to sequence 2 brought it to five.
That was the bridge to PagedAttention: a sequence has a logical list of blocks without requiring one physically contiguous run. My map was a toy ownership table, not a full KV cache. It did not yet contain per-layer K/V tensors, sharing, reference counting, eviction or a scheduler.
There were ordinary C++ contract questions too. operator[] can create an entry for a missing sequence; returning a vector by value copies it. Those details are easy to ignore in an exercise and important in a real cache manager.
5. GQA forced me to face the shapes
The GQA paper introduced a middle ground between multi-head attention and multi-query attention. Query heads remain separate, while groups of queries share key and value heads.
Before that clicked, I had to resolve a question from the server work: where do K and V come from the first time?
Prompt tokens are not "Q tokens". Tokens become representations, and learned projections in the layer produce Q, K and V. During generation, the new token produces a query and new K/V entries; attention uses the query against the relevant cached keys and values. The cache stores earlier projected K/V. It does not replace the projections that create them.
I also revisited matrix multiplication: (a, b) @ (b, c) -> (a, c). Inner dimensions must match. (4, 16) @ (16, 16) gives (4, 16), not (16, 16). That rule was more useful than memorising a list of attention shapes.
In my 64-dimensional example:
| Mode | Query heads | K/V heads | K and V projection shape, each | Output |
|---|---|---|---|---|
| MHA | 8 | 8 | (64, 64) | (16, 64) |
| GQA | 8 | 2 | (64, 16) | (16, 64) |
| MQA | 8 | 1 | (64, 8) | (16, 64) |
The output width stays the same because query-head outputs are still concatenated. With equal head dimensions, GQA uses one quarter as many K/V heads as MHA here, and MQA one eighth.
My head mapping was short:
# Excerpt of my grouped-query implementation.
group_size = n_heads // n_kv_heads
outputs = []
for i in range(n_heads):
kv_index = i // group_size
out = attention(
Q_heads[:, i, :],
K_heads[:, kv_index, :],
V_heads[:, kv_index, :],
)
outputs.append(out)
return np.concatenate(outputs, axis=-1)
For eight query heads and two K/V heads, queries 0-3 use K/V head 0, and queries 4-7 use K/V head 1. This assumes the query-head count is divisible by the K/V-head count.
Why reshape more than once?
To imitate checkpoint conversion, I grouped the K/V projection heads and mean-pooled inside each group:
# Adapted excerpt from the toy mean-pooling exercise.
heads = W_K_mha.reshape(d_model, n_heads, head_dim)
grouped = heads.reshape(d_model, n_kv_gqa, group_size, head_dim)
pooled = grouped.mean(axis=2)
W_K_gqa = pooled.reshape(d_model, n_kv_gqa * head_dim)
The first reshape exposes heads; the second exposes groups of heads. The mean removes the within-group axis. The last reshape restores a projection matrix.
I spent three or four hours on those transformations. The code seemed to work before I could explain the axes. A copy-paste error made it worse: I initially built MQA's value projection from the key weights instead of the value weights.
The corrected random-weight experiment printed maximum/mean differences from MHA of 33.4157/6.3845 for GQA and 33.5717/6.1541 for MQA. These are toy output differences, not language-model quality scores. Mean-pooling random weights without uptraining does not reproduce the paper's quality result. In the paper, conversion is followed by further training.
A KV cache contains both K and V
My first memory calculation forgot a factor of two. The corrected form is:
# Corrected form of my sizing exercise.
kv_bytes_per_token_per_layer = (
2 * n_kv_heads * head_dim * bytes_per_element
)
total_kv_bytes = (
kv_bytes_per_token_per_layer * context_len * n_layers
)
In that separate configuration, corrected output was about 5.0 GiB per sequence for MHA, 0.6 GiB for GQA and 0.1 GiB for MQA, rounded in the printout. Those figures depend on the chosen dimensions. Dividing an 80-GiB budget by cache size gives only a cache-only upper bound; weights, buffers and runtime overhead still need room.
At the end of this phase, I asked to revisit GQA. A correct-looking output was not enough. I needed to derive the shapes without help.
6. llama.cpp: two weights in one byte
I built and ran llama.cpp locally. An old Makefile command no longer matched the checkout, which directed me to CMake. Missing C++ standard-library headers on my Mac caused more setup trouble before a successful clang build.
Reading thousands of lines at once did not work. I narrowed the task to specific files and functions: KV-cell metadata, q4 block definitions, quantization and dequantization, CPU vector operations, and temperature sampling.
The q4_0 representation became the most useful exercise. Thirty-two weights are encoded as 16 packed bytes plus a scale. Each byte contains two 4-bit codes: one from the first half of the block, one from the second half.
// My float-scale teaching format, not ggml's exact layout.
struct block_q4_0 {
float scale;
uint8_t packed[16];
};
// Corrected recovery indexing for one block.
for (int j = 0; j < 16; ++j) {
int low = (block.packed[j] & 0x0F) - 8;
int high = (block.packed[j] >> 4) - 8;
recovered[start + j] = low * block.scale;
recovered[start + j + 16] = high * block.scale;
}
& 0x0F keeps the low four bits; >> 4 shifts the high four bits down. Subtracting eight maps unsigned codes 0-15 to signed values -8 through 7.
The reference quantizer I read selected the signed weight with the greatest absolute magnitude, then divided it by -8 for the scale. Retaining the sign of that selected extreme was a detail I would have missed by assuming this was just generic min/max quantization.
My first version had several indexing bugs: the packed loop began at a global offset, the recovery buffer was too small, and the destination calculation mixed block and lane indices. After fixing them:
Original size: 4096 bytes
Quantized size: 640 bytes
Compression: 6.4x
Blocks: 32
Max error: 0.122685
Mean error: 0.0295837
The 6.4x reduction belongs to my format: 32 float weights occupy 128 bytes, and my block occupies 20 bytes. It is not 8x once the scale is included. ggml's q4_0 structure uses a half-precision scale; my float-scale implementation was not byte-for-byte compatible with it.
I also traced temperature back to familiar arithmetic: for positive temperature, divide logits by temperature; the non-positive branch selects the maximum logit. I had used this parameter in the small inference server. Finding it in the sampler connected the API knob to the code.
7. vLLM: observe the scheduler, then put it under pressure
This time I wanted to change code and see what happened, rather than only call generate(). Getting there meant dependency conflicts, long installs, edits in the wrong location, and logging that did not appear. I had to identify the installed scheduler module and instrument the path that actually ran.
The log recorded running, new, resumed and preempted requests, scheduled tokens, and the waiting queue. A small batch showed the transition from prompt processing to decoding:
[SCHED] running=0 new=5 resumed=0 preempted=0 tokens=25 waiting=0
[SCHED] running=5 new=0 resumed=0 preempted=0 tokens=5 waiting=0
The first step scheduled prompt tokens for new requests. Subsequent steps scheduled roughly one decode token per active request. tokens meant work across the batch, not the output limit of one request.
Block size is a tradeoff, not a magic setting
I tried block sizes 16 and 32. Size 8 was rejected by the backend/configuration in that environment, not necessarily by every vLLM backend or version.
One fixed-output comparison recorded 10,000 tokens in 0.79 seconds for size 16 and 1.21 seconds for size 32. An earlier comparison had different token totals and much closer timings. These short single runs were not enough to establish a globally best block size.
The underlying tradeoff was clearer: smaller blocks can reduce unused capacity at sequence ends and enable finer-grained reuse; more blocks mean more bookkeeping. An eight-token sequence in a 16-token block leaves eight slots unused. That does not automatically mean eight extra valid-token computations; logical sequence lengths and masking still matter.
For prefix caching, the useful control is the same prompts with caching toggled. Changing prompts and caching simultaneously would make the result harder to interpret. The early logs showed some reduction in scheduled prompt work when prefixes were reused, but not a large gain for those short GPT-2 prompts.
No preemption did not mean no preemption mechanism
With 50 requests and 100 generated tokens each, I saw no preemption. Reducing the memory-utilization setting was not enough: the cache demand was still small.
We increased the workload to 500 requests and 500 generated tokens per request, keeping gpu_memory_utilization=0.3. The behaviour became visible:
[SCHED] running=256 new=0 resumed=0 preempted=0 tokens=256 waiting=192
[SCHED] running=254 new=0 resumed=0 preempted=2 tokens=254 waiting=246
[SCHED] running=252 new=0 resumed=0 preempted=2 tokens=252 waiting=248
...
[SCHED] running=77 new=0 resumed=17 preempted=0 tokens=8192 waiting=272
Requests reached the configured running-request limit. As sequences grew and needed more cache space, some were preempted. Later they returned as resumed requests, with large scheduled-token counts consistent with context recomputation.
| Run | Output tokens | Time | Throughput | Preemption log lines | Responses |
|---|---|---|---|---|---|
| Prefix caching on | 250,000 | 31.51 s | 7,934.9 tok/s | 45 | 500/500 |
| Prefix caching off | 250,000 | 30.77 s | 8,125.4 tok/s | 36 | 500/500 |
The counts were matching log lines, not a sum of preempted requests. preempted=2 contributes one matching line but two requests at that step.
The strongest observation was recovery: all 500 requests completed in both runs. Caching off was slightly faster in these recorded tests. Without repeated, controlled runs, that does not prove prefix caching is harmful or establish the cause of the difference.
One explanation from the discussion also needs correcting. A cached hash does not make a block permanently unavailable. vLLM's documented design puts unused blocks on a free queue, and allocation can evict cached entries. The idea that cached blocks simply cannot be reassigned was too broad.
8. My answers, lightly polished
The follow-up questions tested whether I could explain the process rather than just follow instructions. These keep my reasoning from the chats, with corrections called out where needed.
What happens to a preempted request?
In the path I read, the scheduler frees its cache allocation, marks it preempted, resets its computed-token count, increases its preemption count, and puts it back in the waiting queue. Resuming can require recomputing context because the old K/V allocation was released.
Why prepend rather than append?
My answer was that putting it at the front helps it resume sooner, rather than making it wait behind new requests. That explains the particular line I read; it is not a proof of fairness or freedom from starvation for every scheduling policy.
Why can the log show 8,192 tokens with a 500-token output limit?
The log describes scheduled work across the batch, including possible context recomputation. The output limit is per request, not a cap on the engine's total scheduled tokens in a step.
What changes when the model gets bigger?
On the same device, weights and runtime allocations take part of the memory budget. Less space remains for K/V, so fewer active sequences may fit or pressure may arrive earlier. Fitting the model and fitting the workload are separate questions.
Why did the final exercise feel different?
I spent roughly eight or nine hours on it and needed substantial help. Types, register widths, unpacking and offsets kept tripping me up. But the exercise was challenging enough that I stayed with it. By the end I could see the process, rather than only trying functions until something compiled. That was progress, even though it was not independent mastery.
9. Speculative decoding: my write-up, with the probability logic fixed
I read Fast Inference from Transformers via Speculative Decoding, wrote an explanation in my notes, and revised it after feedback. This is a polished version of that write-up, retaining my example while correcting the draft-token count, acceptance logic and claims about speed.
Autoregressive decoding normally advances one token at a time. For a large model at low batch size, repeated data movement can be expensive relative to the arithmetic for one token. A smaller draft model proposes a short sequence cheaply, and the target evaluates the proposed positions in a batch.
Let q be the draft distribution and p the target distribution. The draft proposes gamma tokens autoregressively. A proposed token x is accepted with probability:
accept_probability(x) = min(1, p(x) / q(x))
If the draft gives it 70% probability and the target gives it 50%, acceptance probability is 0.50 / 0.70, about 71%. If the target gives the proposed token more probability than the draft, acceptance is certain.
Check left to right and stop at the first rejection. Later draft tokens were conditioned on the rejected token; keeping them after substituting a different token would use the wrong context.
At rejection, use a corrected residual distribution:
residual(x) = max(0, p(x) - q(x))
p_new(x) = residual(x) / sum_y(residual(y))
My example began with "The cat sat on the". The draft proposed "mat", "and", "slept". With random draws 0.45, 0.30 and 0.80:
| Token | Draft q | Target p | Acceptance probability | Result |
|---|---|---|---|---|
| mat | 0.70 | 0.50 | about 0.714 | Accept |
| and | 0.60 | 0.65 | 1.0 | Accept |
| slept | 0.40 | 0.10 | 0.25 | Reject |
At that last position, my toy distributions were:
| Token | q | p | Positive residual |
|---|---|---|---|
| slept | 0.40 | 0.10 | 0 |
| peacefully | 0.30 | 0.50 | 0.20 |
| deeply | 0.30 | 0.40 | 0.10 |
Normalising gives two-thirds probability to "peacefully" and one-third to "deeply". "Peacefully" is a possible sample, not a predetermined replacement. If sampled, drafting restarts from "The cat sat on the mat and peacefully".
If all gamma draft tokens are accepted, the target supplies an additional token. Under the paper's simplified constant-acceptance model:
E[tokens] = 1 + alpha + alpha^2 + ... + alpha^gamma
= (1 - alpha^(gamma + 1)) / (1 - alpha)
alpha = 0.8, gamma = 5
E[tokens] = 3.68928
That is expected progress per iteration, not a measured 3.69x speedup. Drafting and verification have costs. More draft tokens offer more possible progress, but add work and exposure to rejection. A small or already efficient target may not benefit; that is something to measure, not a universal rule excluding small models.
In this phase I read the algorithm and wrote this explanation. I did not yet build a speculative-decoding server. Understanding, implementing and benchmarking are separate achievements.
10. The integration exercise: q4 weights into a SIMD dot product
The final exercise combined packing, quantization, shapes and NEON. My function names said "matmul", but the actual operation was matrix-vector multiplication: weights (M, N) times input (N), giving output (M).
Each row had N / 32 blocks. Row m, block b lived at allBlocks[m * blocks_per_row + b]. A packed byte supplied two weights at different input positions:
// Excerpt of my scalar quantized matrix-vector exercise.
// This teaching version requires N divisible by 32.
for (int m = 0; m < M; ++m) {
float sum = 0.0f;
int blocks_per_row = N / 32;
for (int b = 0; b < blocks_per_row; ++b) {
const auto& block = allBlocks[m * blocks_per_row + b];
for (int j = 0; j < 16; ++j) {
int low = (block.packed[j] & 0x0F) - 8;
int high = (block.packed[j] >> 4) - 8;
sum += (low * block.scale) * input[b * 32 + j];
sum += (high * block.scale) * input[b * 32 + j + 16];
}
}
output[m] = sum;
}
The SIMD path unpacked nibbles, converted integer lanes to floats, applied the scale, and multiplied against the matching input positions. It did not load the entire input into a register. It processed fixed-width chunks while preserving their layout.
A byte was not a vector of bytes. A vector-load result was not a scalar. A pointer to an array was not the same expression as a pointer to its first element. Low/high extraction was also not an iterator that advanced automatically when called again. Those distinctions were the source of many of my compilation errors and wrong offsets.
For the small test, scalar-quantized and SIMD-quantized outputs matched at six printed decimal places. Both differed from the original float-weight result, which was expected from quantization. The larger benchmark recorded:
M=512, N=768, 1000 iterations
Float matrix-vector product: 0.343 ms
Scalar quantized product: 0.465 ms
SIMD quantized product: 0.092 ms
SIMD vs scalar quantized: 5.05x
SIMD vs float baseline: 3.71x
Max error, scalar vs float: 1.6663
Max error, SIMD vs float: 1.6663
The scalar quantized path was slower than float: unpacking and conversion cost something. SIMD made that path faster in my recorded run. The small test showed zero difference at printed precision between quantized implementations, and the larger test reported the same maximum error against float.
These tests do not prove bit-identical outputs for every input. This was also not a comparison against tuned BLAS or a production llama.cpp kernel. It was my float-scale format, my simple float reference, and my local benchmark. The archived timing code has not been re-run or audited here for compiler-elimination effects, so the speedups remain reported results rather than independently verified claims.
The lasting result was that I could trace the whole path: a row becomes packed blocks, each block yields signed values and a scale, values line up with input positions, and vector instructions accumulate the output.
What changed in this phase
A compiled program could still have the wrong index. A plausible output shape could hide confusion about an axis. A zero-nanosecond timing could mean a broken benchmark. No preemption could mean insufficient memory pressure. A confident explanation could still need checking.
SIMD, packed weights, GQA, cache blocks and speculative decoding started connecting through one question: what work or data movement can I avoid, and what new cost do I introduce by avoiding it?
I also had a clearer list of gaps. I needed help with SIMD types and shapes. GQA needed another pass. Speculative decoding was reading and writing, not yet an implementation. Reading a few functions did not mean I understood the whole inference engine.
The next step was specific: revisit the weak parts, ask more questions before and after exercises, and work toward experiments I could design and explain myself. Phase 4 would raise the difficulty, but Phase 3 gave me a better map of what I actually understood.
Reading and reference notes
- Hamming's printed motto: source scan.
- Ainslie and colleagues, GQA.
- Leviathan, Kalman and Matias, Fast Inference from Transformers via Speculative Decoding.
- vLLM's prefix-caching design: reference counts, the free queue and eviction. This is a present-day reference; my experiments describe the April setup.
- ggml q4 block definitions, distinguishing the production half-scale layout from my float-scale exercise.
Hitesh Joshi · LinkedIn