9.3  두 가지 테스트 모델

2차원 이차 계곡 같은 해석적 모델은 곡률과 그레이디언트 잡음이 단순한 업데이트 규칙을 어떻게 지배하는지 명쾌하게 설명해 주지만, 현대 옵티마이저를 평가하려면 실제 신경망에서의 실험적 측정이 필요합니다. 왜 AdamW는 트랜스포머에서 SGD를 큰 격차로 앞서는 반면 합성곱 신경망에서는 훨씬 작은 이점만 보일까요? 이러한 질문에 답하려면 통제된 실험 프로토콜 아래에서 실제 모델을 학습시켜야 합니다.

확률적 학습 실행은 무작위 초기화와 미니배치 추출에 따라 매번 달라지므로, 두 옵티마이저 설정 간의 차이는 단일 설정의 실행 간 변동 폭을 넘어설 때만 의미가 있습니다. 이 절에서는 본 장의 나머지 부분 전반에 걸쳐 사용할 두 가지 벤치마크 아키텍처인 바이트 단위 트랜스포머 언어 모델 TinyLM(\(470{,}784\) 개 매개변수)과 합성곱 분류기 FashionCNN(\(421{,}642\) 개 매개변수)을 정의하고, 공통 학습 루프, 학습률 스윕 하네스, 베이스라인 SGD 측정치 및 유의성 임곗값을 함께 확립합니다.

import os
import pandas as pd
import random
import textwrap
import os
import pandas as pd
import textwrap

9.3.1 언어 모델 TinyLM

TinyLM은 연속된 \(64\) 바이트의 문맥 윈도가 주어졌을 때 다음 UTF-8 바이트(\(V = 256\))를 예측하는 자기회귀 바이트 단위 언어 모델입니다(8.2절). \(64\) 개 윈도로 구성된 미니배치로 표준 \(2{,}000\) 스텝 실행을 수행하면 \(2{,}000 \times 64 \times 64 \approx 8.2 \times 10^6\) 개의 타깃 바이트를 처리합니다. 학습 표본의 반복(최적화 속도와 단순 암기를 뒤섞어 버림)을 피하기 위해 WikiText-103 (Merity 기타 2016년) 의 첫 번째 샤드(위키백과 문서 \(\sim 2.7 \times 10^8\) UTF-8 바이트)에서 학습합니다. 매 학습 미니배치는 무작위 바이트 오프셋에서 \(64\) 개의 윈도를 추출하므로, \(2{,}000\) 스텝 실행은 전체 말뭉치의 \(\sim 3\%\) 만 보게 되며 매 스텝 새로운 텍스트를 평가합니다. 검증 혼란도는 \(1.1 \times 10^6\) 바이트 검증 분할의 겹치지 않는 연속 윈도들 위에서 측정합니다.

class WikiText103(d2l.DataModule):
    """WikiText-103 as UTF-8 bytes, cut into windows of num_steps bytes."""
    def __init__(self, batch_size, num_steps, num_train=None, num_val=None):
        super().__init__()
        self.save_hyperparameters()
        self.vocab = d2l.BPETokenizer(vocab_size=256, specials=())  # Bytes
        self.train = self._read('train-00000-of-00002',
                                '3cbc792dfc0eeedf8d7333acdc15a9f536032d9a')
        self.val = self._read('validation-00000-of-00001',
                              '49d15019b0476afc752bd5f010b5a2aab2de89ca')
        self.train, self.val = self.train[:num_train], self.val[:num_val]

    def _read(self, split, sha1):
        url = ('https://huggingface.co/datasets/Salesforce/wikitext/resolve/'
               f'main/wikitext-103-raw-v1/{split}.parquet')
        fname = d2l.download(url, os.path.join(self.root, 'wikitext-103'),
                             sha1)
        lines = pd.read_parquet(fname)['text']  # Each line ends with '\n'
        return np.frombuffer(b''.join(s.encode() for s in lines), np.uint8)

    def windows(self, corpus, starts):
        """Inputs and next-byte targets of the windows at `starts`."""
        idx = np.asarray(starts)[:, None] + np.arange(self.num_steps + 1)
        array = torch.from_numpy(corpus[idx].astype(np.int64))
        return array[:, :-1], array[:, 1:]

    def train_dataloader(self):  # A pass of minibatches at random offsets
        n = len(self.train) - self.num_steps
        for _ in range(n // (self.batch_size * self.num_steps)):
            yield self.windows(self.train,
                               torch.randint(n, (self.batch_size,)).numpy())

    def val_dataloader(self):  # Consecutive, non-overlapping windows
        starts = np.arange(0, len(self.val) - self.num_steps, self.num_steps)
        for i in range(0, len(starts), self.batch_size):
            yield self.windows(self.val, starts[i:i + self.batch_size])
class WikiText103(d2l.DataModule):
    """WikiText-103 as UTF-8 bytes, cut into windows of num_steps bytes."""
    def __init__(self, batch_size, num_steps, num_train=None, num_val=None):
        super().__init__()
        self.save_hyperparameters()
        self.vocab = d2l.BPETokenizer(vocab_size=256, specials=())  # Bytes
        self.train = self._read('train-00000-of-00002',
                                '3cbc792dfc0eeedf8d7333acdc15a9f536032d9a')
        self.val = self._read('validation-00000-of-00001',
                              '49d15019b0476afc752bd5f010b5a2aab2de89ca')
        self.train, self.val = self.train[:num_train], self.val[:num_val]

    def _read(self, split, sha1):
        url = ('https://huggingface.co/datasets/Salesforce/wikitext/resolve/'
               f'main/wikitext-103-raw-v1/{split}.parquet')
        fname = d2l.download(url, os.path.join(self.root, 'wikitext-103'),
                             sha1)
        lines = pd.read_parquet(fname)['text']  # Each line ends with '\n'
        return np.frombuffer(b''.join(s.encode() for s in lines), np.uint8)

    def windows(self, corpus, starts):
        """Inputs and next-byte targets of the windows at `starts`."""
        idx = np.asarray(starts)[:, None] + np.arange(self.num_steps + 1)
        array = corpus[idx].astype(np.int32)
        return array[:, :-1], array[:, 1:]

    def train_dataloader(self):  # A pass of minibatches at random offsets
        n = len(self.train) - self.num_steps
        rng = np.random.default_rng(d2l.get_seed())
        for _ in range(n // (self.batch_size * self.num_steps)):
            yield self.windows(self.train,
                               rng.integers(n, size=self.batch_size))

    def val_dataloader(self):  # Consecutive, non-overlapping windows
        starts = np.arange(0, len(self.val) - self.num_steps, self.num_steps)
        for i in range(0, len(starts), self.batch_size):
            yield self.windows(self.val, starts[i:i + self.batch_size])

WikiText103(batch_size=64, num_steps=64)를 인스턴스화하면 학습 및 검증 샤드를 다운로드하고 말뭉치의 첫 \(300\) 바이트를 디코딩합니다.

data = WikiText103(batch_size=64, num_steps=64)
print(f'{len(data.train):,} training bytes, '
      f'{len(data.val):,} validation bytes')
text = data.vocab.decode(data.train[:300])
print('\n'.join(textwrap.fill(line, 72) for line in text.splitlines()))
269,630,498 training bytes, 1,144,248 validation bytes
 = Valkyria Chronicles III =
 Senjō no Valkyria 3 : Unrecorded Chronicles ( Japanese : 戦場のヴァルキュリア3 ,
lit . Valkyria of the Battlefield 3 ) , commonly referred to as Valkyria
Chronicles III outside Japan , is a tactical role @-@ playing video game
developed by Sega and Media.Vis
data = WikiText103(batch_size=64, num_steps=64)
print(f'{len(data.train):,} training bytes, '
      f'{len(data.val):,} validation bytes')
text = data.vocab.decode(data.train[:300])
print('\n'.join(textwrap.fill(line, 72) for line in text.splitlines()))
269,630,498 training bytes, 1,144,248 validation bytes
 = Valkyria Chronicles III =
 Senjō no Valkyria 3 : Unrecorded Chronicles ( Japanese : 戦場のヴァルキュリア3 ,
lit . Valkyria of the Battlefield 3 ) , commonly referred to as Valkyria
Chronicles III outside Japan , is a tactical role @-@ playing video game
developed by Sega and Media.Vis

9.3.1.1 아키텍처와 매개변수 그룹

TinyLM은 임베딩 너비 \(d_{\text{model}} = 128\), 인과적 어텐션 헤드 \(2\) 개, 블록당 은닉 너비 \(4 d_{\text{model}} = 512\) 인 2층 GELU MLP를 갖춘 2블록 디코더 전용 트랜스포머(11장)입니다. 각 서브층 앞에는 LayerNorm(7.3.4.1절)이 놓이고 잔차 연결로 감싸지며, 마지막에는 최종 LayerNorm과 \(256\) 개 바이트 로짓으로 투영하는 선형 출력 헤드가 이어집니다. 임베딩 행은 \(\mathcal{N}(0, 1)\) 에서 초기화하고, 모든 선형 가중치와 편향은 \([-1/\sqrt{\text{fan-in}}, 1/\sqrt{\text{fan-in}}]\) 에서 균일 추출합니다.

class TinyLM(nn.Module):
    """A small decoder-only transformer language model."""
    def __init__(self, vocab_size, d_model=128, num_heads=2, num_blks=2,
                 max_len=64):
        super().__init__()
        self.num_heads = num_heads
        self.token_emb = nn.Embedding(vocab_size, d_model)
        self.pos_emb = nn.Embedding(max_len, d_model)
        self.blks = nn.ModuleList([nn.ModuleDict(dict(
            norm1=nn.LayerNorm(d_model),
            qkv=nn.Linear(d_model, 3 * d_model),
            proj=nn.Linear(d_model, d_model),
            norm2=nn.LayerNorm(d_model),
            mlp=nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(),
                              nn.Linear(4 * d_model, d_model))))
            for _ in range(num_blks)])
        self.norm = nn.LayerNorm(d_model)
        self.head = nn.Linear(d_model, vocab_size)

    def attention(self, blk, X):
        B, T, D = X.shape
        q, k, v = blk['qkv'](X).chunk(3, dim=-1)
        q, k, v = (u.reshape(B, T, self.num_heads, -1).transpose(1, 2)
                   for u in (q, k, v))
        Y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        return blk['proj'](Y.transpose(1, 2).reshape(B, T, D))

    def forward(self, X):
        H = self.token_emb(X) + self.pos_emb(torch.arange(X.shape[1],
                                                          device=X.device))
        for blk in self.blks:
            H = H + self.attention(blk, blk['norm1'](H))
            H = H + blk['mlp'](blk['norm2'](H))
        return self.head(self.norm(H))
class TinyLM(nnx.Module):
    """A small decoder-only transformer language model."""
    def __init__(self, vocab_size, d_model=128, num_heads=2, num_blks=2,
                 max_len=64, *, rngs):
        self.num_heads = num_heads
        def linear(d_in, d_out):
            a = 1 / math.sqrt(d_in)  # Weights and biases ~ U(-a, a)
            init = lambda key, shape, dtype: jax.random.uniform(
                key, shape, dtype, -a, a)
            return nnx.Linear(d_in, d_out, kernel_init=init, bias_init=init,
                              rngs=rngs)
        def embed(n):  # Embedding rows ~ N(0, I)
            return d2l.Embed(n, d_model, rngs=rngs,
                             embedding_init=nnx.initializers.normal(1.0))
        def norm():
            return nnx.LayerNorm(d_model, epsilon=1e-5, rngs=rngs)
        self.token_emb, self.pos_emb = embed(vocab_size), embed(max_len)
        self.blks = nnx.List([nnx.Dict(
            norm1=norm(), qkv=linear(d_model, 3 * d_model),
            proj=linear(d_model, d_model), norm2=norm(),
            mlp1=linear(d_model, 4 * d_model),
            mlp2=linear(4 * d_model, d_model))
            for _ in range(num_blks)])
        self.norm = norm()
        self.head = linear(d_model, vocab_size)

    def attention(self, blk, X):
        B, T, D = X.shape
        q, k, v = jnp.split(blk['qkv'](X), 3, axis=-1)
        q, k, v = (u.reshape(B, T, self.num_heads, -1) for u in (q, k, v))
        Y = jax.nn.dot_product_attention(q, k, v, is_causal=True)
        return blk['proj'](Y.reshape(B, T, D))

    def __call__(self, X):
        H = self.token_emb(X) + self.pos_emb(jnp.arange(X.shape[1]))
        for blk in self.blks:
            H = H + self.attention(blk, blk['norm1'](H))
            H = H + blk['mlp2'](jax.nn.gelu(blk['mlp1'](blk['norm2'](H)),
                                            approximate=False))
        return self.head(self.norm(H))

옵티마이저 관점에서 TinyLM의 \(470{,}784\) 개 매개변수는 이후 절들에서 서로 다르게 취급할 세 가지 구조적 그룹으로 나뉩니다(예: 9.5.3절 의 분리된 가중치 감쇠 및 9.6절 의 행렬 직교화).

  • 임베딩(\(9\%\)): 토큰 빈도에 비례하는 희소한 행 그레이디언트를 받는 조회 테이블(token_emb, pos_emb).
  • 가중치 행렬(\(90\%\)): 밀집 2차원 투영 행렬(블록당 qkv, proj, 두 개의 MLP 층 및 최종 head).
  • 1차원 벡터(\(<1\%\)): 선형 편향과 LayerNorm 스케일/시프트 벡터.
# nn.Linear and nn.Embedding initialize as described above by default;
# nn.GELU is the exact GELU
model = TinyLM(vocab_size=len(data.vocab))
kinds = {'embeddings': 0, 'matrices': 0, 'vectors': 0}
print(f'{"parameter":<22} {"shape":<14} {"count":>7}')
for name, p in model.named_parameters():
    kind = ('embeddings' if 'emb' in name else
            'matrices' if p.ndim == 2 else 'vectors')
    kinds[kind] += p.numel()
    print(f'{name:<22} {str(tuple(p.shape)):<14} {p.numel():>7}')
for kind, count in kinds.items():
    print(f'{kind:>37} {count:>7}')
print(f'{"total":>37} {sum(kinds.values()):>7}')
parameter              shape            count
token_emb.weight       (256, 128)       32768
pos_emb.weight         (64, 128)         8192
blks.0.norm1.weight    (128,)             128
blks.0.norm1.bias      (128,)             128
blks.0.qkv.weight      (384, 128)       49152
blks.0.qkv.bias        (384,)             384
blks.0.proj.weight     (128, 128)       16384
blks.0.proj.bias       (128,)             128
blks.0.norm2.weight    (128,)             128
blks.0.norm2.bias      (128,)             128
blks.0.mlp.0.weight    (512, 128)       65536
blks.0.mlp.0.bias      (512,)             512
blks.0.mlp.2.weight    (128, 512)       65536
blks.0.mlp.2.bias      (128,)             128
blks.1.norm1.weight    (128,)             128
blks.1.norm1.bias      (128,)             128
blks.1.qkv.weight      (384, 128)       49152
blks.1.qkv.bias        (384,)             384
blks.1.proj.weight     (128, 128)       16384
blks.1.proj.bias       (128,)             128
blks.1.norm2.weight    (128,)             128
blks.1.norm2.bias      (128,)             128
blks.1.mlp.0.weight    (512, 128)       65536
blks.1.mlp.0.bias      (512,)             512
blks.1.mlp.2.weight    (128, 512)       65536
blks.1.mlp.2.bias      (128,)             128
norm.weight            (128,)             128
norm.bias              (128,)             128
head.weight            (256, 128)       32768
head.bias              (256,)             256
                           embeddings   40960
                             matrices  425984
                              vectors    3840
                                total  470784
# Flax's default initializers differ, so TinyLM passes the ones described
# above (and approximate=False for the exact GELU); d2l.Embed computes
# the embedding gradient as one matrix product, far faster than XLA's
# default on frequent bytes such as the space
model = TinyLM(vocab_size=len(data.vocab), rngs=nnx.Rngs(d2l.get_key()))
kinds = {'embeddings': 0, 'matrices': 0, 'vectors': 0}
print(f'{"parameter":<22} {"shape":<14} {"count":>7}')
for path, p in nnx.to_flat_state(nnx.state(model, nnx.Param)):
    name = '.'.join(str(k) for k in path)
    kind = ('embeddings' if 'emb' in name else
            'matrices' if p.ndim == 2 else 'vectors')
    kinds[kind] += p.size
    print(f'{name:<22} {str(tuple(p.shape)):<14} {p.size:>7}')
for kind, count in kinds.items():
    print(f'{kind:>37} {count:>7}')
print(f'{"total":>37} {sum(kinds.values()):>7}')
parameter              shape            count
blks.0.mlp1.bias       (512,)             512
blks.0.mlp1.kernel     (128, 512)       65536
blks.0.mlp2.bias       (128,)             128
blks.0.mlp2.kernel     (512, 128)       65536
blks.0.norm1.bias      (128,)             128
blks.0.norm1.scale     (128,)             128
blks.0.norm2.bias      (128,)             128
blks.0.norm2.scale     (128,)             128
blks.0.proj.bias       (128,)             128
blks.0.proj.kernel     (128, 128)       16384
blks.0.qkv.bias        (384,)             384
blks.0.qkv.kernel      (128, 384)       49152
blks.1.mlp1.bias       (512,)             512
blks.1.mlp1.kernel     (128, 512)       65536
blks.1.mlp2.bias       (128,)             128
blks.1.mlp2.kernel     (512, 128)       65536
blks.1.norm1.bias      (128,)             128
blks.1.norm1.scale     (128,)             128
blks.1.norm2.bias      (128,)             128
blks.1.norm2.scale     (128,)             128
blks.1.proj.bias       (128,)             128
blks.1.proj.kernel     (128, 128)       16384
blks.1.qkv.bias        (384,)             384
blks.1.qkv.kernel      (128, 384)       49152
head.bias              (256,)             256
head.kernel            (128, 256)       32768
norm.bias              (128,)             128
norm.scale             (128,)             128
pos_emb.embedding      (64, 128)         8192
token_emb.embedding    (256, 128)       32768
                           embeddings   40960
                             matrices  425984
                              vectors    3840
                                total  470784

9.3.2 이미지 분류기 FashionCNN

트랜스포머에서의 옵티마이저 순위는 합성곱 신경망에서의 순위와 뚜렷하게 다르므로, 두 번째 벤치마크로 \(28 \times 28\) Fashion-MNIST 이미지(3.2절) 분류기인 FashionCNN을 사용합니다. 두 단계의 \(3 \times 3\) 합성곱 + ReLU + \(2 \times 2\) 최대 풀링(\(32\) 채널 및 \(64\) 채널)이 공간 해상도를 \(64 \times 7 \times 7\) 로 줄이고, 그 뒤에 두 개의 선형 층(\(3{,}136 \to 128 \to 10\))이 이어집니다. 모든 층은 균일 \(\pm 1/\sqrt{\text{fan-in}}\) 초기화를 사용하며 총 매개변수 수는 \(421{,}642\) 개입니다.

class FashionCNN(nn.Module):
    """A compact CNN for Fashion-MNIST: two conv-pool stages, two linear."""
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
        self.fc1 = nn.Linear(64 * 7 * 7, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, X):
        X = F.max_pool2d(F.relu(self.conv1(X)), 2)
        X = F.max_pool2d(F.relu(self.conv2(X)), 2)
        return self.fc2(F.relu(self.fc1(X.flatten(1))))
class FashionCNN(nnx.Module):
    """A compact CNN for Fashion-MNIST: two conv-pool stages, two linear."""
    def __init__(self, *, rngs):
        def init(fan_in):  # Weights and biases ~ U(-a, a), a = 1/sqrt(fan_in)
            a = 1 / math.sqrt(fan_in)
            f = lambda key, shape, dtype: jax.random.uniform(
                key, shape, dtype, -a, a)
            return dict(kernel_init=f, bias_init=f, rngs=rngs)
        self.conv1 = nnx.Conv(1, 32, kernel_size=(3, 3), **init(9))
        self.conv2 = nnx.Conv(32, 64, kernel_size=(3, 3), **init(9 * 32))
        self.fc1 = nnx.Linear(64 * 7 * 7, 128, **init(64 * 7 * 7))
        self.fc2 = nnx.Linear(128, 10, **init(128))

    def __call__(self, X):
        X = nnx.max_pool(nnx.relu(self.conv1(X)), window_shape=(2, 2),
                         strides=(2, 2))
        X = nnx.max_pool(nnx.relu(self.conv2(X)), window_shape=(2, 2),
                         strides=(2, 2))
        return self.fc2(nnx.relu(self.fc1(X.reshape(X.shape[0], -1))))

d2l.num_params를 사용해 FashionCNN의 학습 가능한 매개변수가 \(421{,}642\) 개임을 확인합니다.

# nn.Conv2d and nn.Linear draw from U(-a, a), a = 1/sqrt(fan-in), by default;
# images arrive as (batch, channel, height, width)
print(f'{d2l.num_params(FashionCNN()):,} parameters')
421,642 parameters
# Flax's default initializers differ, so FashionCNN passes U(-a, a)
# explicitly; images arrive as (batch, height, width, channel)
print(f'{d2l.num_params(FashionCNN(rngs=nnx.Rngs(d2l.get_key()))):,} '
      'parameters')
421,642 parameters

배치 크기 \(256\) 에서 \(2{,}000\) 스텝 실행은 \(60{,}000\) 장의 Fashion-MNIST 학습 이미지를 \(\sim 8.5\) 회 순회하므로, evaluate_accuracy를 통해 학습 손실과 함께 홀드아웃 테스트 정확도를 함께 보고합니다.

fashion = d2l.FashionMNIST(batch_size=256)

def evaluate_accuracy(model, batches):
    """Fraction of the examples in batches that model classifies correctly."""
    device = next(model.parameters()).device
    training, correct, total = model.training, 0, 0
    model.eval()  # Dropout off, batch norm on running statistics
    with torch.inference_mode():
        for X, y in batches:
            y_hat = model(X.to(device)).argmax(dim=1)
            correct += (y_hat == y.to(device)).sum()
            total += len(y)
    model.train(training)
    return float(correct) / total
fashion = d2l.FashionMNIST(batch_size=256)

@nnx.jit
def num_correct(model, X, y):
    """Number of examples in (X, y) that model classifies correctly."""
    return (model(X).argmax(axis=1) == y).sum()

def evaluate_accuracy(model, batches):
    """Fraction of the examples in batches that model classifies correctly."""
    # A view with dropout off and batch norm on running statistics
    model = nnx.view(model, deterministic=True, use_running_average=True,
                     raise_if_not_found=False)
    correct, total = 0, 0
    for X, y in batches:
        correct += num_correct(model, jnp.asarray(X), jnp.asarray(y))
        total += len(y)
    return float(correct) / total

9.3.3 학습 하네스 및 평가 헬퍼

두 모델 모두 미니배치를 로짓으로 매핑하고 고정된 스텝 예산 동안 평균 교차 엔트로피 손실을 최소화합니다. 표 9.3.1 에는 d2l에 저장된 학습 루프와 평가 유틸리티들이 요약되어 있습니다.

표 9.3.1: d2l에 저장된 공통 학습 및 평가 함수
함수 용도
train_steps num_steps스텝 동안(또는 stop(step)이 성립할 때까지) 학습하고 스텝별 교차 엔트로피 손실을 반환
lm_perplexity 배치 반복자에 걸쳐 토큰 혼란도 \(\exp(\text{mean cross-entropy})\) 를 계산(8.3절)
evaluate_accuracy 배치 반복자에 걸쳐 분류 정확도를 계산
final_loss 마지막 \(k=100\) 개 스텝 손실의 평균(발산 시 inf)
smooth 플로팅을 위한 연속된 \(k=25\) 개 손실 윈도의 블록 평균
steps_to_reach \(25\)-스텝 평활화 손실이 target 이하로 처음 떨어지는 스텝(없으면 None)
lr_sweep 학습률 목록에 걸쳐 동일한 초기 가중치에서 학습을 수행하고 손실 곡선과 평가 점수를 반환

먼저 num_steps개의 미니배치에 걸쳐(패딩 레이블 -100은 무시) 또는 선택적 조건 함수 stop(step)이 참이 될 때까지 평균 교차 엔트로피를 최소화하는 train_steps를 구현합니다.

def train_steps(model, data, optimizer, num_steps, *, stop=None):
    """Minimize the mean cross-entropy of the logits model(X) for the labels
    Y over the minibatches (X, Y) of data, leaving out the labels -100, for
    num_steps steps or until stop(step) is true; return every step's loss."""
    device = d2l.try_gpu()
    model.to(device)
    losses, step = [], 0
    while step < num_steps:
        for X, Y in data.train_dataloader():
            X, Y = X.to(device), Y.to(device)
            logits = model(X)
            loss = F.cross_entropy(logits.reshape(-1, logits.shape[-1]),
                                   Y.reshape(-1), ignore_index=-100)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            losses.append(loss.detach())
            step += 1
            if step >= num_steps or (stop is not None and stop(step)):
                return torch.stack(losses).tolist()
@nnx.jit
def _cross_entropy_step(model, optimizer, X, Y):
    """One optimizer step on the mean cross-entropy of the logits model(X)
    for the labels Y; negative labels, such as -100, add no loss."""
    def loss_fn(model):
        logits = model(X)
        logits, y = logits.reshape(-1, logits.shape[-1]), Y.reshape(-1)
        valid = y >= 0
        losses = optax.softmax_cross_entropy_with_integer_labels(
            logits, jnp.where(valid, y, 0))
        return (losses * valid).sum() / valid.sum()
    loss, grads = nnx.value_and_grad(loss_fn)(model)
    optimizer.update(model, grads)
    return loss

def train_steps(model, data, optimizer, num_steps, *, stop=None):
    """Minimize the mean cross-entropy of the logits model(X) for the labels
    Y over the minibatches (X, Y) of data, leaving out the labels -100, for
    num_steps steps or until stop(step) is true; return every step's loss."""
    losses, pending, step = [], [], 0
    while step < num_steps:
        for X, Y in data.train_dataloader():
            pending.append(_cross_entropy_step(
                model, optimizer, jnp.asarray(X), jnp.asarray(Y)))
            step += 1
            done = step >= num_steps or (stop is not None and stop(step))
            if len(pending) == 50 or done:  # Sync now and then
                losses.extend(float(l) for l in jax.device_get(pending))
                pending = []
            if done:
                return losses

다음으로 lm_perplexity는 추론 모드에서 미니배치 반복자에 걸쳐 언어 모델을 평가하고 토큰당 \(\exp(\text{mean cross-entropy})\) 를 반환합니다.

def lm_perplexity(model, batches):
    """Perplexity of a language model on the minibatches (X, Y) of batches."""
    device = next(model.parameters()).device
    modes = {m: m.training for m in model.modules()}  # Restored at the end
    model.eval()  # Dropout off while we measure
    total, count = 0, 0
    with torch.inference_mode():
        for X, Y in batches:
            logits = model(X.to(device))
            total += F.cross_entropy(logits.flatten(0, 1),
                                     Y.to(device).flatten(), reduction='sum')
            count += Y.numel()
    for m, training in modes.items():
        m.training = training
    return math.exp(float(total) / count)
@jax.jit(static_argnums=0)
def lm_loss_sum(graphdef, state, X, Y):
    """Summed next-token cross-entropy of a batch, and the model's state."""
    model = nnx.merge(graphdef, state)
    loss = optax.softmax_cross_entropy_with_integer_labels(model(X), Y).sum()
    return loss, nnx.state(model)

def lm_perplexity(model, batches):
    """Perplexity of a language model on the minibatches (X, Y) of batches."""
    # A view with dropout off, sharing the weights; one walk through it
    graphdef, state = nnx.split(nnx.view(model, deterministic=True,
                                         raise_if_not_found=False))
    total, count = 0, 0
    for X, Y in batches:
        loss, state = lm_loss_sum(graphdef, state, X, Y)
        total, count = total + loss, count + Y.size
    nnx.update(model, state)  # Keep statistics the model records, if any
    return math.exp(float(total) / count)

잡음이 섞인 스텝 손실 기록을 요약하고 시각화하기 위해 final_loss는 마지막 \(k = 100\) 개 스텝 손실을 평균 내고, smooth는 \(25\)-스텝 블록 평균을 계산하며, steps_to_reach는 평활화된 손실이 target에 도달하는 첫 스텝을 찾습니다.

def final_loss(losses, k=100):
    """Mean of the last k losses; infinity if the run diverged."""
    v = sum(losses[-k:]) / k
    return v if math.isfinite(v) else float('inf')

def smooth(losses, k=25):
    """Means over consecutive blocks of k losses, for plotting."""
    return [sum(losses[i:i + k]) / k
            for i in range(0, len(losses) - k + 1, k)]

def steps_to_reach(losses, target, k=25):
    """First step at which the smoothed losses reach target; None if they
    never do."""
    for i, v in enumerate(smooth(losses, k)):
        if v <= target:
            return k * (i + 1)
    return None
def final_loss(losses, k=100):
    """Mean of the last k losses; infinity if the run diverged."""
    v = sum(losses[-k:]) / k
    return v if math.isfinite(v) else float('inf')

def smooth(losses, k=25):
    """Means over consecutive blocks of k losses, for plotting."""
    return [sum(losses[i:i + k]) / k
            for i in range(0, len(losses) - k + 1, k)]

def steps_to_reach(losses, target, k=25):
    """First step at which the smoothed losses reach target; None if they
    never do."""
    for i, v in enumerate(smooth(losses, k)):
        if v <= target:
            return k * (i + 1)
    return None

마지막으로 lr_sweep은 lrs의 각 학습률마다 동일한 무작위 seed에서 새 모델을 초기화해 학습시키며, 선택적으로 every스텝마다 evaluate(model)을 실행합니다.

def lr_sweep(make_model, make_optimizer, data, lrs, seed,
             num_steps=2000, *, evaluate=None, metric='score', every=None,
             verbose=True):
    """Train make_model() with make_optimizer(model, lr) for each lr, from
    one initialization; return the loss curves and the evaluations."""
    every = every or num_steps
    curves, scores = {}, {}
    for lr in lrs:
        torch.manual_seed(seed)  # The same initialization for every lr
        model = make_model()
        optimizer = make_optimizer(model, lr)
        curves[lr], scores[lr] = [], []
        for _ in range(num_steps // every):
            curves[lr] += train_steps(model, data, optimizer, every)
            if evaluate is not None:
                scores[lr].append(evaluate(model))
        line = f'lr {lr:g}: final loss {final_loss(curves[lr]):.3f}'
        if scores[lr]:
            line += f', {metric} {scores[lr][-1]:.3f}'
        if verbose:
            print(line)
    return curves, scores
def lr_sweep(make_model, make_tx, data, lrs, seed,
             num_steps=2000, *, evaluate=None, metric='score', every=None,
             verbose=True):
    """Train make_model(rngs=...) with the optax transformation make_tx(lr)
    for each lr, from one initialization; return the loss curves and the
    evaluations."""
    every = every or num_steps
    curves, scores = {}, {}
    for lr in lrs:  # The same initialization for every lr
        model = make_model(rngs=nnx.Rngs(seed))
        optimizer = nnx.Optimizer(model, make_tx(lr), wrt=nnx.Param)
        curves[lr], scores[lr] = [], []
        for _ in range(num_steps // every):
            curves[lr] += train_steps(model, data, optimizer, every)
            if evaluate is not None:
                scores[lr].append(evaluate(model))
        line = f'lr {lr:g}: final loss {final_loss(curves[lr]):.3f}'
        if scores[lr]:
            line += f', {metric} {scores[lr][-1]:.3f}'
        if verbose:
            print(line)
    return curves, scores

9.3.4 베이스라인 미니배치 SGD 실행 및 실험 프로토콜

이제 고정 학습률 미니배치 SGD(\(2{,}000\) 스텝, 모멘텀 및 가중치 감쇠 없음)로 베이스라인을 설정합니다. TinyLM에서 학습되지 않은 모델은 초기 로짓 분산 때문에 균일 분포 교차 엔트로피 \(\ln 256 \approx 5.55\) nats/byte보다 약간 높은 \(\sim 5.71\) nats/byte에서 출발합니다(1 참조). WikiText-103에서의 참고 기준선으로, 유니그램 바이트 빈도 테이블은 \(\sim 3.2\) nats/byte를 달성하고 바이그램 바이트 쌍 테이블은 \(\sim 2.5\) nats/byte를 달성합니다(6 참조). 그림 9.3.1 에서는 이 기준선들을 하나의 눈금 위에 배치하며, 이 장에 등장하는 모든 손실 값은 이 눈금에 비추어 해석할 수 있습니다.

그림 9.3.1: WikiText-103 바이트 단위 언어 모델링의 손실 기준선. 회색: 미학습 TinyLM 및 균일 추측. 파란색: 유니그램 및 바이그램 바이트 테이블. 주황색: 아래에서 측정한 \(2{,}000\) 스텝 SGD 이후의 TinyLM 및 본 장 후반부의 최적 튜닝 실행 결과.

먼저 모델과 기본 SGD 생성 클로저인 make_lm, sgd, new_seed를 정의합니다.

make_lm = lambda: TinyLM(len(data.vocab))
sgd = lambda model, lr: torch.optim.SGD(model.parameters(), lr)
new_seed = lambda: random.getrandbits(31)
make_lm = lambda rngs: TinyLM(len(data.vocab), rngs=rngs)
sgd = optax.sgd
new_seed = d2l.get_seed

TinyLM에서 \(\eta \in \{0.1, 0.5, 2.5\}\) 에 걸쳐 lr_sweep을 실행하고 균일 추측 기준선 \(\ln 256\) 과 함께 스텝 손실을 그리면 세 가지 전형적인 학습률 영역이 뚜렷이 나타납니다.

lm_sgd, _ = lr_sweep(make_lm, sgd, data, lrs=[0.1, 0.5, 2.5], seed=new_seed())
d2l.plot(list(range(1, 2001)),
         list(lm_sgd.values()) + [[math.log(256)] * 2000],
         'step', 'training loss', xscale='log', ylim=[1.5, 6],
         legend=[f'lr {lr:g}' for lr in lm_sgd] + ['uniform guess'],
         legend_loc='outside', figsize=(5, 2.5))
lr 0.1: final loss 2.492
lr 0.5: final loss 2.151
lr 2.5: final loss inf

lm_sgd, _ = lr_sweep(make_lm, sgd, data, lrs=[0.1, 0.5, 2.5], seed=new_seed())
d2l.plot(list(range(1, 2001)),
         list(lm_sgd.values()) + [[math.log(256)] * 2000],
         'step', 'training loss', xscale='log', ylim=[1.5, 6],
         legend=[f'lr {lr:g}' for lr in lm_sgd] + ['uniform guess'],
         legend_loc='outside', figsize=(5, 2.5))
lr 0.1: final loss 2.485
lr 0.5: final loss 2.131
lr 2.5: final loss inf

  • 너무 높은 학습률(\(\eta = 2.5\)): 첫 스텝 직후 국소 안정성 임곗값 \(2/L\) 을 초과하여 열 스텝 안에 inf로 발산합니다.
  • 너무 낮은 학습률(\(\eta = 0.1\)): 매끄럽지만 느리게 하강하여 \(2{,}000\) 스텝에서 \(\sim 2.5\) nats/byte(바이그램 수준)에 그칩니다.
  • 잘 튜닝된 학습률(\(\eta = 0.5\)): 신경망이 초기 고곡률 영역을 통과할 때 짧은 과도 급등을 겪지만 곧 회복하여 약 \(2.1\) nats/byte에 도달합니다.

FashionCNN에서는 \(\eta = 0.3\) 인 기본 SGD가 학습 손실 \(\sim 0.22\) 와 홀드아웃 테스트 정확도 \(\sim 90\%\) 에 도달합니다.

test_acc = lambda model: evaluate_accuracy(model, fashion.val_dataloader())
cnn_sgd, _ = lr_sweep(FashionCNN, sgd, fashion, lrs=[0.3], seed=new_seed(),
                      evaluate=test_acc, metric='test accuracy')
lr 0.3: final loss 0.221, test accuracy 0.901
test_acc = lambda model: evaluate_accuracy(model, fashion.val_dataloader())
cnn_sgd, _ = lr_sweep(FashionCNN, sgd, fashion, lrs=[0.3], seed=new_seed(),
                      evaluate=test_acc, metric='test accuracy')
lr 0.3: final loss 0.216, test accuracy 0.900

9.3.4.1 비교 프로토콜과 유의성 임곗값

Deep Learning Tuning Playbook (Godbole 기타 2023년) 을 따라 두 옵티마이저를 공정하게 비교하려면, 임의의 공유 학습률 하나에서 두 옵티마이저를 비교하는 대신 (Schmidt 기타 2021년) 학습률 \(\eta\) 를 각 기법마다 독립적으로 스윕해야 하는 부수 하이퍼파라미터(nuisance hyperparameter)로 취급해야 합니다(공유된 초기 가중치로부터 로그 간격 격자에서 lr_sweep 수행). 각 옵티마이저의 최적 학습률에서 달성된 최소 손실과 함께 유효 학습률 범위(usable learning-rate range)(최적치로부터 \(0.15\) nats 이내로 마치는 격자점들의 구간)도 함께 추적합니다.

잘 튜닝된 학습률에서 \(5\) 개의 독립 무작위 시드에 걸쳐 측정해 보면, TinyLM의 마지막 \(100\) 스텝 학습 손실(final_loss)과 검증 손실은 \(\sim 0.01\text{--}0.015\) nats 범위에서 변동하고, FashionCNN은 학습 손실 \(\sim 0.02\), 테스트 정확도 \(\sim 1\%\) 범위에서 변동합니다. 보수적인 \(3\times\) 변동 폭 마진을 채택하여, 단일 실행에서의 차이는 TinyLM에서 \(0.05\) nats, FashionCNN에서 학습 손실 \(0.06\)(테스트 정확도 \(3\%\))을 초과할 때만 통계적으로 유의미하다고 간주하며, 그보다 작은 차이는 여러 시드에서 검증되지 않는 한 동률로 취급합니다.

9.3.5 요약

본 장의 실험 비교는 상호 보완적인 두 신경망 벤치마크를 짝지어 사용합니다. 첫째는 WikiText-103의 무작위 \(64\)-바이트 윈도 위에서 단일 패스 스트리밍 방식으로 학습하여 \(2{,}000\) 스텝 내내 새로운 텍스트를 평가하는 TinyLM(\(470{,}784\) 개 매개변수: 2차원 투영 행렬 \(90\%\), 임베딩 \(9\%\), 1차원 벡터 \(<1\%\))이고, 둘째는 Fashion-MNIST의 \(256\)-이미지 미니배치에서 \(\sim 8.5\) 에포크 동안 학습하며 학습 손실과 홀드아웃 테스트 정확도로 평가하는 FashionCNN(\(421{,}642\) 개 매개변수)입니다. 닫힌 형식의 균일, 유니그램, 바이그램 바이트 엔트로피는 학습이 시작되기 전 TinyLM 손실 눈금의 기준점 역할을 합니다. 진정한 알고리즘적 개선을 하이퍼파라미터 및 시드 민감도와 분리하기 위해, 모든 비교는 동일한 초기 가중치에서 각 옵티마이저의 학습률 \(\eta\) 를 독립적으로 스윕하며 TinyLM \(0.05\) nats(FashionCNN 손실 \(0.06\) 또는 정확도 \(3\%\))의 다중 시드 유의성 임곗값을 기준으로 최적 손실과 유효 학습률 범위를 함께 보고합니다.

9.3.6 연습 문제

  1. 학습 전 초기 손실.

    1. 로짓 \(z_1, \ldots, z_V\) 가 타깃과 독립적으로 \(\mathcal{N}(0, s^2)\) 에서 i.i.d.로 추출될 때, \(\sum_{i=1}^V e^{z_i} \approx V \mathbb{E}[e^{z_i}] = V e^{s^2/2}\) 를 이용하여 기대 초기 교차 엔트로피가 근사적으로 \(\ln V + s^2 / 2\) 임을 보이십시오.
    2. 평균 \(0\), 분산 \(1\) 인 LayerNorm 출력과 \(\mathcal{U}(-1/\sqrt{128}, 1/\sqrt{128})\) 에서 추출한 헤드 가중치/편향이 주어졌을 때, \(s^2 = 129/384 \approx 1/3\) 이고 \(\ln 256 + 1/6 \approx 5.71\) nats가 되어 TinyLM의 \(1\) 스텝 손실과 일치함을 보이십시오. 헤드 가중치와 편향을 0으로 초기화하면 초기 손실은 얼마입니까?
  2. [code] FashionCNN에서의 손실 곡선 진단. \(\eta \in \{0.003, 0.03, 0.3, 1.0\}\) 에 걸쳐 기본 SGD로 FashionCNN을 학습시키고, 균일 기준선 \(\ln 10 \approx 2.3026\) 과 함께 로그 스텝 축 위에 스텝 손실을 그리십시오. \(\ln 10\) 근처에서 정체되는 실행에 대해 미니배치 전체에서 죽은 ReLU(dead ReLU) 활성화 비율을 조사하여 왜 그레이디언트가 소실되는지 설명하십시오.

  3. [code] TinyLM에서의 발산 경계. \(5\) 개의 시드에 걸쳐 \(\eta \in \{0.7, 1.0, 1.4, 2.0\}\) 에서 기본 SGD로 TinyLM을 스윕하십시오(lr_sweep(..., verbose=False)). 생존율, 발산하는 실행이 무너지는 스텝 번호, 그리고 생존 실행 중 최저 손실을 기록하십시오.

  4. [code] 다중 시드 변동 폭과 표준 오차. ● \(\eta = 3 \times 10^{-3}\)(weight_decay=0)인 AdamW(9.5절)로 TinyLM을 \(20\) 개 시드에서 실행하고, final_loss의 표본 표준편차 \(\sigma\) 를 정규 범위 추정량 \(\text{range}/3.7\) 과 비교한 뒤, 표준 오차의 두 배(\(\sigma\sqrt{2/k}\)) 수준에서 \(0.005\)-nat 차이를 검출하려면 몇 개의 시드 \(k\) 가 필요한지 계산하십시오.

  5. [code] 학습 손실 대 검증 손실 및 소규모 말뭉치 과적합.

    1. TinyLM에서 final_loss(마지막 \(100\) 개 학습 스텝의 평균)가 \(2000\) 스텝 직후 검증 손실보다 약간 더 높은 이유(\(0.02\text{--}0.03\) nats)를 설명하고, 홀드아웃 학습 윈도에서 최종 체크포인트를 평가하여 이를 검증하십시오.
    2. WikiText103(batch_size=64, num_steps=64, num_train=100000)을 통해 말뭉치를 \(100{,}000\) 바이트(\(2{,}000\) 스텝 동안 \(\sim 80\) 에포크)로 제한하고 \(250\) 스텝마다(every=250) 학습 손실 대 검증 손실을 그리십시오.
  6. [code] 빈도 기반 \(n\)-그램 기준선. WikiText103의 첫 \(10^7\) 개 학습 바이트로부터 경험적 바이트 유니그램 엔트로피(\(\sim 3.2\) nats)와 1-가산 평활화된 바이그램(\(\sim 2.5\) nats) 및 트라이그램 교차 엔트로피를 검증 분할 위에서 계산하고, 이를 TinyLM의 \(2{,}000\)-스텝 SGD(약 \(2.1\) nats) 및 AdamW(\(1.59\) nats, 9.5절) 손실과 비교하십시오.

토론