선형대수, 확률, 미분과 최적화를 따로 봤다. 이제 decoder-only Transformer 한 layer의 forward, training loss, autoregressive generation을 한 경로로 연결한다.
2017년 원 논문의 Transformer는 encoder-decoder, sinusoidal position encoding, post-LayerNorm 구조다. 오늘날 decoder-only LLM은 pre-norm, RMSNorm, RoPE, SwiGLU, GQA 같은 변형을 자주 사용한다. “Transformer 공식” 하나가 모든 model의 정확한 구현은 아니다.
전체 계산 지도
text
→ tokenizer
→ token ids (B, T)
→ token embedding (B, T, D)
→ position information (B, T, D) 또는 Q/K rotation
→ N × Transformer block (B, T, D)
├─ normalization
├─ causal self-attention
├─ residual
├─ normalization
├─ feed-forward / gated MLP
└─ residual
→ final normalization (B, T, D)
→ vocabulary projection (B, T, V)
→ shifted cross-entropy scalar
기호는 다음과 같다.
- — batch size
- — sequence length
- — vocabulary size
- — model dimension
- — query head 수
- — key-value head 수
- — head dimension
- — layer 수
일반 multi-head attention에서는 이고 다.
Tokenization은 수학 이전의 계약이다
text를 token id sequence로 바꾸는 tokenizer는 model 밖의 전처리처럼 보이지만 다음을 바꾼다.
- sequence length
- vocabulary size
- 숫자·코드·한국어의 분해 방식
- input/output embedding parameter 수
- context window에 들어가는 실제 text 양
- perplexity의 token 단위
같은 문장이 tokenizer A에서는 10 token, B에서는 16 token일 수 있다. “8K context”는 8K 글자나 단어가 아니라 해당 tokenizer의 token 수다.
Token embedding
embedding table은
이다. token id 의 row를 고른다.
batch 전체는
이다. lookup은 one-hot 와의 곱으로도 쓸 수 있다.
구현은 one-hot을 만들지 않고 index로 row를 가져온다.
Position이 필요한 이유
self-attention의 content 연산만 보면 token row를 같은 permutation으로 섞었을 때 output도 같은 방식으로 섞이는 permutation equivariance가 있다. 순서를 model에 알려줄 별도 signal이 필요하다.
Sinusoidal position encoding
원 논문의 식은 짝수·홀수 dimension에 sine과 cosine을 사용한다.
입력 embedding에 더한다.
서로 다른 주파수로 position을 표현한다. 원 논문은 fixed sinusoidal과 learned positional embedding이 비슷한 결과를 냈고, 더 긴 length extrapolation 가능성을 보고 sinusoidal을 선택했다. 이것이 모든 후속 model에서 sinusoidal이 최선이라는 뜻은 아니다.
Learned absolute position embedding
position table 를 학습한다. training에서 보지 않은 position으로 확장하는 방법이 자동으로 정해지지 않는다.
Rotary Position Embedding
RoPE는 query와 key의 dimension pair를 position-dependent angle로 회전한다. 2차원 pair를 단순화하면
회전된 dot product에는 상대 position 가 들어간다.
실제 RoPE는 여러 frequency를 dimension pair마다 적용한다. position vector를 hidden state에 더하는 대신 attention의 Q와 K에 회전을 적용한다. context extension에서는 base frequency scaling과 training length 조건을 확인해야 한다.
한 layer의 입력
layer 입력을
라 하자. modern pre-norm block을 단순화하면
이다. dropout, bias, parallel residual 같은 세부는 model마다 다르다.
Q, K, V projection
일반 MHA부터 본다.
projection 뒤
이고 head를 나누면
이다.
이름을 정보 검색과 연결해 읽는다.
- query — 현재 position이 찾는 조건
- key — 각 position이 match될 주소
- value — match weight로 섞을 내용
와 가 같지 않은 이유는 “어디를 볼지”와 “무엇을 가져올지”에 다른 projection을 학습하게 하기 위해서다.
Scaled dot-product attention
head 하나에 대해
이다.
shape는
다. 는 batch , head 에서 query position 와 key position 의 compatibility score다.
왜 로 나누는가
가 mean 0, variance 1이고 대략 independent라고 단순 가정하면 dot product는
이고 variance는 대략 다.
standard deviation은 이므로 나누면 score scale을 order 1로 유지한다.
큰 logit은 softmax를 포화시켜 gradient가 작아질 수 있다. 이 유도는 independence와 unit variance를 둔 직관이다. 실제 trained Q, K가 정확히 그 distribution이라는 주장은 아니다.
Causal mask
decoder-only model이 position 에서 미래 를 보지 못하게 한다.
이므로 미래 key probability가 0이 된다. 구현은 dtype에서 충분히 작은 finite value를 사용할 수 있다.
padding mask는 batch마다 실제 token이 아닌 padding position을 막는다. causal mask와 목적이 다르며 broadcasting shape를 검증해야 한다.
모든 key가 masked된 row에 softmax를 적용하면 undefined한 또는 NaN 문제가 생길 수 있다. library kernel의 all-masked behavior를 확인한다.
Softmax axis
query 를 고정하고 key axis 로 합이 1이다.
의 마지막 axis다. query axis로 softmax하면 다른 의미의 연산이 된다.
Value의 가중합
shape는
각 query output은 허용된 value vector의 convex combination이다.
attention weight이 explanation과 같다는 보장은 없다. output projection, residual, 다음 layer의 nonlinear transformation을 거친 최종 prediction 영향과 한 head의 weight는 다르다.
손으로 계산하는 causal attention
두 token, head dimension 2라고 하자.
raw score는
로 나누고 causal mask를 더한다.
첫 row의 probability는 이다. 첫 token은 자기 자신만 본다.
둘째 row는 두 logit 차이가
이므로
이다. output은
이다.
Multi-head attention
head마다 다른 projection으로 다른 subspace의 관계를 계산한다.
concat 뒤 shape는 이고 가 head 정보를 다시 섞는다.
head 수를 늘려도 를 고정하면 각 head dimension 는 작아진다. head 수 증가가 parameter와 표현력을 단순히 비례 증가시키지는 않는다.
MHA, MQA, GQA
query head 수를 , KV head 수를 라 하자.
- MHA —
- MQA —
- GQA —
GQA는 여러 query head가 한 KV head를 공유하는 group을 만든다. query 표현 수는 유지하면서 KV cache와 decode memory bandwidth를 줄인다.
Q shape는
K, V shape는
다. attention 계산 때 KV head를 query group에 대응시킨다. 단순히 H_q == H_kv라고 가정한 코드는 GQA model에서 shape가 틀린다.
Output projection과 residual
head output을 합친 뒤
입력과 같은 shape이므로 residual 덧셈이 가능하다.
residual은 새 계산 에 원래 representation 를 보존하는 경로를 제공한다. shape가 같아야 한다.
Feed-forward network
attention이 token axis의 정보를 섞는다면 FFN은 각 token position에 같은 nonlinear function을 독립 적용해 feature를 변환한다.
원 논문 형태는
이다.
shape는
이다. token끼리 섞이지 않고 각 token row에 동일 weight를 쓴다.
SwiGLU
gated FFN의 한 형태는
이다. projection 두 개를 element-wise 곱하므로 hidden width와 parameter 수를 vanilla FFN과 비교할 때 projection 개수를 같이 세야 한다.
Normalization과 block 순서
LayerNorm은 mean을 빼고 variance로 나눈 뒤 trainable scale과 bias를 적용한다.
RMSNorm은 mean subtraction 없이 RMS로 나눈다.
원 논문의 post-norm은
modern pre-norm은
형태다. checkpoint architecture를 구현할 때 normalization 종류와 위치가 모두 맞아야 weight를 올바르게 사용할 수 있다.
Layer를 쌓는다
self-attention 한 layer에서 모든 token이 이전 token의 정보를 섞을 수 있어도 여러 layer가 불필요한 것은 아니다. attention, nonlinear FFN, residual이 반복되며 representation을 단계적으로 바꾼다.
causal model에서 information은 미래에서 과거로 흐르지 않는다. 어느 layer에서도 position 는 의 input token을 볼 수 없다.
Vocabulary projection
마지막 hidden을 vocabulary logit으로 바꾼다.
input embedding 와 output weight를 공유하는 weight tying을 쓰면 형태가 된다. 모든 model이 tying을 쓰는 것은 아니다.
각 position 의 next-token distribution은
이다.
Shifted language-model loss
입력 token이
[BOS, 나는, 학교에, 간다]
라면 target은 한 칸 왼쪽으로 민
[나는, 학교에, 간다, EOS]
다. 식은
이다.
teacher forcing에서는 training 시 position 의 context에 model이 전에 생성한 token이 아니라 dataset의 실제 prefix가 들어간다. inference에서는 model output이 다음 input이 되어 error가 누적될 수 있다.
instruction tuning에서 prompt token loss를 mask하고 answer token만 학습할 수 있다.
mask 정책이 system, user, assistant token 중 어디에 loss를 주는지 확인한다.
Backpropagation 경로
한 target token의 gradient는
cross-entropy
→ vocabulary logits
→ output projection
→ final hidden
→ 모든 Transformer block
→ attention/FFN weights
→ token embedding
로 흐른다. shared parameter는 sequence의 여러 position과 batch sample에서 받은 gradient가 합쳐진다.
causal mask는 forward information flow뿐 아니라 gradient path도 제한한다. 미래 token의 loss는 과거 token representation과 weight에 영향을 줄 수 있지만 과거 position output이 미래 input을 직접 본 것은 아니다.
Parameter 수를 근사한다
bias와 norm을 잠시 제외한다.
Attention projection
MHA에서 Q, K, V, O가 모두 면
Vanilla FFN
면
따라서 한 block은 대략 다. embedding은 , layer 개면 주요 parameter는
이다. SwiGLU, GQA, bias, tying 여부에 따라 coefficient가 달라진다. model card의 정확한 architecture config로 다시 계산해야 한다.
Compute 비용을 분리한다
한 layer, batch 생략, MHA 기준의 큰 항만 본다.
Projection과 FFN
linear projection은 대략 다. FFN도 다.
Attention score와 value mixing
head 전체는 대략
이고 도 같은 order다.
attention matrix memory는 라 다. FlashAttention 같은 exact attention algorithm은 tiling과 recomputation으로 materialized memory traffic을 줄이지만 attention의 수학적 output을 근사 ANN으로 바꾸는 것은 아니다.
짧은 에서는 projection과 FFN이 지배할 수 있고, 긴 에서는 attention 항이 커진다. “Transformer 비용은 항상 ” 한 줄만으로 실제 latency를 설명할 수 없다.
Training, prefill, decode
Training
sequence 전체 position을 병렬로 계산하지만 activation을 backward용으로 저장해야 한다. memory에는 parameter, gradient, optimizer state, activation이 들어간다.
Prefill
prompt token 전체의 Q, K, V와 hidden을 병렬 계산한다. 긴 prompt에서는 compute-heavy한 matrix multiplication 비중이 크다.
Decode
매 step 새 token 하나를 계산한다. 이전 token의 K, V를 cache하지 않으면 prefix 전체를 매번 다시 계산해야 한다.
KV cache
layer마다 이전 token의 K와 V를 저장한다. batch당 element 수는
이다. byte 수는 dtype byte와 batch를 곱한다.
예를 들어
- BF16, 2 byte
이면
약 512 MiB다. allocator overhead, cache metadata, padding은 제외한 값이다.
MHA의 였다면 같은 조건에서 약 2 GiB다. GQA가 decode memory에 큰 영향을 주는 이유다.
KV cache는 model parameter memory와 별개이며 concurrent sequence 수와 context length에 비례한다.
Cached decode의 attention
새 token query 는 지금까지 cache된 key와 dot product한다.
한 step의 attention은 history length 에 선형이지만 개 token을 순차 생성한 총합은
이다. cache는 이전 K, V projection의 재계산을 없애지만 모든 과거 key와의 attention 자체를 없애지는 않는다.
Decoding
마지막 position logit 로 distribution을 만든다.
greedy면 argmax, sampling이면 categorical draw다. top-, top-, repetition penalty, constrained decoding은 model forward 뒤 distribution 또는 logit을 변형한다.
생성 loop는
1. prompt prefill, KV cache 생성
2. 마지막 logit에서 token 선택
3. 선택한 token 하나를 입력
4. 새 K/V를 cache에 append
5. stop condition까지 반복
이다. autoregressive dependency 때문에 token step 자체는 순차적이다. batch, speculative decoding과 parallel hardware가 throughput을 높여도 한 sequence의 accepted token dependency는 남는다.
Attention과 retrieval의 차이
둘 다 query-key similarity와 weighted value를 사용하지만 범위가 다르다.
| 구분 | Self-attention | External retrieval |
|---|---|---|
| 후보 | 현재 context의 token | corpus document/chunk |
| index | 매 forward의 K | 미리 구축한 search index |
| normalization | 보통 context key에 softmax | top- score가 확률일 필요 없음 |
| 학습 | model 내부 end-to-end | retriever와 generator가 분리될 수 있음 |
| 목적 | representation mixing | 외부 evidence 후보 recall |
“attention이 있으므로 RAG가 필요 없다”거나 “vector search가 곧 attention”이라고 동일시하면 system 경계를 놓친다.
구현을 읽을 때 확인할 순서
- config에서 를 찾는다.
- tensor shape를 batch와 head까지 적는다.
- normalization 종류와 pre/post 위치를 본다.
- position encoding이 absolute, relative, RoPE 중 무엇인지 본다.
- causal mask와 padding mask를 구분한다.
- softmax axis와 dtype cast를 본다.
- FFN activation과 projection 개수를 본다.
- input/output embedding tying 여부를 본다.
- training target shift와 loss mask를 본다.
- inference에서 KV cache update 위치를 본다.
자주 생기는 오해
Attention weight가 model의 설명이다
한 layer 한 head의 local mixing coefficient다. 최종 output의 causal attribution과 같지 않다.
Context window가 길면 모든 token을 잘 사용한다
입력 가능 길이와 long-context retrieval 정확도는 다르다. position method, training length, attention behavior와 evaluation을 확인한다.
KV cache가 attention을 constant time으로 만든다
과거 K/V projection 재계산을 피하지만 새 query는 여전히 과거 key를 본다.
Head 수가 많으면 항상 더 좋다
가 고정이면 head당 dimension이 줄고, 원 Transformer 논문 ablation에서도 head 수를 지나치게 늘렸을 때 품질 저하가 있었다.
모든 Transformer가 원 논문 식 그대로다
encoder-decoder와 decoder-only, MHA와 GQA, LayerNorm과 RMSNorm, sinusoidal과 RoPE가 다르다.
Parameter 수가 inference memory 전부다
weight 외에 KV cache, activation, workspace, runtime allocator가 필요하다. concurrency가 커지면 KV cache가 병목이 될 수 있다.
완료 체크
- token id에서 vocabulary logit까지 모든 shape를 적는다.
- 의 원소 의미를 말한다.
- scaling의 variance 직관을 유도한다.
- causal mask와 padding mask를 구분한다.
- MHA, MQA, GQA의 차이를 설명한다.
- attention과 FFN이 각각 어느 axis를 섞는지 설명한다.
- pre-norm과 post-norm 식을 구분한다.
- shifted LM loss와 teacher forcing을 설명한다.
- attention, FFN, KV cache의 비용이 각각 무엇에 비례하는지 계산한다.
- prefill과 decode의 실행 경로를 구분한다.
다음 글은 model 밖으로 나가 corpus를 찾고, ranking하고, RAG 답변을 평가하는 수학을 다룬다. LLM 수학 05 — 검색과 RAG.
Reference
- Ashish Vaswani 외. Attention Is All You Need, 2017.
- Jianlin Su 외. RoFormer — Enhanced Transformer with Rotary Position Embedding, 2021.
- Noam Shazeer. GLU Variants Improve Transformer, 2020.
- Joshua Ainslie 외. GQA — Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints, 2023.
- Tri Dao 외. FlashAttention, 2022.
댓글