import random9.8 배치 크기
실무에서는 흔히 가속기 메모리를 꽉 채우도록 미니배치 크기 \(b\) 를 정한 뒤 그대로 고정해 둡니다. 그러나 여러 GPU로 훈련을 확장하거나 실제 소요 훈련 시간과 총 연산 FLOPs를 맞바꾸려는 순간 근본적인 질문과 마주하게 됩니다. 미니배치 크기 \(b\) 를 두 배로 늘리면(스텝당 병렬 연산량을 두 배로 늘리면) 목표 손실에 절반의 스텝 만에 도달할 수 있을까요?
9.2절 에서 살펴보았듯 \(b\) 개의 표본으로 이루어진 미니배치는 그레이디언트 표본 추출 분산을 \(\operatorname{tr}(\boldsymbol{\Sigma})/b\) 로 줄입니다. 이로부터 두 가지 뚜렷한 영역이 도출됩니다.
- 소배치(잡음 지배) 영역: 표본 추출 잡음이 실제 그레이디언트보다 클 때는 \(b\) 를 두 배로 늘리면 잡음 분산이 절반으로 줄어들어 더 큰 학습률을 쓸 수 있으므로, 처리된 총 표본 수 \(E(b) = b\,S(b)\) 를 일정하게 유지한 채 필요 스텝 수 \(S(b)\) 가 절반으로 줄어듭니다(완벽한 선형 스케일링).
- 대배치(곡률 지배) 영역: 미니배치 그레이디언트가 실제 전체 배치 그레이디언트를 이미 잘 근사할 만큼 \(b\) 가 충분히 커지면, \(b\) 를 더 키워도 \(S(b)\) 감소 폭은 점점 줄어드는 반면 데이터 및 연산 비용 \(E(b)\) 는 선형으로 증가합니다.
McCandlish 기타 (2018년) 연구진은 이 두 영역 사이의 전이가 임계 배치 크기(critical batch size) \(b_{\text{crit}}\) 에서 일어나며, 이를 그레이디언트 잡음 스케일(gradient-noise scale) \(b_{\text{noise}} = \operatorname{tr}(\boldsymbol{\Sigma}) / \|\nabla f\|^2\) 로 예측할 수 있음을 보였습니다. 이 절에서는 \(b_{\text{noise}}\) 를 위한 2-배치 추정량을 구축하고, 스텝 대 데이터 상충 관계의 파레토 경계와 SGD(\(\eta \propto b\)) 및 Adam(\(\eta \propto \sqrt{b}\))의 학습률 스케일링 법칙을 유도한 뒤 TinyLM과 FashionCNN에서 두 예측을 모두 검증합니다.
9.8.1 그레이디언트 잡음 스케일
9.8.1.1 신호, 잡음 및 2-배치 추정량
정확한 전체 데이터셋 그레이디언트를 \(\nabla f(\mathbf{x})\) 라 하고, 표본별 그레이디언트 공분산이 \(\boldsymbol{\Sigma}\) 일 때 \(b\) 개의 독립 표본에 걸쳐 평균 낸 미니배치 그레이디언트를 \(\hat{\mathbf{g}}_b\) 라 합시다. \(\mathbb{E}[\hat{\mathbf{g}}_b] = \nabla f\) 이고 \(\mathbb{E}[\|\hat{\mathbf{g}}_b - \nabla f\|^2] = \operatorname{tr}(\boldsymbol{\Sigma})/b\) 이므로, 미니배치 그레이디언트의 기대 제곱 노름은 신호 전력 \(\|\nabla f\|^2\) 과 잡음 전력 \(\operatorname{tr}(\boldsymbol{\Sigma})/b\) 의 합으로 분해됩니다.
\[\mathbb{E}\big[\|\hat{\mathbf{g}}_b\|^2\big] = \|\nabla f\|^2 + \frac{\operatorname{tr} \boldsymbol{\Sigma}}{b}. \tag{9.8.1}\]
신호 전력과 잡음 전력이 정확히 같아지는 배치 크기가 바로 단순 그레이디언트 잡음 스케일(simple gradient-noise scale)입니다 (McCandlish 기타 2018년).
\[b_{\textrm{noise}} = \frac{\operatorname{tr} \boldsymbol{\Sigma}}{\|\nabla f\|^2}. \tag{9.8.2}\]
두 배치 크기 \(b_{\text{s}} < b_{\text{l}}\) 에서 평균 제곱 그레이디언트 노름 \(N_b = \mathbb{E}[\|\hat{\mathbf{g}}_b\|^2]\) 을 측정하고 식 9.8.1 의 이원 일차 연립방정식을 풀면 데이터셋 전체를 순회하지 않고도 \(\operatorname{tr}\boldsymbol{\Sigma}\) 와 \(\|\nabla f\|^2\) 을 모두 추정할 수 있습니다.
\[ \operatorname{tr} \boldsymbol{\Sigma} \approx \frac{N_{b_{\textrm{s}}} - N_{b_{\textrm{l}}}}{1/b_{\textrm{s}} - 1/b_{\textrm{l}}}, \qquad \|\nabla f\|^2 \approx \frac{b_{\textrm{l}} N_{b_{\textrm{l}}} - b_{\textrm{s}} N_{b_{\textrm{s}}}}{b_{\textrm{l}} - b_{\textrm{s}}}. \]
먼저 WikiText-103과 Fashion-MNIST를 가속기 메모리에 올리고 무작위 미니배치 샘플러 sample_fashion(b)와 sample_lm(b)를 정의합니다.
device = d2l.try_gpu()
data = d2l.WikiText103(batch_size=64, num_steps=64)
fashion = d2l.FashionMNIST(batch_size=256)
X_f = (fashion.train.data.float() / 255).unsqueeze(1).to(device)
y_f = fashion.train.targets.to(device)
def sample_fashion(b): # b random training images
i = torch.randint(len(y_f), (b,), device=device)
return X_f[i], y_f[i]
def sample_lm(b): # b windows at random offsets in the training text
starts = torch.randint(len(data.train) - data.num_steps, (b,))
X, Y = data.windows(data.train, starts.numpy())
return X.to(device), Y.to(device)Downloading ../data/wikitext-103/train-00000-of-00002.parquet from https://huggingface.co/datasets/Salesforce/wikitext/resolve/main/wikitext-103-raw-v1/train-00000-of-00002.parquet...
Downloading ../data/wikitext-103/validation-00000-of-00001.parquet from https://huggingface.co/datasets/Salesforce/wikitext/resolve/main/wikitext-103-raw-v1/validation-00000-of-00001.parquet...
data = d2l.WikiText103(batch_size=64, num_steps=64)
fashion = d2l.FashionMNIST(batch_size=256)
X_f = jnp.asarray(fashion.train[0], jnp.float32)[..., None] / 255
y_f = jnp.asarray(fashion.train[1], jnp.int32)
rng = np.random.default_rng(d2l.get_seed())
def sample_fashion(b): # b random training images
i = rng.integers(len(y_f), size=b)
return X_f[i], y_f[i]
def sample_lm(b): # b windows at random offsets in the training text
return data.windows(data.train,
rng.integers(len(data.train) - data.num_steps, size=b))이 샘플러들을 사용하여 교차 엔트로피 헬퍼 ce_loss, 전체 매개변수 제곱 그레이디언트 노름 grad_sq_norm, 2-배치 추정량 noise_scale을 d2l에 저장합니다.
def ce_loss(model, X, Y):
"""Mean cross-entropy of the logits model(X) for the labels Y."""
logits = model(X)
return F.cross_entropy(logits.reshape(-1, logits.shape[-1]),
Y.reshape(-1))
def grad_sq_norm(model, X, Y):
"""Squared norm of the gradient of ce_loss over all parameters."""
grads = torch.autograd.grad(ce_loss(model, X, Y),
list(model.parameters()))
return sum((g ** 2).sum() for g in grads)
def noise_scale(model, sample, b_small=16, b_big=2048, m=400):
"""Gradient-noise scale from the mean squared gradient norms of m
minibatches of size b_small and m // 8 of size b_big from sample(b)."""
def mean_sq_norm(b, m): # N_b, averaged over m random minibatches
return torch.stack([grad_sq_norm(model, *sample(b))
for _ in range(m)]).mean()
n_small, n_big = mean_sq_norm(b_small, m), mean_sq_norm(b_big, m // 8)
tr_sigma = (n_small - n_big) / (1 / b_small - 1 / b_big)
sq_norm = (b_big * n_big - b_small * n_small) / (b_big - b_small)
return (tr_sigma / sq_norm).item()def ce_loss(model, X, Y):
"""Mean cross-entropy of the logits model(X) for the labels Y."""
logits = model(X)
return optax.softmax_cross_entropy_with_integer_labels(
logits.reshape(-1, logits.shape[-1]), Y.reshape(-1)).mean()
@nnx.jit
def grad_sq_norm(model, X, Y):
"""Squared norm of the gradient of ce_loss over all parameters."""
grads = nnx.grad(ce_loss)(model, X, Y)
return sum((g ** 2).sum() for g in jax.tree.leaves(grads))
def noise_scale(model, sample, b_small=16, b_big=2048, m=400):
"""Gradient-noise scale from the mean squared gradient norms of m
minibatches of size b_small and m // 8 of size b_big from sample(b)."""
def mean_sq_norm(b, m): # N_b, averaged over m random minibatches
return jnp.stack([grad_sq_norm(model, *sample(b))
for _ in range(m)]).mean()
n_small, n_big = mean_sq_norm(b_small, m), mean_sq_norm(b_big, m // 8)
tr_sigma = (n_small - n_big) / (1 / b_small - 1 / b_big)
sq_norm = (b_big * n_big - b_small * n_small) / (b_big - b_small)
return float(tr_sigma / sq_norm)이제 초기화 시점과 Adam(\(\eta = 3 \times 10^{-3}\)) \(500\) 스텝 이후의 TinyLM(\(b_{\text{s}} = 8, b_{\text{l}} = 256\))에서 noise_scale을 계산해 봅니다.
lm = d2l.TinyLM(len(data.vocab)).to(device)
print(f'noise scale at initialization: '
f'{noise_scale(lm, sample_lm, b_small=8, b_big=256):.1f}')
optimizer = torch.optim.Adam(lm.parameters(), lr=0.003)
d2l.train_steps(lm, data, optimizer, num_steps=500)
print(f'after 500 steps of Adam: '
f'{noise_scale(lm, sample_lm, b_small=8, b_big=256):.0f}')noise scale at initialization: 2.2
after 500 steps of Adam: 93
lm = d2l.TinyLM(len(data.vocab), rngs=nnx.Rngs(d2l.get_key()))
print(f'noise scale at initialization: '
f'{noise_scale(lm, sample_lm, b_small=8, b_big=256):.1f}')
optimizer = nnx.Optimizer(lm, optax.adam(0.003), wrt=nnx.Param)
d2l.train_steps(lm, data, optimizer, num_steps=500)
print(f'after 500 steps of Adam: '
f'{noise_scale(lm, sample_lm, b_small=8, b_big=256):.0f}')noise scale at initialization: 2.0
after 500 steps of Adam: 91
이미지를 다루는 합성곱 신경망의 잡음 스케일도 같은 방식으로 증가할까요? 기본값인 \(b_{\text{s}} = 16\), \(b_{\text{l}} = 2{,}048\) 장의 이미지를 사용하여 초기화 시점과 Adam(\(\eta = 0.004\), 아래 스윕이 \(b = 256\) 에서 사용하는 학습률) \(200\) 스텝 이후의 FashionCNN에서 동일한 측정을 반복합니다.
cnn = d2l.FashionCNN().to(device)
print(f'noise scale at initialization: {noise_scale(cnn, sample_fashion):.0f}')
optimizer = torch.optim.Adam(cnn.parameters(), lr=0.004)
d2l.train_steps(cnn, fashion, optimizer, num_steps=200)
print(f'after 200 steps of Adam: {noise_scale(cnn, sample_fashion):.0f}')noise scale at initialization: 64
after 200 steps of Adam: 120
cnn = d2l.FashionCNN(rngs=nnx.Rngs(d2l.get_key()))
print(f'noise scale at initialization: {noise_scale(cnn, sample_fashion):.0f}')
optimizer = nnx.Optimizer(cnn, optax.adam(0.004), wrt=nnx.Param)
d2l.train_steps(cnn, fashion, optimizer, num_steps=200)
print(f'after 200 steps of Adam: {noise_scale(cnn, sample_fashion):.0f}')noise scale at initialization: 95
after 200 steps of Adam: 76
초기화 시점의 TinyLM에서는 모든 윈도가 동일한 거친 유니그램 조정을 요구하므로 신호 \(\|\nabla f\|^2\) 이 매우 커서 \(b_{\text{noise}} \approx 2\) 시퀀스에 불과합니다. 그러나 흔한 바이트 통계가 학습되고 나면(스텝 \(500\) 무렵) 시퀀스 간 분산 \(\operatorname{tr}\boldsymbol{\Sigma}\) 는 유지되는 동안 \(\|\nabla f\|^2\) 이 급감하여 \(b_{\text{noise}}\) 가 열 배 이상 커진 \(\sim 50\text{--}150\) 시퀀스로 증가합니다.
FashionCNN은 다르게 거동합니다. 열 개의 클래스가 균형을 이루고 있으므로 미학습 신경망에서도 모든 이미지가 한목소리로 요구하는 공통 조정 방향이 없으며, 따라서 첫 스텝부터 잡음 스케일이 약 \(100\) 장 수준에서 시작합니다. \(200\) 스텝 동안 추정치는 실행에 따라 위아래로 두 배 미만 범위에서만 움직이며 줄곧 약 \(100\) 장 수준에 머뭅니다.
9.8.2 배치 크기, 스텝 효율성 및 학습률 스케일링
9.8.2.1 최적 스텝 크기와 효율성 경계
\(L\)-매끄러운 하강 상한 \(f(\mathbf{x} - \eta\hat{\mathbf{g}}_b) - f(\mathbf{x}) \le -\eta\nabla f^\top \hat{\mathbf{g}}_b + \frac{L}{2}\eta^2\|\hat{\mathbf{g}}_b\|^2\) 의 기댓값을 취하고 식 9.8.1 의 결과를 대입하면 다음을 얻습니다.
\[ \mathbb{E}\big[f(\mathbf{x} - \eta\, \hat{\mathbf{g}}_b)\big] - f(\mathbf{x}) \leq -\eta\, \|\nabla f\|^2 + \frac{L}{2}\, \eta^2 \Big(\|\nabla f\|^2 + \frac{\operatorname{tr} \boldsymbol{\Sigma}}{b}\Big). \tag{9.8.3}\]
우변을 \(\eta\) 에 대해 최소화하면 최적 스텝 크기 \(\eta_{\text{opt}}(b)\) 와 보장되는 단일 스텝 감소량을 얻습니다.
\[ \begin{aligned} \eta_{\textrm{opt}}(b) &= \frac{1}{L} \cdot \frac{1}{1 + b_{\textrm{noise}} / b}, \\ f(\mathbf{x}) - \mathbb{E}\big[f(\mathbf{x} - \eta_{\textrm{opt}}\, \hat{\mathbf{g}}_b)\big] &\geq \frac{\|\nabla f\|^2}{2L} \cdot \frac{1}{1 + b_{\textrm{noise}} / b}. \end{aligned} \tag{9.8.4}\]
(스칼라 매끄러움 상한 \(L\mathbf{I}\) 를 국소 헤세 행렬 \(\mathbf{H}\) 로 대체하면 곡률 가중 잡음 스케일 \(\operatorname{tr}(\mathbf{H}\boldsymbol{\Sigma}) / (\nabla f^\top\mathbf{H}\nabla f)\) (McCandlish 기타 2018년) 에 대해 정확히 동일한 형태의 식이 유도되며, 식 9.8.2 의 \(b_{\text{noise}}\) 는 이에 대한 헤세 프리 근사치 역할을 합니다.)
배치 크기 \(b\) 에서의 한 스텝은 정확한 전체 배치 한 스텝 대비 \((1 + b_{\text{noise}}/b)^{-1}\) 비율만큼 전진하므로, 전체 배치로 \(S_{\min}\) 스텝이 걸리는 목표 손실에 도달하려면 \(S(b)\) 스텝과 총 \(E(b) = b\,S(b)\) 개의 훈련 표본이 필요합니다.
\[ \frac{S(b)}{S_{\min}} = 1 + \frac{b_{\textrm{noise}}}{b}, \qquad \frac{E(b)}{E_{\min}} = 1 + \frac{b}{b_{\textrm{noise}}}, \tag{9.8.5}\]
여기서 \(E_{\min} = b_{\text{noise}} S_{\min}\) 은 소배치 극한 \(b \ll b_{\text{noise}}\) 에서 달성되는 최소 데이터 예산입니다. 임계 배치 크기 \(b_{\text{crit}} = b_{\text{noise}}\) 에서는 스텝 수와 표본 수가 모두 이론적 최솟값의 정확히 두 배(\(S = 2S_{\min}, E = 2E_{\min}\))가 되며, 파레토 경계 \(((E/E_{\min} - 1)(S/S_{\min} - 1) = 1\))의 무릎(knee) 지점을 형성합니다.
9.8.2.2 선형 대 제곱근 학습률 스케일링
잡음 지배 영역(\(b_0, b \ll b_{\text{noise}}\))에서 배치 크기를 \(b_0\) 에서 \(b\) 로 키울 때 학습률 \(\eta\) 는 어떻게 스케일링되어야 할까요?
- SGD 및 모멘텀(선형 스케일링): 식 9.8.4 에 의해 \(b \ll b_{\text{noise}}\) 일 때 \(\eta_{\text{opt}}(b) \approx \frac{b}{L b_{\text{noise}}} \propto b\) 입니다. 동치적으로 배치 크기 \(b_0\), 스텝 크기 \(\eta_0\) 인 \(k\) 번의 스텝은 정상 잡음 바닥 \(\propto \eta / b\) 를 유지하면서 배치 크기 \(k b_0\), 스텝 크기 \(k\eta_0\) 인 한 스텝과 일치합니다 (Goyal 기타 2017년; Smith 기타 2018년).
- Adam 및 AdamW(제곱근 스케일링): 좌표 그레이디언트가 평균 \(\bar{g}\) 와 표준편차 \(\sigma / \sqrt{b}\) 를 갖는 잡음 지배 영역에서 Adam은 그레이디언트를 RMS 스케일 \(\sqrt{\hat{v}_t} \approx \sigma / \sqrt{b}\) 로 정규화하여 단일 스텝 드리프트 \(-\eta(\sqrt{b}/\sigma)\bar{g}\) 와 스텝 잡음 \(-\eta z\)(\(z \sim \mathcal{N}(0, 1)\))를 만듭니다. 분모 \(\sigma/\sqrt{b}\) 가 이미 \(\sqrt{b/b_0}\) 인자를 공급하므로 단일 대배치 스텝 하나로 \(k = b/b_0\) 번의 소배치 스텝이 만드는 누적 드리프트와 누적 분산을 동시에 일치시키려면 \(\eta\) 를 \(\sqrt{b/b_0}\) 배로 스케일링해야 합니다 (Malladi 기타 2022년).
\[ \begin{aligned} \eta(b) &= \frac{b}{b_0}\, \eta_0 \;\; \textrm{(SGD)}, \\ \eta(b) &= \sqrt{\frac{b}{b_0}}\, \eta_0 \;\; \textrm{(Adam / AdamW)}. \end{aligned} \tag{9.8.6}\]
\(b\) 가 \(b_{\text{crit}}\) 를 넘어서면 더 이상 그레이디언트 잡음이 분모를 지배하지 않으므로 최적 학습률은 \(b\) 를 따라 계속 커지지 않고 결정론적 곡률 한계에서 포화됩니다 (Shallue 기타 2019년).
9.8.3 실험적 검증: 목표 도달 스텝 수와 스케일링 규칙
고정된 홀드아웃 목표 손실에 도달하는 데 필요한 스텝 수 \(S(b)\) 를 측정하기 위해, 먼저 검증 텐서를 \(4{,}096\) 개 표본 단위로 나누어 ce_loss를 계산하는 eval_loss를 정의합니다.
def eval_loss(model, X, Y, chunk=4096):
with torch.inference_mode():
return torch.stack([ce_loss(model, X[i:i + chunk], Y[i:i + chunk])
for i in range(0, len(Y), chunk)]).mean().item()eval_chunk = nnx.jit(ce_loss)
def eval_loss(model, X, Y, chunk=4096):
return float(jnp.stack([eval_chunk(model, X[i:i + chunk], Y[i:i + chunk])
for i in range(0, len(Y), chunk)]).mean())조기 종료 하네스 train_to_target은 d2l.train_steps 내부에서 eval_every스텝마다 eval_loss를 확인하여 target에 도달한 스텝 수(max_steps 소진 시 inf)를 반환합니다.
def train_to_target(model, data, optimizer, X_eval, Y_eval, target,
max_steps, eval_every=10):
"""Return the number of steps until the eval loss reaches target."""
def reached(step):
return (step % eval_every == 0
and eval_loss(model, X_eval, Y_eval) <= target)
steps = len(d2l.train_steps(model, data, optimizer, max_steps,
stop=reached))
return steps if reached(steps) else float('inf')def train_to_target(model, data, optimizer, X_eval, Y_eval, target,
max_steps, eval_every=10):
"""Return the number of steps until the eval loss reaches target."""
def reached(step):
return (step % eval_every == 0
and eval_loss(model, X_eval, Y_eval) <= target)
steps = len(d2l.train_steps(model, data, optimizer, max_steps,
stop=reached))
return steps if reached(steps) else float('inf')먼저 공유 초기화에서 출발하여 Adam 학습률을 \(\eta = 0.003\sqrt{b / 64}\) 로 스케일링하면서 \(b \in \{4, 16, 64, 256\}\) 시퀀스에 걸쳐 TinyLM(목표 검증 손실 \(1.9\) nats/byte)에 train_to_target을 실행합니다.
starts = np.arange(0, len(data.val) - data.num_steps, data.num_steps)
X_val, Y_val = (t.to(device) for t in data.windows(data.val,
starts[::8][:2048]))
lm_bs, lm_steps = [4, 16, 64, 256], []
seed = random.getrandbits(32) # One initialization for all batch sizes
for b in lm_bs:
torch.manual_seed(seed)
data.batch_size = b
model = d2l.TinyLM(len(data.vocab)).to(device)
optimizer = torch.optim.Adam(model.parameters(),
lr=0.003 * math.sqrt(b / 64))
lm_steps.append(train_to_target(model, data, optimizer, X_val, Y_val,
target=1.9, max_steps=8000))
print(f'b={b:4d} steps={lm_steps[-1]:6.0f} '
f'examples={b * lm_steps[-1]:8.0f}')
d2l.plot(lm_bs, [lm_steps, [lm_steps[0] * lm_bs[0] / b for b in lm_bs]],
'batch size (sequences)', 'steps to loss 1.9', xscale='log',
yscale='log', legend=['measured', 'perfect scaling'])b= 4 steps= 3880 examples= 15520
b= 16 steps= 1200 examples= 19200
b= 64 steps= 440 examples= 28160
b= 256 steps= 210 examples= 53760
starts = np.arange(0, len(data.val) - data.num_steps, data.num_steps)
X_val, Y_val = data.windows(data.val, starts[::8][:2048])
lm_bs, lm_steps = [4, 16, 64, 256], []
seed = d2l.get_seed() # One initialization for all batch sizes
for b in lm_bs:
data.batch_size = b
model = d2l.TinyLM(len(data.vocab), rngs=nnx.Rngs(seed))
optimizer = nnx.Optimizer(model,
optax.adam(0.003 * math.sqrt(b / 64)),
wrt=nnx.Param)
lm_steps.append(train_to_target(model, data, optimizer, X_val, Y_val,
target=1.9, max_steps=8000))
print(f'b={b:4d} steps={lm_steps[-1]:6.0f} '
f'examples={b * lm_steps[-1]:8.0f}')
d2l.plot(lm_bs, [lm_steps, [lm_steps[0] * lm_bs[0] / b for b in lm_bs]],
'batch size (sequences)', 'steps to loss 1.9', xscale='log',
yscale='log', legend=['measured', 'perfect scaling'])b= 4 steps= 4110 examples= 16440
b= 16 steps= 1130 examples= 18080
b= 64 steps= 420 examples= 26880
b= 256 steps= 220 examples= 56320
이번에는 \(b = 512\) 까지 \(\eta = 0.004\sqrt{\min(b, 512)/256}\) 으로 스케일링하면서 \(b \in \{8, 32, 128, 512, 2048\}\) 장의 이미지에 걸쳐 FashionCNN(목표 손실 \(0.35\))에서 목표 도달 스텝 스윕을 반복합니다.
cnn_bs, cnn_steps = [8, 32, 128, 512, 2048], []
seed = random.getrandbits(32) # One initialization for all batch sizes
for b in cnn_bs:
torch.manual_seed(seed)
fashion_b = d2l.FashionMNIST(batch_size=b)
model = d2l.FashionCNN().to(device)
lr = 0.004 * math.sqrt(min(b, 512) / 256) # Held fixed above 512
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
cnn_steps.append(train_to_target(model, fashion_b, optimizer,
X_f[:8192], y_f[:8192], target=0.35,
max_steps=8000))
print(f'b={b:4d} steps={cnn_steps[-1]:6.0f} '
f'examples={b * cnn_steps[-1]:8.0f}')
d2l.plot(cnn_bs, [cnn_steps,
[cnn_steps[0] * cnn_bs[0] / b for b in cnn_bs]],
'batch size', 'steps to loss 0.35', xscale='log', yscale='log',
legend=['measured', 'perfect scaling'])b= 8 steps= 2340 examples= 18720
b= 32 steps= 650 examples= 20800
b= 128 steps= 230 examples= 29440
b= 512 steps= 130 examples= 66560
b=2048 steps= 80 examples= 163840
cnn_bs, cnn_steps = [8, 32, 128, 512, 2048], []
seed = d2l.get_seed() # One initialization for all batch sizes
for b in cnn_bs:
fashion_b = d2l.FashionMNIST(batch_size=b)
model = d2l.FashionCNN(rngs=nnx.Rngs(seed))
lr = 0.004 * math.sqrt(min(b, 512) / 256) # Held fixed above 512
optimizer = nnx.Optimizer(model, optax.adam(lr), wrt=nnx.Param)
cnn_steps.append(train_to_target(model, fashion_b, optimizer,
X_f[:8192], y_f[:8192], target=0.35,
max_steps=8000))
print(f'b={b:4d} steps={cnn_steps[-1]:6.0f} '
f'examples={b * cnn_steps[-1]:8.0f}')
d2l.plot(cnn_bs, [cnn_steps,
[cnn_steps[0] * cnn_bs[0] / b for b in cnn_bs]],
'batch size', 'steps to loss 0.35', xscale='log', yscale='log',
legend=['measured', 'perfect scaling'])b= 8 steps= 3040 examples= 24320
b= 32 steps= 760 examples= 24320
b= 128 steps= 250 examples= 32000
b= 512 steps= 110 examples= 56320
b=2048 steps= 80 examples= 163840
\(S(b) = S_{\min}(1 + b_{\text{crit}}/b)\) 는 \(1/b\) 에 대한 일차함수이므로, fit_steps는 가중 최소제곱법으로 두 모델의 점근 스텝 하한 \(S_{\min}\) 과 경험적 임계 배치 크기 \(b_{\text{crit}}\) 를 추출합니다.
def fit_steps(bs, steps):
"""Fit S(b) = S_min (1 + b_crit / b) by least squares in 1/b."""
b, S = np.array(bs, dtype=float), np.array(steps, dtype=float)
ok = np.isfinite(S) # Leave out runs that never reached the target
slope, S_min = np.polyfit(1 / b[ok], S[ok], 1, w=1 / S[ok])
assert S_min > 0, 'step counts never level off: no floor to fit'
return S_min, slope / S_min
fits = {'TinyLM': fit_steps(lm_bs, lm_steps),
'FashionCNN': fit_steps(cnn_bs, cnn_steps)}
for name, (S_min, b_crit) in fits.items():
print(f'{name:10s} S_min = {S_min:4.0f} steps b_crit = {b_crit:4.0f}')TinyLM S_min = 157 steps b_crit = 102
FashionCNN S_min = 78 steps b_crit = 241
def fit_steps(bs, steps):
"""Fit S(b) = S_min (1 + b_crit / b) by least squares in 1/b."""
b, S = np.array(bs, dtype=float), np.array(steps, dtype=float)
ok = np.isfinite(S) # Leave out runs that never reached the target
slope, S_min = np.polyfit(1 / b[ok], S[ok], 1, w=1 / S[ok])
assert S_min > 0, 'step counts never level off: no floor to fit'
return S_min, slope / S_min
fits = {'TinyLM': fit_steps(lm_bs, lm_steps),
'FashionCNN': fit_steps(cnn_bs, cnn_steps)}
for name, (S_min, b_crit) in fits.items():
print(f'{name:10s} S_min = {S_min:4.0f} steps b_crit = {b_crit:4.0f}')TinyLM S_min = 161 steps b_crit = 98
FashionCNN S_min = 68 steps b_crit = 340
각 실행의 총 표본 수 \(E(b) = b\,S(b)\) 를 \(E_{\min} = b_{\text{crit}} S_{\min}\) 으로, 스텝 수를 \(S_{\min}\) 으로 정규화하면 두 모델을 보편적인 파레토 경계 식 9.8.5 위에 함께 올려 그릴 수 있습니다.
x = np.logspace(0.005, 1.3, 100) # E / E_min along the model curve
xs, ys = [x], [1 + 1 / (x - 1)]
for (S_min, b_crit), bs, steps in zip(fits.values(), (lm_bs, cnn_bs),
(lm_steps, cnn_steps)):
xs.append([b * S / (b_crit * S_min) for b, S in zip(bs, steps)])
ys.append([S / S_min for S in steps])
d2l.plot(xs, ys, 'examples / minimum', 'steps / minimum', xscale='log',
yscale='log', fmts=('-', 'o', 's'),
legend=['model', 'TinyLM', 'FashionCNN'])x = np.logspace(0.005, 1.3, 100) # E / E_min along the model curve
xs, ys = [x], [1 + 1 / (x - 1)]
for (S_min, b_crit), bs, steps in zip(fits.values(), (lm_bs, cnn_bs),
(lm_steps, cnn_steps)):
xs.append([b * S / (b_crit * S_min) for b, S in zip(bs, steps)])
ys.append([S / S_min for S in steps])
d2l.plot(xs, ys, 'examples / minimum', 'steps / minimum', xscale='log',
yscale='log', fmts=('-', 'o', 's'),
legend=['model', 'TinyLM', 'FashionCNN'])두 아키텍처 모두 보편 곡선 \((E/E_{\min} - 1)(S/S_{\min} - 1) = 1\) 근처에 깔끔하게 놓이며(\(E = E_{\min}\) 가까운 점은 곡선의 가파른 벽 위에 있어 측정 스텝 수의 작은 오차에도 위아래로 크게 움직임), 피팅된 임계 배치 크기는 TinyLM이 \(b_{\text{crit}} \sim 100\) 시퀀스, FashionCNN이 \(b_{\text{crit}} \sim 200\text{--}400\) 장입니다. TinyLM에서 피팅된 값은 앞서 측정한 \(b_{\text{noise}}\) 의 2-배치 추정치(약 \(100\) 시퀀스 미만)와 잘 일치합니다. FashionCNN에서는 약 \(100\) 장이었던 추정치보다 두세 배에서 네 배가량 크게 나옵니다. 단순 잡음 스케일은 곡률을 무시하므로 정확한 값보다는 \(b_{\text{crit}}\) 의 자릿수(order of magnitude)를 알려 줍니다.
마지막으로 \(12{,}800\) 장의 고정 데이터 예산(\(1/5\) 에포크)에서 FashionCNN을 통해 선형(\(\eta \propto b\)) 대 제곱근(\(\eta \propto \sqrt{b}\)) 식 9.8.6 의 학습률 스케일링 규칙을 직접 검증합니다. 헬퍼 final_loss_at은 배치 크기 b에서 num_examples // b스텝 동안 d2l.lr_sweep을 실행하고 각 실행 마지막 사분위 구간의 평균 종단 손실을 반환합니다.
def final_loss_at(make_optimizer, lrs, b, seed, num_examples=12800):
"""Train the CNN once per learning rate; return the final losses."""
curves, _ = d2l.lr_sweep(d2l.FashionCNN, make_optimizer,
d2l.FashionMNIST(batch_size=b), lrs, seed,
num_examples // b, verbose=False)
return [d2l.final_loss(c, k=len(c) // 4) for c in curves.values()]def final_loss_at(make_tx, lrs, b, seed, num_examples=12800):
"""Train the CNN once per learning rate; return the final losses."""
init_key, order_key = jax.random.split(jax.random.key(seed))
data = d2l.DataModule() # Every run sees the images in one order
data.train_dataloader = lambda: d2l.ArrayLoader(
(X_f, y_f), b, shuffle=True, key=order_key)
curves, _ = d2l.lr_sweep(d2l.FashionCNN, make_tx, data, lrs, init_key,
num_examples // b, verbose=False)
return [d2l.final_loss(c, k=len(c) // 4) for c in curves.values()]모멘텀 SGD(\(\beta = 0.9\)) 아래에서 배치 크기를 \(b = 8\) 에서 \(b = 64\) 로 \(8\times\) 늘리면 sgd_lrs에 걸친 최적 학습률이 오른쪽으로 \(4\text{--}8\times\) 이동합니다(\(b = 64\) 에서는 최종 손실이 \(\eta = 0.05\) 와 \(0.1\) 사이에서 거의 평평함).
sgd_lrs = [0.003125, 0.00625, 0.0125, 0.025, 0.05, 0.1, 0.2]
make_sgd = lambda model, lr: torch.optim.SGD(model.parameters(), lr,
momentum=0.9)
seed = random.getrandbits(32)
sgd_small = final_loss_at(make_sgd, sgd_lrs, b=8, seed=seed)
sgd_big = final_loss_at(make_sgd, sgd_lrs, b=64, seed=seed)
for b, loss in ((8, sgd_small), (64, sgd_big)):
print(f'b={b:2d}: best lr {sgd_lrs[np.nanargmin(loss)]:g}')
d2l.plot(sgd_lrs, [sgd_small, sgd_big], 'learning rate', 'final loss',
xscale='log', legend=['b=8', 'b=64'])b= 8: best lr 0.0125
b=64: best lr 0.05
sgd_lrs = [0.003125, 0.00625, 0.0125, 0.025, 0.05, 0.1, 0.2]
make_sgd = lambda lr: optax.sgd(lr, momentum=0.9)
seed = d2l.get_seed()
sgd_small = final_loss_at(make_sgd, sgd_lrs, b=8, seed=seed)
sgd_big = final_loss_at(make_sgd, sgd_lrs, b=64, seed=seed)
for b, loss in ((8, sgd_small), (64, sgd_big)):
print(f'b={b:2d}: best lr {sgd_lrs[np.nanargmin(loss)]:g}')
d2l.plot(sgd_lrs, [sgd_small, sgd_big], 'learning rate', 'final loss',
xscale='log', legend=['b=8', 'b=64'])b= 8: best lr 0.0125
b=64: best lr 0.1
이와 대조적으로 Adam 아래에서 배치 크기를 \(b = 2\) 에서 \(b = 128\) 로 \(64\times\) 늘리면 adam_lrs에 걸친 최적 학습률은 단 \(4\text{--}8\times\)(\(2\times\) 격자로 \(2\) 칸에서 \(3\) 칸)만 이동하여, \(64\times\) 가 아니라 \(\sqrt{64} = 8\times\) 규칙과 정확히 일치합니다.
adam_lrs = [0.0001 * 2 ** k for k in range(13)] # 0.0001 to 0.4096
make_adam = lambda model, lr: torch.optim.Adam(model.parameters(), lr)
seed = random.getrandbits(32)
adam_small = final_loss_at(make_adam, adam_lrs, b=2, seed=seed)
adam_big = final_loss_at(make_adam, adam_lrs, b=128, seed=seed)
i, j = int(np.nanargmin(adam_small)), int(np.nanargmin(adam_big))
print(f'best lr: {adam_lrs[i]:g} at b=2; {adam_lrs[j]:g} at b=128, '
f'final loss {adam_big[j]:.3f}')
for rule, k in (('no scaling', 0), ('square root', 3), ('linear', 6)):
if i + k < len(adam_lrs):
print(f'{rule:11s}: lr {adam_lrs[i + k]:g} at b=128, '
f'final loss {adam_big[i + k]:.3f}')
else:
print(f'{rule:11s}: lr {adam_lrs[i] * 2 ** k:g}, beyond the grid')
d2l.plot(adam_lrs, [adam_small, adam_big], 'learning rate', 'final loss',
xscale='log', legend=['b=2', 'b=128'])best lr: 0.0008 at b=2; 0.0064 at b=128, final loss 0.510
no scaling : lr 0.0008 at b=128, final loss 0.635
square root: lr 0.0064 at b=128, final loss 0.510
linear : lr 0.0512 at b=128, final loss 0.726
adam_lrs = [0.0001 * 2 ** k for k in range(13)] # 0.0001 to 0.4096
make_adam = optax.adam
seed = d2l.get_seed()
adam_small = final_loss_at(make_adam, adam_lrs, b=2, seed=seed)
adam_big = final_loss_at(make_adam, adam_lrs, b=128, seed=seed)
i, j = int(np.nanargmin(adam_small)), int(np.nanargmin(adam_big))
print(f'best lr: {adam_lrs[i]:g} at b=2; {adam_lrs[j]:g} at b=128, '
f'final loss {adam_big[j]:.3f}')
for rule, k in (('no scaling', 0), ('square root', 3), ('linear', 6)):
if i + k < len(adam_lrs):
print(f'{rule:11s}: lr {adam_lrs[i + k]:g} at b=128, '
f'final loss {adam_big[i + k]:.3f}')
else:
print(f'{rule:11s}: lr {adam_lrs[i] * 2 ** k:g}, beyond the grid')
d2l.plot(adam_lrs, [adam_small, adam_big], 'learning rate', 'final loss',
xscale='log', legend=['b=2', 'b=128'])best lr: 0.0016 at b=2; 0.0064 at b=128, final loss 0.455
no scaling : lr 0.0016 at b=128, final loss 0.528
square root: lr 0.0128 at b=128, final loss 0.495
linear : lr 0.1024 at b=128, final loss 2.305
9.8.3.1 배치 크기 선택을 위한 실무 절차
- 먼저 하드웨어 산술 처리량 포화시키기: 스텝당 실행 시간이 \(b\) 에 선형 비례해 증가하기 시작할 때까지 최소한 \(b\) 를 키웁니다(9.2절).
- 웜업 이후에 \(b_{\text{noise}}\) 추정하기: 초기 손실 급락이 지난 뒤(예: 훈련 시작 후 수백 스텝 시점)
noise_scale을 측정합니다.TinyLM에서 보았듯 \(b_{\text{noise}}\) 는 초기화 시점에 매우 작게 시작했다가 훈련 도중 \(1\text{--}2\) 자릿수까지 커질 수 있기 때문입니다(GPT-3 (Brown 기타 2020년) 같은 대규모 사전 학습 실행에서 배치 크기 웜업 램프를 쓰는 이유이기도 함). - \(b_{\text{crit}} \approx b_{\text{noise}}\) 기준으로 \(b\) 배치하기: 연산량이나 데이터가 병목이면 \(b \lesssim 0.3\,b_{\text{crit}}\) 를 택하고, 병렬 가속기들에서의 실제 소요 시간이 병목이면 \(b \approx b_{\text{crit}}\)(\(S = 2S_{\min}\), \(E = 2E_{\min}\))를 택하되 \(b \gg b_{\text{crit}}\) 는 피합니다.
- 식 9.8.6 에 따른 \(\eta\) 스케일링: \(b_{\text{crit}}\) 까지는 SGD/모멘텀에서 \(\eta \propto b\), AdamW에서 \(\eta \propto \sqrt{b}\) 로 스케일링하며 반드시 선형 웜업(9.7.3절)을 함께 적용합니다.
9.8.4 요약
그레이디언트 잡음 스케일 \(b_{\text{noise}} = \operatorname{tr}(\boldsymbol{\Sigma}) / \|\nabla f\|^2\) 은 표본 추출 잡음 전력과 신호 전력이 같아지는 배치 크기를 나타내며, 두 배치 크기 \(b_{\text{s}} < b_{\text{l}}\) 에서의 제곱 그레이디언트 노름(식 9.8.1)만으로 전체 데이터셋 순회 없이 온라인 추정할 수 있습니다. 학습률을 튜닝한 조건에서 목표 손실 도달에 필요한 스텝 수 \(S(b)\) 와 표본 수 \(E(b) = b\,S(b)\) 는 무릎 지점 \(b_{\text{crit}} \approx b_{\text{noise}}\) 를 중심으로 쌍곡선 상충 관계 \(S(b)/S_{\min} = 1 + b_{\text{crit}}/b\) 및 \(E(b)/E_{\min} = 1 + b/b_{\text{crit}}\) 를 따르며 데이터 효율적인 소배치 영역(\(b \ll b_{\text{crit}}\))과 스텝이 포화되는 대배치 영역(\(b \gg b_{\text{crit}}\))을 가릅니다. \(b_{\text{crit}}\) 아래에서 최적 학습률은 SGD와 모멘텀의 경우 선형(\(\eta \propto b\))으로, Adam과 AdamW의 경우 제곱근(\(\eta \propto \sqrt{b}\))으로 증가하다가 \(b\) 가 \(b_{\text{crit}}\) 를 넘어서면 평평하게 포화됩니다.
9.8.5 연습 문제
학습률을 고정한 채 배치 크기만 키우기. 식 9.8.3 및 식 9.8.4 의 식을 사용하여 \(\eta\) 를 \(\eta_0 = \eta_{\text{opt}}(b_0)\) 로 고정한 상태에서 배치 크기만 \(b > b_0\) 로 늘리면 보장되는 단일 스텝 감소량이 \(2 - (1 + b_{\text{noise}}/b)/(1 + b_{\text{noise}}/b_0) < 2\) 배로 개선되어 \(b \to \infty\) 극한에서도 결코 두 배를 넘지 못함을 보이십시오.
시간 최적 배치 크기 대 연산 최적 배치 크기. 배치 크기 \(b\) 에서의 한 스텝이 실제 소요 시간 \(t(b) = t_0(1 + b/b_{\text{sat}})\) 를 소비할 때, 식 9.8.5 의 관계를 사용하여 총 소요 시간 \(T(b) = t(b)S(b)\) 를 최소화하는 배치 크기 \(b^\star\) 를 유도하고 데이터 오버헤드 \(E(b^\star)/E_{\min}\) 을 계산하십시오.
[code] 훈련 중 신호와 잡음의 진화. \(\operatorname{tr}\boldsymbol{\Sigma}\), \(\|\nabla f\|^2\), 그리고 비율 \(b_{\text{noise}}\) 를 개별 반환하도록
noise_scale을 수정하고, 스텝 \(0, 25, 50, 100, 200, 500, 1000, 2000, 3000\) 에서TinyLM의 세 값을 모두 추적하여 \(b_{\text{noise}}\) 의 \(100\times\) 증가가 \(\operatorname{tr}\boldsymbol{\Sigma}\) 의 상승이 아니라 주로 신호 \(\|\nabla f\|^2\) 의 하락에서 비롯됨을 확인하십시오.[code] 임계 배치 크기 너머로의 스케일링. 9.8.3절 의
TinyLM목표 도달 스텝 스윕을 \(b = 1{,}024\) 까지 확장하여 제곱근 규칙 \(\eta \propto \sqrt{b}\) 를 계속 적용할 때와 \(\eta\) 를 \(b = 256\) 값으로 고정(clamping)할 때를 비교하고, 왜 \(b_{\text{crit}}\) 위에서 \(\eta\) 를 계속 키우면 수렴이 나빠지는지 설명하십시오.