19Sliding Window — Cap at block_size

Real sequence from your notebook: block_size=6, oldest entries evicted once full
idx_cond = idx[:, -block_size:] # naive version k_cache = k_cache[:, -block_size:] # KV-cache version, same idea
once total length > block_size: oldest entry dropped, size stays capped

The exact same constraint applies whether you're sliding raw token ids or K/V cache entries — the model architecturally cannot attend beyond block_size positions. This is why the cache is not infinitely growing: it has the same hard ceiling as the naive version.

Real captured output, your notebook (B=3, block_size=4): steps 1-4 grow the cache to (3,1,4)→(3,2,4)→(3,3,4)→(3,4,4); from step 5 onward it stays capped at (3,4,4) with each new step printing "← 已触发淘汰,丢弃最旧一条" (eviction triggered, oldest entry dropped).
full source — HeadWithSlidingCache.forward() (gpt-dev.ipynb)same class as step 18, the eviction check
def forward(self, x_new):
        q_new = self.Wq(x_new)
        k_new = self.Wk(x_new)
        v_new = self.Wv(x_new)

        self.k_cache = k_new if self.k_cache is None else torch.cat([self.k_cache, k_new], dim=1)
        self.v_cache = v_new if self.v_cache is None else torch.cat([self.v_cache, v_new], dim=1)

        if self.k_cache.shape[1] > block_size:
            self.k_cache = self.k_cache[:, -block_size:, :]
            self.v_cache = self.v_cache[:, -block_size:, :]

        wei = q_new @ self.k_cache.transpose(-2, -1) * head_size**-0.5
        wei = F.softmax(wei, dim=-1)
        return wei @ self.v_cache

📓 Jupyter source — live from gpt-dev.ipynb, not hand-copied

cell 76b4b966
# NOTE (cleanup, no values/behavior changed): renamed the bare n_embd/n_head/vocab_size/block_size in this self-contained demo to *_demo below, so this illustration can't silently overwrite the REAL model's globals set earlier in the notebook.
import torch

# 用 nanoGPT 的 generate() 逐步打印窗口行为(不修改原函数,直接模拟逻辑)

block_size_demo  = 6   # 模型支持的最大上下文长度
generate_n  = 10  # 要生成的新 token 数
prompt_len  = 4   # prompt 长度

# 模拟 prompt: token IDs [10, 20, 30, 40]
idx = torch.tensor([[10, 20, 30, 40]])

print(f"block_size_demo(最大窗口)= {block_size_demo}")
print(f"prompt 长度 = {prompt_len},生成 {generate_n} 个新 token")
print(f"{'步骤':<6} {'窗口内容(idx[:,-block_size_demo:])':<35} {'cache大小':<10} {'是否滑动'}")
print("-" * 72)

# Step 0: 处理整个 prompt(并行)
idx_cond = idx[:, -block_size_demo:]
print(f"{'S0':<6} {str(idx_cond[0].tolist()):<35} {idx_cond.shape[1]:<10} {'初始(并行处理prompt)'}")

for step in range(1, generate_n + 1):
    # 模拟采样新 token(用随机整数代替真实 logits)
    new_token = torch.randint(50, 100, (1, 1))
    idx = torch.cat([idx, new_token], dim=1)

    # nanoGPT generate() 里的窗口裁剪
    idx_cond = idx[:, -block_size_demo:]

    sliding = "← 滑动!丢掉最旧token" if idx.shape[1] > block_size_demo else ""
    print(f"{'S'+str(step):<6} {str(idx_cond[0].tolist()):<35} {idx_cond.shape[1]:<10} {sliding}")

print()
print(f"最终序列总长度: {idx.shape[1]},但每次 forward 最多看最近 {block_size_demo} 个 token")
print()
print("对应 nanoGPT 源码中的一行:")
print("  idx_cond = idx[:, -block_size_demo:]  # 这就是滑动窗口的全部实现")
cell 8deef03f
# NOTE (cleanup, no values/behavior changed): renamed the bare n_embd/n_head/vocab_size/block_size in this self-contained demo to *_demo below, so this illustration can't silently overwrite the REAL model's globals set earlier in the notebook.
import torch
import torch.nn as nn
import torch.nn.functional as F

# 验证两件事:
# (1) cache 超过 block_size_demo 后必须淘汰最旧的一条 —— 滑动窗口作用在 K/V 上
# (2) batch 维度 B 在 KV Cache 生成过程中原样保留,不会被"一次前进一个"压缩成 1
torch.manual_seed(0)
n_embd_demo, head_size, block_size_demo = 8, 4, 4  # block_size_demo 故意设小,方便观察淘汰

class HeadWithSlidingCache(nn.Module):
    def __init__(self):
        super().__init__()
        self.Wq = nn.Linear(n_embd_demo, head_size, bias=False)
        self.Wk = nn.Linear(n_embd_demo, head_size, bias=False)
        self.Wv = nn.Linear(n_embd_demo, head_size, bias=False)
        self.k_cache = None
        self.v_cache = None

    def forward(self, x_new):                       # x_new: (B, 1, n_embd_demo) —— B 不是写死的 1
        q_new = self.Wq(x_new)                       # (B, 1, head_size)
        k_new = self.Wk(x_new)
        v_new = self.Wv(x_new)

        self.k_cache = k_new if self.k_cache is None else torch.cat([self.k_cache, k_new], dim=1)
        self.v_cache = v_new if self.v_cache is None else torch.cat([self.v_cache, v_new], dim=1)

        # 滑动窗口:cache 超过 block_size_demo 就砍掉最旧的一条,等价于 idx[:, -block_size_demo:] 但作用对象是 K/V
        if self.k_cache.shape[1] > block_size_demo:
            self.k_cache = self.k_cache[:, -block_size_demo:, :]
            self.v_cache = self.v_cache[:, -block_size_demo:, :]

        wei = q_new @ self.k_cache.transpose(-2, -1) * head_size**-0.5
        wei = F.softmax(wei, dim=-1)
        return wei @ self.v_cache                    # (B, 1, head_size)

B = 3            # 故意用 B>1,验证"批"这个维度在生成阶段并未消失
T_total = 7      # 总共前进 7 步,超过 block_size_demo=4,必然触发淘汰
x_seq = torch.randn(B, T_total, n_embd_demo)

head = HeadWithSlidingCache()
print(f"batch_size B={B},block_size_demo={block_size_demo}(cache 容量上限)\n")
for t in range(T_total):
    x_new = x_seq[:, t:t+1, :]                       # 每步只喂 1 个新位置,batch 维度 B 原样保留
    out_new = head(x_new)
    evicted = "  ← 已触发淘汰,丢弃最旧一条" if (t + 1) > block_size_demo else ""
    print(f"步骤 {t+1}: x_new.shape={tuple(x_new.shape)} → out_new.shape={tuple(out_new.shape)} "
          f"| k_cache.shape={tuple(head.k_cache.shape)}{evicted}")

print(f"\n结论1(滑动窗口 ↔ KV Cache):cache 的容量上限就是 block_size_demo,超出后淘汰最旧的一条,")
print(f"        和朴素版 idx[:, -block_size_demo:] 的滑动窗口是同一个约束,只是作用对象从 token id 变成了 K/V。")
print(f"结论2(batch vs token):k_cache.shape[0] 始终等于 {head.k_cache.shape[0]}(=B),")
print(f"        '一次前进一个' 消掉的是序列长度维度 T,batch 维度 B 完全不受影响。")

📝 笔记 Chinese notes — live from gpt-dev.ipynb, not hand-copied

note 2a5d5d0b

推理全流程 + 上下文窗口

Pre-trained 模型(权重全部固定)
  ↓
prompt 文本 → tokenizer → token IDs (整数序列,长度 P)
  ↓
Step 0  第一次前向传播(处理整个 prompt):
  - prompt 的 P 个 token 一次并行喂入
  - 走 embedding → n_layer 个 Block(attention + FFN)
  - 每个 Block 的 K/V 全部 cache(shape: B, n_head, P, head_size)
  - 取最后一个位置的 logits → 采样 → 得到第一个输出 token t₁
  ↓
Step 1  只喂入 t₁(1 个 token):
  - 计算 t₁ 的 Q、K_new、V_new
  - K_new 追加到 cache → cache size = P+1
  - Q 对整个 cache 做 attention → 得到 t₁ 位置的输出 → 采样 t₂
  ↓
Step 2  只喂入 t₂ ...(重复)

当 cache size 达到 block_size(最大上下文长度):
  - 丢掉最旧的那条 cache(向左滑动)
  - 模型"忘记"最早的 token
  - 窗口始终保持 block_size 大小

关键:prompt 处理是一次并行,后续 token 生成是逐步串行 + 窗口滑动

note d815cbed

融会贯通:Embedding 固定 + Q/K/V 复用差异 + 滑动窗口 + Batch 维度

1)确认:两次查表(token_embedding_table、position_embedding_table)在推理时权重同样固定

nn.Embedding 的 .weight 本质就是一个可学习的查找表矩阵(形状分别是 (vocab_size, n_embd) 和 (block_size, n_embd))。 训练结束后这两个矩阵和 W_q/W_k/W_v 一样被固定;推理时 tokenizer → token_id → 查表 得到的 tok_emb、pos_emb, 用的都是训练好的固定权重,数学过程与训练时完全一致,只是不再有 loss.backward() / optimizer.step()。

2)再确认一次用词:"追加"应改成"加权求和"

wei @ v 不是把标量"追加"进 v,而是每个 wei[t,t'](标量)缩放对应的 v[t'](向量)后按位相加, 输出仍是 head_size 维——是加权融合,不是拼接/追加。

3)KV Cache 必须和滑动窗口(block_size)绑在一起理解

朴素版 generate()(idx_cond = idx[:, -block_size:])每一步都把窗口内全部 token 重新算一遍—— 滑动窗口在朴素版里只解决"模型能接受多长输入",不解决"重复计算"。

引入 KV Cache 后,滑动窗口的含义要多加一层:

朴素版滑动窗口:       idx     = idx[:, -block_size:]      → 砍掉最旧的 token id
KV Cache 版滑动窗口:  k_cache = k_cache[:, -block_size:]   → 砍掉最旧的 K
                       v_cache = v_cache[:, -block_size:]   → 砍掉最旧的 V(同理)

"一次前进一个" 指的是:每一步只对 1 个新 token 跑一次前向(只算它的 q_new/k_new/v_new), k_new/v_new 追加进 cache,cache 一旦超过 block_size 就砍掉最旧的一条—— 这就是为什么必须先理解滑动窗口,才能理解 KV Cache 的边界条件(cache 不是无限增长的)。

而 Q 不需要缓存的原因和滑动窗口无关(上一轮已确认过):q_new 只在诞生的这一步内部用一次,用完即弃, 根本不存在"要不要用滑动窗口保留它"这个问题——它从一开始就没打算被复用。

4)"一次前进一个"指的是 batch 里每条序列各前进一个 token,不是把 batch 折叠成 1

训练时:get_batch() 一次给出 (B, block_size) 个 token,B 条序列全部并行、每条序列内部 T 个位置也全部并行(teacher forcing)。

生成时(用 KV Cache):每一步的输入形状是 (B, 1, n_embd),不是 (1, 1, n_embd)—— B 这个维度原封不动地保留,因为完全可以同时生成 B 条独立序列(比如一次采样 4 个候选回答); "一次前进一个"消掉的是序列长度维度 T(从"一次处理多个位置"变成"一次只处理新增的 1 个位置"), 这和 batch 维度 B 是两件独立的事——B 条序列各自独立地、各前进 1 个 token,互不合并、互不影响。