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 CMultiply-adds
q, k and v projections, for one token3 · C²
output projection1 · C²
MLP, up to 4C and back down8 · C²
each token you run through it12 · C²
attention: one query scores t keys, then blends t values2 · t · C

Now the cost of the next token, after t tokens of context:

no cache:12 t C2+2 t2Cwith a cache:12 C2+2 t C\begin{aligned} \text{no cache:} &\quad 12\,t\,C^2 + 2\,t^2 C \\ \text{with a cache:} &\quad 12\,C^2 + 2\,t\,C \end{aligned}

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")
Predict

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
Predict

With a cache, does step 10,000 cost the same as step 10?

Pick an answer above to see the rest