Implement a paged KV block allocator in Python
CPU · your Macscript150 minrequiredGoal · A BlockManager class with block tables, prefix sharing and refcounts, plus a measurement of fragmentation versus a contiguous allocator.
- 1Define BlockManager(num_blocks, block_size) with a free list and a dict seq_id to block table.
- 2Implement allocate_prefill(seq_id, prompt_tokens) and append_token(seq_id) that allocates a new block only when the last one is full.
- 3Implement free(seq_id) returning blocks to the free list and add refcounts so shared blocks are freed only at zero.
- 4Add prefix caching by hashing full blocks (hash of prefix tokens) and reusing a cached block when the hash matches.
- 5Write a ContiguousAllocator that reserves max_len slots per sequence for comparison.
- 6Simulate 500 requests with random prompt lengths 50-500 and output lengths 20-400 (uniform), max_len 1024, on a budget of 2000 blocks of 16 tokens.
- 7Record peak concurrent sequences and wasted slots for both allocators; print a comparison table.
- 8Rerun with 60 percent of requests sharing a 200-token system prompt and report the extra concurrency from prefix caching.
- Deliverable
- block_manager.py, a test file with at least 8 pytest cases, and a printed comparison table.
- Check
- All tests pass; the paged allocator sustains at least 2x the concurrent sequences of the contiguous one and no physical block is ever double-owned without a refcount above 1.