import random9.9 스케일업
신경망은 작은 규모에서 개발되어 큰 규모로 배포됩니다. 수십억 매개변수의 사전 학습 실행에서는 학습률 격자 탐색을 감당할 수 없으므로, 실무자들은 동일한 아키텍처 계열의 작은 프록시 모델(proxy model)에서 하이퍼파라미터를 튜닝한 뒤 목표 규모로 전이합니다.
딥러닝 프레임워크가 기본으로 사용하는 표준 매개변수화(standard parametrization, SP)—층 가중치를 분산 \(1/\text{fan-in}\) 으로 초기화하고 모든 층이 단일 전역 학습률 \(\eta\) 를 공유하는 방식—아래에서는 최적 학습률이 모델 너비에 걸쳐 전이되지 않습니다. 층 너비 \(n\) 이 커질수록 행렬-벡터 곱 \(\Delta\mathbf{W}\,\mathbf{h}\) 안의 \(n\) 개 항이 입력 활성화 \(\mathbf{h}\) 와 부호가 정렬되므로, 단 한 번의 Adam 스텝이 은닉층 사전 활성화를 \(O(\eta n)\) 만큼 변화시킵니다. 그 결과 모델이 넓어질수록 최적 학습률은 아래쪽으로 표류(drift)합니다.
최대 업데이트 매개변수화(Maximal Update Parametrization)(\(\mu\text{P}\), Yang 와/과 Hu (2021년); Yang 기타 (2022년) 참조)는 각 층의 팬인(fan-in) 및 팬아웃(fan-out) 증가율에 맞춰 학습률과 출력 승수를 스케일링함으로써 이러한 표류를 제거하고, 너비 \(n \to \infty\) 극한에서도 모든 은닉층이 \(\Theta(1)\) 크기의 특성 업데이트를 겪도록 보장합니다. 이 절에서는 \(64\times\) 범위의 MLP 너비(\(n = 128\) 부터 \(8{,}192\) 까지)에 걸쳐 SP 아래에서의 학습률 표류를 측정하고, 첫 스텝 스케일링 법칙을 유도하며, \(\mu\text{P}\) 를 구현해 단일 스텝 좌표 점검(coordinate check) (Yang 기타 2022년; Dey 기타 2024년) 으로 검증한 뒤, 너비 간 제로샷 학습률 전이를 시연하고 트랜스포머·스펙트럼 노름 옵티마이저·깊이로 규칙을 확장합니다.
import random9.9.1 표준 매개변수화 아래에서의 학습률과 너비
9.9.1.1 너비 계열과 학습률 표류
은닉 너비 \(n\) 이 \(\{128, 512, 2048, 8192\}\)(\(1.35 \times 10^5\) 개부터 \(1.41 \times 10^8\) 개 매개변수까지)에 걸쳐 변하는 Fashion-MNIST 위의 3-은닉층 ReLU MLP를 생각해 봅시다. 각 가중치 행렬이 \(n\) 에 따라 어떻게 스케일링되는지 살펴보십시오.
- 입력층(
fc_in, \(784 \to n\)): 팬인은 고정(\(784\))되어 있고 팬아웃만 \(n\) 에 비례해 커집니다. - 은닉층(
fc_h1,fc_h2, \(n \to n\)): 팬인과 팬아웃이 모두 \(n\) 에 비례해 커집니다. - 출력 헤드(
fc_out, \(n \to 10\)): 팬인은 \(n\) 에 비례해 커지고 팬아웃은 고정(\(10\))되어 있습니다.
표준 매개변수화(SP) 아래에서 모든 가중치 행렬은 \(\mathcal{N}(0, 1/\text{fan-in})\) 에서 초기화되고, 편향은 0으로 초기화되며, 모든 매개변수가 단일 Adam 학습률 \(\eta\) 를 공유합니다. 먼저 \(60{,}000\) 장의 Fashion-MNIST 훈련 이미지를 평탄화·정규화하여 가속기에 적재합니다.
fashion = d2l.FashionMNIST()
device = d2l.try_gpu()
X = (fashion.train.data.float().reshape(-1, 784) / 255).to(device)
Y = fashion.train.targets.to(device)fashion = d2l.FashionMNIST()
X = jnp.asarray(fashion.train[0], dtype=jnp.float32).reshape(-1, 784) / 255
Y = jnp.asarray(fashion.train[1], dtype=jnp.int32)다음으로 표준편차 \(\text{fan-in}^{-1/2}\) 초기화와 전체 매개변수 단일 Adam 학습률을 사용하는 \(784 \to n \to n \to n \to 10\) 구조의 MLP(width)를 정의합니다.
class MLP(nn.Module):
"""A three-hidden-layer ReLU network under standard parametrization."""
def __init__(self, width):
super().__init__()
self.fc_in = nn.Linear(784, width)
self.fc_h1 = nn.Linear(width, width)
self.fc_h2 = nn.Linear(width, width)
self.fc_out = nn.Linear(width, 10)
for lin in (self.fc_in, self.fc_h1, self.fc_h2, self.fc_out):
nn.init.normal_(lin.weight, std=lin.in_features ** -0.5)
nn.init.zeros_(lin.bias)
def features(self, X):
h = F.relu(self.fc_h1(F.relu(self.fc_in(X))))
return F.relu(self.fc_h2(h))
def forward(self, X):
return self.fc_out(self.features(X))
def configure_adam(self, lr):
return torch.optim.Adam(self.parameters(), lr)class MLP(nnx.Module):
"""A three-hidden-layer ReLU network under standard parametrization."""
def __init__(self, width, *, rngs):
init = nnx.initializers.variance_scaling(1.0, 'fan_in', 'normal')
self.fc_in = nnx.Linear(784, width, kernel_init=init, rngs=rngs)
self.fc_h1 = nnx.Linear(width, width, kernel_init=init, rngs=rngs)
self.fc_h2 = nnx.Linear(width, width, kernel_init=init, rngs=rngs)
self.fc_out = nnx.Linear(width, 10, kernel_init=init, rngs=rngs)
def features(self, X):
h = nnx.relu(self.fc_h1(nnx.relu(self.fc_in(X))))
return nnx.relu(self.fc_h2(h))
def __call__(self, X):
return self.fc_out(self.features(X))
def configure_adam(self, lr):
return nnx.Optimizer(self, optax.adam(lr), wrt=nnx.Param)최적 학습률이 너비 \(n\) 에 따라 어떻게 달라지는지 측정하기 위해 train_mlp는 Adam(\(b = 512\))으로 arch(width)를 \(400\) 스텝 훈련하고 마지막 \(50\) 스텝의 평균 손실(발산 시 \(2.5\) 로 상한 처리)을 반환합니다.
def train_step(model, optimizer, Xb, Yb):
loss = F.cross_entropy(model(Xb), Yb)
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss.detach()
def train_mlp(arch, width, lr, seed, num_steps=400, batch_size=512):
torch.manual_seed(seed)
model = arch(width).to(device)
optimizer = model.configure_adam(lr)
idx = torch.as_tensor(np.random.default_rng(seed).integers(
0, X.shape[0], (num_steps, batch_size)), device=device)
losses = torch.stack([train_step(model, optimizer, X[i], Y[i])
for i in idx])
v = float(losses[-50:].mean()) # Mean minibatch loss of the last 50 steps
return min(v, 2.5) if math.isfinite(v) else 2.5@nnx.jit
def train_step(model, optimizer, Xb, Yb):
def loss_fn(model):
return optax.softmax_cross_entropy_with_integer_labels(
model(Xb), Yb).mean()
loss, grads = nnx.value_and_grad(loss_fn)(model)
optimizer.update(model, grads)
return loss
def train_mlp(arch, width, lr, seed, num_steps=400, batch_size=512):
model = arch(width, rngs=nnx.Rngs(seed))
step = nnx.cached_partial(train_step, model, model.configure_adam(lr))
idx = jnp.asarray(np.random.default_rng(seed).integers(
0, X.shape[0], (num_steps, batch_size)))
losses = jnp.stack([step(X[i], Y[i]) for i in idx])
v = float(losses[-50:].mean()) # Mean minibatch loss of the last 50 steps
return min(v, 2.5) if math.isfinite(v) else 2.5헬퍼 sweep, print_optimum, plot_sweep은 너비, 학습률, 시드 격자에 걸쳐 train_mlp를 평가하고 너비 \(n\) 대비 최적 학습률 \(\eta^\star(n)\) 의 로그–로그 기울기를 피팅하여 시드 평균 손실 곡선을 그립니다.
def sweep(arch, widths, lrs, seeds):
"""Score of every width and learning rate, one column per seed."""
return {w: np.array([[train_mlp(arch, w, lr, s) for s in seeds]
for lr in lrs]) for w in widths}
def print_optimum(loss, lrs):
"""Best rate of the seed-averaged loss per width; slope in log-log."""
widths = list(loss)
best = [lrs[loss[w].mean(1).argmin()] for w in widths]
slope = np.polyfit(np.log(widths), np.log(best), 1)[0]
print('best lr:', ' '.join(f'{lr:.1e}' for lr in best),
f' slope {slope:+.2f}')
def plot_sweep(loss, lrs):
d2l.plot(lrs, [l.mean(1) for l in loss.values()], 'learning rate',
'training loss', xscale='log', ylim=[0.2, 0.8],
legend=[f'width {w}' for w in loss])def sweep(arch, widths, lrs, seeds):
"""Score of every width and learning rate, one column per seed."""
return {w: np.array([[train_mlp(arch, w, lr, s) for s in seeds]
for lr in lrs]) for w in widths}
def print_optimum(loss, lrs):
"""Best rate of the seed-averaged loss per width; slope in log-log."""
widths = list(loss)
best = [lrs[loss[w].mean(1).argmin()] for w in widths]
slope = np.polyfit(np.log(widths), np.log(best), 1)[0]
print('best lr:', ' '.join(f'{lr:.1e}' for lr in best),
f' slope {slope:+.2f}')
def plot_sweep(loss, lrs):
d2l.plot(lrs, [l.mean(1) for l in loss.values()], 'learning rate',
'training loss', xscale='log', ylim=[0.2, 0.8],
legend=[f'width {w}' for w in loss])이제 두 개의 공유 시드에 걸쳐 너비 \(n \in \{128, 512, 2048, 8192\}\) 와 \(10\) 개의 로그 간격 학습률 \(\eta \in \{2^{-14}, \ldots, 2^{-5}\}\) 에서 MLP에 대한 sweep을 실행합니다.
widths = [128, 512, 2048, 8192]
lrs = [2.0 ** k for k in range(-14, -4)]
seeds = [random.getrandbits(32) for _ in range(2)] # Shared by every sweep
sp_loss = sweep(MLP, widths, lrs, seeds)
print_optimum(sp_loss, lrs)
plot_sweep(sp_loss, lrs)best lr: 3.9e-03 2.0e-03 4.9e-04 2.4e-04 slope -0.70
widths = [128, 512, 2048, 8192]
lrs = [2.0 ** k for k in range(-14, -4)]
seeds = [random.getrandbits(32) for _ in range(2)] # Shared by every sweep
sp_loss = sweep(MLP, widths, lrs, seeds)
print_optimum(sp_loss, lrs)
plot_sweep(sp_loss, lrs)best lr: 3.9e-03 2.0e-03 4.9e-04 2.4e-04 slope -0.70
표준 매개변수화 아래에서는 너비가 커질수록 U자형 손실 곡선이 왼쪽으로 꾸준히 이동합니다. 최적 학습률은 너비 \(128\) 의 \(\sim 3.9 \times 10^{-3}\) 에서 너비 \(8{,}192\) 의 \(\sim 1\)–\(2 \times 10^{-4}\) 까지 \(16\)–\(32\times\) 떨어집니다(로그–로그 기울기 \(-0.7\)~\(-0.8\)). 너비-\(128\) 의 최적 학습률을 너비-\(8{,}192\) 모델에 그대로 적용하면 곡선의 불안정한 오른쪽 팔 위로 밀려 올라가 \(1{,}000\times\) 더 많은 매개변수의 이점을 완전히 날려 버립니다.
9.9.1.2 첫 번째 Adam 스텝에서의 최적 학습률 표류 원리
왜 \(\eta^\star\) 가 너비 \(n\) 에 따라 낮아져야 하는지 이해하기 위해, 활성화 벡터 \(\mathbf{h} \in \mathbb{R}^n\) 을 \(\mathbf{z} = \mathbf{W}\mathbf{h}\) 로 매핑하는 정사각 은닉 가중치 행렬 \(\mathbf{W} \in \mathbb{R}^{n \times n}\) 을 생각해 봅시다. 초기화 시점에는 \(W_{ij} \sim \mathcal{N}(0, 1/n)\) 이 \(\mathbf{h}\) 와 독립이므로 각 좌표 \(z_i\) 는 \(n\) 과 무관하게 \(\Theta(1)\) 분산을 가집니다.
역전파된 출력 그레이디언트가 \(\boldsymbol{\delta} = \partial \ell / \partial \mathbf{z}\) 인 단일 표본에 대해 가중치 그레이디언트는 외적 \(\mathbf{G} = \boldsymbol{\delta}\mathbf{h}^\top\) 입니다. \(1\) 스텝에서 Adam의 편향 보정 업데이트는 \(\Delta\mathbf{W} = -\eta\,\operatorname{sign}(\mathbf{G}) = -\eta\,\operatorname{sign}(\boldsymbol{\delta})\operatorname{sign}(\mathbf{h})^\top\) 가 됩니다. 이를 동일한 활성화 벡터 \(\mathbf{h}\) 위에서 평가하면 사전 활성화 \(z_i\) 의 변화량은 다음과 같습니다.
\[ \begin{aligned} (\Delta\mathbf{W}\, \mathbf{h})_i &= -\eta \sum_{j=1}^{n} \operatorname{sign}(\delta_i h_j)\, h_j = -\eta\, \operatorname{sign}(\delta_i) \sum_{j=1}^{n} |h_j| \\ &= -\eta\, \operatorname{sign}(\delta_i)\, n\, \overline{|h|}, \end{aligned} \tag{9.9.1}\]
여기서 \(\overline{|h|} = \frac{1}{n}\sum_{j=1}^n |h_j| = \Theta(1)\) 입니다. \(\Delta W_{ij}\) 가 \(h_j\) 와 상관되어 있으므로 합 안의 \(n\) 개 항 모두가 같은 부호를 공유하여 무작위 부호 초기화 항처럼 상쇄(\(O(\sqrt{n})\))되는 대신 결맞게(coherently) 더해집니다(\(O(n)\)). 특성 업데이트 \((\Delta\mathbf{W}\,\mathbf{h})_i = \Theta(1)\) 을 너비 \(n\) 에 불변으로 유지하려면 팬인이 \(n\) 인 은닉 행렬의 학습률은 반드시 \(\eta \propto 1/n\)으로 스케일링되어야 합니다(로그–로그 기울기 \(-1\). 전체 MLP에서 측정된 경험적 기울기 \(-0.7\)~\(-0.8\) 은 \(n \times n\) 은닉 행렬들과 고정 팬인 입력층 및 편향 사이의 절충을 반영합니다).
9.9.2 최대 업데이트 매개변수화(\(\mu\text{P}\))
9.9.2.1 \(\mu\text{P}\) 스케일링 규칙
팬인 스케일링이 서로 다른 층들에 단일 전역 학습률을 강제하는 대신, 최대 업데이트 매개변수화(\(\mu\text{P}\), Yang 와/과 Hu (2021년); Yang 기타 (2022년) 참조)는 너비 배수(width multiplier) \(m = n / n_{\text{base}}\) 를 통해 기준 기본 너비(base width) \(n_{\text{base}}\) 대비 각 층을 다음과 같이 스케일링합니다(표 9.9.1).
- 입력 가중치 및 1차원 편향/정규화(고정 팬인): 초기 분산 \(1/\text{fan-in}\) 과 학습률 \(\eta\) 를 그대로 유지합니다.
- 은닉 행렬(팬인 및 팬아웃 \(\propto n\)): 초기 분산 \(1/\text{fan-in} = 1/n\) 을 유지하고 Adam 학습률을 \(\eta / m\)으로 스케일링하여 모든 너비에서 \((\eta / m)\,n\,\overline{|h|} = \eta\,n_{\text{base}}\,\overline{|h|} = \Theta(1)\) 이 되게 합니다.
- 출력 헤드 행렬(팬인 \(\propto n\), 고정 팬아웃): \(\Delta\mathbf{W}_{\text{out}}\,\mathbf{h}\) 와 \(\mathbf{W}_{\text{out}}\,\Delta\mathbf{h}\) 모두 \(n\) 개의 상관된 항을 합산하여 출력 로짓을 만드므로, \(\mathbf{W}_{\text{out}}\) 의 원소 크기는 \(O(1/\sqrt{n})\) 이 아니라 \(O(1/n)\) 이어야 합니다. 스케일링 전 가중치 초기화 분산을 \(1/n_{\text{base}}\) 로 고정하고 순전파에서 출력 로짓에 \(1/m\)을 곱하며 Adam 학습률을 \(\eta\) 로 유지하면, 유효 출력 가중치와 그 업데이트가 모두 \(O(1/n)\) 으로 스케일링되어 모든 너비에서 \(\Theta(1)\) 크기의 로짓 업데이트를 생성합니다.
| 매개변수 그룹 | 초기 분산 | Adam 학습률 | 순전파 승수 |
|---|---|---|---|
| 입력 가중치 및 모든 편향 | \(1/\textrm{fan-in}\) (편향은 \(0\)) | \(\eta\) | \(1\) |
| 은닉 행렬 (\(n \times n\)) | \(1/\textrm{fan-in} = 1/n\) | \(\eta / m\) | \(1\) |
| 출력 헤드 (\(n \times d_{\text{out}}\)) | \(1/n_{\textrm{base}}\) | \(\eta\) | \(1/m\) |
class MuMLP(MLP):
"""The same network under muP, relative to a width-8,192 base."""
def __init__(self, width, base_width=8192):
super().__init__(width)
self.m = width / base_width
# Rule 3: output init variance 1/base_width at every width
with torch.no_grad():
self.fc_out.weight.mul_(self.m ** 0.5)
def forward(self, X):
# Rule 3: scale the output matrix's logits; the bias is untouched
return self.fc_out(self.features(X) / self.m)
def configure_adam(self, lr):
hidden = [self.fc_h1.weight, self.fc_h2.weight]
rest = [p for p in self.parameters()
if not any(p is q for q in hidden)]
return torch.optim.Adam([
{'params': rest, 'lr': lr},
{'params': hidden, 'lr': lr / self.m}]) # Rule 2: hidden LR / mclass MuMLP(MLP):
"""The same network under muP, relative to a width-8,192 base."""
def __init__(self, width, base_width=8192, *, rngs):
super().__init__(width, rngs=rngs)
self.m = width / base_width
# Rule 3: output init variance 1/base_width at every width
self.fc_out.kernel[...] *= self.m ** 0.5
def __call__(self, X):
# Rule 3: scale the output matrix's logits; the bias is untouched
return self.fc_out(self.features(X) / self.m)
def configure_adam(self, lr):
def label(path, _):
name = jax.tree_util.keystr(path)
return 'hidden' if 'fc_h' in name and 'kernel' in name else 'rest'
tx = optax.multi_transform(
{'hidden': optax.adam(lr / self.m), # Rule 2: hidden LR / m
'rest': optax.adam(lr)},
lambda params: jax.tree_util.tree_map_with_path(label, params))
return nnx.Optimizer(self, tx, wrt=nnx.Param)(base_width=8192로 설정하면 가장 넓은 너비 \(n = 8{,}192\) 에서 MuMLP가 MLP와 완전히 동일해져 앞선 SP 스윕과 직접 비교할 수 있습니다. 실제 상용 환경에서는 작은 프록시 너비를 base_width로 두고 \(m > 1\) 로 목표 모델까지 스케일업합니다.)
9.9.2.2 좌표 점검과 학습률 전이
본격적인 스윕을 시작하기 전에 \(\mu\text{P}\) 구현이 올바른지 검증하기 위해, 좌표 점검(coordinate check) (Yang 기타 2022년; Dey 기타 2024년) 은 너비 \(n \in \{128, 256, \ldots, 8192\}\) 에 걸쳐 Adam을 단 한 스텝 밟은 뒤 activations와 coord_check를 통해 각 층의 평균 절대 활성화값 \(\overline{|h_\ell|}\) 을 측정합니다.
def activations(model, Xb):
with torch.inference_mode():
h1 = F.relu(model.fc_in(Xb))
h2 = F.relu(model.fc_h1(h1))
h3 = F.relu(model.fc_h2(h2))
return [float(h.abs().mean()) for h in (h1, h2, h3, model(Xb))]
def coord_check(arch, widths, lr, seed, num_steps=1):
Xb, Yb = X[:256], Y[:256]
sizes = []
for width in widths:
torch.manual_seed(seed)
model = arch(width).to(device)
optimizer = model.configure_adam(lr)
for _ in range(num_steps):
train_step(model, optimizer, Xb, Yb)
sizes.append(activations(model, Xb))
return list(zip(*sizes))def activations(model, Xb):
h1 = nnx.relu(model.fc_in(Xb))
h2 = nnx.relu(model.fc_h1(h1))
h3 = nnx.relu(model.fc_h2(h2))
return [float(jnp.abs(h).mean()) for h in (h1, h2, h3, model(Xb))]
def coord_check(arch, widths, lr, seed, num_steps=1):
Xb, Yb = X[:256], Y[:256]
sizes = []
for width in widths:
model = arch(width, rngs=nnx.Rngs(seed))
optimizer = model.configure_adam(lr)
for _ in range(num_steps):
train_step(model, optimizer, Xb, Yb)
sizes.append(activations(model, Xb))
return list(zip(*sizes))너비 \(128\) 의 최적 학습률 lr_128에서 일곱 개 너비 \(n \in \{128, 256, \ldots, 8192\}\) 에 걸쳐 표준 매개변수화 MLP에 coord_check를 실행하면 너비에 따른 심각한 활성화 폭주가 드러납니다.
check_widths = [128 * 2 ** k for k in range(7)] # 128 to 8,192
lr_128 = lrs[sp_loss[128].mean(1).argmin()] # SP's best rate at width 128
sp_acts = coord_check(MLP, check_widths, lr_128, seeds[0])
d2l.plot(check_widths, list(sp_acts), 'width', 'mean |activation|',
xscale='log', yscale='log', ylim=[0.05, 1000],
legend=['layer 1', 'layer 2', 'layer 3', 'logits'])check_widths = [128 * 2 ** k for k in range(7)] # 128 to 8,192
lr_128 = lrs[sp_loss[128].mean(1).argmin()] # SP's best rate at width 128
sp_acts = coord_check(MLP, check_widths, lr_128, seeds[0])
d2l.plot(check_widths, list(sp_acts), 'width', 'mean |activation|',
xscale='log', yscale='log', ylim=[0.05, 1000],
legend=['layer 1', 'layer 2', 'layer 3', 'logits'])기본 너비 학습률 lr_base에서 MuMLP에 정확히 동일한 1스텝 coord_check를 실행하면 \(\mu\text{P}\) 가 세 은닉층과 출력 로짓을 모두 너비에 불변으로 유지함을 확인할 수 있습니다.
lr_base = lrs[sp_loss[8192].mean(1).argmin()] # Best at the base width
mup_acts = coord_check(MuMLP, check_widths, lr_base, seeds[0])
d2l.plot(check_widths, list(mup_acts), 'width', 'mean |activation|',
xscale='log', yscale='log', ylim=[0.05, 1000],
legend=['layer 1', 'layer 2', 'layer 3', 'logits'])lr_base = lrs[sp_loss[8192].mean(1).argmin()] # Best at the base width
mup_acts = coord_check(MuMLP, check_widths, lr_base, seeds[0])
d2l.plot(check_widths, list(mup_acts), 'width', 'mean |activation|',
xscale='log', yscale='log', ylim=[0.05, 1000],
legend=['layer 1', 'layer 2', 'layer 3', 'logits'])SP(MLP) 아래에서는 가장 넓은 너비들로 갈수록 층 \(2\), 층 \(3\), 출력 로짓이 각각 \(O(n)\), \(O(n^2)\), \(O(n^3)\) 성장에 근접합니다(단 한 스텝 만에 로짓 크기가 너비 \(128\) 에서 너비 \(8{,}192\) 사이에 약 \(1{,}000\times\) 치솟음). 반면 \(\mu\text{P}\)(MuMLP) 아래에서는 일곱 개 너비 전체에 걸쳐 모든 층의 활성화와 로짓 스케일이 평평하게 유지됩니다.
\(\mu\text{P}\) 아래에서 \(400\)-스텝 학습률 스윕을 반복하면 \(64\times\) 너비 범위 전체에서 최적 학습률이 일렬로 정렬됨이 확인됩니다.
mup_loss = sweep(MuMLP, widths[:-1], lrs, seeds)
mup_loss[widths[-1]] = sp_loss[widths[-1]] # At the base width muP is SP
print_optimum(mup_loss, lrs)
plot_sweep(mup_loss, lrs)best lr: 2.4e-04 2.4e-04 2.4e-04 2.4e-04 slope +0.00
mup_loss = sweep(MuMLP, widths[:-1], lrs, seeds)
mup_loss[widths[-1]] = sp_loss[widths[-1]] # At the base width muP is SP
print_optimum(mup_loss, lrs)
plot_sweep(mup_loss, lrs)best lr: 1.2e-04 1.2e-04 2.4e-04 2.4e-04 slope +0.20
마지막으로 SP와 \(\mu\text{P}\) 각각에 대해 좁은 너비-\(128\) 프록시에서 튜닝한 학습률을 너비 \(8{,}192\) 에 그대로 전이했을 때 달성되는 훈련 손실을 너비 \(8{,}192\) 에서 직접 튜닝한 손실과 비교합니다.
for name, loss in (('SP', sp_loss), ('muP', mup_loss)):
mean = {w: l.mean(1) for w, l in loss.items()}
print(f'{name:3s} best loss per width:',
' '.join(f'{m.min():.3f}' for m in mean.values()))
small, wide = widths[0], widths[-1]
tuned, own = mean[small].argmin(), mean[wide].argmin()
for label, i in ((f'the width-{small} lr', tuned), ('its own lr', own)):
runs = ' '.join(f'{v:.3f}' for v in loss[wide][i])
print(f' width {wide} at {label:16s} {mean[wide][i]:.3f}'
f' (seeds {runs})')SP best loss per width: 0.323 0.298 0.262 0.230
width 8192 at the width-128 lr 0.355 (seeds 0.382 0.329)
width 8192 at its own lr 0.230 (seeds 0.232 0.228)
muP best loss per width: 0.335 0.265 0.241 0.230
width 8192 at the width-128 lr 0.230 (seeds 0.232 0.228)
width 8192 at its own lr 0.230 (seeds 0.232 0.228)
for name, loss in (('SP', sp_loss), ('muP', mup_loss)):
mean = {w: l.mean(1) for w, l in loss.items()}
print(f'{name:3s} best loss per width:',
' '.join(f'{m.min():.3f}' for m in mean.values()))
small, wide = widths[0], widths[-1]
tuned, own = mean[small].argmin(), mean[wide].argmin()
for label, i in ((f'the width-{small} lr', tuned), ('its own lr', own)):
runs = ' '.join(f'{v:.3f}' for v in loss[wide][i])
print(f' width {wide} at {label:16s} {mean[wide][i]:.3f}'
f' (seeds {runs})')SP best loss per width: 0.325 0.297 0.262 0.228
width 8192 at the width-128 lr 0.341 (seeds 0.332 0.350)
width 8192 at its own lr 0.228 (seeds 0.227 0.229)
muP best loss per width: 0.324 0.264 0.234 0.228
width 8192 at the width-128 lr 0.231 (seeds 0.232 0.231)
width 8192 at its own lr 0.228 (seeds 0.227 0.229)
\(\mu\text{P}\) 아래에서 \(\eta^\star(n)\) 의 로그–로그 기울기는 SP의 \(-0.7\) 이하 가파른 음수에서 0 근처로 축소됩니다(\(64\times\) 너비 범위 전체에서 최적점이 기껏해야 격자 한 칸 이내로만 움직임). 그 결과 너비 \(128\) 에서 튜닝한 학습률을 너비 \(8{,}192\) 로 곧바로 전이해도 손실 저하가 \(\le 0.003\) nats(시드 잡음보다 훨씬 작은 수준)에 그치는 반면, SP에서는 \(0.10\text{--}0.15\) nats의 큰 페널티가 발생합니다.
9.9.3 트랜스포머와 스펙트럼 옵티마이저로의 확장
9.9.3.1 트랜스포머를 위한 \(\mu\text{P}\) 규칙
모델 차원이 \(d\) 이고 너비 배수가 \(m = d / d_{\text{base}}\) 인 TinyLM(9.3.1절) 같은 트랜스포머에 \(\mu\text{P}\) 를 적용할 때는 앞선 팬인/팬아웃 분류를 정확히 그대로 따르되, 어텐션 로짓에 대한 규칙 하나만 추가하면 됩니다(표 9.9.2). 훈련 중 학습된 쿼리와 키 벡터가 서로 정렬되면서 헤드 차원 \(d_k \propto d\) 에 걸친 내적 \(\mathbf{q}^\top\mathbf{k}\) 가 \(O(d_k)\) 로 커지므로, 어텐션 점수를 \(1/d_k\) 로 스케일링해야 합니다(표준 \(1/\sqrt{d_k}\) 스케일링 대비 \(1/\sqrt{m}\) 추가 인자 적용 (Yang 기타 2022년)).
| 구성 요소 | 스케일링 이유 | \(\mu\text{P}\) 규칙 |
|---|---|---|
| 임베딩, 1차원 편향, LayerNorm 스케일/시프트 | 고정 팬인(조회 또는 원소별 연산) | 학습률 \(\eta\) |
내부 블록 행렬 (qkv, proj, mlp1, mlp2) |
팬인과 팬아웃 모두 \(\propto d\) | 학습률 \(\eta/m\), 초기 분산 \(1/\text{fan-in}\) |
출력 head |
팬인 \(\propto d\), 고정 어휘 사전 크기 \(V\) | 초기 분산 \(1/d_{\text{base}}\), 로짓 \(\times 1/m\), 학습률 \(\eta\) |
| 어텐션 점곱 점수 | 정렬된 \(d_k\)-벡터들의 내적 | 점수를 \(1/d_k\) 로 스케일링 (추가 인자 \(1/\sqrt{m}\)) |
| 깊이 \(L\) 도 함께 커질 때의 잔차 분기 | 잔차 스트림에 \(L\) 개의 분기 출력이 합산됨 | 각 분기에 \(L_{\text{base}}/L\) 곱하기 (9.9.3.3절) |
9.9.3.2 스펙트럼 스케일링 조건과 Muon
Yang 기타 (2023년) 연구진이 보였듯, 모든 \(\mu\text{P}\) 규칙은 단일 연산자 노름 원리 아래 통합할 수 있습니다. \(\|\mathbf{h}\|_2 = \Theta(\sqrt{d_{\text{in}}})\) 인 \(\mathbf{h} \in \mathbb{R}^{d_{\text{in}}}\) 을 \(\|\mathbf{z}\|_2 = \Theta(\sqrt{d_{\text{out}}})\) 인 \(\mathbf{z} \in \mathbb{R}^{d_{\text{out}}}\) 으로 매핑하는 층에서 원소당 \(\Theta(1)\) 활성화와 업데이트를 보존하려면 가중치 행렬 \(\mathbf{W}\) 와 그 업데이트 \(\Delta\mathbf{W}\) 모두 다음 스펙트럼 노름을 가져야 합니다.
\[ \|\Delta\mathbf{W}\|_2 = \Theta\!\left(\sqrt{\frac{d_{\textrm{out}}}{d_{\textrm{in}}}}\right). \tag{9.9.2}\]
정사각 \(n \times n\) 은닉 행렬에서 식 9.9.2 의 조건은 \(\|\Delta\mathbf{W}\|_2 = \Theta(1)\) 을 요구합니다. Adam에서는 랭크-\(1\) 부호 업데이트가 \(\|\Delta\mathbf{W}\|_2 = \Theta(\eta n)\) 을 가지므로 \(\eta \propto 1/n\) 이 필요합니다. 반면 Muon(9.6절)에서는 직교화된 업데이트 \(\mathrm{NS}_5(\cdot)\) 가 구조상 단위 스펙트럼 노름을 가지므로, 만약 \(\sqrt{d_{\text{out}}/d_{\text{in}}}\) (Bernstein 2025년) 으로 스케일링하면 \(1/m\) 보정 없이 학습률이 너비 간 곧바로 전이됩니다(반면 9.6절 의 AdamW 정렬 인자 \(0.2\sqrt{\max(d_{\text{out}}, d_{\text{in}})}\) 은 스펙트럼 노름이 \(\Theta(\eta\sqrt{n})\) 이므로 \(\eta \propto 1/\sqrt{n}\) 으로 스케일링됩니다. 3 참조).
9.9.3.3 깊이, 가중치 감쇠 및 유한 크기의 한계
지금까지는 너비만 변화시켰습니다. 하지만 실제 스케일업에서는 층도 함께 추가되며, AdamW 아래에서는 학습률 조정에 맞추어 가중치 감쇠도 함께 조정되어야 합니다. 두 경우 모두 고유한 규칙이 필요합니다.
먼저 깊이를 살펴봅시다. \(L\) 개의 잔차 블록을 가진 신경망에서 잔차 스트림은 \(L\) 개 분기 출력의 합입니다. 모든 분기가 \(\Theta(1)\) 씩 기여하면 합은 \(L\) 에 따라 커지며, 모든 블록이 출력을 움직이므로 옵티마이저 한 스텝의 효과도 함께 커집니다. 해법은 로짓 승수와 같은 형태입니다. 즉, 각 잔차 분기에 \((L_{\text{base}}/L)^{\alpha}\) 를 곱합니다. 지수로는 두 가지가 제안되었습니다. \(\alpha = 1/2\) 로 두면 분기 출력들이 초기화 시점처럼 독립 무작위 항으로 더해질 때에 맞춰집니다 (Bordelon 기타 2024년; Yang 기타 2024년). 반면 \(\alpha = 1\) 로 두면 훈련을 통해 분기들이 서로 상관된 뒤 정렬된 항으로 더해질 때에 맞춰집니다. 이는 출력 헤드에서 \(1/\sqrt{n}\) 이 아니라 \(1/n\) 을 유도했던 바로 그 논리입니다. Dey 기타 (2025년) 연구진은 트랜스포머에서 \(L\) 이 커질 때 모든 블록이 특성을 계속 학습하게 만드는 지수는 오직 \(\alpha = 1\) 뿐이며, 이때 너비에서와 마찬가지로 깊이 간에도 학습률이 전이됨을 확인했습니다.
다음은 가중치 감쇠입니다. AdamW에서 감쇠 시간 척도 \(\tau = 1/(\eta\lambda)\) 는 가중치가 평형 노름에 다가가는 속도를 결정합니다(9.5절). 어떤 층의 학습률을 \(m\) 으로 나누면서 \(\lambda\) 를 그대로 두면 그 층의 \(\tau\) 가 \(m\) 배 길어지므로, 넓은 모델은 튜닝에 사용한 작은 모델과 다른 정칙화를 받게 됩니다. 일관된 한 가지 선택은 \(\tau\) 를 고정하는 것입니다. 즉, \(\eta\) 를 \(m\) 으로 나누는 곳마다 \(\lambda\) 에 \(m\) 을 곱합니다 (Wang 와/과 Aitchison 2025년).
마지막으로 이 모든 규칙은 무한 크기 극한에서만 엄밀히 성립합니다. 실제 유한한 너비에서는 최적점이 여전히 미세하게 움직입니다(앞서 수행한 스윕에서도 격자 한 칸만큼 이동했습니다). 따라서 전이된 학습률은 목표 규모에서의 탐색을 완전히 대체하기보다는 좁은 범위 스윕의 중심점으로 삼는 것이 가장 좋습니다.
9.9.4 요약
표준 매개변수화(SP) 아래에서는 단일 Adam 스텝이 팬인 \(n\) 인 은닉층의 출력을 \(\Theta(\eta n)\) 만큼 변화시키므로 신경망이 넓어질수록 최적 학습률 \(\eta^\star(n)\) 이 아래로 표류합니다. 최대 업데이트 매개변수화(\(\mu\text{P}\))는 은닉 행렬 학습률을 \(1/m\)(단, \(m = n/n_{\text{base}}\))배 스케일링하고, 출력층 초기화 분산을 \(1/n_{\text{base}}\) 로 고정한 채 로짓에 \(1/m\) 을 곱하며, 트랜스포머 어텐션 점수를 \(1/d_k\) 로 스케일링하여 \(\Theta(1)\) 특성 업데이트와 너비 간 제로샷 학습률 전이를 달성합니다. 1스텝 좌표 점검은 기하급수적으로 늘린 너비들에 걸쳐 옵티마이저 한 스텝 직후 층 활성화 크기가 평평하게 유지되는지 검증합니다. 전체 규모 스케일업으로 하이퍼파라미터 전이를 확장할 때는 깊이에 따라 잔차 분기에 \(L_{\text{base}}/L\) 을 곱하고 층별 학습률 변화에 맞춰 AdamW 감쇠 시간 척도 \(\tau = 1/(\eta\lambda)\) 를 일정하게 유지하며, 이렇게 얻은 값을 중심으로 목표 규모에서 좁은 스윕을 수행할 수 있습니다.
9.9.5 연습 문제
[code] 좌표 점검으로 깨진 \(\mu\text{P}\) 규칙 진단하기.
MuMLP에서base_width=128로 설정하고lr_128에서coord_check를 사용해 세 가지 의도적 버그를 하나씩 테스트하십시오: (a) \(1/m\) 로짓 승수 생략, (b) \(\eta/m\) 은닉 학습률 스케일링 생략, (c) 은닉 학습률을 \(\eta/m^2\) 으로 스케일링.coord_check가 어떤 오류를 즉시 잡아내는지 확인하고, 왜 업데이트를 과도하게 축소하는 오류(\(\eta/m^2\))를 검출하려면 다중 스텝 손실 스윕이 필요한지 설명하십시오.[code] 기준 기본 너비의 영향. 너비 \(\{128, 512, 2048, 8192\}\) 에 걸쳐
base_width=128로 \(\mu\text{P}\) 스윕을 다시 실행하여 \(\eta^\star(n)\) 의 로그–로그 기울기가 0 근처에 머묾을 확인하고, 너비 \(8{,}192\) 에서의 손실 차이를 설명하는 상수 비율(입력 대 은닉 학습률 비율 대 초기 로짓 스케일)이 무엇인지 밝히십시오.층과 옵티마이저 전반의 스펙트럼 노름 조건. ● 식 9.9.2 의 조건을 사용하여 표 9.9.1 의 \(\mu\text{P}\) 규칙이 랭크-\(1\) Adam 스텝 아래에서 입력층, 은닉층, 출력층에 스펙트럼 노름 \(\Theta(\sqrt{d_{\text{out}}/d_{\text{in}}})\) 인 업데이트를 부여함을 확인하고,
TinyLM의 네 블록 행렬에서 Muon(9.6절)에 필요한 \(\eta\) 의 너비 스케일링을 유도하십시오.[code]
TinyLM에 \(\mu\text{P}\) 구현 및 좌표 점검 수행하기. ●d_model\(\in \{64, 128, 256, 512, 1024\}\)(num_heads=2,base_width=64)에 걸쳐d2l.TinyLM에 표 9.9.2 의 규칙을 적용하고, \(\eta = 3 \times 10^{-3}\) 에서의 1스텝 좌표 점검을 통해 모든 서브층 출력과 로짓 크기가 너비에 대해 평평하게 유지됨을 확인하십시오.