4단계 세 번째 논문. 이 글은 Nelson Elhage 외의 A Mathematical Framework for Transformer Circuits 원문을 직접 읽고 썼다. 이 글은 2021-12-01 공개된 웹 논문을 기준으로 한다. 이 framework(프레임워크)는 Transformer를 한 덩어리 함수로 보지 않고, 여러 component가 residual stream(잔차 흐름)이라는 공용 vector 장부에 읽고 쓰는 작은 회로의 합으로 분해한다.
이 글에서 얻을 답과 범위
앞 글의 Primer는 “어떤 component가 output에 영향을 줬는가”를 묻는 도구를 소개했다. 이 논문은 그 component들이 어떻게 서로 연결되어 계산 가능한 path를 만드는지를 위한 수학 언어다.
이 글을 마치면 다음을 설명할 수 있어야 한다.
- 왜 여러 attention head를 concat한 뒤 matrix 하나를 곱하는 구현을, 독립 write의 합으로 다시 볼 수 있는가.
- QK(Query-Key) circuit과 OV(Output-Value) circuit이 각각 무엇을 하는가.
- direct path, full OV path, virtual attention head가 무엇이며 왜 행렬 곱으로 나타나는가.
- 한 head output이 다음 head의 Query·Key·Value 중 어디에 들어가는 Q·K·V composition(합성)을 어떻게 구분하는가.
- “circuit을 발견했다”가 attention map을 예쁘게 그린 것보다 강한 주장인 이유와 아직 남는 한계는 무엇인가.
범위는 attention-only Transformer의 해석적 framework다. MLP(Multi-Layer Perceptron, 다층 퍼셉트론), LayerNorm, activation patching 전체 기법을 대체하지 않는다. 실제 GPT류 모델은 softmax·MLP·normalization을 포함하므로 아래의 완전 선형 path 식을 그대로 사실이라고 적용하면 안 된다.
핵심은 head가 “다른 head의 output을 직접 호출”하는 것이 아니라, 모두 residual stream에 쓰고 다음 head가 그 stream의 일부를 Q·K·V로 읽는다는 것이다. 이 shared channel이 path와 composition을 만든다.
왜 필요한가 — head 이름만으로는 계산을 설명할 수 없다
“이 head는 이전 단어를 본다”는 설명은 시작일 뿐이다. 다음 질문이 남는다.
어느 이전 위치를 읽었나 → attention pattern
읽은 vector를 무엇으로 바꿨나 → OV write
그 write를 다음 head가 어디에 썼나 → Q·K·V composition
마지막 token score에 얼마나 도착했나 → path와 unembedding
head가 같은 token을 보더라도 V가 작거나 OV가 반대 방향으로 쓰면 logit 영향은 작을 수 있다. 또 두 head가 각각 중요해 보여도 둘 사이 edge가 중요하다는 뜻은 아니다. Transformer Circuits 연구는 이런 차이를 “회로의 node와 path”로 적기 위해 생겼다.
무엇인가 — residual stream은 모든 component의 공용 장부
한 token 위치의 residual vector를 x∈R^d라 하자. embedding, 각 attention head output, MLP output은 길이 d가 같아 더할 수 있다.
[ x^{l}=x^{l-1}+\sum_h\operatorname{Attn}^{l,h}(x^{l-1})+\operatorname{MLP}^{l}(x^{mid,l}) \tag{1} ]
실제 구현은 H head 결과를 concatenate(이어 붙이기)한 뒤 output projection을 한 번 곱하는 일이 많다. 논문은 그 output matrix를 head별 block으로 나누면 각 head output이 residual stream에 독립적으로 더해지는 합과 수학적으로 같다고 보인다. 따라서 head를 독립 write operation으로 분석할 수 있다.원문 Architecture — Attention Heads are Independent and Additive
| 물건 | 쉬운 비유 | 실제 역할 |
|---|---|---|
| residual stream | 모든 부서가 쓰는 공용 화이트보드 | layer와 position마다 있는 d차원 vector |
| attention head | 읽고 메모를 쓰는 작은 부서 | 다른 position 정보를 선택해 residual에 write |
| QK circuit | 주소를 고르는 질문지 | 어떤 position을 읽을지 attention score 생성 |
| OV circuit | 읽은 내용을 바꾸는 번역기 | selected value를 residual 방향으로 write |
| unembedding | 마지막 점수표 | residual을 vocabulary logit으로 projection |
선행 개념 — QK와 OV를 분리해 본다
head h가 현재 위치 i에서 과거 j를 읽는 비율은 Q와 K의 dot product를 softmax한 값이다.
[ a_{i,j}^{h}=\operatorname{softmax}_j\left(\frac{(x_iW_Q^h)(x_jW_K^h)^T}{\sqrt{d_h}}\right) \tag{2} ]
이 부분이 QK circuit이다. Q는 현재 위치가 무엇을 찾는지, K는 각 위치가 어떤 주소표를 내는지 표현한다. 실제 write는 V와 O를 포함한다.
[ \operatorname{Attn}^{h}i=\sum{j\le i}a_{i,j}^{h}x_jW_V^hW_O^h \tag{3} ]
W_V^hW_O^h가 OV circuit이다. 행 vector convention에서는 이 순서로 곱고, column vector convention에서는 전치와 순서가 달라 보일 수 있다. 중요한 사실은 두 작은 projection을 합쳐 “attention을 받았을 때 input residual 방향을 어떤 output residual 방향으로 옮기는가”를 나타내는 low-rank map으로 볼 수 있다는 점이다.원문 Summarizing OV and QK Matrices
attention weight만 explanation이 아닌 이유가 여기 있다. a_{i,j}는 읽는 비율만 말한다. x_jW_VW_O의 크기와 방향, 다른 head·MLP의 덧셈, 마지막 W_U까지 봐야 token score 영향이 보인다.
밑바닥 원리 — path expansion은 덧셈을 펼치는 일이다
MLP와 attention pattern 변화를 잠시 빼고, 두 attention-only layer의 OV write만 보자. 첫 layer를 A_1, 둘째를 A_2라 하면
[ x_1=x+xA_1,\qquad x_2=x_1+x_1A_2 \tag{4} ]
두 번째 식에 첫 식을 넣으면
[ x_2=x+xA_1+xA_2+xA_1A_2 \tag{5} ]
네 항은 각각 다음 path다.
| 항 | 이름 | 뜻 |
|---|---|---|
x | direct path | embedding이 바로 output으로 가는 경로 |
xA_1 | full OV path 1 | 첫 head를 한 번 통과 |
xA_2 | full OV path 2 | 둘째 head를 한 번 통과 |
xA_1A_2 | virtual attention head | 첫 head write를 둘째 head가 value로 읽어 다시 쓴 합성 |
마지막 A_1A_2가 V-composition(값 합성)이다. 두 physical head를 지나지만 end-to-end에서는 한 개의 virtual head처럼 input token을 output 방향으로 바꾼다. 논문은 이런 path expansion으로 Transformer가 shallow network ensemble처럼 보인다고 설명한다.원문 Virtual Attention Heads
단, 식 (5)는 attention pattern을 고정한 단순화다. 실제 a는 Q·K와 softmax로 x에 의존한다. 그래서 논문은 linear structure가 많다고 하되 Transformer 전체가 선형이라고 주장하지 않는다.
내부 구조와 실제 실행 흐름 — 세 종류의 composition
head A가 residual에 write하면 다음 head B는 그 write를 세 장소에서 읽을 수 있다.
A write → B Query → B가 무엇을 찾을지 바뀜 Q-composition
A write → B Key → B가 어느 위치로 선택될지 바뀜 K-composition
A write → B Value → B가 읽은 내용을 무엇으로 쓸지 바뀜 V-composition
V-composition은 위 A_1A_2처럼 output map을 곱해 path로 직접 펼치기 쉽다. Q·K composition은 attention pattern 자체를 바꾸므로 더 비선형적이고, “어떤 token을 복사할지” 같은 routing algorithm을 만들 수 있다. 이 셋을 모두 같은 “head가 head를 본다”로 뭉개면 circuit의 역할을 잃는다.원문 Three Kinds of Composition
또한 residual stream의 모든 dimension이 모든 component에 똑같이 보이는 것은 아니다. head projection matrix는 어떤 subspace를 읽고 어떤 subspace에 쓰는지 선택한다. 논문은 이 관점을 residual stream communication channel(통신 채널)이라고 부른다. 단순히 vector 전체의 cosine similarity만 보는 것보다, sender write와 receiver read가 실제로 alignment되는지 보는 이유다.원문 Virtual Weights and the Residual Stream as a Communication Channel
직접 검증과 재현 — two-layer path를 끝까지 더하기
직접 실행 확인이다. 2026-07-24, Python 3.9.6 표준 라이브러리로 d=2 attention-only toy model을 만들었다. attention pattern은 고정했고 A_1, A_2는 OV write matrix다. 사람이 정한 숫자이므로 학습된 language circuit 발견이 아니다.
input x: ['1.000000', '-1.000000']
layer-1 write: ['0.400000', '-0.200000']
layer-2 write: ['0.180000', '-0.860000']
final residual: ['1.580000', '-2.060000']
direct path: ['1.000000', '-1.000000']
full OV path layer-1: ['0.400000', '-0.200000']
full OV path layer-2: ['0.100000', '-0.700000']
virtual value-composition path: ['0.080000', '-0.160000']
sum of paths: ['1.580000', '-2.060000']
token-C logit: 2.610000
path logit contributions: ['1.500000', '0.500000', '0.450000', '0.160000'] sum= 2.610000
checks passed
파일은 /tmp/transformer-circuits-research/verify_paths.py다. final residual은 식 (5)의 네 path 합과 같고, unembedding vector와의 dot product도 path별 logit contribution 합과 같다. 이 검증은 덧셈과 행렬 분배법칙을 확인한 것이며, 실제 head의 attention pattern·MLP·LayerNorm까지 선형이라는 주장이 아니다.
성능과 트레이드오프 — 해석 path 수는 빠르게 폭발한다
layer와 head가 늘면 가능한 path 수는 조합적으로 커진다. 모든 path를 전부 열거하면 큰 model에서 불가능하다. 그래서 실무 circuit analysis는 먼저 task를 좁히고, candidate head·position을 DLA(Direct Logit Attribution, 직접 logit 기여), activation patching, gradient attribution 같은 방법으로 ranking한 뒤, 필요한 edge만 검증한다.
| 접근 | 얻는 것 | 빠지는 것 |
|---|---|---|
| attention pattern | routing 가설 | value·OV와 output effect |
| OV·QK matrix 분석 | head의 read·write 성질 | 실제 prompt별 nonlinear interaction |
| path expansion | end-to-end linear contribution | pattern 변화와 MLP 영향 |
| activation patching | 특정 counterfactual output 변화 | template·baseline·self-repair 의존 |
| full circuit claim | task algorithm 설명 | 가장 강한 재현·causal evidence 필요 |
실패와 운영 기준 — 회로라는 이름을 너무 쉽게 붙이지 않기
- attention pattern이 반복된다고 circuit이라고 선언하지 않는다. OV write와 output effect를 확인한다.
- head ablation 하나로 edge 역할을 단정하지 않는다. downstream compensation과 self-repair가 가능하다.
- LayerNorm·MLP·softmax를 생략한 linear decomposition은 가설 생성용 범위라고 적는다.
- model revision, tokenizer, prompt template, layer·head index convention, seed, metric을 기록한다.
- 한 example을 여러 paraphrase·counterfactual·position에서 재검증한다.
이 framework는 RAG retrieval 품질, agent tool 권한, output validation을 대체하지 않는다. model 내부 계산을 설명하려는 관측 언어다.
대안과 선택 기준 — 질문에 맞는 해석 단위를 택한다
| 질문 | 먼저 보는 단위 | 다음 검증 |
|---|---|---|
| 어느 token을 읽나 | QK와 attention pattern | value·OV-weighted contribution |
| 어떤 방향으로 쓰나 | OV matrix와 unembedding projection | DLA와 prompt별 output |
| A가 B에 정보를 넘기나 | Q·K·V composition 가설 | edge 또는 path patching |
| feature가 어디 있나 | probe 또는 SAE(Sparse Autoencoder, 희소 오토인코더) | feature intervention |
| 실제 task 회로인가 | candidate path 집합 | counterfactual·ablation·faithfulness |
흔한 오해와 최초 질문에 대한 답
attention head는 서로 독립인가
같은 layer에서 outputs가 residual에 additive하게 더해진다는 뜻에서는 독립적으로 볼 수 있다. 하지만 다음 layer는 그 합을 읽으므로 model 전체에서 서로 무관하다는 뜻은 아니다.
OV circuit만 보면 head 역할을 알 수 있나
아니다. OV는 “attention을 받았을 때 무엇을 쓸지”다. QK가 어느 position을 읽게 하는지와 prompt별 pattern을 같이 봐야 한다.
virtual head는 실제 parameter인가
아니다. 여러 physical head path의 행렬 곱으로 드러나는 해석용 end-to-end map이다. checkpoint에 따로 저장되지 않는다.
이 논문이 induction head를 증명하나
이 논문은 induction head 같은 후속 circuit을 읽는 공통 언어를 준다. 특정 induction algorithm의 실험 증명은 다음 In-context Learning and Induction Heads 원 논문에서 다룬다.
출처 및 검증 경로
1차 자료
- Elhage 외. A Mathematical Framework for Transformer Circuits — Introduction, Architecture, OV·QK Matrix, Three Kinds of Composition, Virtual Attention Heads, Residual Stream Communication Channel을 직접 확인했다.
- Vaswani 외. Attention Is All You Need — scaled dot-product attention의 원전이다.
직접 실행 기록
- 환경 — macOS, Python 3.9.6, 외부 numerical library 없음.
- 파일 —
/tmp/transformer-circuits-research/verify_paths.py. - 검증 — fixed-attention 2-layer attention-only model의 direct path, 두 full OV path, virtual V-composition path의 residual 합과 unembedding logit 기여 합.
- 한계 — 작은 선형 산술 예제다. 실제 Transformer의 nonlinear attention pattern, MLP, LayerNorm, 학습된 circuit을 재현하지 않았다.
댓글