5/26
Part 1 of 4 · Why a cache helpsLearn and do
What a step costs, with and without a cache
Count the work in multiply-adds, one multiply and one add each, for a block of width C:
| One block, width C | Multiply-adds |
|---|---|
| q, k and v projections, for one token | 3 · C² |
| output projection | 1 · C² |
| MLP, up to 4C and back down | 8 · C² |
| each token you run through it | 12 · C² |
| attention: one query scores t keys, then blends t values | 2 · t · C |
Now the cost of the next token, after t tokens of context:
Without a cache, all t tokens go through the block, and t queries each read t keys. With a cache, one token goes through, and its one query reads t keys.
C, t = 768, 1000
# no cache
print(f"{12 * t * C**2 + 2 * t**2 * C:,}")
# with a cache
print(f"{12 * C**2 + 2 * t * C:,}")
no_cache = sum(12 * t * C**2 + 2 * t**2 * C for t in range(1, 1025))
cached = sum(12 * C**2 + 2 * t * C for t in range(1, 1025))
print(round(no_cache / 1e12, 1), "trillion")
print(round(cached / 1e9, 1), "billion")
print(round(no_cache / cached), "times less")
At C = 768 and t = 1,000 tokens of context, how many times cheaper is one cached step than one uncached step?
Pick one to see what it prints.
Pick an answer above to see the rest
With a cache, does step 10,000 cost the same as step 10?
Pick an answer above to see the rest