2Batch Assembly — get_batch()
ix = torch.randint(len(data)-block_size, (batch_size,))
x = torch.stack([data[i:i+block_size] for i in ix])
B independent, randomly-sampled windows — the box's height axis (Batch) shows separate layers that never touch or mix; this isolation holds true through every step of this entire page. Each layer's width (Sequence, T=32 in your real config) is how long this window is — starting next step, we'll also call it "position" (which slot within the window).
ix = torch.randint(..., (batch_size,)) is one single call that returns batch_size random integers together — ix[0], ix[1], ix[2] above are 3 simultaneous draws from that one call, not 3 separate training steps. This diagram shows exactly one get_batch() call. What repeated calls (i.e. many training steps, each with a brand-new random ix) accomplish over time — eventually touching most of the dataset — is a completely different question, answered below.batch_size = 16 # how many independent sequences will we process in parallel?
block_size = 32 # what is the maximum context length for predictions?
def get_batch(split):
# generate a small batch of data of inputs x and targets y
data = train_data if split == 'train' else val_data
ix = torch.randint(len(data) - block_size, (batch_size,))
x = torch.stack([data[i:i+block_size] for i in ix])
y = torch.stack([data[i+1:i+block_size+1] for i in ix])
x, y = x.to(device), y.to(device)
return x, y
N = 200 # 缩小版演示,代表原始 token 序列长度 _block = 8 _batch = 4 n_steps = 20 # 模拟 20 次 get_batch 调用 coverage = np.zeros(N) for step in range(n_steps): starts = np.random.randint(0, N - _block, size=_batch) # a NEW random ix, every step for s in starts: coverage[s:s + _block] += 1 # ...plot coverage as a bar chart... print(f"After {n_steps} steps: {(coverage > 0).sum()} / {N} positions covered ({100*(coverage>0).mean():.1f}%)")
torch.randint draws batch_size independent random integers on the CPU/GPU in one vectorized call (no Python loop). torch.stack then takes a Python list of batch_size separate 1D tensors (each length block_size) and allocates one new contiguous 2D tensor, copying each row in — this is where the (B,T) shape is physically created.📓 Jupyter source — live from gpt-dev.ipynb, not hand-copied
cell e756bf49
batch_size = 16 # how many independent sequences will we process in parallel? block_size = 32 # what is the maximum context length for predictions? i.e. how many characters do we feed into the model to get a prediction? n_embd = 64 # the dimensionality of the character embedding vectors n_head = 4 # the number of heads we'd like in the self-attention layer n_layer = 4 # the number of layers we'd like in the Transformer dropout = 0.0 # the dropout probability for the Transformer def get_batch(split): # generate a small batch of data of inputs x and targets y data = train_data if split == 'train' else val_data ix = torch.randint(len(data) - block_size, (batch_size,)) x = torch.stack([data[i:i+block_size] for i in ix]) y = torch.stack([data[i+1:i+block_size+1] for i in ix]) x, y = x.to(device), y.to(device) return x, y
📝 笔记 Chinese notes — live from gpt-dev.ipynb, not hand-copied
note 6da58823
ix 的覆盖机制
ix 不是"一次性扫描全部",而是靠随机采样 + 多次迭代来统计覆盖整个数据集。
原始 1D token 序列(长度 N ≈ 100万):
[0, 1, 2, 3, ......................., N-1]
第1次 get_batch → ix = [42, 1800, 55000, 3] → 采样4个起点(示意,实际是 batch_size 个)
第2次 get_batch → ix = [201, 9900, 77, 40000] → 又采样4个起点
...
第10000次 → 经过足够多次后,整个序列都被随机触及过
每个起点各自的窗口宽度 = block_size(比如 32)——batch_size 只决定"一次采几个这样的窗口",
不会让单个窗口变宽;batch_size 个窗口是并行、各自独立的,不是拼接成一个更宽的窗口。
第1次 get_batch 的 4 个起点,各自覆盖:
data[42 : 42+32] ← 宽度 32
data[1800 : 1800+32] ← 宽度 32
data[55000 : 55000+32] ← 宽度 32
data[3 : 3+32] ← 宽度 32
这一次调用总共覆盖的 token 数(batch_size 个独立窗口的宽度之和)= batch_size × block_size = 16×32 = 512
(这是"不重叠情况下"的总量,不是"某一个起点自己"覆盖的宽度)
但训练跑 10000 步 → 理论上触及 5,120,000 个位置(含重叠)
关键约束:上界是 len(data) - block_size 而不是 len(data),
是为了防止 data[i : i+block_size] 末尾越界。
"训练跑 10000 步" 里的"步",是不是就是"采样 ix 的次数"
在本 notebook 这种最朴素的训练循环里,是的,一一对应:
for steps in range(10000):
xb, yb = get_batch('train') # 采样一次 ix → 一次前向 → 一次反向 → 一次 optimizer.step()
logits, loss = m(xb, yb)
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
每一次 for 循环,get_batch(采样 ix)、loss.backward()(算梯度)、optimizer.step()(更新权重)都只发生一次,
所以"训练步数"="ix 采样次数"="权重更新次数",三者严格相等——但这个等式只在没有梯度累积的前提下成立。
真实训练常见的做法是梯度累积(gradient accumulation),此时三者会分离:
optimizer.zero_grad()
for micro_step in range(accum_steps): # 比如 accum_steps=4
xb, yb = get_batch('train') # 每个 micro_step 都采样一次新 ix
logits, loss = m(xb, yb)
loss.backward() # 梯度累加,但先不更新权重
optimizer.step() # 累积 4 次 micro_step 后,才真正更新一次权重
这种情况下:"1 个训练 step"(1 次 optimizer.step())对应了 accum_steps 次 ix 采样,
不再是一一对应。这么做的常见原因是:单张 GPU 显存放不下想要的大 batch_size,
于是把一个"大 batch"拆成几个"小 batch(micro-batch)"分别算梯度、累加起来,再当作一次大 batch 的效果去更新权重。
校正:训练时 T 是否恒等于 block_size——是的,且不需要 padding
ix = torch.randint(len(data) - block_size, (batch_size,)) 的采样上界就是 len(data) - block_size,
这保证了每一次采样出来的 i,data[i:i+block_size] 都必然是完整的 block_size 长度,不存在越界、也不存在"最后一批需要补齐 padding"的情况——
因为 get_batch 是有放回的随机采样,不是按顺序切分数据集,不会出现"数据集切到最后不够凑成一批"的场景。
结论:训练时 T 严格恒等于 block_size,每一步都不例外;这也意味着 position_embedding_table 的 block_size 行,训练时每一步都会被查全(torch.arange(T) 里 T=block_size)。
但这只是训练这套 get_batch 实现下的数值巧合,不代表 T(sequence size)和 block_size 是同一个概念可以合并——
Head.forward() 里写的是通用的 B,T,C = x.shape,没有写死 T=block_size,这正是同一份代码在推理阶段(T 从 1 到 block_size 之间任意取值,包括 KV Cache 每步 T=1)也能正确工作的原因。
note 32ba12ef
import matplotlib.pyplot as plt import numpy as np
N = 200 # 用缩小版演示,代表原始 token 序列长度 _block = 8 _batch = 4 n_steps = 20 # 模拟 20 次 get_batch 调用
coverage = np.zeros(N) fig, axes = plt.subplots(n_steps // 5, 5, figsize=(14, 6)) axes = axes.flatten()
for step in range(n_steps): starts = np.random.randint(0, N - _block, size=_batch) for s in starts: coverage[s:s + _block] += 1 ax = axes[step] ax.bar(range(N), (coverage > 0).astype(int), color='steelblue', width=1) ax.set_title(f'step {step+1}', fontsize=8) ax.set_ylim(0, 1.2) ax.axis('off')
plt.suptitle(f'Coverage grows with training steps (N={N}, block={_block}, batch={_batch})', fontsize=11) plt.tight_layout() plt.show() print(f"After {n_steps} steps: {(coverage > 0).sum()} / {N} positions covered ({100*(coverage>0).mean():.1f}%)")