9.10  실전 가이드

지금까지 수행한 소규모 실험에서는 실행 한 번이 몇 초면 끝났으므로 학습률 격자를 마음껏 스윕하고 업데이트가 발산하면 다시 돌릴 수 있었습니다. 상용 훈련 실행은 다릅니다. 단일 훈련 실행에 며칠에서 몇 주가 걸릴 때는 대부분의 설정을 사전에 확정해야 하며, 방어되지 않은 단 한 번의 그레이디언트 급등이 수 시간의 진척을 망가뜨릴 수 있고, 최종 체크포인트가 마지막 미니배치 추출 운에 좌우되어서도 안 됩니다.

초대규모 환경(예: 그레이디언트 클리핑을 켠 상태에서도 약 \(20\) 차례의 갑작스러운 손실 급등을 겪으며 \(6{,}144\) 개의 TPU 칩에서 훈련된 \(540\) 십억(5,400억) 매개변수 PaLM 모델 (Chowdhery 기타 2022년))에서조차 안정적인 훈련은 세 가지 운영 기둥 위에 서 있습니다.

  1. 일시적 불안정성에 대한 안전장치: 전역 노름 그레이디언트 클리핑(8.4.2절)은 SGD에서 비정상적인 스텝을 제한하고 일시적인 그레이디언트 급등으로부터 AdamW의 2차 모멘트 누적기 \(\mathbf{v}_t\) 를 보호하며, 체크포인트 되감기 복구와 함께 운용됩니다.
  2. 반복해 평활화: 모델 가중치의 지수 이동 평균(EMA)을 유지하면 학습률을 0까지 완전히 감쇠시키지 않고도 고주파 잡음 공 요동을 제거할 수 있습니다.
  3. 짧은 프록시 실행을 통한 체계적 보정: 장치 처리량과 \(b_{\text{noise}}\) 로부터 배치 크기를 선택하고(9.8절), 실전에서 검증된 옵티마이저 기본값을 채택한 뒤, 전체 웜업·감쇠 스케줄(9.7절)을 실행하기 전에 짧은 실행(전체 지평의 \(10\%\))에서 정점 학습률을 보정합니다.

이 절에서는 이 세 기둥을 차례로 살펴보고 이를 하나로 조립하여 튜닝되지 않은 \(3.3\) 백만(330만) 매개변수, \(4\)-블록 TinyLM의 완결된 엔드투엔드 설정을 구성합니다.

import random

9.10.1 그레이디언트 클리핑과 급등 복구

8.4.2절 에서 순환 신경망을 위해 도입했듯이, 전역 노름 그레이디언트 클리핑(gradient clipping)은 모든 매개변수의 그레이디언트를 이어 붙인 단일 벡터 \(\mathbf{g}\) 의 유클리드 노름 \(\|\mathbf{g}\|_2\) 가 임곗값 \(\theta\) 를 초과할 때마다 이를 재스케일링합니다.

\[ \mathbf{g} \leftarrow \min\left(1,\; \frac{\theta}{\|\mathbf{g}\|_2}\right) \mathbf{g}. \tag{9.10.1}\]

스케일링 인자 \(\theta / \|\mathbf{g}\|_2\) 가 전역적으로 동일하게 곱해지므로, 클리핑은 모든 층에 걸친 상대적인 방향을 보존하면서 옵티마이저에 입력되는 그레이디언트의 유클리드 노름 상한을 \(\theta\) 로 묶어 둡니다.

class Clipped:
    """Clip the global gradient norm before every optimizer step."""
    def __init__(self, optimizer, params, max_norm=1.0):
        self.optimizer, self.params = optimizer, list(params)
        self.max_norm, self.norms = max_norm, []

    def step(self):
        self.norms.append(nn.utils.clip_grad_norm_(self.params, self.max_norm))
        self.optimizer.step()

    def zero_grad(self):
        self.optimizer.zero_grad()
def record_norms(num_steps):
    """Pass the gradients through unchanged, storing each step's norm."""
    def init(params):
        return dict(norms=jnp.zeros(num_steps), step=jnp.zeros((), jnp.int32))

    def update(grads, state, params=None):
        norm = optax.global_norm(grads)
        norms = state['norms'].at[state['step']].set(norm)
        return grads, dict(norms=norms, step=state['step'] + 1)

    return optax.GradientTransformation(init, update)

def clipped(tx, num_steps, max_norm=1.0):
    """Clip the global gradient norm before an optimizer's update, recording
    the norm before clipping on each of the first num_steps steps."""
    return optax.chain(record_norms(num_steps),
                       optax.clip_by_global_norm(max_norm), tx)

9.10.1.1 안전장치로서의 클리핑 대 상시 브레이크로서의 클리핑

9.5절 에서 TinyLM 위의 모멘텀 \(0.9\) SGD는 \(\eta = 1.0\) 에서 처음 \(20\) 스텝 안에 inf로 발산했습니다. 과연 \(\eta = 1.0\) 이 손실 곡면 전체에 대해 너무 큰 것일까요, 아니면 막 초기화된 가중치가 큰 그레이디언트를 만드는 초기 과도 스텝 동안에만 너무 큰 것일까요? 먼저 WikiText103 스트림(\(b = 64\), 윈도 길이 \(64\))을 불러옵니다.

data = d2l.WikiText103(batch_size=64, num_steps=64)
data = d2l.WikiText103(batch_size=64, num_steps=64)

다음으로 run(seed, lr, max_norm)은 max_norm으로 클리핑된 모멘텀 \(0.9\) SGD로 TinyLM을 \(2{,}000\) 스텝 훈련하며 스텝 손실과 클리핑 전 그레이디언트 노름을 함께 반환합니다.

new_seed = lambda: random.getrandbits(31)

def run(seed, lr, max_norm, num_steps=2000):
    """SGD with momentum 0.9 on TinyLM, clipped at max_norm (math.inf: not
    at all); return the losses and the gradient norms before clipping."""
    torch.manual_seed(seed)  # The initialization and the minibatch order
    model = d2l.TinyLM(len(data.vocab))
    optimizer = Clipped(torch.optim.SGD(model.parameters(), lr, momentum=0.9),
                        model.parameters(), max_norm)
    losses = d2l.train_steps(model, data, optimizer, num_steps)
    return losses, torch.stack(optimizer.norms).cpu().numpy()
new_seed = d2l.get_seed

def run(seed, lr, max_norm, num_steps=2000):
    """SGD with momentum 0.9 on TinyLM, clipped at max_norm (math.inf: not
    at all); return the losses and the gradient norms before clipping."""
    model = d2l.TinyLM(len(data.vocab), rngs=nnx.Rngs(seed))
    tx = clipped(optax.sgd(lr, momentum=0.9), num_steps, max_norm)
    optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param)
    losses = d2l.train_steps(model, data, optimizer, num_steps)
    return losses, np.asarray(optimizer.opt_state[0]['norms'][...])

이제 두 시드에 걸쳐 \((\eta, \theta) \in \{(1.0, \infty), (1.0, 1.0), (0.3, \infty), (3.0, 1.0)\}\) 을 테스트하며 클리핑이 작동한 스텝 수(\(\|\mathbf{g}_t\|_2 > \theta\)), 클리핑이 마지막으로 작동한 스텝 번호, 그리고 그레이디언트 노름의 중앙값을 기록합니다.

settings = [(1.0, math.inf), (1.0, 1.0), (0.3, math.inf), (3.0, 1.0)]
seeds, runs = [new_seed() for _ in range(2)], {}
print(f'{"lr":>4}{"clip at":>9}{"final loss":>12}{"steps clipped":>15}'
      f'{"last":>6}{"median norm":>13}{"largest / median":>18}')
for seed in seeds:
    for lr, max_norm in settings:
        losses, norms = runs[seed, lr, max_norm] = run(seed, lr, max_norm)
        line = f'{lr:4g}{max_norm:9g}{d2l.final_loss(losses):12.3f}'
        if max_norm < math.inf:
            fired = np.nonzero(norms > max_norm)[0]  # Steps clipping changed
            median = np.median(norms)
            line += (f'{len(fired):15d}{fired.max(initial=0):6d}{median:13.2f}'
                     f'{norms[100:].max() / median:18.1f}')  # After step 100
        print(line)
  lr  clip at  final loss  steps clipped  last  median norm  largest / median
   1      inf         inf
   1        1       1.626             17    28         0.25               1.8
 0.3      inf       1.671
   3        1         inf           1997  1996          nan               nan
   1      inf         inf
   1        1       1.619             17    16         0.26               1.8
 0.3      inf       1.652
   3        1         inf           1636  1635          nan               nan
settings = [(1.0, math.inf), (1.0, 1.0), (0.3, math.inf), (3.0, 1.0)]
seeds, runs = [new_seed() for _ in range(2)], {}
print(f'{"lr":>4}{"clip at":>9}{"final loss":>12}{"steps clipped":>15}'
      f'{"last":>6}{"median norm":>13}{"largest / median":>18}')
for seed in seeds:
    for lr, max_norm in settings:
        losses, norms = runs[seed, lr, max_norm] = run(seed, lr, max_norm)
        line = f'{lr:4g}{max_norm:9g}{d2l.final_loss(losses):12.3f}'
        if max_norm < math.inf:
            fired = np.nonzero(norms > max_norm)[0]  # Steps clipping changed
            median = np.median(norms)
            line += (f'{len(fired):15d}{fired.max(initial=0):6d}{median:13.2f}'
                     f'{norms[100:].max() / median:18.1f}')  # After step 100
        print(line)
  lr  clip at  final loss  steps clipped  last  median norm  largest / median
   1      inf         inf
   1        1       1.613             14    13         0.26               1.7
 0.3      inf       1.669
   3        1     197.921           2000  1999        43.59               1.7
   1      inf         inf
   1        1       1.616             15    23         0.26               1.5
 0.3      inf       1.679
   3        1     103.020           2000  1999        35.99              13.0

\(\eta = 1.0\) 에서 \(\theta = 1.0\) 클리핑은 처음 몇십 스텝(모두 스텝 \(50\) 이전)에서만 작동하고 나머지 \(1{,}950\) 스텝(그레이디언트 노름 중앙값 \(\sim 0.25\)) 동안에는 단 한 번도 작동하지 않으면서도 실행을 inf 발산에서 구출해 \(\sim 1.61\text{--}1.64\) nats까지 끌어내립니다. 여기서 클리핑은 안전장치(guard)로 작동합니다. 즉, \(<2\%\) 의 스텝에만 개입하여 초기 과도 폭주를 막고 두꺼운 꼬리 그레이디언트 잡음을 처리합니다 (Zhang 기타 2020년). 이와 대조적으로 \(\eta = 3.0\) 에서는 그레이디언트 노름이 유한하게 남아 있는 내내 매 스텝마다 클리핑이 작동하며 그런데도 훈련에 실패합니다(손실이 \(100\text{--}200\) nats에서 정체되거나 inf로 오버플로됨). 클리핑이 상시 브레이크(brake)처럼 걸려 있다면 단순히 학습률 \(\eta\) 가 너무 큰 것입니다 (Godbole 기타 2023년). 실무에서는 정상 상태 그레이디언트 노름 중앙값보다 약 \(3\text{--}5\times\) 높게 \(\theta\) 를 설정(보통 \(\theta = 1.0\))하고 클리핑 작동 비율을 모니터링하십시오.

9.10.1.2 AdamW 아래에서의 클리핑과 운영상 급등 복구

AdamW(9.5절)에서는 단일 비정상 그레이디언트 \(g \gg \sqrt{v_{t-1}}\) 가 들어오더라도 당장의 스텝 크기는 기껏해야 \(\eta(1-\beta_1)/\sqrt{1-\beta_2}\)(\(\beta_2 = 0.999\) 에서 \(\approx 3.2\,\eta\), \(\beta_2 = 0.95\) 에서 \(0.45\,\eta\))로 이미 유계되어 있습니다. 즉각적인 스텝을 제한하는 대신 AdamW에서의 클리핑은 2차 모멘트 상태 \(\mathbf{v}_t\) 를 보호합니다. 클리핑되지 않은 \(100\times\) 크기의 그레이디언트 급등은 정상 제곱 그레이디언트의 \((1-\beta_2) \times 10^4\) 배를 \(v_t\) 에 주입하여 분모 \(\sqrt{\hat{v}_t}\) 를 부풀리고 이후 \(\sim 1/(1-\beta_2)\) 스텝(\(\beta_2 = 0.999\) 에서는 \(1{,}000\) 스텝, \(\beta_2 = 0.95\) 에서는 \(20\) 스텝) 동안 학습을 마비시킵니다.

그레이디언트 클리핑(및 PaLM의 \(z\)-손실 \(10^{-4}\log^2(\sum_j e^{o_j})\) 같은 보조 로짓 정칙화기, 2 참조)에도 불구하고 갑작스러운 손실 급등이 발생했을 때 표준 운영 해법 (Chowdhery 기타 2022년; Zhang 기타 2022년) 은 급등 \(\sim 100\) 스텝 전에 저장된 체크포인트로 되감고 급등 전후의 \(200\text{--}500\) 개 미니배치를 건너뛰는 것이며, 이를 위해서는 모델 가중치, 옵티마이저 모멘트 \((\mathbf{m}_t, \mathbf{v}_t)\), 스케줄러 스텝 카운터, 데이터 스트림 커서를 주기적으로 함께 체크포인팅해야 합니다.

9.10.2 가중치 평균화(EMA)

고정 학습률이나 0이 아닌 학습률에서는 확률적 반복해가 최적점 주위의 잡음 공(9.2절) 내부에서 끊임없이 요동하며, 곡률 \(\lambda_{\text{curv}}\) 인 모드는 \(\sim 1/(\eta\lambda_{\text{curv}})\) 스텝의 자기상관 시간을 가집니다. 감쇠 계수 \(\alpha \in [0.99, 0.9999]\) (Polyak 와/과 Juditsky 1992년) 를 사용하여 실시간 매개변수 \(\mathbf{x}_t\) 의 지수 이동 평균(EMA) \(\bar{\mathbf{x}}_t\) 를

\[ \bar{\mathbf{x}}_t = \alpha\, \bar{\mathbf{x}}_{t-1} + (1 - \alpha)\, \mathbf{x}_t, \tag{9.10.2}\]

와 같이 유지하면, 실시간 훈련 궤적은 전혀 건드리지 않으면서 직전 \(1/(1-\alpha)\) 스텝 윈도에 걸쳐 평균을 취해 평가 시점의 잡음 공 요동을 상쇄할 수 있습니다.

FashionCNN에서 \(15\) 에포크(\(3{,}525\) 스텝) 동안 가중치 EMA(\(\alpha = 0.999\), 윈도 \(1{,}000\) 스텝 \(\approx 4.2\) 에포크, 초기 지연을 피하기 위해 에포크 \(5\) 이후 시작)를 켠 고정 학습률 SGD(\(\eta = 0.3\))와 끄고 실행한 고정 학습률 SGD를 코사인 학습률 감쇠와 비교해 봅시다. 먼저 FashionMNIST(\(b = 256\))를 불러오고 검증 정확도 헬퍼 test_acc를 정의합니다.

fashion = d2l.FashionMNIST(batch_size=256)
num_epochs, num_batches = 15, len(fashion.train_dataloader())
test_acc = lambda model: d2l.evaluate_accuracy(model, fashion.val_dataloader())
fashion = d2l.FashionMNIST(batch_size=256)
num_epochs, num_batches = 15, len(fashion.train_dataloader())
test_acc = lambda model: d2l.evaluate_accuracy(model, fashion.val_dataloader())

다음으로 warmup_cosine 스케줄 헬퍼와 가중치 EMA를 정의합니다.

PyTorch에서는 torch.optim.swa_utils.AveragedModel이 EMA를 관리하므로 여기서는 스케줄만 정의하면 됩니다.

ema_of_weights는 옵티마이저 상태 안에 EMA를 보관하는 optax 변환이며, averaged는 해당 가중치로 모델을 복제합니다.

def warmup_cosine(peak, warmup, num_steps):
    """A linear warmup to peak over warmup steps, then a cosine to zero."""
    def schedule(t):
        if t < warmup:
            return peak * t / warmup
        return peak * (1 + math.cos(math.pi * (t - warmup)
                                    / (num_steps - warmup))) / 2
    return schedule
warmup_cosine = lambda peak, warmup, num_steps: (
    optax.warmup_cosine_decay_schedule(0.0, peak, warmup, num_steps))

def ema_of_weights(alpha=0.999, start=0):
    """Pass the updates through unchanged, keeping an EMA of the updated
    weights that averages from step start on (copies them before)."""
    def init(params):
        return dict(ema=params, step=jnp.zeros((), jnp.int32))

    def update(updates, state, params):
        new = optax.apply_updates(params, updates)
        rate = jnp.where(state['step'] < start, 1.0, 1 - alpha)
        ema = optax.incremental_update(new, state['ema'], rate)
        return updates, dict(ema=ema, step=state['step'] + 1)

    return optax.GradientTransformation(init, update)

def averaged(model, optimizer):
    """A copy of model with the EMA kept by the last transformation."""
    ema = nnx.clone(model)
    nnx.update(ema, optimizer.opt_state[-1]['ema'])
    return ema

훈련 루프 train_fashion은 num_epochs=15에포크 동안 schedule(t) 아래에서 기본 SGD를 실행하며 매 에포크 종료 시 실시간 가중치와 EMA(에포크 start=5에서 시작) 양쪽의 홀드아웃 테스트 정확도를 기록합니다.

def train_fashion(seed, schedule, alpha=0.999, start=5):
    """Plain SGD on FashionCNN at the rate schedule(t); the test accuracy
    after every epoch of the weights and of their EMA from epoch start on."""
    torch.manual_seed(seed)  # The initialization and the minibatch order
    model = d2l.FashionCNN().to(d2l.try_gpu())
    optimizer = torch.optim.SGD(model.parameters(), lr=1.0)  # Times schedule
    scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, schedule)
    optimizer.register_step_post_hook(lambda *_: scheduler.step())
    ema = torch.optim.swa_utils.AveragedModel(
        model, multi_avg_fn=torch.optim.swa_utils.get_ema_multi_avg_fn(alpha))
    live, avg = [], []
    for epoch in range(num_epochs):
        if epoch == start:  # Its first update copies the current weights
            optimizer.register_step_post_hook(
                lambda *_: ema.update_parameters(model))
        d2l.train_steps(model, fashion, optimizer, num_batches)
        live.append(test_acc(model))
        avg.append(test_acc(ema) if epoch >= start else math.nan)
    return live, avg
def train_fashion(seed, schedule, alpha=0.999, start=5):
    """Plain SGD on FashionCNN at the rate schedule(t); the test accuracy
    after every epoch of the weights and of their EMA from epoch start on."""
    model = d2l.FashionCNN(rngs=nnx.Rngs(seed))
    tx = optax.chain(optax.sgd(schedule),
                     ema_of_weights(alpha, start * num_batches))
    optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param)
    live, avg = [], []
    for epoch in range(num_epochs):
        d2l.train_steps(model, fashion, optimizer, num_batches)
        live.append(test_acc(model))
        avg.append(test_acc(averaged(model, optimizer)) if epoch >= start
                   else math.nan)
    return live, avg

고정 학습률(\(\eta = 0.3\))과 코사인 감쇠(\(\eta: 0.3 \to 0\)) 양쪽에 대해 두 시드에서 train_fashion을 실행하여 마지막 다섯 에포크 동안의 실시간 정확도 변동 범위와 최종 EMA 정확도를 비교합니다.

schedules = {'constant rate': lambda t: 0.3,
             'cosine decay': warmup_cosine(0.3, 0, num_epochs * num_batches)}
cnn_seeds, curves = [new_seed() for _ in range(2)], {}
print(f'{"test accuracy":<15}{"live, last five epochs":>24}{"live, final":>13}'
      f'{"EMA, final":>12}')
for seed in cnn_seeds:
    for name, schedule in schedules.items():
        live, avg = curves[seed, name] = train_fashion(seed, schedule)
        print(f'{name:<15}{min(live[-5:]):15.3f} to {max(live[-5:]):.3f}'
              f'{live[-1]:13.3f}{avg[-1]:12.3f}')
test accuracy    live, last five epochs  live, final  EMA, final
constant rate            0.792 to 0.913        0.908       0.914
cosine decay             0.906 to 0.912        0.911       0.909
constant rate            0.870 to 0.902        0.902       0.910
cosine decay             0.899 to 0.908        0.908       0.906
schedules = {'constant rate': lambda t: 0.3,
             'cosine decay': warmup_cosine(0.3, 0, num_epochs * num_batches)}
cnn_seeds, curves = [new_seed() for _ in range(2)], {}
print(f'{"test accuracy":<15}{"live, last five epochs":>24}{"live, final":>13}'
      f'{"EMA, final":>12}')
for seed in cnn_seeds:
    for name, schedule in schedules.items():
        live, avg = curves[seed, name] = train_fashion(seed, schedule)
        print(f'{name:<15}{min(live[-5:]):15.3f} to {max(live[-5:]):.3f}'
              f'{live[-1]:13.3f}{avg[-1]:12.3f}')
test accuracy    live, last five epochs  live, final  EMA, final
constant rate            0.890 to 0.906        0.890       0.913
cosine decay             0.910 to 0.913        0.912       0.911
constant rate            0.863 to 0.904        0.904       0.911
cosine decay             0.903 to 0.910        0.910       0.906

첫 번째 시드의 에포크별 테스트 정확도 궤적을 그려 보면 고정 학습률 EMA가 실시간 가중치의 잡음 공 떨림을 어떻게 제거하는지 한눈에 드러납니다.

(live, avg), (decayed, _) = (curves[cnn_seeds[0], name] for name in schedules)
d2l.plot(list(range(1, num_epochs + 1)), [live, avg, decayed], 'epoch',
         'test accuracy', ylim=[0.85, 0.925], figsize=(5, 2.5),
         legend=['constant rate, live weights', 'constant rate, EMA',
                 'cosine decay, live weights'], legend_loc='outside')

(live, avg), (decayed, _) = (curves[cnn_seeds[0], name] for name in schedules)
d2l.plot(list(range(1, num_epochs + 1)), [live, avg, decayed], 'epoch',
         'test accuracy', ylim=[0.85, 0.925], figsize=(5, 2.5),
         legend=['constant rate, live weights', 'constant rate, EMA',
                 'cosine decay, live weights'], legend_loc='outside')

고정 학습률에서 실시간 가중치는 마지막 다섯 에포크 동안 몇 퍼센트포인트 폭의 테스트 정확도 대역 안에서 위아래로 흔들리며 특정 에포크가 나쁘게 풀릴 때는 훨씬 크게 떨어지기도 하는 반면, EMA는 대역 상단을 따라 매끄럽게 약 \(91\%\) 까지 올라가 학습률을 한 번도 낮추지 않고도 코사인 감쇠 실행의 최종 정확도와 일치합니다. 따라서 WSD 스케줄의 상수 고원 단계 동안 가중치 EMA는 추가 스텝 비용이 전혀 들지 않는 저렴한 쿨다운 가지 근사 역할을 합니다(9.7.4.1절). 물론 완전한 대체재는 아닙니다. 언어 모델에서 고원을 따라 평균을 취하면 쿨다운 이득의 전부가 아니라 일부만 회수됩니다 (Hägele 기타 2024년).

9.10.3 엔드투엔드 실전 설정 예제

이제 이 장 전체의 내용을 종합하여 아직 튜닝되지 않은 \(4\)-블록, 너비-\(256\), \(4\)-헤드 TinyLM(\(3.3\) 백만(330만) 매개변수)의 \(3{,}000\)-스텝 훈련 실행을 구성해 보겠습니다. 표 9.10.1 에는 네 가지 최첨단 사전 학습 실행의 공개된 옵티마이저 설정이 요약되어 있으며, 표 9.10.2 에는 훈련 로그 증상과 그 해결책을 연결하는 진단 조회 테이블이 정리되어 있습니다.

표 9.10.1: 네 가지 대규모 언어 모델 사전 학습 실행의 공개 옵티마이저 설정
모델 옵티마이저 \(\beta_1, \beta_2\) 정점 LR 및 스케줄 웜업 클리핑 \(\theta\) 가중치 감쇠 \(\lambda\) 배치 크기
Llama 3 405B (Grattafiori 기타 2024년) AdamW — \(8{\times}10^{-5}\), \(8{\times}10^{-7}\) 까지 코사인 8k 스텝 — — 4M \(\to\) 16M 토큰 램프
DeepSeek-V3 (DeepSeek-AI 기타 2024년) AdamW 0.9, 0.95 \(2.2{\times}10^{-4}\), \(2.2{\times}10^{-5}\) 까지 WSD 코사인 2k 스텝 1.0 0.1 3,072 \(\to\) 15,360 시퀀스 램프
OLMo 2 7B (Team OLMo 기타 2025년) AdamW 0.9, 0.95 \(3{\times}10^{-4}\), \(3{\times}10^{-5}\) 까지 코사인 2k 스텝 1.0 0.1 (임베딩 제외) 1,024 시퀀스
Kimi K2 (Kimi Team 2025년) MuonClip — \(2{\times}10^{-4}\), \(2{\times}10^{-5}\) 까지 WSD 코사인 500 스텝 — 0.1 67M 토큰
표 9.10.2: 기록된 지표(손실, 클리핑 전 그레이디언트 노름, 클리핑 비율 및 상대 스텝 크기 \(\|\Delta\mathbf{W}\|_{\text{RMS}}/\|\mathbf{W}\|_{\text{RMS}}\))로 진단하는 최적화 실패 유형
기록된 증상 진단 일차 해법
처음 몇 스텝 안에 그레이디언트 노름 폭주와 함께 손실 발산 스텝 크기가 초기 국소 첨예도 \(2/L\) 초과 선형 웜업 또는 전역 노름 클리핑 추가
Adam에서 높은 손실 정체; 초기 상대 가중치 업데이트 \(>10\%\) 콜드 스타트 스텝이 초기화 훼손 선형 웜업(전체 스텝의 \(1\%\text{--}5\%\)) 추가
웜업 뒤에서도 Adam 손실이 높은 수준에 정체 정점 학습률 \(\eta_0\) 과다 \(\eta_0\) 를 \(2\text{--}3\times\) 낮춤
훈련 내내 \(>20\%\text{--}50\%\) 스텝에서 클리핑 작동 클리핑이 상시 브레이크로 작동 중 \(\theta\) 조정 전에 \(\eta_0\) 부터 낮춤
스텝 간 큰 분산을 동반하며 손실이 일찍 고원 정체 현재 \(\eta / b\) 에서의 정상 잡음 공 도달 \(\eta_t \to 0\) 감쇠, 가중치 EMA 평가, 또는 \(b\) 확대
마지막 스텝까지 일정한 기울기로 손실이 매끄럽게 하강 누적 이동 예산 \(B_T\) 부족 정점 \(\eta_0\) 또는 총 스텝 \(T\) 확대

표 9.10.1 에 따라 \(3.3\text{M}\)-매개변수 TinyLM을 다음과 같이 구성합니다.

  1. 배치 크기: 하드웨어 처리량이 포화되며 웜업 이후 그레이디언트 잡음 스케일 \(b_{\text{noise}} \sim 100\text{--}200\) 과 맞먹는 \(b = 256\) 시퀀스.
  2. 옵티마이저 및 안전장치: \((\beta_1, \beta_2) = (0.9, 0.95)\) 인 AdamW, 2차원 은닉 행렬에만 선택적으로 적용한 분리된 가중치 감쇠 \(\lambda = 0.1\)(9.5.3.3절), \(\theta = 1.0\) 전역 노름 그레이디언트 클리핑, 단기 윈도 가중치 EMA(\(\alpha = 0.995\)).
  3. 정점 학습률 보정: \(\eta \in \{10^{-3}, 3 \times 10^{-3}, 10^{-2}\}\) 에 걸친 세 번의 \(300\)-스텝(\(10\%\) 지평) 시험 실행을 통해 \(\eta_0 = 3 \times 10^{-3}\) 이 최적임을 확인합니다(클리핑 스텝 비율 \(<5\%\) 로 \(\theta = 1.0\) 이 순수한 안전장치로 작동함을 입증).
  4. 스케줄: \(60\)-스텝 선형 웜업(\(T = 3{,}000\) 의 \(2\%\)) 후 0까지의 코사인 감쇠를 적용하여 고정 학습률 베이스라인보다 검증 손실을 \(0.05\text{--}0.06\) nats 낮춥니다(시드 간 편차 \(<0.01\) nat).

먼저 \(4\)-블록, 너비-\(256\), \(4\)-헤드 TinyLM을 생성하는 tiny_lm(seed)와 잡음 스케일 추정용 무작위 훈련 윈도를 추출하는 sample_lm(b)를 정의합니다.

def tiny_lm(seed):
    """A TinyLM of four blocks of width 256 on the GPU."""
    torch.manual_seed(seed)  # The initialization and the minibatch order
    return d2l.TinyLM(len(data.vocab), d_model=256, num_heads=4,
                      num_blks=4).to(d2l.try_gpu())

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(d2l.try_gpu()), Y.to(d2l.try_gpu())
def tiny_lm(seed):
    """A TinyLM of four blocks of width 256."""
    return d2l.TinyLM(len(data.vocab), d_model=256, num_heads=4, num_blks=4,
                      rngs=nnx.Rngs(seed))

rng = np.random.default_rng(d2l.get_seed())

def sample_lm(b):  # b windows at random offsets in the training text, on the GPU
    X, Y = data.windows(data.train,
                        rng.integers(len(data.train) - data.num_steps, size=b))
    return jnp.asarray(X), jnp.asarray(Y)

하네스 train(seed, schedule, num_steps)는 임베딩이 아닌 2차원 행렬에만 제한된 가중치 감쇠 \(0.1\) 과 \((\beta_1, \beta_2) = (0.9, 0.95)\) 로 AdamW를 구성하고, 이를 전역 노름 클리핑(max_norm=1.0) 및 가중치 EMA(alpha=0.995)로 감싸 손실 기록, 실시간 모델, EMA 모델, 클리핑 비율을 반환합니다.

def train(seed, schedule, num_steps, max_norm=1.0, alpha=0.995):
    """AdamW with betas (0.9, 0.95) and weight decay 0.1 on the matrices at
    the rate schedule(t), clipped at max_norm, with an EMA of the weights;
    return the losses, the model, the EMA and the fraction of clipped steps."""
    model = tiny_lm(seed)
    matrices = [p for name, p in model.named_parameters()
                if p.ndim == 2 and 'emb' not in name]
    others = [p for name, p in model.named_parameters()
              if p.ndim != 2 or 'emb' in name]
    adamw = torch.optim.AdamW([{'params': matrices, 'weight_decay': 0.1},
                               {'params': others, 'weight_decay': 0.0}],
                              lr=1.0, betas=(0.9, 0.95))  # Times schedule
    scheduler = torch.optim.lr_scheduler.LambdaLR(adamw, schedule)
    ema = torch.optim.swa_utils.AveragedModel(
        model, multi_avg_fn=torch.optim.swa_utils.get_ema_multi_avg_fn(alpha))
    adamw.register_step_post_hook(lambda *_: scheduler.step())
    adamw.register_step_post_hook(lambda *_: ema.update_parameters(model))
    optimizer = Clipped(adamw, model.parameters(), max_norm)
    losses = d2l.train_steps(model, data, optimizer, num_steps)
    clip_rate = (torch.stack(optimizer.norms) > max_norm).float().mean()
    return losses, model, ema, float(clip_rate)
def decay_mask(params):  # True for the matrices, False for the rest
    return jax.tree_util.tree_map_with_path(
        lambda path, p: p.ndim == 2 and 'emb' not in str(path), params)

def train(seed, schedule, num_steps, max_norm=1.0, alpha=0.995):
    """AdamW with betas (0.9, 0.95) and weight decay 0.1 on the matrices at
    the rate schedule(t), clipped at max_norm, with an EMA of the weights;
    return the losses, the model, the EMA and the fraction of clipped steps."""
    model = tiny_lm(seed)
    adamw = optax.adamw(schedule, b1=0.9, b2=0.95, weight_decay=0.1,
                        mask=decay_mask)
    tx = optax.chain(clipped(adamw, num_steps, max_norm), ema_of_weights(alpha))
    optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param)
    losses = d2l.train_steps(model, data, optimizer, num_steps)
    norms = optimizer.opt_state[0][0]['norms'][...]  # Recorded by clipped
    clip_rate = (norms > max_norm).mean()
    return losses, model, averaged(model, optimizer), float(clip_rate)

\(b = 256\) 에서 초기화 시점의 d2l.noise_scale을 측정하고, \(\eta \in \{10^{-3}, 3 \times 10^{-3}, 10^{-2}\}\) 에 걸쳐 세 번의 \(300\)-스텝(\(10\%\) 지평) 프록시 시험을 실행해 정점 학습률 peak를 선택한 뒤 \(300\) 스텝 이후의 noise_scale을 다시 추정합니다.

data.batch_size = 256  # Where the throughput levels off
seed, short = new_seed(), {}
print('noise scale at initialization: '
      f'{d2l.noise_scale(tiny_lm(seed), sample_lm, b_small=8, b_big=256):.0f}')
for lr in [1e-3, 3e-3, 1e-2]:
    losses, model, _, clip_rate = train(seed, lambda t: lr, num_steps=300)
    short[lr] = (d2l.final_loss(losses), model)
    print(f'lr {lr:g}: loss {short[lr][0]:.3f} after 300 steps, '
          f'{clip_rate:.0%} of the steps clipped')
peak = min(short, key=lambda lr: short[lr][0])
print(f'peak rate {peak:g}; noise scale after its 300 steps: '
      f'{d2l.noise_scale(short[peak][1], sample_lm, b_small=8, b_big=256):.0f}')
noise scale at initialization: 2
lr 0.001: loss 1.881 after 300 steps, 3% of the steps clipped
lr 0.003: loss 1.740 after 300 steps, 3% of the steps clipped
lr 0.01: loss 2.498 after 300 steps, 6% of the steps clipped
peak rate 0.003; noise scale after its 300 steps: 153
data.batch_size = 256  # Where the throughput levels off
seed, short = new_seed(), {}
print('noise scale at initialization: '
      f'{d2l.noise_scale(tiny_lm(seed), sample_lm, b_small=8, b_big=256):.0f}')
for lr in [1e-3, 3e-3, 1e-2]:
    losses, model, _, clip_rate = train(seed, lambda t: lr, num_steps=300)
    short[lr] = (d2l.final_loss(losses), model)
    print(f'lr {lr:g}: loss {short[lr][0]:.3f} after 300 steps, '
          f'{clip_rate:.0%} of the steps clipped')
peak = min(short, key=lambda lr: short[lr][0])
print(f'peak rate {peak:g}; noise scale after its 300 steps: '
      f'{d2l.noise_scale(short[peak][1], sample_lm, b_small=8, b_big=256):.0f}')
noise scale at initialization: 2
lr 0.001: loss 1.880 after 300 steps, 2% of the steps clipped
lr 0.003: loss 1.769 after 300 steps, 3% of the steps clipped
lr 0.01: loss 2.482 after 300 steps, 6% of the steps clipped
peak rate 0.003; noise scale after its 300 steps: 173

마지막으로 두 시드에 걸쳐 전체 \(3{,}000\)-스텝 실행을 수행하여 구성한 스케줄(warmup_cosine(peak, 60, 3000)) 및 그 가중치 EMA를 peak 고정 학습률 베이스라인과 비교합니다.

num_steps = 3000
val_loss = lambda model: math.log(d2l.lm_perplexity(model, data.val_dataloader()))
print(f'{"validation loss":<16}{"configured":>11}{"its EMA":>9}'
      f'{"clipped":>9}{"baseline":>10}{"gap":>7}')
results = []
for seed in [new_seed() for _ in range(2)]:
    _, model, ema, clip_rate = train(
        seed, warmup_cosine(peak, num_steps // 50, num_steps), num_steps)
    _, baseline, _, _ = train(seed, lambda t: peak, num_steps)
    results.append((val_loss(model), val_loss(baseline)))
    print(f'{"seed " + str(len(results)):<16}{results[-1][0]:11.3f}'
          f'{val_loss(ema):9.3f}{clip_rate:9.1%}{results[-1][1]:10.3f}'
          f'{results[-1][1] - results[-1][0]:7.3f}')
(c1, b1), (c2, b2) = results
print(f'spread between the seeds: configured {abs(c1 - c2):.3f}, '
      f'baseline {abs(b1 - b2):.3f}')
validation loss  configured  its EMA  clipped  baseline    gap
seed 1                1.245    1.245     0.5%     1.303  0.058
seed 2                1.248    1.249     0.5%     1.300  0.052
spread between the seeds: configured 0.004, baseline 0.003
num_steps = 3000
val_loss = lambda model: math.log(d2l.lm_perplexity(model, data.val_dataloader()))
print(f'{"validation loss":<16}{"configured":>11}{"its EMA":>9}'
      f'{"clipped":>9}{"baseline":>10}{"gap":>7}')
results = []
for seed in [new_seed() for _ in range(2)]:
    _, model, ema, clip_rate = train(
        seed, warmup_cosine(peak, num_steps // 50, num_steps), num_steps)
    _, baseline, _, _ = train(seed, lambda t: peak, num_steps)
    results.append((val_loss(model), val_loss(baseline)))
    print(f'{"seed " + str(len(results)):<16}{results[-1][0]:11.3f}'
          f'{val_loss(ema):9.3f}{clip_rate:9.1%}{results[-1][1]:10.3f}'
          f'{results[-1][1] - results[-1][0]:7.3f}')
(c1, b1), (c2, b2) = results
print(f'spread between the seeds: configured {abs(c1 - c2):.3f}, '
      f'baseline {abs(b1 - b2):.3f}')
validation loss  configured  its EMA  clipped  baseline    gap
seed 1                1.247    1.247     0.6%     1.300  0.053
seed 2                1.249    1.249     0.6%     1.305  0.056
spread between the seeds: configured 0.002, baseline 0.006

9.10.4 요약

전역 노름 그레이디언트 클리핑(\(\mathbf{g} \leftarrow \min(1, \theta/\|\mathbf{g}\|_2)\mathbf{g}\))은 초반이나 비정상적인 소수 스텝(\(<5\%\))에서만 작동할 때 안전장치 역할을 하여 SGD의 초기 폭주를 막고 그레이디언트 급등으로부터 AdamW의 2차 모멘트 버퍼 \(\mathbf{v}_t\) 를 보호하는 반면, 내내 켜져 있다면 \(\eta\) 가 너무 커서 클리핑이 브레이크가 되었음을 알리는 신호입니다. 모델 가중치의 지수 이동 평균(EMA)(\(\bar{\mathbf{x}}_t = \alpha\bar{\mathbf{x}}_{t-1} + (1-\alpha)\mathbf{x}_t\))은 실시간 궤적을 수정하지 않고도 정상 잡음 공 요동을 평활화하여 고정 학습률 실행에서 전체 코사인 감쇠와 동등한 정확도를 달성합니다. 신뢰할 수 있는 대규모 훈련은 하드웨어를 포화시키면서 \(b_{\text{noise}}\) 근처에 배치한 배치 크기, 2차원 가중치 행렬에만 \(\lambda = 0.1\) 분리 감쇠를 적용한 \((\beta_1, \beta_2) = (0.9, 0.95)\) AdamW, \(\theta = 1.0\) 전역 노름 클리핑, 단기 정점 LR 보정, 그리고 선형 웜업과 코사인 또는 WSD 쿨다운을 하나로 결합합니다.

9.10.5 연습 문제

  1. [code] 클리핑 영역: 안전장치 대 브레이크. TinyLM의 \(\eta = 1.0\) 에서 \(\theta \in \{0.01, 0.1, 0.5, 1.0, 4.0, \infty\}\) 에 걸쳐 run을 스윕하며 최종 손실과 클리핑 비율을 기록하고, 클리핑을 사용하는 대신 \(20\)-스텝 또는 \(100\)-스텝 선형 웜업으로 대체했을 때와 비교하십시오.

  2. 소프트맥스 로짓 표류와 PaLM의 \(z\)-손실. 출력 로짓 \(\mathbf{o} \in \mathbb{R}^V\) 와 분배 함수 \(Z = \sum_{j=1}^V e^{o_j}\) 에 대해 교차 엔트로피 그레이디언트의 원소 합이 0(\(\mathbf{1}^\top \nabla_{\mathbf{o}}\ell_{\text{CE}} = 0\))임을 보이고, 반면 보조 페널티 \(10^{-4}\log^2 Z\) (Chowdhery 기타 2022년) 를 추가하면 \(\mathbf{p} = \operatorname{softmax}(\mathbf{o})\) 의 상수 이동 불변성을 해치지 않으면서 \(\log Z\) 를 \(0\) 쪽으로 끌어당기는 복원 그레이디언트 \(2 \times 10^{-4}(\log Z)\,\mathbf{p}\) 가 도입됨을 보이십시오.

  3. [code] 가중치 EMA 윈도와 시작 시점. 고정 \(\eta = 0.3\) 인 train_fashion에서 EMA 감쇠율 \(\alpha \in \{0.9, 0.99, 0.999, 0.9999\}\) 와 시작 에포크 start \(\in \{0, 5, 10\}\) 을 스윕하고, 정확도 궤적을 에포크 단위 유효 윈도 \(1/(1-\alpha)\) 와 연결해 설명하십시오.

  4. [code] 실전 설정 절제 연구(ablation). ● train의 \(4\)-블록 너비-\(256\) TinyLM에서 다음 네 가지를 테스트하는 2-시드 절제 실험을 수행하십시오: (a) WSD 후반 선형 감쇠 대 코사인 감쇠, (b) 웜업 제거 또는 그레이디언트 클리핑 제거, (c) 정점 학습률을 \(10^{-3}\) 또는 \(10^{-2}\) 로 이동, (d) \(\alpha \in \{0.995, 0.999\}\) 에서 고정 학습률 베이스라인의 가중치 EMA 평가.

토론