The source is Alex Wang’s post “You could have invented transformers from memory” (2026-10-15). For the original’s interactive figures, I have carried over only the numbers stated in the text.
Related lessons: /study/dl/attention/ · /study/dl/transformer/
1. Summary
- Treat every layer as a key-value memory store. Storing means adding a key-value pair; retrieval means taking a weighted sum of values according to the similarity between the query and the keys.
- Retrieval result = signal (the target value) + interference (the sum of the other values). Capacity is defined as the number of stored items at which the interference/signal ratio reaches 1.
- There are two ways to reduce interference: store better (the optimal linear store), or retrieve selectively (apply a nonlinearity to the similarity).
- Varying recovers the standard layers one after another: linear → ReLU MLP → squared ReLU (GLU) → SwiGLU → softmax (self-attention). The harder suppresses low similarities, the larger the capacity.
- Capacity (, random keys and values, queried with a stored key): linear 64 → squared ReLU about 2,700 → self-attention about 1.2 million. For long context, growing with makes it effectively unlimited.
2. Starting point: the outer-product store
Storing is just a matter of adding outer products.
- A new memory is stored by adding (Hebbian). This has the same form as the state of linear attention and fast weights.
- As an aside, a gradient step on a linear layer, , can also be seen as writing one memory with key and value .
- With unit-length keys, querying with a stored key gives
- With random keys the similarities are about , and the interference terms accumulate like a random walk, so interference/signal . The capacity is therefore .
- Numbers (): 0.46 at , 0.97 at 64, 1.39 at 128, 3.90 at 1024.
3. Storing better: the optimal linear store
- Solve the regression that fits all memories at once, .
- The solution is . In effect the query is whitened by the inverse of the key covariance before comparison, so directions shared by many keys are not overweighted.
- If , interference is 0 as long as the keys are linearly independent (they need not be orthogonal; this is the dual basis).
- If , interference/signal , so the capacity is , twice that of the outer-product store.
- Numbers: 1.00 at . As grows, the gap to the outer-product store shrinks (because the interference that can be cancelled is fixed at items’ worth).
- Limitation: it is still linear in similarity, so it can only treat small and large similarities in the same proportion.
4. Retrieving selectively: the MLP
This is a 2-layer MLP. The rows of the first weight matrix are the keys, and the columns of the second weight matrix are the values.
- Prior work with the same view: Sukhbaatar et al. (FFN ≈ memory), Geva et al. (keys of a trained FFN respond to specific input patterns). The arXiv v2 and v3 of the original Transformer paper also described the FFN as “a kind of attention” and included an experiment replacing it with learned key-value attention, but this was removed in later versions.
- With , the signal is unchanged while the interference term shrinks to , giving interference/signal and capacity .
| Capacity | ||
|---|---|---|
| Linear | 64 | |
| ReLU (removes negative similarities, interference down by ) | 128 | |
| Squared ReLU = weight-shared GLU () | about 2,700 | |
| SwiGLU ( with a shared gate) | about | about 2,900 |
| Cubed ReLU | about 35,000 |
- Real MLPs store in superposition (multiple memories share weights). Garcia et al. used a GLU hidden layer as random features and stored far more facts than there were hidden units, and trained ReLU MLPs can activate only 1% of their hidden units per input (Li et al.).
5. Taking it all the way: self-attention
The exponential function is a weighted sum of all powers.
(sharpness) sets the weight of the higher-order terms. Keeping 2 Taylor terms gives a capacity of about 40 (worse than linear because of the constant term), 3 terms about 450, 4 terms about 3,100, and the full exponential goes off the chart.
If the similarity of random unit keys is , then
- When is sufficiently smaller than , the capacity grows exponentially in . The earlier layers were polynomial in .
- With , it is 1.2 million, about 20,000 times the linear store. The measured value is also about 1.2 million.
- Interference depends only on the ratios of the weights, so we may divide by their sum (for numerical stability). That gives , which is self-attention.
- The transformer’s scaling is there because is on the order of ; in terms of unit-length vectors it is equivalent to .
- Difference from the MLP: the keys and values are not learned weights but are computed from the tokens in the context. It is a non-parametric store, and is the context length.
6. Long context: matching to
Taking to infinity gives a hard argmax, which is not differentiable, and a large saturates the softmax so the gradients to the other keys vanish. So is grown only as much as requires. The variants below are calibrated so that equals its original value at a reference length (usually the training length).
| Method | Logit multiplier |
|---|---|
| Su (2021), Scalable-Softmax | (always). SSMax learns in |
| Qwen LogN-Scaling | The same multiplier, only when |
| YaRN (Qwen2.5-1M) | , i.e. grows like |
- Experiment (, ): at 2 million items, the Su/Qwen approach gives interference/signal of about 0.004, YaRN about . Either way, as long as the keys are distinct, storage is effectively unlimited.
7. Limitations and follow-up work
- This capacity only counts “how many random vectors one layer can retrieve without interference.” It does not consider what the training data puts into the keys and values.
- Measurements on trained models: GPT-family models memorize about 3.6 bits per parameter and switch to generalization once capacity is full (Morris et al.). Factual knowledge is about 2 bits per parameter and survives int8 (Allen-Zhu & Li).
- Directions to follow
- Theory of how much a layer stores: Nichani, Lee & Bietti; Zhong et al. (the source of the interference/signal estimates)
- Associative memories with exponential capacity: Dense Associative Memory (Krotov & Hopfield), Ramsauer et al. (Hopfield ↔ attention)
- Short-term memory updated during inference: fast weights, Mamba and Mamba-2, DeltaNet and Gated DeltaNet, TTT, Titans, MesaNet, test-time regression
- Huge sparse parametric memories: product-key memory, Memory Layers at Scale, UltraMem, Mixture of A Million Experts, Engram
- Non-parametric memory outside the weights: kNN-LM, RETRO, Memorizing Transformers
- Locating and editing memories: ROME, MEMIT. Compressing short-term into long-term: KVzip, gist tokens, Cartridges. Continual learning: sparse memory finetuning
원문은 Alex Wang의 글 “You could have invented transformers from memory”(2026-10-15)다. 원문의 인터랙티브 그림은 본문에 적힌 수치만 옮겼다.
관련 레슨: /study/dl/attention/ · /study/dl/transformer/
1. 요약
- 모든 층을 key-value 메모리 저장소로 본다. 저장은 key·value 쌍을 넣는 것이고, 조회는 질의와 key의 유사도로 value를 가중합하는 것이다.
- 조회 결과 = 신호(목표 value) + 간섭(다른 value들의 합)이다. 용량은 간섭/신호 비율이 1이 되는 저장 개수 으로 정의한다.
- 간섭을 줄이는 길은 둘이다. 저장을 잘하거나(최적 선형 저장소), 조회를 선택적으로 하거나(유사도에 비선형 를 적용).
- 를 바꿔 가면 표준 층이 그대로 나온다: 선형 → ReLU MLP → 제곱 ReLU(GLU) → SwiGLU → softmax(self-attention). 가 낮은 유사도를 더 세게 누를수록 용량이 커진다.
- 용량(, 랜덤 key·value, 저장된 key로 질의): 선형 64 → 제곱 ReLU 약 2,700 → self-attention 약 120만. long context에서는 를 에 맞춰 키우면 사실상 무제한이다.
2. 출발점: outer product 저장소
저장은 outer product를 더하기만 하면 된다.
- 새 기억은 를 더하면 된다(Hebbian). linear attention·fast weights의 상태와 같은 형태다.
- 곁가지로, linear 층의 gradient step 도 key가 , value가 인 기억 하나를 쓰는 것으로 볼 수 있다.
- key를 단위 길이로 두면 저장된 key 로 질의했을 때
- 랜덤 key면 유사도가 약 이고, 간섭 개가 random walk처럼 쌓여 간섭/신호 가 된다. 따라서 용량은 다.
- 수치(): 에서 0.46, 64에서 0.97, 128에서 1.39, 1024에서 3.90.
3. 저장을 잘하기: 최적 선형 저장소
- 모든 기억을 한 번에 맞추는 회귀 를 푼다.
- 해는 이다. 질의를 key 공분산의 역행렬로 whitening한 뒤 비교하는 셈이라, 여러 key가 공유하는 방향을 과대평가하지 않는다.
- 면 key가 선형독립인 한 간섭이 0이다(직교일 필요는 없다, dual basis).
- 면 간섭/신호 이라 용량은 로, outer product의 2배다.
- 수치: 에서 1.00. 이 커질수록 outer product와의 차이가 줄어든다(상쇄할 수 있는 간섭이 개분으로 고정되기 때문).
- 한계: 여전히 유사도에 선형이라 작은 유사도와 큰 유사도를 같은 비율로만 다룬다.
4. 조회를 선택적으로: MLP
이것이 2층 MLP다. 첫 weight 행렬의 행이 key, 둘째 weight 행렬의 열이 value다.
- 같은 관점의 선행 연구: Sukhbaatar et al.(FFN ≈ 메모리), Geva et al.(학습된 FFN의 key가 특정 입력 패턴에 반응). 원조 Transformer 논문의 arXiv v2·v3에도 FFN을 “a kind of attention”으로 설명하고 learned key-value attention으로 바꿔 본 실험이 있었으나 이후 버전에서 삭제되었다.
- 로 두면 신호 은 그대로인데 간섭 항 는 로 줄어, 간섭/신호 , 용량 가 된다.
| 용량 | ||
|---|---|---|
| 선형 | 64 | |
| ReLU (음수 유사도 제거, 간섭 배 감소) | 128 | |
| 제곱 ReLU = 가중치 공유 GLU () | 약 2,700 | |
| SwiGLU (gate 공유 시 ) | 약 | 약 2,900 |
| 세제곱 ReLU | 약 35,000 |
- 실제 MLP는 superposition으로 저장한다(여러 기억이 weight를 공유). Garcia et al.은 GLU 은닉층을 random feature로 써서 은닉 유닛 수보다 훨씬 많은 사실을 저장했고, 학습된 ReLU MLP는 입력당 은닉 유닛의 1%만 켜지기도 한다(Li et al.).
5. 끝까지 밀기: self-attention
지수 함수는 모든 거듭제곱의 가중합이다.
(sharpness)가 고차항의 비중을 정한다. 테일러 2항까지 쓰면 용량 약 40(상수항 때문에 선형보다 나쁘다), 3항은 약 450, 4항은 약 3,100이고, 전체 지수는 차트 밖으로 나간다.
랜덤 단위 key의 유사도가 이면 다음이 성립한다.
- 가 보다 충분히 작으면 용량이 에 지수적으로 증가한다. 앞의 층들은 에 다항식이었다.
- 이면 만으로, 선형의 약 2만 배다. 실험값도 약 120만이다.
- 간섭은 가중치의 비율에만 의존하므로 합으로 나눠도 된다(수치 안정). 그러면 , 곧 self-attention이다.
- 트랜스포머의 스케일은 의 크기가 규모라서 붙는 것이고, 단위 길이 기준으로는 와 같다.
- MLP와의 차이: key·value가 학습된 weight가 아니라 context의 token에서 계산된다. 즉 비모수(non-parametric) 저장소이고 은 context 길이다.
6. long context: 를 에 맞추기
를 무한대로 키우면 hard argmax라 미분할 수 없고, 큰 는 softmax를 포화시켜 다른 key의 gradient가 사라진다. 그래서 이 요구하는 만큼만 키운다. 아래 변형들은 기준 길이 (보통 학습 길이)에서 원래 가 되도록 맞춘다.
| 방식 | logit 배율 |
|---|---|
| Su (2021), Scalable-Softmax | (항상). SSMax는 에서 를 학습 |
| Qwen LogN-Scaling | 위와 같은 배율을 일 때만 |
| YaRN (Qwen2.5-1M) | , 즉 처럼 증가 |
- 실험(, ): Su·Qwen 방식은 200만 개에서 간섭/신호 약 0.004, YaRN은 약 다. 어느 쪽이든 서로 다른 key라면 사실상 무제한 저장이다.
7. 한계와 이어 볼 연구
- 이 용량은 “한 층이 랜덤 벡터를 간섭 없이 몇 개 꺼낼 수 있나”만 센 것이다. 학습 데이터가 key·value에 무엇을 담는지는 고려하지 않는다.
- 학습된 모델 기준 측정: GPT 계열은 파라미터당 약 3.6 bit를 암기하고 용량이 차면 일반화로 넘어간다(Morris et al.). 사실 지식은 파라미터당 약 2 bit이고 int8에서도 유지된다(Allen-Zhu & Li).
- 이어 볼 방향
- 층 저장량 이론: Nichani·Lee·Bietti, Zhong et al.(간섭/신호 추정의 출처)
- 지수 용량 연상 메모리: Dense Associative Memory(Krotov & Hopfield), Ramsauer et al.(Hopfield ↔ attention)
- 추론 중 갱신되는 단기 기억: fast weights, Mamba·Mamba-2, DeltaNet·Gated DeltaNet, TTT, Titans, MesaNet, test-time regression
- 거대 희소 파라미터 메모리: product-key memory, Memory Layers at Scale, UltraMem, Mixture of A Million Experts, Engram
- 가중치 밖 비모수 메모리: kNN-LM, RETRO, Memorizing Transformers
- 기억 찾기·편집: ROME, MEMIT. 단기 → 장기 압축: KVzip, gist token, Cartridges. continual learning: sparse memory finetuning