AdvancedAbout 21 min

    KV Cache & Attention Optimization

    Read the full article on Substack

    6 min read.

    Watch the KV cache turn quadratic recomputation into linear, then work the 2 × B × S × L × H × M formula that makes it 54 GB for a single Llama 2 13B batch — and see how Character.AI stacked three techniques to cut theirs by over twenty times.

    Think of it this way: Reading a book aloud, where before every word you re-read every page so far. The KV cache is the margin notes you make as you go: one note per page, written once, glanced at thereafter. The notes make the reading fast — and eventually the notes outweigh the book.

    step 11 computedstep 21 computedstep 31 computed
    Generation steps3

    Red is computed now, green is read from the cache. 3 projections in total, 1 at the last step. Work grows linearly with the output length.

    Check your understanding

    Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.

    Why the cache exists

    Sequence

    Order what happens on each decoding step with a KV cache.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Quiz

    20 questions
    Question 1 of 20
    Score: 0

    The KV cache exists because, across generation steps, previous tokens' key and value vectors:

    Done with this lesson?

    Sign in free to keep your progress, streak and quiz scores.

    Keep going