Measure cached vs uncached generation and cache memory on CPU
CPU · your Macexperiment90 minrequiredGoal · Produce timing curves for generation with and without the KV cache and verify the cache's byte size against the formula for GPT-2 and TinyLlama.
- 1Load gpt2 in fp32 on CPU; build a 64-token prompt; set torch.set_num_threads to your core count.
- 2Generate 128 tokens greedily with model.generate(use_cache=True) and again with use_cache=False, timing each; confirm the token ids are identical.
- 3Write your own loop that records the wall time of each decode step for both modes; plot step time vs step index.
- 4After a 512-token prefill, sum numel()*element_size() over every key and value tensor in past_key_values (DynamicCache exposes per-layer key and value tensors; call to_legacy_cache() if needed).
- 5Compare the measured bytes with 2 * 12 * 768 * 4 * 512 and report the ratio.
- 6Repeat the byte measurement with TinyLlama in bfloat16 for a 512-token prompt and compare with 2 * 22 * 4 * 64 * 2 * 512.
- 7Compute how many 2048-token conversations of TinyLlama cache fit in 16 GB alongside the 2.2 GB of bf16 weights.
- Deliverable
- A plot of per-step latency for both modes, a table of measured vs formula bytes for both models, and the concurrency number.
- Check
- Uncached per-step time grows roughly linearly with step index while cached stays flat; measured cache bytes match the formula within 1 percent for both models (37,748,736 for GPT-2 at 512 tokens fp32).