Q2HardPart Q · AI Infra 硬件算力与显存调度算子

显存碎片压缩与 PagedAttention 页式零碎片设计对照

⚡闪卡盲测➔

模拟连续显存分配产生外部碎片后需触发 Compaction 搬运代价,对比解释为何 PagedAttention 物理非连续分页彻底消灭外部碎片。

⏱️ 时间复杂度: O(N log N)
💾 空间复杂度: O(N)
🎯 免登录实战自测闭环(先做再看答案)
按「机制回忆 → 关键行填空 → 边界反例 → 追问与错题记录」顺序自测,进度自动保存在本地。
Step 1 · 机制口述与数值稳定性自检
Step 2 · 核心代码关键行补全
def compact_contiguous_kv_slabs(blocks: list[tuple[int, int]], total_slots: int) -> dict:
# Compact fragmented allocated ranges [(start, length), ...] toward slot 0 via minimal relocate moves
sorted_blocks = sorted(blocks, key=lambda x: x[0])
moves = []
cursor = 0
for start, length in sorted_blocks:
if start != cursor:
moves.append((start, cursor, length))
cursor += length
largest_contiguous_free =
return {"moves": moves, "used_slots": cursor, "largest_free_contiguous": largest_contiguous_free}
Step 3 · 反例与边界断言核对
Step 4 · 面试追问盲答与错题记录
Q1: 既然 PagedAttention 彻底消除了外部碎片,还有哪一部分显存浪费?
Q2: Block Size 设太小(比如 1)和太大(比如 256)各有什么工程弊端?
下一题: CUDA 双流计算-通信流水掩盖(Compute/AllReduce Overlap)仿真 →
💡

实战一句话记忆口诀

连续分配靠搬家治外部碎片,分页 BlockTable 直接物理离散零外部碎片

📐 核心数学公式与机理推导

$$\text{FragRatio} = \frac{\sum_{\text{free}} b_j - \max_{\text{free}} b_j}{\text{TotalFree}}$$
连续分配要求单个请求独占连续地址空间,请求交替释放后即使空闲总显存足够,也因最大连续空块不足而 OOM,必须触发代价昂贵的 cudaMemcpy Compaction;PagedAttention 将逻辑块通过 Block Table 映射到任意离散物理页,从而将外部碎片率永久压降至 0,仅剩末页平均半块的微小内部碎片。

🔄 张量维度与形状流转说明

fragmented blocks [(start, len)] -> greedy left compaction plan & copy overhead

🛡️ 数值稳定性自检与边界要点

  • 拷贝前必须按原起始位置由小到大排序(左移覆盖安全),避免后段尚未读取即被覆盖
  • 即使采取左压缩,线上搬迁大块 KV 依然触发 GPU Stall;页式非连续映射才是更优解
  • 检测连续空闲最大块,避免新大 Prompt 在未压缩前假性 OOM

💻 完整参考代码实现

def compact_contiguous_kv_slabs(blocks: list[tuple[int, int]], total_slots: int) -> dict:
    # Compact fragmented allocated ranges [(start, length), ...] toward slot 0 via minimal relocate moves
    sorted_blocks = sorted(blocks, key=lambda x: x[0])
    moves = []
    cursor = 0
    for start, length in sorted_blocks:
        if start != cursor:
            moves.append((start, cursor, length))
        cursor += length
    largest_contiguous_free = total_slots - cursor
    return {"moves": moves, "used_slots": cursor, "largest_free_contiguous": largest_contiguous_free}

🧪 本地测试与正确性断言

可直接复制到本地 Python / Jupyter 验证:

res = compact_contiguous_kv_slabs([(2, 3), (7, 2), (12, 4)], total_slots=20)
assert res['used_slots'] == 9 and res['largest_free_contiguous'] == 11
assert len(res['moves']) == 3 and res['moves'][0] == (2, 0, 3)
print('Q2 PASS')

🎯 核心工程追问与标准应答

Q1:既然 PagedAttention 彻底消除了外部碎片,还有哪一部分显存浪费?
仅存在每个请求最后一个物理块的内部碎片(Internal Fragmentation),按每块 16 个 token 计,均摊浪费仅为 8 个 token/请求(不到总 KV 显存的 4%)。
Q2:Block Size 设太小(比如 1)和太大(比如 256)各有什么工程弊端?
设太小导致 Block Table 元数据膨胀与随机访存分散、TensorCore 无法充分合并读取;设太大则会放大末块内部碎片并降低 Prefix Cache 复用粒度。工业常用 16 或 32。
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!
🎯 立即在闪卡中盲测此题➔
← 上一题: GPU Roofline 计算强度与 Ridge Point 瓶颈诊断器返回 Part Q 与全部 105 题下一题: CUDA 双流计算-通信流水掩盖(Compute/AllReduce Overlap)仿真 →