BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / LLM inference and serving6 of 36 in topic

432. Write new keys and values into a preallocated batched KV cache

EasyLLM inference and serving
Asked atOpenAI

Why it matters Every decode step of a batched LLM server writes one key and value per sequence into a preallocated cache, so this indexing is on the hot path.

Serving engines allocate one big KV cache buffer up front and then write each new token's key and value into the next free slot of every sequence, instead of growing arrays with concatenate.

Write kv_write(cache_k, cache_v, lengths, k_new, v_new, active=None). cache_k and cache_v have shape (B, H, T, D). lengths (B,) holds how many slots each sequence has filled. k_new and v_new have shape (B, H, D). For every active sequence b, write k_new[b] and v_new[b] at time slot lengths[b] for all heads and add 1 to its length. active is an optional (B,) boolean array; inactive rows (finished or padding sequences) are left untouched. If an active row is already full (lengths[b] == T), raise ValueError. Do not modify the inputs: return new arrays (cache_k, cache_v, new_lengths).

Functiondef kv_write(cache_k, cache_v, lengths, k_new, v_new, active=None)

Example 1

Input: B=2, H=1, T=3, D=2 zero caches, lengths [0, 2], k_new [[[1, 2]], [[3, 4]]]

Output: cache_k[:, 0] = [[[1, 2], [0, 0], [0, 0]], [[0, 0], [0, 0], [3, 4]]] and new lengths [1, 3]

Example 2

Input: (lambda r: (r[0][:, 0], r[2]))(kv_write(np.zeros((2, 1, 3, 2)), np.zeros((2, 1, 3, 2)), [0, 2], [[[1, 2]], [[3, 4]]], [[[10, 20]], [[30, 40]]]))

Output: ([[[1.0, 2.0], [0.0, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.0, 0.0], [3.0, 4.0]]], [1, 3])

Example 3

Input: kv_write(np.zeros((2, 1, 3, 2)), np.zeros((2, 1, 3, 2)), [0, 2], [[[1, 2]], [[3, 4]]], [[[10, 20]], [[30, 40]]])[1][:, 0]

Output: [[[10.0, 20.0], [0.0, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.0, 0.0], [30.0, 40.0]]]

Constraints

  • cache_v has shape (B, H, T, D)
  • v_new has shape (B, H, D)
  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
Hint 1

Loop over the batch and index the time axis with that row's own length.

Hint 2

Copy the inputs first so the caller's arrays do not change.

Hint 3

Different rows write at different time slots, so loop over b.

Hint 4

Check active before checking for a full cache.

Common mistakes
  • Writing every row at the same position, for example max(lengths).
  • Raising for an inactive row that happens to be full.
  • Mutating the caller's lengths array in place.
Understand the idea

Think of the KV cache as a notebook with T empty lines per sequence. Each decode step, every sequence writes one new line: its key and value for the token it just produced. Because sequences in a batch started at different times, sequence 0 may be on line 3 while sequence 1 is on line 7, so each row needs its own write position.

Worked example

lengths are [0, 2] and T is 3. Sequence 0 writes at slot 0 and becomes length 1; sequence 1 writes at slot 2 and becomes length 3, which is now full.

cache[b, :, lengths[b]] = new[b], then lengths[b] += 1, skipping rows that are not active and refusing to write past T

Real servers preallocate this buffer once because growing arrays every token would copy the whole cache again and again.

Shapes and data flow
cache (B, H, T, D)  k_new (B, H, D)  write cache[b, :, lengths[b], :] = k_new[b]  (H, D)
Topics
LLM inference and serving
Companies1
  • OpenAI a candidate reported this question OpenAI Research Engineer Interview Guide (Dataford)

From public interview reports and guides. Not affiliated with or endorsed by these companies.

Similar questions
  • Trim a chat history to fit the context windowEasy
  • Work out how many tokens fit in GPU memory for the KV cacheEasy
  • Compute TTFT, TPOT and throughput from request timestampsEasy
  • Price an API request with cached input tokensEasy
All LLM inference and serving problems
Report
432 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def kv_write(cache_k, cache_v, lengths, k_new, v_new, active=None):
# your code here
pass
​
(lambda r: (r[0][:, 0], r[2]))(kv_write(np.zeros((2, 1, 3, 2)), np.zeros((2, 1, 3, 2)), [0, 2], [[[1, 2]], [[3, 4]]], [[[10, 20]], [[30, 40]]]))

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS