最終正規化と重み共有出力ヘッド(\mathbf{E}^\top):正規化されたストリームベクトルを語彙ロジット \mathbf{Z} = \mathrm{Norm}(\mathbf{H}^{(L)})\mathbf{E}^\top \in \mathbb{R}^{B \times T \times V} へ射影し、\mathbf{E} を再利用して V d 個のパラメータ(GPT-2 Small で 38.6\text{M} 個)を節約する
def init_weights(self):"""GPT-2's initialization of the linear layers: N(0, 0.02^2) weights and zero biases; W_o and W_2, which write to the stream, get std 0.02 / sqrt(2L).""" L =len(self.blks)for name, m inself.named_modules():ifisinstance(m, nn.Linear): std =0.02/ (2* L) **0.5if name.endswith( ('W_o', 'W_2')) else0.02 nn.init.normal_(m.weight, std=std)if m.bias isnotNone: nn.init.zeros_(m.bias)
自己回帰の交差エントロピー目的関数
訓練の目的関数
入力ウィンドウ \mathbf{x} = (x_1, \dots, x_T) とシフトされたターゲット \mathbf{y} = (x_2, \dots, x_{T+1}) が与えられたとき、訓練では全 B \times T 個の位置にわたる平均の負の対数尤度を最小化する。
X[0]: 'the European lobster ) a'
Y[0]: 'he European lobster ) an'
[[1 0 0 0 0]
[1 1 0 0 0]
[1 1 1 0 0]
[1 1 1 1 0]
[1 1 1 1 1]]
WikiText-103 におけるバイトレベル言語モデリング
コーパスと初期化の確認
6 ブロックのバイトレベル GPT(V = 256, d = 256, H = 8, L = 6, T = 128、4.79\text{M} パラメータ)を、WikiText-103 の生の UTF-8 バイト列(270\text{M} バイト)上で訓練する。
data = d2l.WikiText103(batch_size=64, num_steps=128)print(f'{len(data.train) /1e6:.0f}M training bytes, 'f'{len(data.val) /1e6:.2f}M validation bytes, 'f'vocabulary of {len(data.vocab)}')
270M training bytes, 1.14M validation bytes, vocabulary of 256
model = gpt(len(data.vocab), max_len=128)loss = math.log(d2l.lm_perplexity(model, [next(data.val_dataloader())]))print(f'{d2l.num_params(model) /1e6:.2f}M parameters; loss before 'f'training {loss:.2f} nats per byte, log 256 = {math.log(256):.2f}')
4.79M parameters; loss before training 5.66 nats per byte, log 256 = 5.55
\tau = 0.7, k = 8 では自然な英単語に確率質量が集中するのに対し、\tau = 2.0 では分布が平坦化して意味不明な文字列に近づく。
T=1.0, top_k=None: 'The history of the 2010 lead in Cecil . The shiwn trees
about his improvement appearances helped attack actual film songs , were
aportimely'
T=0.7, top_k=8: 'The history of the story to the ship wife . \n = = =
Control = = = \n The contrast of the final part of the time , and
interviewers , and the'
T=2.0, top_k=None: 'The history of the
lar��\u038d\u038d���Е�;v���ױ����岙��Ӄ�\x1c,ϐ \n
Trenreodoviti��Ě�\x08q���nve VS ÷tu KopaxodSq ;
�t3nĀohjnetoKcckakizonþon U�6'
事前学習済み OpenAI GPT-2 Small(124M)の読み込み
チェックポイントの読み込み
GPT-2 の 2019 年の設定(norm='layer'、act='gelu'、pos='learned'、bias=True)を d2l.GPT に渡すと、厳密な GPT-2 Small アーキテクチャがインスタンス化される。
text = ("The Time Machine, by H. G. Wells. The Time Traveller was ""expounding a recondite matter to us.")x = torch.tensor(enc.encode(text), device=d2l.try_gpu())[None]with torch.inference_mode(): logits = gpt2(x)loss = F.cross_entropy(logits[0, :-1], x[0, 1:])print(f'per-token loss {loss.item():.2f}, 'f'perplexity {loss.exp().item():.0f}')
per-token loss 3.89, perplexity 49
GPT-2 Small による貪欲生成とサンプリング生成
チェックポイントの検証
Alan Turing theorized that computers would one day become the most powerful
machines on the planet.
The computer is a computer that
The secret of a good deep learning textbook is that it can be read by
anyone. The easiest way to learn a deep learning language is to read the
book, or the software. It's also the easiest way to learn a framework.