前回は、Multi Head Attentionに関するTwitterの一連のスレッドを紹介した。
Multi Head Attentionの概要を掴む - stMind
今回はGPTについて。
GPT has been a core part of the unsupervised learning revolution that’s been happening in NLP.
— Misha Laskin 🇺🇦 (@MishaLaskin) 2022年1月13日
In part 2 of the transformer series, we’ll build GPT from the ground up. This thread → masked causal self-attention, the transformer block, tokenization & position encoding.
1/N pic.twitter.com/odEG44KFaM
以下、前回同様に自分が理解したメモを残す。
2/n. Multi Head Attentionの振り返り
Attentionは、ネットワークが入力に含まれる全ての単語とその関係を捉えることを可能にする。結果として、ネットワークはその目的を最適化するための最も重要な単語に注意を向ける様になる。
3/n. MHAの最適化
これまでのところ、MHAが最適化する目的を定義していない。GPTでは、非常にシンプルな、次の単語の予測というunsupervisedな目的を用いる。直前までの単語が与えられたら、次の単語を予測する。この目的であればラベルは不要なので、unsupervisedと呼ばれる。
4/n. Causal構造
未来の単語を予測する場合には、直前までの単語だけ参照するCausal構造を強制する必要がある。Causal Attention行列において、0は「関係性なし」を意味し、現在の単語と未来の単語間のAttentionは全て0にする必要がある。そのために、Weights行列()において、未来の単語を-infとする。
5/n. Causal Attention
Weights行列にSoftmaxを適用した後で、未来の単語をマスクして0にすると正規化されなくなる。そのため、Weights行列で未来の単語を-infにしてからSoftmaxを適用する。
6/n. Masked Causal Attention
Masked Causal AttentionがGPTのメインアイデア。GPTのTransformer BlockはMHA→LayerNorm→MLP→LayerNrom。入力shapeは(B, T, D_in)、出力shapeは(B, T, D_out)で、大抵はD_out=D_inとなる。
7/n. Loss
GPTの目的は次の単語の予測であった。英語には約100万語あり、文字通りに単語を予測する場合、100万クラスの分類をすることになる。GPTが最適化するロスを記述する。
loss = cross_entropy(preds, targets) # (B, T, 1e-7)
8/n. Tokens
ロスにおけるクラス数を削減するために、トークンを用いる。トークンは文字とベクトル間のmapで、例えばアルファベットの文字は26個の一意なベクトルで表すことができる(one-hot ベクトル)。文字列からユニークなベクトルへの変換はトークン化(Tokenization)と呼ばれる。
9/n. Byte Pair Encoding
GPTでは、頻度の高い文字グループ(ペア)をトークンにするByte Pair Encoding(BPE)を用いる。以下は、Attention is not too shabbyにBPEを適用して、11個のユニークなトークンになった例(ユニークなCharは12個)。
For simple problems tokenizing each char is OK. But it’s not efficient - char groups like “it” “the” occur frequently so we’d prefer to group them into their own tokens. For this reason, GPT uses Byte Pair Encoding which iteratively clusters common char groups into tokens.
— Misha Laskin 🇺🇦 (@MishaLaskin) 2022年1月13日
9/N pic.twitter.com/JBNhNL6RET
10/n. The order of words
最後の、しかし重要な問題は、今のモデルには語順を知る方法がないということ。
11/n. Positional tokens
語順をエンコードするために、Positional tokensを使用する。文字トークンと同じように、位置をユニークなベクトルで表す。文字と位置のトークンをそれぞれ線形層で変換した後、それらを足し合わせる。その後、Transformerブロックに入力される。
12/n. 実装
We covered masked causal attention, the GPT objective, transformer blocks, tokens & positions. Note: there are ofc many other strategies for tokenization / pos encoding.
— Misha Laskin 🇺🇦 (@MishaLaskin) 2022年1月13日
Putting it all together, here’s the code for the GPT architecture! https://t.co/wy0cM6gIaC
12/N END pic.twitter.com/NQYvGcSAam