본문으로 건너뛰기
9/3030개 중 9장

평균에서 유도하는 Attention과 Transformer Block

context를 가장 싼 요약인 평균에서 시작해 실패 지점을 측정하고, 그 수리를 통해 attention 공식을 끌어냅니다.

이 페이지에서

Chapter 7에서 만든 tokenizer, Chapter 8의 embedding table, 그리고 그것들과 함께 오는 목표를 가지고 여기까지 왔습니다. 지금까지의 tokens가 주어졌을 때 다음 token에 확률을 부여하는 것입니다.

빠진 것은 중간입니다. token tt를 예측하려면 model은 그 앞의 모든 것을 요약하는 하나의 vector가 필요하지만, 지금까지 만든 것 중에는 그런 것을 만들어내는 것이 없습니다. token t1t-1의 embedding은 그것이 아닙니다. 그것은 bigram model이고, 문장이 질문으로 시작했다는 사실을 알 수 없습니다. 이전 embeddings를 모두 이어 붙이는 것도 아닙니다. 그 수는 매 step마다 달라지고, 고정된 weight matrix는 variable-length input을 받을 수 없습니다.

그러니 문제는 이것입니다. 가변 개수의 vectors를 요약하는 하나의 fixed-size vector. 이것이 전체 문제이고, attention은 이 문제를 가능한 한 게으르게 풀고 나서 망가지는 두 가지를 고치면 얻게 되는 것입니다.

이 분야에 있던 답, 그리고 우리가 그것을 만들지 않는 이유

섹션 링크: 이 분야에 있던 답, 그리고 우리가 그것을 만들지 않는 이유

1997년부터 대략 2017년까지 그 요약은 recurrent state였습니다. vector h\mathbf{h}를 유지하고 매 token마다 ht=f(ht1,xt)\mathbf{h}_t = f(\mathbf{h}_{t-1}, \mathbf{x}_t)로 업데이트합니다. fixed size, variable input, 정확히 맞는 모양입니다.

그것은 세 가지 방식으로 실패했고, 이 장의 architecture는 그 셋 모두에 답합니다. TT steps를 거쳐 backpropagation하면 TT Jacobians가 곱해집니다. 그래서 gradient가 사라지거나 폭발합니다. 이는 Chapter 5가 하나의 tanh\tanh node 안에서 측정했던 병입니다. LSTM1은 바로 그것에 맞서 설계되었고, 사용할 수 있는 범위를 수십 step에서 수백 step으로 밀어 올렸지만, token 5의 정보가 token 500에 도달하려면 495개의 sequential updates를 살아남아야 한다는 사실은 바꾸지 못했습니다. 전체 source가 하나의 vector에 들어가야 했습니다. sequence-to-sequence translation2에서는 encoder가 input을 final state로 압축합니다. Bahdanau, Cho, Bengio는 2014년에, transformer보다 3년 앞서, 그 bottleneck에 이름을 붙이고 고쳤습니다. decoder가 직접 계산한 weights로 모든 encoder states의 weighted sum을 취하게 한 것입니다.3 아래의 모든 것은 그 아이디어를 sequence가 자기 자신에게 적용하고 recurrence를 삭제한 것입니다. 그리고 update는 구조상 sequential입니다. ht\mathbf{h}_t에는 ht1\mathbf{h}_{t-1}가 필요하고, 1만 개 cores가 있는 GPU도 그것으로는 아무것도 할 수 없습니다. 이긴 architecture가 명백히 더 똑똑했던 것은 아닙니다. 비싼 step이 matrix multiply인 architecture가 이긴 것입니다.

다른 고전적 inductive bias인 convolution도 여기서는 만들지 않습니다. 작은 filter 하나를 전체 input 위로 slide시켜 어디에서 검출된 feature든 어디에서나 검출되게 하는 방식입니다. 이는 images에는 거의 정확히 맞고, vision course에 맡깁니다. 이 페이지 뒤로는 recurrence도 convolution도 다시 등장하지 않습니다. 그래서 둘 다 chapter를 얻지 못합니다. Chapter 1은 생략을 조용히 넘기지 않고 선언하겠다고 약속했습니다.

가변 개수의 vectors를 받아 하나의 vector를 반환하는 가장 뻔한 함수는 average입니다.

ct=1ti=1txi\mathbf{c}_t = \frac{1}{t}\sum_{i=1}^{t} \mathbf{x}_i

input은 몇 개든 되고, output size는 고정이며, differentiable이고, 공짜입니다. Embedding table에 이 average와 vocabulary로 가는 linear layer를 더하면 15줄짜리 완전한 language model이 됩니다. 또한 끔찍합니다. 그리고 그것이 어떻게 끔찍한지가 전체 derivation입니다.

아래 corpus는 Shakespeare 1메가바이트, 1,115,394 characters이며, Chapter 7에서 만든 종류의 byte-level BPE tokenizer를 vocabulary 1024로 통과시킨 것입니다. 459,760 tokens, token당 2.43 characters이고, 90/10으로 나눴습니다. 모든 model은 width 128이고, 128 tokens를 보며, batch 64로 10310^{-3}에서 AdamW 3000 steps를 학습합니다. Perplexity는 held-out split에서 측정했습니다.4

modelparametersvalidation perplexity
현재 token만 사용, context 전혀 없음263,16859.71
그 앞 모든 것의 uniform average 추가263,168248.07
learned position embeddings 추가279,552245.93
uniform average가 token을 대체하지 않고 token에 더해짐263,16860.45

두 번째 row를 두 번 읽어보세요. context를 평균내는 것은 조금 도움이 안 되는 정도가 아닙니다. context를 완전히 무시하는 것보다 model을 네 배 더 나쁘게 만듭니다. 이유는 둘이며, 둘 다 empirical이 아니라 증명 가능합니다.

Average는 order를 볼 수 없습니다. Addition은 commutative이므로 window를 shuffle해도 summary는 변하지 않습니다. 대략 그런 것이 아니라 정확히 그렇습니다.

order.pyPYTHON
A = torch.tril(torch.ones(T, T))
A = A / A.sum(1, keepdim=True)          # rows of the averaging matrix
y = x[torch.randperm(T)]                # the same tokens, shuffled
print((A[-1] @ x - A[-1] @ y).abs().max().item())
TEXT
2.9802322387695312e-08

재정렬된 sum에서 나는 floating-point noise입니다. 두 summaries는 같은 vector입니다. context를 보는 유일한 시야가 average인 model은 the dog bit the manthe man bit the dog를 구별할 수 없습니다. 세 번째 row는 이것이 inputs에 positions를 더한다고 고쳐지지 않음을 증명합니다. averaging 전에 모든 token에 learned position embedding을 더해도 188점 중 2.14점밖에 얻지 못했습니다. positions는 sum 안으로 들어가고, sum은 그것들을 잊습니다.

그리고 average는 현재를 익사시킵니다. position 100에서 현재 token은 summary의 100분의 1입니다. 이미 가지고 있는 싼 해결책이 있습니다. token을 유지하고 summary를 거기에 더하는 것입니다. Chapter 6의 residual connection이고, 네 번째 row가 그 결과입니다. dilution이 수리되면 uniform average는 아무것도 기여하지 않습니다. baseline 59.71에 대해 60.45입니다. 모든 token이 들어 있고, 모두 똑같이 weight됩니다. 그리고 equal weighting은 정보가 없다는 것과 같습니다.

문제는 averaging이 아닙니다. weights입니다.

Average는 matrix multiply이고, mask는 softmax입니다

섹션 링크: Average는 matrix multiply이고, mask는 softmax입니다

커지는 prefix에 대해 average를 내는 것은 loop처럼 보입니다. 그러나 rows가 1로 sum되는 lower-triangular matrix 하나를 곱하는 것입니다. 그리고 정확히 softmax이기도 합니다.

mechanics.pyPYTHON
loop = torch.stack([x[:t + 1].mean(0) for t in range(T)])   # the obvious version

A = torch.tril(torch.ones(T, T))
A = A / A.sum(1, keepdim=True)
mat = A @ x                                                  # the same thing

S = torch.zeros(T, T).masked_fill(torch.tril(torch.ones(T, T)) == 0, float("-inf"))
soft = F.softmax(S, dim=-1) @ x                              # and the same thing again
TEXT
loop vs matmul   max |diff| = 5.960464477539063e-08
loop vs softmax  max |diff| = 5.960464477539063e-08

the averaging matrix A (rows sum to 1, upper triangle is zero):
  1.000 0.000 0.000 0.000 0.000 0.000
  0.500 0.500 0.000 0.000 0.000 0.000
  0.333 0.333 0.333 0.000 0.000 0.000
  0.250 0.250 0.250 0.250 0.000 0.000
  0.200 0.200 0.200 0.200 0.200 0.000
  0.167 0.167 0.167 0.167 0.167 0.167

transformer의 세 가지 named components가 이제 화면에 있습니다. triangle은 causal mask이며, objective가 강제합니다. position tt가 position t+1t{+}1를 볼 수 있다면 답이 input 안에 있게 됩니다. Chapter 6이 감사하라고 했던 leak이 architecture 내부에 있는 것입니다. softmax는 mask가 구현되는 방식입니다. forbidden entries를 -\infty로 설정하면 정확히 zero가 되고 남은 것을 normalise하므로, masking과 normalising은 하나의 operation입니다. (-1e9가 아니라 -\infty를 쓰세요. 그것이 masking이 의미하는 값이고, float16으로 cast해도 -\infty로 살아남으며, 우연히 있는 range에서 고른 constant가 충분히 큰지 판단하지 않아도 되게 해줍니다. 이는 Chapter 2의 floating-point 상자가 답하지 않아도 되는 질문을 던지는 상황입니다.) 그리고 scores는 자유 parameter입니다. uniform average는 허용된 모든 score가 같은 number일 때 얻는 것입니다. 아무 numbers나 넣으면 softmax가 그것들을 valid weights로 바꿉니다.

이 장의 나머지는 하나의 질문입니다. 그 numbers는 어디에서 오는가?

그것들은 plain parameters일 수 없습니다. learned T×TT \times T matrix는 모든 sentence에서 동일할 것입니다. "네 tokens 뒤를 보라"는 encode할 수 있어도, "이 pronoun이 가리키는 noun을 보라"는 결코 encode할 수 없습니다. position tt와 position ii를 연결하는 weight는 positions에 무엇이 있는지에 의존해야 합니다. relevance는 property가 아니라 relation이기 때문입니다. 단어 it은 본질적으로 relevant한 것이 아니라, 어떤 것에 대해 relevant합니다.

두 vectors를 받아 number를 반환하는 가장 싼 함수는 Chapter 1의 dot product입니다. position ii를 position tt에 대해 xtxi\mathbf{x}_t \cdot \mathbf{x}_i로 score하면 mechanism은 작동합니다. 두 가지 방식으로 나쁘게 작동하며, 그 둘이 나머지 모든 것을 강제합니다. vector와 자기 자신의 dot product는 squared norm이므로 모든 token은 대부분 자기 자신에 attend할 것입니다. 그리고 relation이 symmetric입니다. itanimal에 강하게 attend하면 animalit에 강하게 attend합니다. 이는 language에 대해 거짓입니다. adjective는 noun을 필요로 하는 정도가 noun이 adjective를 필요로 하는 정도보다 훨씬 큽니다.

그래서 각 token에 두 역할을 줍니다. 그것의 두 learned linear maps입니다. 이 position이 찾고 있는 것, qt=Wqxt\mathbf{q}_t = W_q\mathbf{x}_t, 즉 query. 그리고 그것이 찾아지기 위해 제공하는 것, ki=Wkxi\mathbf{k}_i = W_k\mathbf{x}_i, 즉 key입니다. qtki\mathbf{q}_t \cdot \mathbf{k}_i로 score하면 symmetry는 사라집니다. WqWkW_q \neq W_k이기 때문입니다. token은 하나를 광고하고 다른 것을 검색할 수 있습니다.

하나가 아직 틀렸습니다. weighted sum은 xi\mathbf{x}_i 자체에 대해 이루어졌고, 이는 copy되는 것이 match되는 것과 같아야 함을 강제합니다. Matching은 token을 식별하는 features를 원합니다. Copying은 downstream에 유용한 features를 원합니다. 그래서 세 번째 map vi=Wvxi\mathbf{v}_i = W_v\mathbf{x}_i, value를 학습하고 그것들을 sum합니다.

이제 formula는 bookkeeping입니다.

Attention(Q,K,V)=softmax ⁣(QKdk+M)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V

여기서 MM은 causal mask이고, diagonal 위는 -\infty, diagonal과 그 아래는 zero입니다. code로는 30줄이고, 그중 20줄은 shapes입니다.

attention.pyPYTHON
class Head(nn.Module):
    """One head of causal self-attention."""

    def __init__(self, d_model, d_head, block):
        super().__init__()
        self.q = nn.Linear(d_model, d_head, bias=False)      
        self.k = nn.Linear(d_model, d_head, bias=False)      
        self.v = nn.Linear(d_model, d_head, bias=False)      
        self.d_head = d_head
        self.register_buffer("mask", torch.tril(torch.ones(block, block)).bool())

    def forward(self, x):
        T = x.shape[1]
        q, k, v = self.q(x), self.k(x), self.v(x)
        s = q @ k.transpose(-2, -1) / math.sqrt(self.d_head)          
        s = s.masked_fill(~self.mask[:T, :T], float("-inf"))          
        w = F.softmax(s, dim=-1)                                      
        return w @ v                                                  

Score, mask, normalise, mix. 나머지는 전부 projection입니다.

Square root로 나누는 것, 그리고 그것이 막아주는 것

섹션 링크: Square root로 나누는 것, 그리고 그것이 막아주는 것

dk\sqrt{d_k}에 대한 거의 모든 설명은 "softmax가 saturate하지 않게 하려고"라고 말합니다. 맞지만 아무것도 설명하지 않습니다. 논증은 Chapter 2의 variance 두 줄입니다. q\mathbf{q}k\mathbf{k}의 entries가 mean zero, variance one으로 independent라면, 각 product qjkjq_j k_j는 variance one이고 independent한 것들의 variances는 더해집니다.

Var(qk)=j=1dkVar(qjkj)=dk\mathrm{Var}(\mathbf{q}\cdot\mathbf{k}) = \sum_{j=1}^{d_k}\mathrm{Var}(q_j k_j) = d_k

그래서 scores의 standard deviation은 dk\sqrt{d_k}입니다. 2만 개 random pairs에서 측정하면 다음과 같습니다.

TEXT
     d     Var(q.k)         std   sqrt(d)
     4        3.975       1.994     2.000
    16       16.071       4.009     4.000
    64       64.249       8.016     8.000
   256      253.065      15.908    16.000
  1024     1015.562      31.868    32.000

왜 이것이 중요한가. softmax는 linear layer와 달리 scale-sensitive합니다. linear layer의 input을 두 배로 하면 output도 두 배가 됩니다. softmax 전에 scores를 10배로 곱하면 부드러운 blend가 hard choice로 바뀝니다. 64개 scores로 된 한 row를 division 유무에 따라 보면 다음과 같습니다.

dkd_klargest weight, undividedentropyeffective tokenslargest weight, dividedentropyeffective tokens
40.2052.94419.00.0813.75842.9
160.4381.6925.40.0753.84946.9
640.4890.8742.40.0853.67339.4
2560.99990.00071.00.1433.54734.7
10241.00000.00001.00.1323.64438.3

"Effective tokens"는 entropy의 exponential입니다. row가 실제로 몇 positions에 걸쳐 average하는지를 뜻합니다. 나누지 않으면 dk=256d_k = 256에서 갓 initialised된 head가 64개 중 정확히 하나의 token에 attend합니다. random draw 말고는 아무것도 선택 이유가 없습니다.

이는 forward에서도 나쁘고 backward에서는 더 나쁩니다. Chapter 5가 이미 tanh\tanh에서 측정한 모양입니다. 한 entry에 committed된 softmax는 derivative가 거의 없습니다. Jacobian의 diagonal은 wi(1wi)w_i(1-w_i)이고, 양끝에서 zero입니다. 2천 개 random rows에서 보면 다음과 같습니다.

dkd_kiwi(1wi)\sum_i w_i(1-w_i) undivideddividedrows saturated (largest weight above 0.99)
40.84270.95680.2 % → 0.0 %
640.29400.960917.9 % → 0.0 %
2560.14060.960949.1 % → 0.0 %
10240.06810.961170.4 % → 0.0 %

dk=1024d_k = 1024에서는 열 row 중 일곱 row가 training이 시작되기 전에 frozen이고, frozen으로 시작한 head는 무엇을 볼지 학습할 수 없습니다. 나누면 그 quantity는 모든 width에서 0.96으로 flat하고 아무것도 saturate하지 않습니다.

이제 아무도 publish하지 않는 부분입니다. 최종 perplexity를 바꾸는가? division을 지우고 네 가지 head widths에서 학습합니다.

head widthundivideddivided by dk\sqrt{d_k}divided by dkd_k
four heads, dk=32d_k = 3237.2938.0737.89
one head, dk=128d_k = 12848.5146.1045.99
one head, dk=256d_k = 25665.3747.53
one head, dk=512d_k = 51267.0649.15
one head, dk=1024d_k = 102476.6959.17

처음 두 rows는 위의 3000-step budget에서 왔습니다. 마지막 세 rows는 더 짧은 run입니다. 1500 steps, batch 32, one head, projections 전에 normalisation 없음, 두 variants 모두 동일한 settings입니다.

dk=32d_k = 32에서는 division이 아무 가치도 없고, 그것 없이 돌린 run이 아주 조금 앞섭니다. 그렇다고 그것을 빼도 된다는 licence는 아닙니다. 256에서는 perplexity 18점의 가치가 있고, 1024에서는 17점의 가치가 있기 때문입니다. mechanism은 scores 자체에서 보입니다.

dkd_kscore std at initafter 1500 steps, undividedafter 1500 steps, dividedrows saturated, undivideddivided
25610.49121.672.1391.9 %0.8 %
51215.13836.852.6698.7 %1.3 %
102421.155147.463.4499.9 %16.5 %

undivided head는 회복하지 않습니다. 그것은 폭주합니다. scores의 standard deviation은 initialisation에서 21이었다가 5147이 되고, attention entropy는 zero로 떨어지며, rows의 99.9 %가 weight의 0.99 이상을 하나의 token에 둡니다. head가 hard selector가 되고 나면 gradient는 거의 zero이고 아무것도 그것을 되돌리지 못하므로 collapse는 stable합니다. divided head는 같은 training 뒤에 score standard deviation 3.44에 머무릅니다. 여전히 바뀔 수 있는 soft blend입니다.

Vaswani et al.은 정확히 이 말만 하고 더 말하지 않습니다. products가 dkd_k의 큰 값에서 "grow large in magnitude"할 것이라 의심하고 나눕니다.5 large라는 단어가 하중을 지탱하고, tables는 large가 어디서 시작되는지를 말합니다. 32에서는 아무 일도 없고, 256쯤이면 전부입니다.

하나보다 많은 의견, 그리고 아무도 말하지 않는 3분의 2

섹션 링크: 하나보다 많은 의견, 그리고 아무도 말하지 않는 3분의 2

one head는 position당 one softmax row이므로 "여기서 무엇이 relevant한가"에 대한 하나의 답을 담습니다. the animal that crossed the wet street에서 the 뒤의 word를 예측하려면 syntactic slot, subject, previous token이 동시에 필요하고, 하나의 probability distribution은 세 곳에 동시에 concentrated될 수 없습니다. 그래서 여러 heads를 parallel로 돌리고, 각각 width dmodel/hd_{\text{model}}/h를 갖게 하며, concatenate한 뒤 matrix WoW_o 하나로 더 mix합니다. width를 partition한 것이지 더한 것이 아닙니다.

Attention은 또한 정확히 한 가지 일을 합니다. positions 사이에서 information을 옮깁니다. 위 code의 모든 operation은 feature axis를 따라 linear이고, Chapter 5는 linear maps를 stack하면 무엇이 되는지 증명했습니다. 그래서 각 block은 각 position에 독립적으로 적용되는 작은 MLP도 가지고 있습니다. width를 네 배로 확장했다가 돌아오며, 중간에 GELU가 있습니다. 역할 분담은 외워둘 만합니다. attention은 positions를 가로질러 mix하고, feed-forward network는 한 position 안에서 compute합니다.

전체 ladder는 다음과 같습니다. 각 row는 그 위 row에 하나의 piece를 더합니다.

modelparametersvalidation perplexity
uniform average, added279,55260.45
one attention head, replacing the token328,70455.47
one attention head, added328,70446.10
four heads instead of one345,21643.21
plus the feed-forward network476,92839.87
plus LayerNorm — the complete block477,69638.07

Learned weights는 uniform ones를 perplexity 14점 차이로 이깁니다. 이것이 이 장의 전체 argument가 한 row에 담긴 것입니다. four heads는 extra parameters 16,512개로 또 3점을 삽니다. 그리고 같은 head도 replacing보다 added일 때 9점 더 가치 있습니다. attention은 information을 가져오는 것이지, position이 무엇인지 결정하지 않습니다.

이제 parameters가 실제로 어디에 있는지 봅니다. diagram만 본 사람들은 놀랍니다.

widthheadsattentionfeed-forwardtotal per block
128465,664 (33.2 %)131,712 (66.6 %)197,888
768122,360,064 (33.3 %)4,722,432 (66.6 %)7,085,568
40963267,112,960 (33.3 %)134,238,208 (66.7 %)201,367,552

모든 transformer block의 3분의 2는 feed-forward network입니다. 모든 scale에서 그렇습니다. attention에는 d×dd \times d matrices가 네 개 있고, MLP에는 그 두 배에 해당하는 여덟 개가 있기 때문입니다. model이 무엇을 알고 있든, 그것을 보관하는 parameters의 대부분은 per-position MLP 안에 있습니다.

Chapter 6에서 물려받은 residuals와 LayerNorm

섹션 링크: Chapter 6에서 물려받은 residuals와 LayerNorm

LayerNorm은 Chapter 6에서 만들어지고 측정되었고, 이 장은 그것을 거기서 남긴 그대로 사용합니다. residual connections도 거기서 이름 붙이고 ablate했으며, 여기서 만듭니다. 위의 "added, not replacing" rows는 residual connections이고, average에서는 perplexity 188점, one head에서는 9점의 가치가 있습니다. LayerNorm7은 각 example을 features에 걸쳐 normalise합니다. Chapter 6은 왜 BatchNorm이 아니라 이것이 여기서 살아남았는지 이유를 제시했습니다. batch에 dependence가 없고, running statistics가 없으며, training과 inference에서 동일하고, sequence length에 무관합니다. 이 모든 것은 Chapter 13이 도달하는 지점, 즉 한 user에게 token을 하나씩 generate할 때 requirement가 됩니다. 비용은 768 parameters이고 perplexity 1.8점을 삽니다.

block.pyPYTHON
class Block(nn.Module):
    def forward(self, x):
        x = x + self.att(self.ln1(x))     
        x = x + self.ff(self.ln2(x))      
        return x

normalisation이 어디에 있는지 보세요. 각 sub-layer의 input에 있고, input에서 output으로 가는 residual path는 절대 normalise되지 않습니다. 이것이 pre-norm입니다. 2017년 paper는 반대로 합니다. x = LayerNorm(x + Att(x)), 즉 post-norm이며, LayerNorm을 residual path 자체에 둡니다.

Xiong et al.은 initialisation에서의 gradient를 통해 그 차이를 설명했습니다. post-norm network에서는 depth에 따라 badly scaled되며, 이것이 original transformer가 학습하려면 learning-rate warmup이 필요했던 이유입니다.8 12 blocks, 1000 steps, learning rate 3×1033 \times 10^{-3}:

TEXT
gradient norm per block at initialisation, before any step
  pre-norm    block 1 0.0498 ... block 12 0.0657   ratio last/first  1.32
  post-norm   block 1 0.0977 ... block 12 0.1613   ratio last/first  1.65

  pre-norm,  no warmup          perplexity   37.82
  pre-norm,  200-step warmup    perplexity   37.62
  post-norm, no warmup          perplexity  308.05
  post-norm, 200-step warmup    perplexity   37.88

warmup 없는 post-norm은 여덟 배 더 나쁘고, warmup이 있는 post-norm은 pre-norm과 정확히 맞습니다. 여기서 warmup은 일반적인 좋은 practice가 아닙니다. normalisation의 특정 arrangement에 대한 patch이고, LayerNorm을 옮기면 그것이 필요 없어집니다. 그래서 2019년 이후 거의 모든 model이 pre-norm이고, 2017년 diagram은 specification이 아니라 history로 읽어야 합니다.

position embeddings를 삭제해도 model은 여전히 학습됩니다. 단지 무엇이 어디에 있는지 알 수 없을 뿐이고, 이는 training failure가 아니라 symmetry입니다. attention score 안에는 ttii 자체가 전혀 언급되지 않으므로 input을 permute하면 output도 permute됩니다. self-attention은 permutation-equivariant입니다. 더 나은 disguise를 쓴 average의 order-blindness입니다. causal mask가 어느 정도 order를 복구합니다. 각 position이 다른 prefix를 보기 때문입니다. 하지만 prefix 안에서는 모든 orderings가 같습니다.

position을 주입하는 네 가지 방법을 64-token windows에서 학습하고, 본 적 없는 길이인 64, 128, 256에서 평가했습니다.

positionsperplexity at 64at 128at 256
none at all48.7952.6357.52
learned absolute embeddings38.63108.47181.94
fixed sinusoids42.9695.26152.25
RoPE44.1250.5284.84
ALiBi44.9543.5142.49

Learned absolute embeddings는 token에 더해지는 position당 하나의 vector입니다. 학습된 length에서는 이기고 그 뒤에는 절벽에서 떨어집니다. position 100은 batch 안에 있었던 적이 없고, 그 embedding은 시작할 때의 random vector 그대로이기 때문입니다. Sinusoids는 original choice였고, learned가 아니라 geometrically spaced frequencies의 sines와 cosines에서 computed됩니다. 2017년 paper는 이것이 extrapolate하기를 바랐지만, table은 그렇지 않다고 말합니다. function은 position 200에서 정의되어 있지만, model은 거기서 그것을 읽는 법을 학습한 적이 없습니다. RoPE9는 아무것도 더하지 않고, 대신 query와 key를 position에 proportional한 angle로 two-dimensional slices 안에서 rotate합니다. dot product의 양쪽을 똑같이 rotate하면 값이 변하지 않으므로, score는 결국 tit - i에만 의존합니다. 그래서 position은 공짜로 relative가 되고, 다 써버릴 table이 없습니다. degrade되지만, 그래도 degrade됩니다. ALiBi10는 여기서 가장 단순하고도 가장 이상한 결과입니다. distance에 proportional한 linear penalty on the score이고, head마다 다른 slope를 가집니다. window가 training length를 지나 커질수록 perplexity가 44.95에서 42.49로 개선됩니다. penalty는 어떤 distance에서도 정의되어 있고 모든 head가 학습된 일을 계속하기 때문입니다.

lesson은 table보다 오래갑니다. architecture가 무언가를 represent할 수 없는 문제와, 그 range를 결코 learned하지 못한 문제는 서로 다릅니다. 그리고 물어뜯는 것은 두 번째입니다. 이것은 모든 "context를 128K로 확장했다" 발표 뒤의 machinery이기도 합니다. 그것들은 거의 항상 rotary encoding의 re-scaling이고, Chapter 16이 context limit은 사라지는 것이 아니라 움직인다고 말하는 이유입니다.

Dropout도 같은 방식으로 물려받습니다. softmax 뒤의 attention weights, residual addition 전 각 sub-layer의 output, embedding sum에 나타나며, Chapter 6이 설명한 바로 그 일을 합니다. large pretraining runs에서는 종종 zero로 설정됩니다. 각 token을 한 번만 보는 model은 overfit할 처지가 아니기 때문입니다.

layer 안의 두 tensors는 shape이 n×nn \times n입니다. 여기서 nn는 tokens 수입니다. scores와 softmax 뒤의 weights입니다. 그 밖의 모든 것, 즉 모든 projection과 전체 MLP는 nn에 linear입니다.

attention layer 하나, width 512, 8 heads, batch one, float32, laptop GPU에서 측정했습니다. 두 millisecond columns는 ratios만 읽으세요. 8 GB laptop card의 wall clock이고, 뜨거워지면 1,785 MHz에서 300 MHz 아래로 throttle합니다. 그래서 같은 code의 cold run은 7배에서 10배 빠르게 돌아오고, busy run은 더 느립니다. megabyte columns는 allocator byte counts이고 움직이지 않습니다.

TEXT
  tokens   ms total    ms x4   ms projections   attn matrix MB    peak MB    MB x4
     128      2.246        -            1.324              0.5       14.6        -
     256      2.855     1.27            2.113              2.0       19.2     1.31
     512      5.761     2.02            3.105              8.0       34.4     1.79
    1024     16.414     2.85            4.008             32.0       89.1     2.59
    2048     51.573     3.14            9.989            128.0      296.1     3.32
    4096    225.432     4.37           20.176            512.0     1100.1     3.72
    8192    832.838     3.69           40.106           2048.0     4300.1     3.91
   16384   OUT OF MEMORY                                 8192.0

fitted exponent (log-log slope, last four rows):  time ~ n^1.91   memory ~ n^1.87

x4 columns는 바로 위 row 대비 ratio이고, nn를 double하면 time과 memory 모두 정확히 4로 수렴합니다. 마지막 step에서 theoretical 4에 대해 3.91입니다. projections column은 control입니다. 1024 tokens에서 4.0 ms, 8192에서 40.1 ms로, factor eight에 대해 factor ten입니다. 말한 대로 linear입니다.

그리고 마지막 row입니다. attention layer 하나, sequence 하나, 그 주변에 model도 없는데, 16,384 tokens에서 8 GB GPU의 memory가 바닥납니다. score matrix만 8 GB입니다. 8 heads × 16,384 × 16,384 × 4 bytes이기 때문입니다. model이 아닙니다. 한 layer 안의 intermediate tensor 하나입니다.

이것이 뒤의 세 chapters 아래에 놓인 물리적 사실입니다. context window에 limit이 있는 이유이고, Chapter 16은 그것을 price로 바꿉니다. FlashAttention이 존재하는 이유이기도 합니다. matrix를 절대 저장하지 않고 tiles로 같은 결과를 계산하며, speed optimisation이기 전에 memory optimisation입니다.11 또한 long prompt의 price 뒤에 있는 arithmetic이기도 합니다. Chapter 24는 agent loop에서 그 값을 치릅니다. 이는 그 chapter의 다른 발견, 즉 model이 long context를 더 나쁘게 사용한다는 것과는 별개의 문제이며, 그 chapter는 그것을 측정하고 이 formula 탓으로 돌리지 않습니다.

세부 정보 보기

두 가지 cache-shrinking variants, 여기서 이름 붙이고 Chapter 13에서 비용을 계산합니다.

Generation은 이미 처리된 tokens의 keys와 values를 cache합니다. token당 하나의 key와 하나의 value, head당 layer당입니다. Multi-query attention12hh query projections를 유지하지만 모든 heads가 공유하는 single key와 value projection을 사용해 그 cache를 hh로 나눕니다. Grouped-query attention13은 그 사이를 보간합니다. heads를 group으로 묶고, 각 group이 하나의 key와 value를 공유합니다. 그래서 g=hg = h은 ordinary attention이고 g=1g = 1는 multi-query입니다. 2023년 이후 거의 모든 open model은 4 또는 8 groups로 이것을 사용합니다. 둘 다 quality를 위해 존재하지 않습니다. 둘 다 그 cache의 size를 위해 존재하고, Chapter 13은 그것을 "어떤 model이 당신의 GPU에 들어가는가"로 바꾸는 arithmetic을 합니다.

두 가지 모양, 그리고 하나의 크기

섹션 링크: 두 가지 모양, 그리고 하나의 크기

2017년 paper는 encoder-decoder를 설명합니다. source를 unmasked attention으로 읽는 stack 하나, target을 causally generate하는 두 번째 stack, 그리고 decoder의 queries가 encoder의 keys를 만나는 가운데의 세 번째 종류의 attention입니다. input과 output이 두 sequences인 translation에는 맞습니다.

이긴 것은 decoder-only half였습니다. 하나의 stack, 전부 causal, input과 output이 같은 sequence입니다. 이유는 elegance가 아닙니다. "다음 token을 예측하라"는 어떤 text에서도 돌아가므로 training set은 parallel corpus가 아니라 internet이 되고, 모든 것이 그 하나의 task가 됩니다. translation은 source 다음 target이 들어 있는 document이고, question과 answer도 document이며, 중간에 tool call이 있는 conversation도 document입니다. Chapter 11은 마지막 것이 어떻게 제조되는지에 관한 장입니다. Encoders는 사라지지 않았습니다. encoder는 input 전체를 한 번에 보며, 이는 job이 text를 계속하는 것이 아니라 represent하는 것일 때 원하는 것입니다. 그래서 Chapter 19의 retrieval embeddings는 chatting을 하는 model이 아니라 encoders에서 나옵니다.

block이 정의되었으니 model size는 arithmetic입니다. width dd이고 four-times expansion일 때 block당: GPT-2처럼 네 개 모두에 biases가 있는 Wq,Wk,Wv,WoW_q, W_k, W_v, W_o에 대해 4d2+4d4d^2 + 4d입니다. 위 table은 그중 셋에서 bias를 뺐으므로 d=768d = 768에서 block당 2,304개 더 적습니다. MLP에 8d2+5d8d^2 + 5d, 두 LayerNorms에 4d4d입니다. 즉 12d2+13d12d^2 + 13d, 여기에 token table V×dV \times d와, absolute positions라면 nctx×dn_{\text{ctx}} \times d를 더합니다. GPT-2 small의 shape, 즉 d=768d = 768, 12 blocks, vocabulary 50,257, context 1024, output layer가 embedding weights를 공유하는 경우:

TEXT
  token embeddings     50,257 x 768 = 38,597,376
  position embeddings   1,024 x 768 =    786,432
  one block                             7,087,872
  12 blocks                            85,054,464
  final LayerNorm         2 x 768 =        1,536
  total (weights tied)                124,439,808

이것이 그 model의 published size입니다. formula는 approximation이 아닙니다. 그것이 model입니다. 또한 small model의 거의 3분의 1이 embedding table이라는 점도 보세요. 그래서 vocabulary size는 preprocessing 결정이 아니라 architectural decision입니다. Chapter 7이 설정한 trade-off입니다.

Head는 실제로 무엇을 보는가

섹션 링크: Head는 실제로 무엇을 보는가

Perplexity는 corpus에 관한 number입니다. head 하나가 무엇을 하는가는 다른 question이고, Shakespeare 1메가바이트로 학습한 model은 그것에 맞는 instrument가 아닙니다. 500,000-parameter model의 attention map에 대해 정직하게 말할 수 있는 것은 대부분 interpretable하지 않다는 것입니다. 그러니 right answer가 있는 language를 봅니다.

고전적 illustration은 the animal did not cross the street because it was too tired입니다. 여기서 it은 animal입니다. 반대로 …because it was too wet에서는 한 word가 referent를 street으로 옮깁니다. 이것들은 Winograd schemas14입니다. 한 word만 다르고 그 word가 pronoun이 무엇을 가리키는지 결정하는 sentence pairs입니다.

그것들은 또한 cheating으로 풀 수 있습니다. tutorials가 건너뛰는 부분입니다. 두 candidates가 animal과 place라면, tiredwetcategory로 referent를 식별합니다. 그리고 어떤 words가 있는지만 아는 model도 order를 전혀 모르면서 정답을 맞힙니다. animal/place pairs를 held-out으로 둔 그 버전의 task에서 측정하면 다음과 같습니다.

TEXT
uniform causal average           held-out referent accuracy 100.0 %
one transformer block            held-out referent accuracy  91.7 %

bag of words가 transformer를 이깁니다. 그 sentence 위에 세운 demonstration은 attention에 대해 아무것도 증명하지 않습니다.

그래서 구멍을 막습니다. candidates를 16 nouns의 한 pool에서 뽑고, 둘 중 어느 것이든 어느 slot에든 올 수 있게 하며, adjectives를 category가 아니라 role로 나눕니다. 네 개는 it을 crosser로 만듭니다(tired, scared, slow, weak). 네 개는 it을 crossed로 만듭니다(wet, wide, busy, steep).

TEXT
the {x} did not cross the {y} because it was too {adj} , so the {ref} waited .

ordinary next-token predictor로 학습하고, 한 position, 즉 so the 다음 word만 score합니다. held-out set은 reversed order가 training에 있었던 noun pairs로 만듭니다. 그래서 어떤 두 nouns가 있는지는 알지만 무엇이 먼저 나왔는지 모르는 것은 반드시 거꾸로 답해야 합니다.

modelparametersheld-outnames the other noun
current token only5,7965.2 %5.2 %
uniform causal average5,79627.9 %50.0 %
one head of learned attention18,08435.4 %64.6 %
four heads22,24475.0 %15.6 %
one transformer block55,71692.7 %4.2 %
two transformer blocks105,508100.0 %0.0 %

present한 두 nouns 사이의 chance는 50 %입니다. uniform average는 27.9 %에 도달하고, pair의 wrong noun을 정확히 절반의 경우에 답합니다. 이는 어떤 words가 있는지는 알지만 order에 대해서는 아무것도 모르는 것의 signature입니다. 세 sections 전에 shuffle test가 예측한 그대로입니다.

이제 map입니다. referent를 이름 붙여야 하는 position에서의 attention을 각 block의 네 heads에 대해 평균낸 것입니다. 한 word만 다른 두 sentences입니다. uniform average라면 보이는 15 tokens 각각에 0.067을 둘 것입니다.

TEXT
the animal did not cross the street because it was too tired , so the animal waited .
  blk 1  the:0.00 animal:0.70 did:0.00 not:0.00 cross:0.00 the:0.00 street:0.06
         because:0.00 it:0.00 was:0.00 too:0.00 tired:0.00 ,:0.05 so:0.00 the:0.19
  blk 2  the:0.00 animal:0.00 did:0.00 not:0.00 cross:0.00 the:0.00 street:0.00
         because:0.00 it:0.00 was:0.00 too:0.00 tired:1.00 ,:0.00 so:0.00 the:0.00

the animal did not cross the street because it was too wet , so the street waited .
  blk 1  the:0.00 animal:0.70 did:0.00 not:0.00 cross:0.00 the:0.00 street:0.06
         because:0.00 it:0.00 was:0.00 too:0.00   wet:0.00 ,:0.05 so:0.00 the:0.19
  blk 2  the:0.00 animal:0.00 did:0.00 not:0.00 cross:0.03 the:0.00 street:0.49
         because:0.00 it:0.00 was:0.00 too:0.20   wet:0.03 ,:0.00 so:0.00 the:0.25

Block 1은 두 sentences에서 identical합니다. adjective가 무엇이든 first noun에 0.70입니다. 이것은 failure가 아니라 proof입니다. 첫 layer에서 position의 query는 그 position 자체의 token과 index의 function이고, position 14의 the는 두 sentences에서 같은 token입니다. first-layer head는 아직 fetch하지 않은 word에 condition할 수 없습니다. 그래서 block 1은 가능한 유일한 유용한 일을 하고, first noun을 앞으로 끌고 옵니다.

Block 2에서 sentences가 갈라지고, 모든 여덟 adjectives에 걸친 같은 row가 model이 찾은 rule을 보여줍니다.

adjectiveblock 2 on animalon streeton the adjectiveanswer
tired, scared, slow, weak0.0000.0001.000animal
wet, wide, busy, steep0.0000.4910.00–0.03street

crosser-adjective의 경우 두 번째 block은 weight 전체를 adjective에 씁니다. answer가 이미 residual stream 안에 있기 때문입니다. block 1이 그것을 거기에 넣었습니다. 이제 필요한 것은 confirmation뿐입니다. crossed-adjective의 경우에는 대신 다른 noun을 fetch하러 갑니다. 이것은 two-hop circuit입니다. 한 head가 candidate를 앞으로 옮기고, later layer의 head가 keep할지 결정하는 token을 읽습니다. layers를 가로지르는 composition이 mechanism이고, one block이 92.7 %, two blocks가 100 %에 도달한 이유입니다.

이는 real models에서 가장 잘 documented된 circuit의 모양이기도 합니다. Induction heads — previous-token head가 다음 layer의 head에 feed하여 pattern [A][B] … [A] → [B]을 완성하는 것 — 는 Anthropic의 interpretability work가 in-context learning의 큰 부분 뒤에 있다고 식별한 것이며, pretraining 중 식별 가능한 순간에 형성됩니다. 이 장은 그 analysis를 시도하지 않습니다. real model에서 circuits를 읽어내는 것은 section이 아니라 research field이므로, 두 papers를 references에 두고 위임합니다.

마지막으로 implementation입니다. 위의 30줄 code에 PyTorch 자체의 weights를 복사했습니다.

TEXT
ours vs nn.MultiheadAttention           max |diff| = 1.7881393432617188e-07
ours vs F.scaled_dot_product_attention  max |diff| = 1.7881393432617188e-07

mean magnitude가 0.159인 outputs에서 1.8×1071.8 \times 10^{-7}입니다. 다른 order로 한 같은 arithmetic이며, float32 precision입니다.

이제 이 course의 나머지 모든 model이 기반으로 삼는 architecture를 가지고 있습니다. 그리고 그것은 명성보다 작습니다. weights가 learned되는 weighted average, parameters의 3분의 2를 담는 per-position MLP, 두 normalisations와 두 additions, 그리고 stack입니다.

아직 없는 것은 무엇이든 아는 model입니다. stack한다고 그것이 저절로 고쳐지지는 않습니다. 이 corpus에서 two blocks는 training perplexity 14.49와 validation perplexity 40.57에 도달합니다. one block의 18.77과 38.07에 비해, 본 것에서는 더 좋은 capacity, 보지 못한 것에서는 더 나쁜 결과입니다. transformer를 넣은 Chapter 6의 table입니다. 이 model과 Chapters 14 to 30이 대화하는 models 사이의 거리는 architectural한 것이 아닙니다. 같은 block을 훨씬 더 많이 반복하고, 엄청나게 더 많은 text 위에서 학습한 것입니다.

그래서 이것은 accounting problem이 됩니다. 그리고 그 accounting은 보기보다 이상합니다. text는 얼마나 필요하고, 사람들은 그것을 어디서 얻는가? arithmetic은 얼마나 필요하며, 돈을 쓰기 전에 그것을 어떻게 estimate하는가? fixed budget이 주어졌을 때 model을 더 크게 만드는 것이 나은가, 아니면 더 많은 data를 보여주는 것이 나은가. 그리고 correct answer가 있는가, 아니면 fashion뿐인가? Chapter 10은 세 가지 모두를 measurement로 답하고, question의 가장 싼 useful form에 price를 붙입니다. 오늘, GPT-2 같은 model을 처음부터 train하는 데 비용이 얼마인가?


이 material에 대한 세 가지 설명은 각자의 목적에서 이 글보다 낫고, 이 장은 그것들과 함께 읽히도록 쓰였습니다. Jay Alammar의 The Illustrated Transformer는 data flow를 그린 최고의 그림입니다. Harvard NLP의 The Annotated Transformer는 2017년 paper에 실행 code를 line by line으로 끼워 넣은 것입니다. Andrej Karpathy의 Let's build GPT: from scratch, in code, spelled out는 같은 model을 두 시간 동안 live로 처음부터 만들며, 위 ablations의 ladder는 다른 corpus에서 측정한 같은 spine입니다. 이 장이 살짝만 다루는 interpretability question에 대해서는 Anthropic interpretability group의 Elhage et al., A Mathematical Framework for Transformer Circuits (2021)와 Olsson et al., In-context Learning and Induction Heads (2022)가 primary sources입니다.

  1. Hochreiter, S. and Schmidhuber, J. Long Short-Term Memory. Neural Computation 9(8), pp. 1735–1780 (1997).

  2. Sutskever, I., Vinyals, O. and Le, Q. V. Sequence to Sequence Learning with Neural Networks. arXiv:1409.3215 (2014). single context vector가 bottleneck인 encoder-decoder입니다.

  3. Bahdanau, D., Cho, K. and Bengio, Y. Neural Machine Translation by Jointly Learning to Align and Translate. arXiv:1409.0473 (2014). transformer보다 3년 앞선 Attention입니다.

  4. Perplexity는 Chapter 8에서 나온 token당 mean cross-entropy의 exponential입니다. 여기의 모든 number는 같은 tokenizer와 같은 validation split을 사용합니다. 그것만이 두 perplexities를 비교할 수 있는 유일한 조건입니다.

  5. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł. and Polosukhin, I. Attention Is All You Need. arXiv:1706.03762 (2017). Section 3.2.1은 dk\sqrt{d_k}에 관한 한 문장이고, 이 장은 그 한 문장을 한 section으로 측정합니다.

  6. Shazeer, N., Mirhoseini, A., Maziarz, K., Davis, A., Le, Q., Hinton, G. and Dean, J. Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer. arXiv:1701.06538 (2017).

  7. Ba, J. L., Kiros, J. R. and Hinton, G. E. Layer Normalization. arXiv:1607.06450 (2016). Chapter 6에서 도입하고 측정했으며, 여기서는 그대로 사용합니다.

  8. Xiong, R., Yang, Y., He, D., Zheng, K., Zheng, S., Xing, C., Zhang, H., Lan, Y., Wang, L. and Liu, T.-Y. On Layer Normalization in the Transformer Architecture. arXiv:2002.04745 (2020). pre-norm 뒤의 gradient analysis와, warmup이 symptom이라는 argument입니다.

  9. Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B. and Liu, Y. RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv:2104.09864 (2021).

  10. Press, O., Smith, N. A. and Lewis, M. Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation. arXiv:2108.12409 (2021). 위에 재현한 extrapolation result입니다.

  11. Dao, T., Fu, D. Y., Ermon, S., Rudra, A. and Ré, C. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135 (2022).

  12. Shazeer, N. Fast Transformer Decoding: One Write-Head is All You Need. arXiv:1911.02150 (2019).

  13. Ainslie, J., Lee-Thorp, J., de Jong, M., Zemlyanskiy, Y., Lebrón, F. and Sanghai, S. GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. arXiv:2305.13245 (2023).

  14. Levesque, H. J., Davis, E. and Morgenstern, L. The Winograd Schema Challenge. KR (2012). 모든 attention tutorial이 사용하는 animal / street sentence 뒤의 construction입니다.

이제 모델 선택은 LIA에게 맡기세요

모든 AI 모델을 한곳에서. 오늘 무료로 시작하세요.