AI engineering and inferenceLoading progress…

Hash-based lookup

Identify reusable prompt prefixes, calculate saved prefill work and distinguish token savings from hit rates.

Finding cached blocks by hash

Systems look up cached blocks by a key. A good key for block i is a hash of the previous block's key plus the model identity plus this block's tokens. Chaining the previous key means identical tokens after a different beginning get a different key, as they should. Including the model (and any adapter or setting that changes the computed state) keeps one model's cache from being used for another. Only full blocks are hashed.

value of the first block's tokens1block size4
model:
blocktokenskey = hash(previous key, model, tokens)same as the reference prompt?
11 1 1 1cb7d17yes
27 7 7 7de3df1yes
11 tokens → 2 full blocks; the last 3 token(s) are not hashed yet The second block holds the same tokens (7 7 7 7) in every row, but its key changes when the FIRST block or the MODEL changes. (the hash here is a small demo function; the exercise uses sha256)
Change the first block or the model: the second block keeps the same tokens, yet its key changes.

Predict first. Why include ancestry or preceding context in a block's identity?

Chapter context

Prefix caching reuses compatible KV state for a repeated beginning of a prompt. A repeated suffix alone is not enough, because causal hidden states depend on the preceding context.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

A simple saved-token estimate is

S=H P,S=H\,P,

where H is the number of hits reusing P prefix tokens. If all R requests contain P prefix and U unique tokens, the baseline prompt work is R(P+U)R(P+U) and the nominal fraction saved is HP/[R(P+U)]HP/[R(P+U)]. This models token work, not directly wall-clock speed.

Worked example

One hundred requests each contain a 500-token common prefix and a 300-token unique suffix. Eighty hits reuse the entire prefix. Saved prefill tokens are 80×500=40,000 out of 100×800=80,000 baseline tokens: 50% token work saved despite an 80% request hit rate. Cache lookup and new-output generation still take work.

Reference code

The following example uses the Python standard library and does not call a remote service.

requests,hits,prefix,unique=100,80,500,300
saved=hits*prefix
baseline=requests*(prefix+unique)
assert saved == 40000 and baseline == 80000
assert saved/baseline == .5
assert hits/requests == .8

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

Textual similarity is not cache identity. A common suffix is not a common causal prefix. Hit rates need definitions and do not directly translate into end-to-end speedups.