Track VII · Architecture Deep Dives · 11/12

Nemotron — Mamba 하이브리드 계보Nemotron — the hybrid Mamba lineage

Nemotron-H → Nano 2 → Nemotron 3(Nano·Super·Ultra) → Nemotron 4(발표만)로 이어지는 NVIDIA의 하이브리드 계보를 config에서 직접 읽는다. Mamba-2가 attention 대부분을 대신하는 이유(decode 비용과 고정 state)를 계산으로 유도하고, 그래도 attention을 몇 층 남기는 이유(고정 state의 recall 용량, 층 배치 ablation)를 장난감 실험과 층 배치 편집기로 확인한 뒤, LatentMoE·MTP·NVFP4가 이 골격에 어떻게 얹히는지 본다.NVIDIA's hybrid line — Nemotron-H → Nano 2 → Nemotron 3 (Nano, Super, Ultra) → Nemotron 4 (announced only) — read directly from the configs. We derive why Mamba-2 replaces most attention layers (decode cost, constant state), check with a toy experiment and a layer-pattern editor why a few attention layers stay (the recall capacity of a fixed state, the layer-pattern ablations), and see how LatentMoE, MTP and NVFP4 sit on top of this skeleton.

Most frontier labs answered “attention is too expensive at long context” with a cheaper attention: sliding windows (gpt-oss, MiMo, MAI), sparse top-k selection (DeepSeek, GLM-5), or linear attention (Qwen3-Next, Kimi Linear). NVIDIA is the one lab that, since April 2025, has built every size of its open model line on a state-space backbone: Mamba-2 layers do most of the token mixing, and a handful of ordinary attention layers are kept. This lesson reads that lineage from the models’ own config.json files and asks two questions a research engineer should be able to answer with numbers: why is Mamba-2 cheaper at decode, and why not go all the way and drop attention?

Background: the linear attention & SSM lesson derives Mamba-2 (SSD) and the chunkwise algorithms; MoE anatomy covers LatentMoE; the Nemotron 3 Ultra review covers Ultra’s data, NVFP4 divergences and MOPD post-training. Here we stay on the architecture and on what changed from generation to generation.

The lineage at a glance

Layer codes follow the configs’ hybrid_override_pattern: M = Mamba-2, A = self-attention (GQA, no positional embedding), F = dense FFN (squared ReLU), E = MoE FFN. Counts below are read from the Hugging Face configs; the rest is from each report.

Nemotron-H 8B / 56BNano 2 (12B → 9B)Nemotron 3 NanoNemotron 3 SuperNemotron 3 Ultra
Report · datearXiv 2504.03624 · 2025-04arXiv 2508.14444 · 2025-08white paper 2512.20856 · 2025-12arXiv 2604.12374 · 2026-03/04arXiv 2606.15007 · 2026-06
Params8B / 56B (→ 47B pruned)12B base → 9B30B total / ~3B active120.6B / 12.7B550B / 55B
Layers (M / A / FFN)52 (24/4/24) · 118 (54/10/54)62 (28/6/28) → 56 (27/4/25)52 (23/6/23 E)88 (40/8/40 E)108 (48/12/48 E)
Attention share of mixers14% · 16%18% → 13%21%17%20%
KV heads × dim8 × 1288 × 1282 × 1282 × 1282 × 128
Mamba-2 heads × dim, state N128×64, 128 · 256×64, 256128×80, 12864×64, 128128×64, 128256×64, 128
FFNdensedenseMoE 128, top-6 + sharedLatentMoE 512, top-22, ℓ = 1024LatentMoE 512, top-22, ℓ = 2048
MTP–––1 shared block, applied twicesame
Pretraining precisionFP8 (56B)FP8NVFP4NVFP4, 25T tokensNVFP4, 20T tokens
Throughput claim (report)56B: 2.4× vs Qwen-2.5-72B / Llama-3.1-70B (65,536 in, 1,024 out, H100)9B: up to 6× vs Qwen3-8B (8K in, 16K out, A10G)3.3× vs Qwen3-30B-A3B (8K in, 16K out)2.2× vs GPT-OSS-120B, 7.5× vs Qwen3.5-122B (8K in, 64K out, B200)5.9× / 4.8× / 1.6× vs GLM-5.1 / Kimi-K2.6 / Qwen-3.5 (8K in, 64K out, GB200)

Three trends are visible before any equation. (1) The ratio never moved much: attention is 1 in 5 to 1 in 8 token mixers in every model. (2) The KV heads fell from 8 to 2 in Nemotron 3, so each attention layer got 4× cheaper in KV, and the generation that did this added attention layers (Ultra has 12). (3) The FFN went dense → MoE → LatentMoE, and the precision FP8 → NVFP4. Note that every throughput claim is measured with long outputs (16K–64K); the next section shows why that is where a hybrid wins.

Why Mamba-2 takes over the token mixing

Count what one layer costs per decoded token, per sequence, at context length TT.

An attention layer (GQA, nqn_q query heads, nkvn_{kv} KV heads, head dim dhd_h) must read the whole cache and does two matrix–vector products against it:

bytesattn(T)=2 nkv dh T bKV,FLOPsattn(T)=4 nq dh T.\text{bytes}_{\text{attn}}(T) = 2\, n_{kv}\, d_h\, T\, b_{\text{KV}}, \qquad \text{FLOPs}_{\text{attn}}(T) = 4\, n_q\, d_h\, T .

A Mamba-2 layer keeps, per head ii, a P×NP \times N state and updates it with a scalar decay (the SSD form):

ht=at ht−1+xtBt⊤,yt=ht Ct,at=exp⁡(−ΔtA)∈(0,1),h_t = a_t\, h_{t-1} + x_t B_t^{\top}, \qquad y_t = h_t\, C_t, \qquad a_t = \exp(-\Delta_t A) \in (0, 1),

so with HH heads it reads and writes HPNH P N numbers and does about 6HPN6 H P N FLOPs (outer product, decay, read-out), independent of TT:

bytesM=2 HPN bstate,FLOPsM≈6 HPN.\text{bytes}_{\text{M}} = 2\, H P N\, b_{\text{state}}, \qquad \text{FLOPs}_{\text{M}} \approx 6\, H P N .

Plug in Nemotron 3 Super’s dimensions (nq=32n_q = 32, nkv=2n_{kv} = 2, dh=128d_h = 128; H=128H = 128, P=64P = 64, N=128N = 128; BF16 KV, FP32 state). The two layers cost the same FLOPs at T=6HPN/4nqdh=384T = 6HPN / 4n_q d_h = 384 tokens and the same memory traffic at T=2HPN⋅4/(2nkvdh⋅2)=8,192T = 2HPN\cdot 4 / (2 n_{kv} d_h \cdot 2) = 8{,}192 tokens. Below a few thousand tokens a Mamba layer is not cheaper than one of these thin GQA-2 attention layers; past them the attention layer keeps growing and the Mamba layer does not. At a 64K-token context one attention layer reads 64 MiB per step, one Mamba layer 8 MiB.

Memory is the larger effect because it decides the batch. Decode is memory-bound (roofline lesson): one step reads the weights once for the whole batch, plus every sequence’s cache. The per-sequence memory of a hybrid is

M(T)=nA⋅2nkvdhbKV⏟KV per token T+nM HPN bstate⏟constant,M(T) = \underbrace{n_A \cdot 2 n_{kv} d_h b_{\text{KV}}}_{\text{KV per token}}\, T + \underbrace{n_M\, H P N\, b_{\text{state}}}_{\text{constant}},

and the number of sequences that fit is (HBM−weights)/M(T)(\text{HBM} - \text{weights}) / M(T). For Super (nA=8n_A = 8, nM=40n_M = 40) that is 8 KiB per token plus ~160 MiB per sequence; had all 48 mixers been attention, 48 KiB per token. At 64K context that is ~0.7 GiB vs 3 GiB per sequence, i.e. a 4× larger batch in the same memory, and the weight read is amortised over 4× more tokens. Nemotron-H’s report names exactly these two sources of its speedup: “constant computation in the Mamba-2 layers” and a “lower memory footprint” that “facilitates using higher batch sizes” (§2.6).

It also explains the benchmark settings: with 8K input and 64K output the average context during decode is ~40K tokens, deep in the region where the KV term dominates. In a prefill-heavy setting (50K in, 2K out) the cost is set by active parameters instead, and Ultra (55B active) is slower than Qwen-3.5 (17B active) — the Ultra review works through that case.

Why attention is kept: a fixed state has a capacity

If Mamba is cheaper at long context, why not 100% Mamba? Because the state is a fixed-size associative memory. Take one head with no decay (at=1a_t = 1) and think of BtB_t as a key kt∈RNk_t \in \mathbb{R}^N and xtx_t as a value vt∈RPv_t \in \mathbb{R}^P. After nn writes, h=∑iviki⊤h = \sum_i v_i k_i^\top. Reading with a stored key kjk_j:

h kj=vj ∥kj∥2+∑i≠jvi (ki⊤kj).h\, k_j = v_j\, \|k_j\|^2 + \sum_{i \ne j} v_i\, (k_i^\top k_j) .

With random unit-norm keys, ki⊤kjk_i^\top k_j has variance 1/N1/N, so the cross-talk term has variance ≈(n−1)/N\approx (n-1)/N per coordinate against a signal of 1: the signal-to-noise ratio is about N/n\sqrt{N/n}. Once the number of facts nn is a small multiple of NN, retrieval fails, no matter how the state was trained. Attention keeps every key and value (n(N+P)n(N+P) numbers instead of PNPN) and its softmax can pick the right one exactly. Selectivity (input-dependent Δt\Delta_t, gating, the delta rule of DeltaNet) lets a recurrent layer choose what to store, but it cannot raise the capacity of a P×NP \times N matrix.

프론티어 랩 대부분은 “긴 컨텍스트에서 attention이 너무 비싸다”는 문제에 더 싼 attention으로 답했다. sliding window(gpt-oss, MiMo, MAI), top-k sparse 선택(DeepSeek, GLM-5), linear attention(Qwen3-Next, Kimi Linear)이 그렇다. NVIDIA는 2025년 4월부터 공개 모델 계열의 모든 크기를 state-space backbone 위에 쌓아 온 유일한 랩이다. token mixing의 대부분은 Mamba-2 층이 맡고, 평범한 attention 층은 몇 개만 남긴다. 이 레슨은 그 계보를 모델의 config.json에서 직접 읽고, 연구 엔지니어라면 숫자로 답할 수 있어야 할 두 질문을 던진다. Mamba-2는 decode에서 왜 싼가, 그리고 그렇다면 왜 attention을 아예 버리지 않는가.

배경: linear attention과 SSM 레슨이 Mamba-2(SSD)와 chunkwise 알고리즘을 유도하고, MoE 해부가 LatentMoE를, Nemotron 3 Ultra 리뷰가 Ultra의 데이터·NVFP4 발산·MOPD 사후학습을 다룬다. 여기서는 구조와 세대 사이에 바뀐 것에 집중한다.

한눈에 보는 계보

층 기호는 config의 hybrid_override_pattern을 따른다. M = Mamba-2, A = self-attention(GQA, 위치 임베딩 없음), F = dense FFN(squared ReLU), E = MoE FFN. 층 개수는 Hugging Face config에서 읽었고 나머지는 각 보고서에서 가져왔다.

Nemotron-H 8B / 56BNano 2 (12B → 9B)Nemotron 3 NanoNemotron 3 SuperNemotron 3 Ultra
보고서 · 시기arXiv 2504.03624 · 2025-04arXiv 2508.14444 · 2025-08white paper 2512.20856 · 2025-12arXiv 2604.12374 · 2026-03/04arXiv 2606.15007 · 2026-06
파라미터8B / 56B (→ 47B로 가지치기)12B base → 9B총 30B / 활성 약 3B120.6B / 12.7B550B / 55B
층 (M / A / FFN)52 (24/4/24) · 118 (54/10/54)62 (28/6/28) → 56 (27/4/25)52 (23/6/23 E)88 (40/8/40 E)108 (48/12/48 E)
mixer 중 attention 비율14% · 16%18% → 13%21%17%20%
KV head × 차원8 × 1288 × 1282 × 1282 × 1282 × 128
Mamba-2 head × 차원, state N128×64, 128 · 256×64, 256128×80, 12864×64, 128128×64, 128256×64, 128
FFNdensedenseMoE 128, top-6 + sharedLatentMoE 512, top-22, ℓ = 1024LatentMoE 512, top-22, ℓ = 2048
MTP–––공유 블록 1개를 두 번 적용같음
사전학습 정밀도FP8 (56B)FP8NVFP4NVFP4, 25T 토큰NVFP4, 20T 토큰
처리량 주장(보고서)56B: Qwen-2.5-72B / Llama-3.1-70B 대비 2.4× (입력 65,536, 출력 1,024, H100)9B: Qwen3-8B 대비 최대 6× (입력 8K, 출력 16K, A10G)Qwen3-30B-A3B 대비 3.3× (입력 8K, 출력 16K)GPT-OSS-120B 대비 2.2×, Qwen3.5-122B 대비 7.5× (입력 8K, 출력 64K, B200)GLM-5.1 / Kimi-K2.6 / Qwen-3.5 대비 5.9× / 4.8× / 1.6× (입력 8K, 출력 64K, GB200)

식을 쓰기 전에 세 흐름이 보인다. (1) 비율은 거의 움직이지 않았다. 모든 모델에서 attention은 token mixer 5–8개 중 1개다. (2) Nemotron 3에서 KV head가 8에서 2로 줄어 attention 층 하나의 KV가 4배 싸졌고, 바로 그 세대가 attention 층을 늘렸다(Ultra는 12개). (3) FFN은 dense → MoE → LatentMoE로, 정밀도는 FP8 → NVFP4로 갔다. 처리량 주장이 모두 긴 출력(16K–64K)에서 측정되었다는 점도 눈여겨보자. 다음 절이 그 이유를 보여 준다.

Mamba-2가 token mixing을 넘겨받는 이유

컨텍스트 길이 TT에서 시퀀스 하나가 토큰 하나를 decode할 때 층 하나의 비용을 세어 보자.

attention 층(GQA, query head nqn_q, KV head nkvn_{kv}, head 차원 dhd_h)은 캐시 전체를 읽고 그것과 행렬–벡터 곱을 두 번 한다.

bytesattn(T)=2 nkv dh T bKV,FLOPsattn(T)=4 nq dh T.\text{bytes}_{\text{attn}}(T) = 2\, n_{kv}\, d_h\, T\, b_{\text{KV}}, \qquad \text{FLOPs}_{\text{attn}}(T) = 4\, n_q\, d_h\, T .

Mamba-2 층은 head ii마다 P×NP \times N state를 두고 스칼라 감쇠로 갱신한다(SSD 형).

ht=at ht−1+xtBt⊤,yt=ht Ct,at=exp⁡(−ΔtA)∈(0,1)h_t = a_t\, h_{t-1} + x_t B_t^{\top}, \qquad y_t = h_t\, C_t, \qquad a_t = \exp(-\Delta_t A) \in (0, 1)

head가 HH개면 숫자 HPNH P N개를 읽고 쓰며 FLOPs는 약 6HPN6 H P N(outer product, 감쇠, 읽기)이다. TT와 무관하다.

bytesM=2 HPN bstate,FLOPsM≈6 HPN.\text{bytes}_{\text{M}} = 2\, H P N\, b_{\text{state}}, \qquad \text{FLOPs}_{\text{M}} \approx 6\, H P N .

Nemotron 3 Super의 차원(nq=32n_q = 32, nkv=2n_{kv} = 2, dh=128d_h = 128; H=128H = 128, P=64P = 64, N=128N = 128; KV는 BF16, state는 FP32)을 넣으면 두 층의 FLOPs는 T=6HPN/4nqdh=384T = 6HPN / 4n_q d_h = 384 토큰에서, 메모리 트래픽은 T=2HPN⋅4/(2nkvdh⋅2)=8,192T = 2HPN\cdot 4 / (2 n_{kv} d_h \cdot 2) = 8{,}192 토큰에서 같아진다. 수천 토큰 아래에서는 Mamba 층이 이 얇은 GQA-2 attention 층보다 싸지 않다. 그 위로 가면 attention 층은 계속 커지고 Mamba 층은 그대로다. 컨텍스트 64K에서 attention 층 하나는 step마다 64 MiB를 읽고 Mamba 층 하나는 8 MiB를 읽는다.

더 큰 효과는 메모리다. 메모리가 batch를 정하기 때문이다. decode는 메모리 대역폭에 묶인다(roofline 레슨). step 하나는 batch 전체를 위해 가중치를 한 번 읽고, 시퀀스마다 캐시를 읽는다. 하이브리드의 시퀀스당 메모리는

M(T)=nA⋅2nkvdhbKV⏟토큰당 KV T+nM HPN bstate⏟상수M(T) = \underbrace{n_A \cdot 2 n_{kv} d_h b_{\text{KV}}}_{\text{토큰당 KV}}\, T + \underbrace{n_M\, H P N\, b_{\text{state}}}_{\text{상수}}

이고, 들어가는 시퀀스 수는 (HBM−가중치)/M(T)(\text{HBM} - \text{가중치}) / M(T)다. Super(nA=8n_A = 8, nM=40n_M = 40)는 토큰당 8 KiB에 시퀀스당 약 160 MiB다. mixer 48개가 모두 attention이었다면 토큰당 48 KiB다. 컨텍스트 64K에서 시퀀스당 약 0.7 GiB 대 3 GiB, 즉 같은 메모리에 batch를 4배 넣을 수 있고 가중치 읽기도 4배 많은 토큰에 나눠진다. Nemotron-H 보고서가 꼽은 속도 향상의 원인도 정확히 이 둘이다. “Mamba-2 층의 일정한 계산량”과, “더 큰 batch를 가능하게 하는” “더 작은 메모리 사용량”(§2.6).

벤치마크 설정도 이것으로 설명된다. 입력 8K, 출력 64K면 decode 동안 평균 컨텍스트가 약 40K 토큰으로, KV 항이 지배하는 영역 깊숙이 있다. prefill이 무거운 설정(입력 50K, 출력 2K)에서는 활성 파라미터가 비용을 정하므로 Ultra(활성 55B)가 Qwen-3.5(활성 17B)보다 느리다. 이 경우는 Ultra 리뷰에서 계산했다.

attention을 남기는 이유: 고정 state에는 용량이 있다

긴 컨텍스트에서 Mamba가 더 싸다면 왜 100% Mamba로 가지 않는가? state가 고정 크기의 associative memory이기 때문이다. 감쇠가 없는(at=1a_t = 1) head 하나를 보고, BtB_t를 key kt∈RNk_t \in \mathbb{R}^N, xtx_t를 value vt∈RPv_t \in \mathbb{R}^P로 생각하자. nn번 쓰고 나면 h=∑iviki⊤h = \sum_i v_i k_i^\top다. 저장된 key kjk_j로 읽으면

h kj=vj ∥kj∥2+∑i≠jvi (ki⊤kj).h\, k_j = v_j\, \|k_j\|^2 + \sum_{i \ne j} v_i\, (k_i^\top k_j) .

key가 무작위 단위 벡터라면 ki⊤kjk_i^\top k_j의 분산은 1/N1/N이므로, 신호 1에 대해 cross-talk 항의 좌표당 분산이 약 (n−1)/N(n-1)/N이다. **신호 대 잡음비가 대략 N/n\sqrt{N/n}**이다. 사실(fact)의 개수 nn이 NN의 몇 배만 되어도 state를 어떻게 학습했든 검색이 실패한다. attention은 모든 key와 value를 보관하고(PNPN개 대신 n(N+P)n(N+P)개) softmax로 정확히 하나를 고를 수 있다. selectivity(입력에 따라 달라지는 Δt\Delta_t, gating, DeltaNet의 delta rule)는 recurrent 층이 무엇을 저장할지 고르게 해 주지만, P×NP \times N 행렬의 용량을 늘려 주지는 못한다.

A sequence writes n random (key, value) pairs (keys are random unit vectors in ℝN, values are 16-dim); then a stored key is used as a query. Left: recall accuracy vs n for a fixed-size state h = Σi an−1−i viki⊤ (N × 16 numbers, what one linear-recurrent head keeps) and for softmax attention over the cached keys. Right: for one query at the current n, the cosine similarity (−1 to 1, zero line in the middle) of the read-out to every stored value (true one in red). Drag n past N: the cross-talk from the other n−1 pairs swamps the signal, accuracy falls once n reaches about N–2N, while attention, which keeps all n(N+16) numbers of the KV cache, stays at 1.00 (with unit-norm keys the query's own key always has the largest score). A decay a<1 forgets old pairs even earlier. Growing N moves the cliff right but never removes it. 시퀀스가 무작위 (key, value) 쌍 n개를 쓰고(key는 ℝN의 무작위 단위 벡터, value는 16차원), 저장된 key 하나로 질의한다. 왼쪽: 고정 크기 state h = Σi an−1−i viki⊤(N × 16개 숫자, linear recurrent head 하나가 들고 있는 것)와 캐시된 key 전체에 대한 softmax attention의 recall 정확도 대 n. 오른쪽: 현재 n에서 질의 하나의 읽기 결과와 저장된 각 value의 cosine 유사도(−1–1, 가운데가 0선, 정답은 빨강). n을 N보다 크게 끌어 보면 나머지 n−1개 쌍의 cross-talk가 신호를 덮어 n이 대략 N–2N에 이르면 정확도가 무너진다. KV cache의 숫자 n(N+16)개를 모두 들고 있는 attention은 1.00에 머문다(key가 단위 벡터이므로 질의한 key 자신의 점수가 언제나 가장 크다). 감쇠 a<1이면 오래된 쌍을 더 일찍 잊는다. N을 키우면 절벽이 오른쪽으로 밀리지만 사라지지는 않는다.

The figure is the argument in miniature. A real Mamba-2 layer has many heads (H=128H = 128 in Super) and many layers, so its total state is large, but each fact must still be retrievable from the heads that stored it, and the cliff only moves right. The empirical record says the same:

  • Pure SSMs fail at copying and recall. In Waleffe et al. (the NVIDIA study Nemotron-H cites for its layer ratio), pure Mamba and Mamba-2 8B models “begin to respond incorrectly for input sequence lengths beyond approximately 500 tokens” on a phonebook lookup task, while the Transformer stays near 100% up to its 4,096-token training length (§3.3.3). At 1.1T tokens pure Mamba-2’s five-shot MMLU was 17 points below the Transformer’s (§3.3.1), a gap the paper ties to in-context learning of the multiple-choice format.
  • A few attention layers fix it, and more is not better. In 130M-parameter, 24-layer hybrids, validation loss was minimised “when roughly 8% of the layers are self-attention layers” (§4.1, Figure 4). The resulting Mamba-2-Hybrid 8B — 56 layers, 4 attention (7.1%), 24 Mamba-2 (42.9%), 28 MLP (50%) — beat a same-data Transformer on all 12 standard tasks by 2.65 points on average and on MMLU by 3.5 points, and was predicted to generate tokens up to 8× faster at long context (§4.2–4.3).
  • Placement: spread them out, start with Mamba. “No significantly better configuration than to evenly distribute self-attention and MLP layers” was found (§4.1, App. A). A Mamba layer goes first so that the model needs no position embedding: the recurrence already encodes order. Dropping RoPE was neutral to better at long context (16K average 53.43 without RoPE vs 52.61 with RoPE base 10K; Table 5).

Nemotron-H turned these into rules (§2.1): attention is “roughly 8% of the total number of layers”, “evenly dispersed”; “the first layer in the model is a Mamba-2 layer”, “the last layer in the model is a FFN layer”, and “self-attention layers always precede FFN layers”. Super’s report gives the role in one phrase: attention layers are “global ‘anchors’” that enable full-token interaction and long-range routing (§2.1.3); the Nemotron 3 white paper calls it “high-fidelity all-to-all information routing” (§2.1).

The compression experiments are a second, independent piece of evidence about how much attention is needed. When Nemotron-H-56B (10 attention layers) was depth-pruned to 47B, layer-importance scores ranked “some self-attention layers … among the least important” (§3.2), and the final 47B kept 5 of 10 (§3.5). When Nano 2’s 12B (6 attention layers) was pruned to 9B, the team kept attention “fixed at 4 … so as to achieve a good balance between KV cache size and long-context performance” (§4.2.2). Both say the same thing: the useful number of attention layers is small but not zero, and below it long-context quality is what breaks.

NumPy SSD recurrence = its attention-like dual form, and the recall capacity of a fixed state
import numpy as np
rs = np.random.default_rng(0)

# --- (1) one Mamba-2 (SSD) head: recurrent form == "attention-like" dual form -------------
T, Pd, N = 64, 8, 16
x = rs.normal(size=(T, Pd)); B = rs.normal(size=(T, N)); C = rs.normal(size=(T, N))
a = np.exp(-np.exp(rs.normal(size=T) - 1.0))          # a_t = exp(-dt_t * A) in (0, 1)

h = np.zeros((Pd, N)); y_rec = np.zeros((T, Pd))
for t in range(T):                                     # decode: O(P*N) per token, for any t
    h = a[t] * h + np.outer(x[t], B[t])
    y_rec[t] = h @ C[t]

logcum = np.cumsum(np.log(a))                          # L[t,s] = a_{s+1} ... a_t  (s <= t)
L = np.tril(np.exp(logcum[:, None] - logcum[None, :]))
y_dual = (L * (C @ B.T)) @ x                           # prefill: a masked, decayed "attention" matrix
print(f"recurrent vs dual form, max |diff| = {np.abs(y_rec - y_dual).max():.1e}")

# --- (2) associative recall: fixed-size state vs attention over a KV cache ----------------
def softmax_rows(S):
    S = S - S.max(1, keepdims=True); E = np.exp(S); return E / E.sum(1, keepdims=True)

def recall(n, N, P=32, decay=1.0, queries=64):
    """Write n (key, value) pairs, then query a stored key. Accuracy of
    (a) a linear state h = sum_i decay^(n-1-i) v_i k_i^T  (P*N numbers) and
    (b) softmax attention over all n cached keys           (n*(N+P) numbers)."""
    K = rs.normal(size=(n, N)) / np.sqrt(N)
    V = rs.normal(size=(n, P))
    w = decay ** np.arange(n - 1, -1, -1)
    Hs = (V * w[:, None]).T @ K                        # P x N; an SSM builds this token by token
    q = rs.choice(n, size=min(queries, n), replace=False)
    y_state = K[q] @ Hs.T
    y_attn = softmax_rows(40 * K[q] @ K.T) @ V
    Vn = V / np.linalg.norm(V, axis=1, keepdims=True)
    acc = lambda Y: np.mean((Y @ Vn.T).argmax(1) == q)  # nearest stored value is the right one?
    return acc(y_state), acc(y_attn)

print(f"\n{'pairs n':>8} | {'state N=16':>10} {'N=64':>6} {'N=256':>6} | {'N=64, decay .99':>15} | {'attention':>9}")
for n in [8, 32, 64, 128, 256, 512]:
    s16 = recall(n, 16)[0]; s64, att = recall(n, 64); s256 = recall(n, 256)[0]
    d64 = recall(n, 64, decay=0.99)[0]
    print(f"{n:>8} | {s16:>10.2f} {s64:>6.2f} {s256:>6.2f} | {d64:>15.2f} | {att:>9.2f}")
print("numbers kept at n=512, N=64: state", 64 * 32, "| KV cache", 512 * (64 + 32))
 

The first line shows that the recurrence and the masked-matrix form agree to rounding: that duality is what lets Mamba-2 prefill with tensor-core matmuls (chunkwise) and decode with an O(1)O(1) update. The table shows the capacity law: accuracy holds while n≲Nn \lesssim N, is roughly halved by n≈2n \approx 2–4N4N depending on NN, and collapses beyond; a decay of 0.99 makes it worse (old pairs fade), and attention stays at 1.00 for every nn at 24× the memory.

Where the attention layers go

Now edit the stack yourself. Every slot has Super’s dimensions, so the only thing that changes is the pattern.

그림은 논증의 축소판이다. 실제 Mamba-2 층은 head가 많고(Super는 H=128H = 128) 층도 많아서 state 전체는 크지만, 각 사실은 여전히 그것을 저장한 head에서 꺼낼 수 있어야 하므로 절벽은 오른쪽으로 밀릴 뿐이다. 실험 기록도 같은 말을 한다.

  • 순수 SSM은 복사와 recall에서 실패한다. Waleffe 등(Nemotron-H가 층 비율의 근거로 인용하는 NVIDIA 연구)에서 순수 Mamba·Mamba-2 8B는 phonebook 조회 과제에서 “입력이 약 500토큰을 넘으면 틀리기 시작”했고, Transformer는 학습 길이 4,096토큰까지 100% 가까이 유지했다(§3.3.3). 1.1T 토큰에서 순수 Mamba-2의 5-shot MMLU는 Transformer보다 17점 낮았고(§3.3.1), 논문은 이를 객관식 형식의 in-context learning과 연결한다.
  • attention 몇 층이면 고쳐지고, 많을수록 좋은 것도 아니다. 130M 파라미터·24층 하이브리드에서 validation loss는 “층의 약 8%가 self-attention일 때” 최소였다(§4.1, Figure 4). 이렇게 만든 Mamba-2-Hybrid 8B(56층: attention 4개 7.1%, Mamba-2 24개 42.9%, MLP 28개 50%)는 같은 데이터의 Transformer를 표준 과제 12개 모두에서 평균 2.65점, MMLU에서 3.5점 앞섰고, 긴 컨텍스트에서 토큰 생성이 최대 8배 빠를 것으로 예측되었다(§4.2–4.3).
  • 배치: 고르게 흩고, Mamba로 시작한다. “self-attention과 MLP 층을 고르게 분포시키는 것보다 유의하게 나은 배치는 찾지 못했다”(§4.1, 부록 A). 맨 앞에 Mamba 층을 두면 위치 임베딩이 필요 없다. 순서는 recurrence가 이미 담고 있다. RoPE를 빼는 것은 긴 컨텍스트에서 중립이거나 더 나았다(16K 평균: RoPE 없음 53.43, RoPE base 10K 52.61; Table 5).

Nemotron-H는 이것을 규칙으로 만들었다(§2.1). attention은 “전체 층 수의 약 8%“이며 “고르게 흩어” 둔다. “모델의 첫 층은 Mamba-2 층”, “마지막 층은 FFN 층”이고, “self-attention 층 뒤에는 항상 FFN 층이 온다”. Super 보고서는 그 역할을 한 구절로 말한다. attention 층은 모든 토큰 사이의 상호작용과 장거리 정보 전달을 가능하게 하는 “전역 ‘anchor‘“다(§2.1.3). Nemotron 3 white paper는 “충실도 높은 all-to-all 정보 전달”이라고 부른다(§2.1).

압축 실험은 attention이 얼마나 필요한지에 대한 독립적인 두 번째 증거다. Nemotron-H-56B(attention 10층)를 47B로 깊이 가지치기할 때 층 중요도 점수는 “일부 self-attention 층을 … 가장 덜 중요한 층” 쪽에 놓았고(§3.2), 최종 47B는 10개 중 5개를 남겼다(§3.5). Nano 2의 12B(attention 6층)를 9B로 줄일 때는 attention을 “KV cache 크기와 긴 컨텍스트 성능 사이의 균형을 위해 4개로 고정”했다(§4.2.2). 둘 다 같은 말이다. 쓸모 있는 attention 층 수는 작지만 0은 아니고, 그 아래로 가면 무너지는 것은 긴 컨텍스트 품질이다.

NumPy SSD recurrence = attention 꼴 쌍대형, 그리고 고정 state의 recall 용량
import numpy as np
rs = np.random.default_rng(0)

# --- (1) Mamba-2(SSD) head 하나: recurrent 형 == "attention 꼴" 쌍대형 ---------------------
T, Pd, N = 64, 8, 16
x = rs.normal(size=(T, Pd)); B = rs.normal(size=(T, N)); C = rs.normal(size=(T, N))
a = np.exp(-np.exp(rs.normal(size=T) - 1.0))          # a_t = exp(-dt_t * A), (0, 1) 사이

h = np.zeros((Pd, N)); y_rec = np.zeros((T, Pd))
for t in range(T):                                     # decode: 어떤 t에서도 토큰당 O(P*N)
    h = a[t] * h + np.outer(x[t], B[t])
    y_rec[t] = h @ C[t]

logcum = np.cumsum(np.log(a))                          # L[t,s] = a_{s+1} ... a_t  (s <= t)
L = np.tril(np.exp(logcum[:, None] - logcum[None, :]))
y_dual = (L * (C @ B.T)) @ x                           # prefill: 마스크·감쇠가 걸린 "attention" 행렬
print(f"recurrent vs dual form, max |diff| = {np.abs(y_rec - y_dual).max():.1e}")

# --- (2) associative recall: 고정 크기 state vs KV cache 위의 attention --------------------
def softmax_rows(S):
    S = S - S.max(1, keepdims=True); E = np.exp(S); return E / E.sum(1, keepdims=True)

def recall(n, N, P=32, decay=1.0, queries=64):
    """(key, value) 쌍 n개를 쓰고 저장된 key로 질의한다. 정확도:
    (a) 선형 state h = sum_i decay^(n-1-i) v_i k_i^T  (숫자 P*N개)
    (b) 캐시된 key n개 전체에 대한 softmax attention  (숫자 n*(N+P)개)"""
    K = rs.normal(size=(n, N)) / np.sqrt(N)
    V = rs.normal(size=(n, P))
    w = decay ** np.arange(n - 1, -1, -1)
    Hs = (V * w[:, None]).T @ K                        # P x N; SSM은 이것을 토큰마다 쌓는다
    q = rs.choice(n, size=min(queries, n), replace=False)
    y_state = K[q] @ Hs.T
    y_attn = softmax_rows(40 * K[q] @ K.T) @ V
    Vn = V / np.linalg.norm(V, axis=1, keepdims=True)
    acc = lambda Y: np.mean((Y @ Vn.T).argmax(1) == q)  # 가장 가까운 저장 value가 정답인가?
    return acc(y_state), acc(y_attn)

print(f"\n{'pairs n':>8} | {'state N=16':>10} {'N=64':>6} {'N=256':>6} | {'N=64, decay .99':>15} | {'attention':>9}")
for n in [8, 32, 64, 128, 256, 512]:
    s16 = recall(n, 16)[0]; s64, att = recall(n, 64); s256 = recall(n, 256)[0]
    d64 = recall(n, 64, decay=0.99)[0]
    print(f"{n:>8} | {s16:>10.2f} {s64:>6.2f} {s256:>6.2f} | {d64:>15.2f} | {att:>9.2f}")
print("numbers kept at n=512, N=64: state", 64 * 32, "| KV cache", 512 * (64 + 32))
 

첫 줄은 recurrence와 마스크 행렬 형이 반올림 오차 안에서 같다는 것을 보여 준다. 이 쌍대성 덕분에 Mamba-2는 prefill을 tensor core 행렬곱(chunkwise)으로, decode를 O(1)O(1) 갱신으로 할 수 있다. 표는 용량 법칙이다. 정확도는 n≲Nn \lesssim N에서 유지되고, NN에 따라 n≈2n \approx 2–4N4N에서 대략 절반이 되며, 그 너머에서 무너진다. 감쇠 0.99는 더 나쁘게 만들고(오래된 쌍이 흐려진다), attention은 24배의 메모리로 모든 nn에서 1.00을 유지한다.

attention 층은 어디에 두는가

이제 직접 층을 바꿔 보자. 모든 칸이 Super의 차원을 가지므로 바뀌는 것은 배치뿐이다.

붓:paint:
Pick a brush and click layers to repaint the stack (every slot has Nemotron 3 Super's dimensions, so only the pattern changes). Left: per-sequence decode memory vs context, solid = this pattern, dashed = the same pattern with every Mamba slot turned into attention. Right: decode tokens/s on one 8-GPU node (memory-bound proxy: 8 × 8 TB/s, 8 × 192 GB, BF16 weights/KV, FP32 SSM state; the batch is capped by what fits). The toy recall score is a stylised rule, not a measurement: each hop needs one attention layer that has a Mamba layer somewhere below it (no RoPE, so position comes from the Mamba layers); hops without one fall back to the fixed state, whose recall is calibrated to fail past a few hundred tokens. Try: delete all attention layers; put the only attention layer first; double the attention layers and watch the KV line and the batch cap. 붓을 고르고 층을 클릭해 층 배치를 바꿔 보자(모든 칸은 Nemotron 3 Super의 차원을 쓰므로 배치만 바뀐다). 왼쪽: 시퀀스 하나의 decode 메모리 대 컨텍스트. 실선은 지금 배치, 점선은 같은 배치에서 Mamba 칸을 모두 attention으로 바꾼 것이다. 오른쪽: 8-GPU 노드 하나의 decode tokens/s(메모리 대역폭 한계 근사: 8 × 8 TB/s, 8 × 192 GB, BF16 가중치·KV, FP32 SSM state, batch는 메모리에 들어가는 만큼으로 잘린다). 장난감 recall 점수는 측정이 아니라 양식화한 규칙이다. hop 하나마다 아래쪽 어딘가에 Mamba 층이 있는 attention 층이 하나 필요하다(RoPE가 없어 위치 정보는 Mamba 층에서 온다). 그런 층이 없는 hop은 고정 state로 버티는데, 그 recall은 수백 토큰을 넘으면 무너지도록 맞췄다. attention을 모두 지워 보고, 유일한 attention을 맨 앞에 두어 보고, attention을 두 배로 늘려 KV 선과 batch 상한이 어떻게 변하는지 보자.

Things to try, and what they show:

  1. Super preset, T = 64K. Memory per sequence ≈ 0.7 GiB vs ≈ 3 GiB if the 40 Mamba slots were attention; the batch cap (and with it the throughput ratio) is several times larger. Slide T down to 4K: the two lines nearly meet, and the all-attention version can even be faster, because 40 FP32 states cost more traffic than 40 thin KV caches at short context.
  2. Mamba only. The memory line is flat and throughput is best, but the toy recall collapses past a few hundred tokens: this is the phonebook result.
  3. Attention first. With the only usable attention at layer 0, nothing below it has mixed neighbouring tokens yet (no RoPE, no Mamba before it), so it cannot bind a key to its value: the “first layer is Mamba” rule. In the preset two attention layers exist but only one is usable.
  4. Recall hops = 2–3. Multi-hop lookups need several attention layers in sequence; this is the one argument for more than one or two anchors (and for spreading them through depth).
  5. Double the attention. KV per token doubles; at 1M context the batch cap halves. This is the trade Ultra made in the other direction when the KV heads fell to 2: more attention layers at the same KV budget.
NumPy Read the real layer patterns from the configs: counts, rules, KV per token, state, crossover
import numpy as np

# hybrid_override_pattern / layers_block_type from each config.json on Hugging Face
# M = Mamba-2, * = attention (GQA, no RoPE), - = dense FFN (ReLU^2), E = MoE FFN
P = {
 "Nemotron-H-8B":  "M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-",
 "Nemotron-H-56B": "M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*"
                   "-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-",
 "Nano-2-12B":     "M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M-",
 "Nano-2-9B":      "M-M-M-MM-M-M-M*-M-M-M*-M-M-M-M*-M-M-M-M*-M-MM-M-M-M-M-M-",
 "N3-Nano":        "MEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEMEM*EMEMEMEME",
 "N3-Super":       "MEMEMEM*EMEMEMEM*EMEMEMEM*EMEMEMEMEM*EMEMEMEMEM*EMEMEMEMEM*EMEMEMEMEM*EMEMEMEM*EMEMEMEME",
 "N3-Ultra":       "MEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEME",
}
# (KV heads, head dim, Mamba heads H, Mamba head dim P, state N, groups G), same configs
D = {"Nemotron-H-8B": (8, 128, 128, 64, 128, 8), "Nemotron-H-56B": (8, 128, 256, 64, 256, 8),
     "Nano-2-12B": (8, 128, 128, 80, 128, 8),    "Nano-2-9B": (8, 128, 128, 80, 128, 8),
     "N3-Nano": (2, 128, 64, 64, 128, 8),        "N3-Super": (2, 128, 128, 64, 128, 8),
     "N3-Ultra": (2, 128, 256, 64, 128, 8)}
KV_B, SSM_B, CONV_B, K_CONV = 2, 4, 2, 4      # BF16 KV, FP32 SSM state, BF16 conv window, conv width 4

print(f"{'model':<15}{'L':>4}{'M':>4}{'*':>4}{'FFN':>4}{'attn/mix':>9}{'KV/token':>10}"
      f"{'state/seq':>11}{'T* KV=state':>13}{'KV@1M':>10}{'all-attn@1M':>12}")
for name, s in P.items():
    nkv, dh, H, Pd, N, G = D[name]
    nM, nA = s.count("M"), s.count("*")
    kv_tok = nA * 2 * nkv * dh * KV_B                               # bytes per token
    state = nM * H * Pd * N * SSM_B + nM * (K_CONV - 1) * (H * Pd + 2 * G * N) * CONV_B
    allattn = (nA + nM) * 2 * nkv * dh * KV_B * 2**20               # every mixer is attention
    print(f"{name:<15}{len(s):>4}{nM:>4}{nA:>4}{len(s)-nM-nA:>4}{nA/(nA+nM):>9.0%}"
          f"{kv_tok/1024:>7.1f}KiB{state/2**20:>8.0f}MiB{state/kv_tok:>13,.0f}"
          f"{kv_tok*2**20/2**30:>7.1f}GiB{allattn/2**30:>9.1f}GiB")

def rules(s):
    pos = [i for i, c in enumerate(s) if c == "*"]
    return dict(first_is_mamba=s[0] == "M", last_is_ffn=s[-1] in "-E",
                attn_then_ffn=all(s[i + 1] in "-E" for i in pos),
                gaps=sorted(set(np.diff(pos).tolist())))
print()
for name in ["Nemotron-H-56B", "N3-Super", "N3-Ultra"]:
    print(f"{name:<15}", rules(P[name]))
nkv, dh, H, Pd, N, G = D["N3-Ultra"]
print("\nUltra check: KV/token =", 12 * 2 * nkv * dh * KV_B, "B; SSM state =",
      round(48 * H * Pd * N * 4 / 1e6, 1), "MB (Ultra review: 12,288 B and ~403 MB)")
# per-layer decode crossover for Super's dims (text above): FLOPs and traffic
nq, nkv, dh, H, Pd, N = 32, 2, 128, 128, 64, 128
print("Super per-layer crossover: FLOPs at T =", 6 * H * Pd * N // (4 * nq * dh),
      "| bytes at T =", 2 * H * Pd * N * 4 // (2 * nkv * dh * 2))
 

Read the output against the text: every model obeys the three rules (Mamba first, FFN last, FFN after each attention layer); in Nemotron-H-56B the attention layers are exactly 11 apart and in Ultra 7–9 apart (evenly dispersed); and the crossover length T∗T^* where the KV equals the fixed state moved from ~6K tokens (Nemotron-H-8B, 8 KV heads) to ~21–33K (Super/Ultra, 2 KV heads). Cutting KV heads made each attention layer cheap enough that Nemotron 3 could afford a higher attention share (17–21% of mixers) and still keep 1M-token KV at 8–12 GiB, five to six times below the all-attention counterfactual.

확인 문제Check yourself

Nemotron 3 Super keeps 8 attention layers with 2 KV heads (8 KiB/token) and 40 Mamba layers (~160 MiB FP32 state per sequence). At which workload does the hybrid layout buy the LEAST over an all-attention model with the same dimensions?

At T=2KT = 2\text{K} the KV of the counterfactual (48 KiB/token) is ~96 MiB per sequence, smaller than the hybrid’s fixed ~160 MiB of state, and each decode step also reads and writes that state. The hybrid’s advantage scales with TT: it pays a constant that is only amortised once TT is in the tens of thousands (the T∗T^* column above). That is why every throughput claim in the lineage table uses 16K–64K outputs.

From dense FFN to LatentMoE

The mixer pattern has stayed the same since Nemotron-H; the FFN slot is what changed. Nemotron 3 replaced each dense ReLU² FFN with an MoE (Nano: 128 experts, top-6, plus one shared expert), so the “E” slots now hold most of the parameters: in Super, 40 MoE layers × ~2.87B ≈ 115B of the 120.6B. Super and Ultra then moved the routed experts into a latent space of width ℓ\ell:

y=x+W↑∑i∈TopK(g(x))gi(x) Ei(W↓x)+S(x),W↓∈Rℓ×d.y = x + W_{\uparrow} \sum_{i \in \text{TopK}(g(x))} g_i(x)\, E_i(W_{\downarrow} x) + S(x), \qquad W_\downarrow \in \mathbb{R}^{\ell \times d}.

Expert weights and all-to-all bytes shrink by d/ℓd/\ell (4× in both Super and Ultra), and the saving is spent on more experts and a larger top-K at the same cost — the white paper’s ablation (8B active / 73B total, 1T tokens) moves from 128 experts top-6 to 512 experts top-22 at ℓ=1024\ell = 1024 and gains MMLU-Pro 48.30 → 52.87, code 51.95 → 55.14, math 78.32 → 80.19 (Table 1; the paper’s own formula K′=Kd/ℓK' = K d/\ell would give 24, not 22, which it does not explain). The derivation and the five design principles are in MoE anatomy and the Ultra review. For this lesson the point is how it composes with the hybrid: the Mamba layers removed the length-dependent cost of token mixing, and LatentMoE attacks the other decode cost, reading expert weights and moving tokens between GPUs.

MTP, and the price of a recurrent state

Nemotron 3 adds multi-token prediction. The white paper’s ablation on an 8B-active MoE base adds about 2.4% on average (MMLU 70.06 → 71.26, MMLU-Pro 45.05 → 47.84, GSM8K 82.49 → 84.46; Table 2) and the head reaches ~97% acceptance on the first two drafted tokens. Super uses one MTP block (attention + MoE, the config’s mtp_hybrid_override_pattern = "*E") whose weights are shared across offsets, so at inference it can be applied recursively to draft long sequences; on SPEED-Bench with 7 drafts its mean acceptance length is 3.45 vs 3.33 for Qwen3-Next and 2.70 for DeepSeek-R1 (§2.1.2). The MTP lesson and speculative decoding cover the mechanics.

Here the hybrid has a cost a Transformer does not. When a verifier rejects draft token jj, an attention layer just truncates its KV cache to position jj. A Mamba layer has no history to truncate: the state after the last draft has already absorbed the rejected tokens. The Ultra report solves this by snapshotting the SSM state at every draft step, and reuses the same mechanism at fixed token intervals for prefix caching (§5.1). A rough estimate of what that costs (ours, not the report’s): with kk drafts the verifier must hold up to k+1k{+}1 states per sequence, i.e. (k+1)×403(k+1) \times 403 MB in FP32 for Ultra — about 3.2 GB per sequence at k=7k = 7, transient but comparable to 260K tokens of its KV. The PyTorch sketch below shows the two cache types side by side.

PyTorch PyTorch: a hybrid stack built from a pattern string, with KV vs SSM caches and draft rollback 로컬에서 실행run locally (pip install torch)
import torch, torch.nn as nn, torch.nn.functional as F   # torch >= 2.4 (nn.RMSNorm)

class Mamba2Mixer(nn.Module):
    """Minimal Mamba-2 mixer, single-token decode path (follows the reference step())."""
    def __init__(self, d, H=8, P=64, N=128, G=1, conv=4):
        super().__init__()
        self.H, self.P, self.N, self.G, self.K = H, P, N, G, conv
        self.di = H * P
        self.conv_dim = self.di + 2 * G * N
        self.in_proj = nn.Linear(d, 2 * self.di + 2 * G * N + H, bias=False)   # z, xBC, dt
        self.conv_w = nn.Parameter(0.1 * torch.randn(self.conv_dim, conv))   # depthwise causal conv
        self.conv_b = nn.Parameter(torch.zeros(self.conv_dim))
        self.A_log = nn.Parameter(torch.log(torch.arange(1, H + 1, dtype=torch.float32)))
        self.dt_bias = nn.Parameter(torch.zeros(H))
        self.D = nn.Parameter(torch.ones(H))
        self.norm = nn.RMSNorm(self.di)
        self.out_proj = nn.Linear(self.di, d, bias=False)

    def init_state(self, b):
        return (torch.zeros(b, self.conv_dim, self.K),           # last K conv inputs
                torch.zeros(b, self.H, self.P, self.N))          # SSM state: no T anywhere

    def step(self, u, state):                                    # u: [b, d]
        conv_s, ssm_s = state
        GN = self.G * self.N
        z, xBC, dt = torch.split(self.in_proj(u), [self.di, self.di + 2 * GN, self.H], dim=-1)
        conv_s = torch.cat([conv_s[..., 1:], xBC[..., None]], dim=-1)
        xBC = F.silu((conv_s * self.conv_w).sum(-1) + self.conv_b)
        x, Bm, Cm = torch.split(xBC, [self.di, GN, GN], dim=-1)
        b = u.shape[0]
        x = x.view(b, self.H, self.P)
        Bm = Bm.view(b, self.G, self.N).repeat_interleave(self.H // self.G, dim=1)   # [b, H, N]
        Cm = Cm.view(b, self.G, self.N).repeat_interleave(self.H // self.G, dim=1)
        dt = F.softplus(dt + self.dt_bias)                                         # [b, H]
        a = torch.exp(-dt * torch.exp(self.A_log))                                 # decay in (0, 1)
        ssm_s = ssm_s * a[..., None, None] + (dt[..., None] * x)[..., None] * Bm[:, :, None, :]
        y = (ssm_s @ Cm[..., None]).squeeze(-1) + self.D[:, None] * x              # [b, H, P]
        y = self.norm(y.reshape(b, self.di) * F.silu(z))                           # gated RMSNorm
        return self.out_proj(y), (conv_s, ssm_s)

class GQAttention(nn.Module):
    """Causal GQA decode step without positional embedding (as in Nemotron's attention layers)."""
    def __init__(self, d, hq=8, hkv=2, dh=64):
        super().__init__()
        self.hq, self.hkv, self.dh = hq, hkv, dh
        self.q = nn.Linear(d, hq * dh, bias=False)
        self.kv = nn.Linear(d, 2 * hkv * dh, bias=False)
        self.o = nn.Linear(hq * dh, d, bias=False)

    def init_state(self, b):
        return (torch.zeros(b, self.hkv, 0, self.dh), torch.zeros(b, self.hkv, 0, self.dh))

    def step(self, u, state):
        k_c, v_c = state
        b = u.shape[0]
        q = self.q(u).view(b, self.hq, 1, self.dh)
        k, v = self.kv(u).view(b, 2, self.hkv, 1, self.dh).unbind(1)
        k_c, v_c = torch.cat([k_c, k], 2), torch.cat([v_c, v], 2)               # grows with T
        rep = self.hq // self.hkv
        o = F.scaled_dot_product_attention(q, k_c.repeat_interleave(rep, 1), v_c.repeat_interleave(rep, 1))
        return self.o(o.reshape(b, -1)), (k_c, v_c)

class ReLU2FFN(nn.Module):                        # stands in for both '-' and 'E' (see arch/moe for MoE)
    def __init__(self, d, ff=4):
        super().__init__(); self.up = nn.Linear(d, ff * d, bias=False); self.down = nn.Linear(ff * d, d, bias=False)
    def forward(self, x): return self.down(F.relu(self.up(x)) ** 2)

class HybridLM(nn.Module):
    def __init__(self, pattern, vocab=1000, d=256):
        super().__init__()
        assert pattern[0] == "M", "Nemotron rule: first layer is Mamba-2 (no positional embedding anywhere)"
        self.pattern = pattern
        make = {"M": lambda: Mamba2Mixer(d), "*": lambda: GQAttention(d), "-": lambda: ReLU2FFN(d), "E": lambda: ReLU2FFN(d)}
        self.emb = nn.Embedding(vocab, d)
        self.norms = nn.ModuleList(nn.RMSNorm(d) for _ in pattern)
        self.layers = nn.ModuleList(make[c]() for c in pattern)
        self.norm_f, self.head = nn.RMSNorm(d), nn.Linear(d, vocab, bias=False)

    def init_cache(self, b):
        return [l.init_state(b) if c in "M*" else None for c, l in zip(self.pattern, self.layers)]

    @torch.no_grad()
    def step(self, tok, cache):                   # tok: [b] -> logits [b, vocab]
        h = self.emb(tok)
        for i, (c, layer, norm) in enumerate(zip(self.pattern, self.layers, self.norms)):
            if c in "M*":
                out, cache[i] = layer.step(norm(h), cache[i])
            else:
                out = layer(norm(h))
            h = h + out
        return self.head(self.norm_f(h)), cache

def cache_bytes(cache, kind, pattern):
    return sum(t.numel() * t.element_size() for c, s in zip(pattern, cache) if c == kind for t in s)

def snapshot(cache):                              # what a verifier must keep per draft position
    return [None if s is None else tuple(t.clone() for t in s) for s in cache]

def rollback(cache, snap, pattern, keep_len):
    """Reject drafts: attention can truncate its KV; Mamba must restore a saved state."""
    out = []
    for c, s, sn in zip(pattern, cache, snap):
        if c == "*": out.append((s[0][:, :, :keep_len], s[1][:, :, :keep_len]))
        elif c == "M": out.append(sn)
        else: out.append(None)
    return out

torch.manual_seed(0)
pat = "MEMEM*EMEMEM*E"
lm = HybridLM(pat).eval()
cache = lm.init_cache(1)
for t in range(512):
    _, cache = lm.step(torch.tensor([t % 1000]), cache)
print("after 512 tokens  KV:", cache_bytes(cache, "*", pat), "B   SSM+conv:", cache_bytes(cache, "M", pat), "B")
snap = snapshot(cache)                            # position 512 accepted
for t in range(4):                                # 4 draft tokens, then all rejected
    _, cache = lm.step(torch.tensor([7]), cache)
cache = rollback(cache, snap, pat, keep_len=512)
print("after rollback    KV:", cache_bytes(cache, "*", pat), "B   SSM+conv:", cache_bytes(cache, "M", pat), "B")
 

Run it locally and the KV bytes grow linearly with the number of tokens while the SSM bytes stay put; after the rejected drafts, the KV is truncated by slicing, but the Mamba layers can only be restored because snapshot() copied them before drafting. In a real engine (the reference mamba_ssm, vLLM, TRT-LLM) the verify pass computes all k+1k{+}1 positions in one chunked forward and keeps the intermediate states instead of calling step() in a loop.

NVFP4, and which layers refuse it

Nemotron 3 trains in NVFP4 (FP4 E2M1 elements, an E4M3 scale per 16 elements, an FP32 tensor scale; 2D weight blocks, Random Hadamard Transform on wgrad inputs, stochastic rounding on gradients), “stable … for up to 25T tokens” with a relative loss gap under 1% for Nano and under 0.6% for an 8B-active model (white paper §2.4). The interesting part for the hybrid is the list of exceptions: the last 15% of the network, the QKV and attention projections, the latent projections and the MTP layers stay in BF16, and the Mamba output projections use MXFP8 because NVFP4 caused up to 40% flush-to-zero on Nano. The same sensitivity shows up after training: in Ultra’s post-training quantization, Four-Over-Six scale selection kept 98.50% median accuracy at 5.03 bits per element but dropped to 84.71% in the setting that also pushed the Mamba linear layers to FP4 (Ultra §4.2). So the few attention layers and the Mamba projections are the precision-critical parts of the stack; the experts, which hold almost all parameters, are the easy part. Formats are derived in the quantization lesson.

Nemotron 4: what has actually been announced

On 2026-12-01 (GTC Washington, D.C.) NVIDIA announced the Nemotron 4 family. Everything that official NVIDIA sources state about it, as of this writing:

  • “a family of open, frontier multimodal models built for long-running coding and knowledge work agents” (NVIDIA press release, 2026-12-01);
  • “powered by a new architecture slated to deliver the highest efficiency in its class for agentic tasks”, one that “keeps agents running fast as context grows” (same release);
  • Nemotron 4 Super comes first, “expected to be available in early 2027”, “followed by Ultra and Lightning models”, each “right-sized for optimal accuracy, performance and compute flexibility”; no dates for Ultra or Lightning;
  • “Nemotron 4 Super achieves up to 5x higher throughput across coding, math and multilingual benchmarks” — no baseline model, hardware or sequence lengths are given;
  • it is developed with “datasets, agent traces, training environments and expertise” from Nemotron Coalition partners (the release names Mistral, Perplexity, Nous Research and others), and the coalition’s first model, “a base model codeveloped by Mistral AI and NVIDIA” and trained on DGX Cloud, “will underpin the upcoming NVIDIA Nemotron 4 family” (coalition press release, 2026-03-16).

There is no technical report, model card, config or parameter count on NVIDIA’s blog, research site, Hugging Face or arXiv. NVIDIA’s text never says “Mamba”, “hybrid”, “MoE”, “LatentMoE”, “MTP” or “NVFP4” about Nemotron 4. Press coverage that attributes those features (or “sparse attention”) to it is inference, and the reports conflict with each other.

What to look for when the report lands, using this lesson’s tools: (1) the layer pattern — is it still ~1 attention per 5–8 mixers, and are the anchors still GQA with 2 KV heads, or has attention itself become sparse? (2) the state: Mamba-2 or a delta-rule variant (Gated DeltaNet, KDA) with higher recall per state byte; (3) the FFN: LatentMoE ratio d/ℓd/\ell and top-K; (4) whether the coalition base model, built with a partner whose public models are Transformers, keeps the hybrid at all; (5) how “multimodal” enters the stack; (6) MTP depth and NVFP4 exceptions; and (7) the baseline and sequence lengths behind “5x” — with the formula for M(T)M(T) above you can predict the claim from the config.

확인 문제Check yourself

A team proposes a Nemotron-style hybrid with zero attention layers 'because the Mamba state is 400 MB per sequence, which is plenty'. Which observation from this lesson is the strongest objection?

Total state size is not capacity per lookup: each head is a linear associative memory with signal-to-noise ≈N/n\approx\sqrt{N/n}, and the empirical record matches (pure Mamba-2 fails phonebook lookups beyond ~500 tokens, Waleffe et al. §3.3.3). The hybrid’s ~8–20% attention layers exist to provide exact, content-addressed retrieval. Mamba layers are what make RoPE unnecessary (option 3 is backwards), NVFP4 trains the hybrid fine with a few exceptions, and MTP works with Mamba layers (with state snapshots).

Summary

  • NVIDIA’s open line has kept one skeleton since 2025: Mamba-2 layers for most token mixing, a few GQA attention layers without positional embeddings as global anchors (about 1 in 5–8 mixers), FFN slots that went dense → MoE → LatentMoE. Layer counts and patterns can be read directly from the configs.
  • Per decoded token an attention layer costs ∝T\propto T in bytes and FLOPs; a Mamba-2 layer costs a constant ∝HPN\propto HPN. With Super’s thin GQA-2 layers the per-layer crossover is only ~8K tokens, so the hybrid’s gain is a long-context, long-output gain — which is where all throughput claims are measured — and it comes mostly from a larger batch.
  • Attention stays because a fixed P×NP \times N state is an associative memory with SNR ≈N/n\approx\sqrt{N/n}. The ablations (≈8% attention minimises loss, even spacing, Mamba first, no RoPE) and the pruning studies (47B keeps 5 of 10 attention layers; 9B keeps 4 for “KV cache size and long-context performance”) say the useful number is small but not zero.
  • Nemotron 3 cut KV heads to 2, which made each anchor cheap enough to raise the attention share to 17–21% while keeping 1M-token KV at 8–12 GiB; MTP (one shared head), LatentMoE (d/ℓ=4d/\ell = 4) and NVFP4 (with BF16/MXFP8 exceptions around attention and Mamba projections) attack the remaining decode costs. The recurrent state complicates speculative decoding and prefix caching (snapshots).
  • Nemotron 4 (announced 2026-12-01; Super early 2027, then Ultra and Lightning) has no public architecture yet: only “a new architecture” that “keeps agents running fast as context grows” and “up to 5x” throughput without a baseline. The comparison lesson places this lineage next to the attention-based alternatives.

해 볼 것과 그것이 보여 주는 것:

  1. Super 프리셋, T = 64K. 시퀀스당 메모리는 약 0.7 GiB, Mamba 칸 40개를 attention으로 바꾸면 약 3 GiB다. batch 상한(과 처리량 비율)이 몇 배 크다. T를 4K로 내리면 두 선이 거의 만나고, 전부-attention 쪽이 오히려 빠를 수도 있다. 짧은 컨텍스트에서는 FP32 state 40개의 트래픽이 얇은 KV cache 40개보다 크기 때문이다.
  2. Mamba만. 메모리 선은 평평하고 처리량은 가장 좋지만, 장난감 recall은 수백 토큰을 넘으면 무너진다. phonebook 결과 그대로다.
  3. attention이 맨 앞. 쓸 수 있는 attention이 0번 층뿐이면 그 아래에서 이웃 토큰을 섞어 준 층이 없어(RoPE도, 앞선 Mamba도 없다) key와 value를 묶을 수 없다. “첫 층은 Mamba” 규칙이다. 이 프리셋에는 attention이 둘 있지만 쓸 수 있는 것은 하나다.
  4. recall hop = 2–3. 다단계 조회에는 attention 층이 여러 개 차례로 필요하다. anchor를 한두 개보다 많이 두고 깊이 방향으로 흩어 두는 유일한 근거다.
  5. attention을 두 배로. 토큰당 KV가 두 배가 되고, 1M 컨텍스트에서 batch 상한이 절반이 된다. KV head가 2로 줄었을 때 Ultra가 반대 방향으로 한 거래가 이것이다. 같은 KV 예산으로 attention 층을 더 둔 것이다.
NumPy config에서 실제 층 배치 읽기: 개수, 규칙, 토큰당 KV, state, 교차점
import numpy as np

# Hugging Face 각 config.json의 hybrid_override_pattern / layers_block_type
# M = Mamba-2, * = attention (GQA, RoPE 없음), - = dense FFN (ReLU^2), E = MoE FFN
P = {
 "Nemotron-H-8B":  "M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-",
 "Nemotron-H-56B": "M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*"
                   "-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-",
 "Nano-2-12B":     "M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M-",
 "Nano-2-9B":      "M-M-M-MM-M-M-M*-M-M-M*-M-M-M-M*-M-M-M-M*-M-MM-M-M-M-M-M-",
 "N3-Nano":        "MEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEMEM*EMEMEMEME",
 "N3-Super":       "MEMEMEM*EMEMEMEM*EMEMEMEM*EMEMEMEMEM*EMEMEMEMEM*EMEMEMEMEM*EMEMEMEMEM*EMEMEMEM*EMEMEMEME",
 "N3-Ultra":       "MEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEME",
}
# (KV head, head 차원, Mamba head H, Mamba head 차원 P, state N, group G), 같은 config
D = {"Nemotron-H-8B": (8, 128, 128, 64, 128, 8), "Nemotron-H-56B": (8, 128, 256, 64, 256, 8),
     "Nano-2-12B": (8, 128, 128, 80, 128, 8),    "Nano-2-9B": (8, 128, 128, 80, 128, 8),
     "N3-Nano": (2, 128, 64, 64, 128, 8),        "N3-Super": (2, 128, 128, 64, 128, 8),
     "N3-Ultra": (2, 128, 256, 64, 128, 8)}
KV_B, SSM_B, CONV_B, K_CONV = 2, 4, 2, 4      # BF16 KV, FP32 SSM state, BF16 conv 창, conv 폭 4

print(f"{'model':<15}{'L':>4}{'M':>4}{'*':>4}{'FFN':>4}{'attn/mix':>9}{'KV/token':>10}"
      f"{'state/seq':>11}{'T* KV=state':>13}{'KV@1M':>10}{'all-attn@1M':>12}")
for name, s in P.items():
    nkv, dh, H, Pd, N, G = D[name]
    nM, nA = s.count("M"), s.count("*")
    kv_tok = nA * 2 * nkv * dh * KV_B                               # 토큰당 바이트
    state = nM * H * Pd * N * SSM_B + nM * (K_CONV - 1) * (H * Pd + 2 * G * N) * CONV_B
    allattn = (nA + nM) * 2 * nkv * dh * KV_B * 2**20               # mixer가 전부 attention이라면
    print(f"{name:<15}{len(s):>4}{nM:>4}{nA:>4}{len(s)-nM-nA:>4}{nA/(nA+nM):>9.0%}"
          f"{kv_tok/1024:>7.1f}KiB{state/2**20:>8.0f}MiB{state/kv_tok:>13,.0f}"
          f"{kv_tok*2**20/2**30:>7.1f}GiB{allattn/2**30:>9.1f}GiB")

def rules(s):
    pos = [i for i, c in enumerate(s) if c == "*"]
    return dict(first_is_mamba=s[0] == "M", last_is_ffn=s[-1] in "-E",
                attn_then_ffn=all(s[i + 1] in "-E" for i in pos),
                gaps=sorted(set(np.diff(pos).tolist())))
print()
for name in ["Nemotron-H-56B", "N3-Super", "N3-Ultra"]:
    print(f"{name:<15}", rules(P[name]))
nkv, dh, H, Pd, N, G = D["N3-Ultra"]
print("\nUltra check: KV/token =", 12 * 2 * nkv * dh * KV_B, "B; SSM state =",
      round(48 * H * Pd * N * 4 / 1e6, 1), "MB (Ultra review: 12,288 B and ~403 MB)")
# 본문의 Super 차원 기준 층 하나의 decode 교차점: FLOPs와 트래픽
nq, nkv, dh, H, Pd, N = 32, 2, 128, 128, 64, 128
print("Super per-layer crossover: FLOPs at T =", 6 * H * Pd * N // (4 * nq * dh),
      "| bytes at T =", 2 * H * Pd * N * 4 // (2 * nkv * dh * 2))
 

출력을 본문과 맞춰 읽어 보자. 모든 모델이 세 규칙(Mamba로 시작, FFN으로 끝, attention 뒤에 FFN)을 지킨다. Nemotron-H-56B의 attention 층은 정확히 11칸 간격, Ultra는 7–9칸 간격이다(고르게 흩어 둠). KV와 고정 state가 같아지는 길이 T∗T^*는 약 6K 토큰(Nemotron-H-8B, KV head 8)에서 약 21–33K(Super/Ultra, KV head 2)로 옮겨 갔다. KV head를 줄여 attention 층 하나가 충분히 싸졌기 때문에 Nemotron 3는 attention 비율을 높이고(mixer의 17–21%) 1M 토큰 KV를 8–12 GiB로, 전부-attention 반사실의 5–6분의 1로 유지할 수 있었다.

확인 문제Check yourself

Nemotron 3 Super는 KV head 2개짜리 attention 8층(토큰당 8 KiB)과 Mamba 40층(시퀀스당 약 160 MiB FP32 state)을 둔다. 같은 차원의 전부-attention 모델과 비교해 하이브리드 배치의 이득이 가장 작은 작업은?

T=2KT = 2\text{K}에서 반사실 모델의 KV(토큰당 48 KiB)는 시퀀스당 약 96 MiB로, 하이브리드의 고정 state 약 160 MiB보다 작고, decode step마다 그 state를 읽고 써야 한다. 하이브리드의 이점은 TT에 비례한다. TT가 수만이 되어야 상각되는 상수를 내는 셈이다(위 T∗T^* 열). 계보 표의 처리량 주장이 모두 16K–64K 출력으로 측정된 이유다.

dense FFN에서 LatentMoE로

mixer 배치는 Nemotron-H 이후 그대로이고, 바뀐 것은 FFN 칸이다. Nemotron 3는 dense ReLU² FFN을 MoE로 바꿨다(Nano: expert 128개, top-6, shared expert 1개). 그래서 이제 “E” 칸이 파라미터 대부분을 갖는다. Super에서는 MoE 40층 × 약 2.87B ≈ 115B가 120.6B 중의 몫이다. Super와 Ultra는 routed expert를 폭 ℓ\ell의 latent 공간으로 옮겼다.

y=x+W↑∑i∈TopK(g(x))gi(x) Ei(W↓x)+S(x),W↓∈Rℓ×d.y = x + W_{\uparrow} \sum_{i \in \text{TopK}(g(x))} g_i(x)\, E_i(W_{\downarrow} x) + S(x), \qquad W_\downarrow \in \mathbb{R}^{\ell \times d}.

expert 가중치와 all-to-all 바이트가 d/ℓd/\ell배(Super·Ultra 모두 4배) 줄고, 그 절약분을 같은 비용에서 expert 수와 top-K를 늘리는 데 쓴다. white paper의 ablation(활성 8B / 총 73B, 1T 토큰)은 expert 128개 top-6에서 ℓ=1024\ell = 1024의 512개 top-22로 바꿔 MMLU-Pro 48.30 → 52.87, code 51.95 → 55.14, math 78.32 → 80.19를 얻었다(Table 1; 논문 자신의 식 K′=Kd/ℓK' = K d/\ell로는 22가 아니라 24가 나오는데, 논문은 이를 설명하지 않는다). 유도와 설계 원칙 다섯 개는 MoE 해부와 Ultra 리뷰에 있다. 이 레슨에서 중요한 것은 하이브리드와 어떻게 맞물리는가다. Mamba 층이 token mixing의 길이 의존 비용을 없앴고, LatentMoE는 decode의 다른 비용, 즉 expert 가중치 읽기와 GPU 사이 토큰 이동을 공략한다.

MTP, 그리고 recurrent state의 대가

Nemotron 3는 multi-token prediction을 더한다. white paper의 ablation(활성 8B MoE base)에서 평균 약 2.4%가 올랐고(MMLU 70.06 → 71.26, MMLU-Pro 45.05 → 47.84, GSM8K 82.49 → 84.46; Table 2), head는 처음 두 draft 토큰에서 약 97% 수락률을 보였다. Super는 MTP 블록 하나(attention + MoE, config의 mtp_hybrid_override_pattern = "*E")의 가중치를 여러 offset에 공유해, 추론 때 재귀적으로 적용해 긴 draft를 만든다. SPEED-Bench에서 draft 7개일 때 평균 수락 길이는 3.45로, Qwen3-Next 3.33, DeepSeek-R1 2.70보다 길다(§2.1.2). 동작 원리는 MTP 레슨과 speculative decoding에 있다.

여기서 하이브리드에는 Transformer에 없는 비용이 있다. 검증기가 draft 토큰 jj를 거부하면 attention 층은 KV cache를 위치 jj까지 잘라내면 된다. Mamba 층에는 잘라낼 과거가 없다. 마지막 draft 뒤의 state는 거부된 토큰을 이미 흡수했다. Ultra 보고서는 draft step마다 SSM state를 snapshot해 이를 풀고, 같은 장치를 일정 토큰 간격으로 써서 prefix caching도 구현한다(§5.1). 그 비용을 어림해 보면(보고서가 아니라 우리의 추정이다) draft가 kk개일 때 검증기는 시퀀스당 최대 k+1k{+}1개의 state를 들고 있어야 하므로 Ultra는 FP32로 (k+1)×403(k+1) \times 403 MB, k=7k = 7이면 시퀀스당 약 3.2 GB다. 일시적이지만 KV 26만 토큰어치와 맞먹는다. 아래 PyTorch 스케치는 두 종류의 캐시를 나란히 보여 준다.

PyTorch PyTorch: 패턴 문자열로 만든 하이브리드 스택, KV와 SSM 캐시, draft 되돌리기 로컬에서 실행run locally (pip install torch)
import torch, torch.nn as nn, torch.nn.functional as F   # torch >= 2.4 (nn.RMSNorm)

class Mamba2Mixer(nn.Module):
    """최소 Mamba-2 mixer, 토큰 하나씩 decode하는 경로(참조 구현의 step()을 따른다)."""
    def __init__(self, d, H=8, P=64, N=128, G=1, conv=4):
        super().__init__()
        self.H, self.P, self.N, self.G, self.K = H, P, N, G, conv
        self.di = H * P
        self.conv_dim = self.di + 2 * G * N
        self.in_proj = nn.Linear(d, 2 * self.di + 2 * G * N + H, bias=False)   # z, xBC, dt
        self.conv_w = nn.Parameter(0.1 * torch.randn(self.conv_dim, conv))   # depthwise causal conv
        self.conv_b = nn.Parameter(torch.zeros(self.conv_dim))
        self.A_log = nn.Parameter(torch.log(torch.arange(1, H + 1, dtype=torch.float32)))
        self.dt_bias = nn.Parameter(torch.zeros(H))
        self.D = nn.Parameter(torch.ones(H))
        self.norm = nn.RMSNorm(self.di)
        self.out_proj = nn.Linear(self.di, d, bias=False)

    def init_state(self, b):
        return (torch.zeros(b, self.conv_dim, self.K),           # 마지막 K개 conv 입력
                torch.zeros(b, self.H, self.P, self.N))          # SSM state: 어디에도 T가 없다

    def step(self, u, state):                                    # u: [b, d]
        conv_s, ssm_s = state
        GN = self.G * self.N
        z, xBC, dt = torch.split(self.in_proj(u), [self.di, self.di + 2 * GN, self.H], dim=-1)
        conv_s = torch.cat([conv_s[..., 1:], xBC[..., None]], dim=-1)
        xBC = F.silu((conv_s * self.conv_w).sum(-1) + self.conv_b)
        x, Bm, Cm = torch.split(xBC, [self.di, GN, GN], dim=-1)
        b = u.shape[0]
        x = x.view(b, self.H, self.P)
        Bm = Bm.view(b, self.G, self.N).repeat_interleave(self.H // self.G, dim=1)   # [b, H, N]
        Cm = Cm.view(b, self.G, self.N).repeat_interleave(self.H // self.G, dim=1)
        dt = F.softplus(dt + self.dt_bias)                                         # [b, H]
        a = torch.exp(-dt * torch.exp(self.A_log))                                 # (0, 1) 사이 감쇠
        ssm_s = ssm_s * a[..., None, None] + (dt[..., None] * x)[..., None] * Bm[:, :, None, :]
        y = (ssm_s @ Cm[..., None]).squeeze(-1) + self.D[:, None] * x              # [b, H, P]
        y = self.norm(y.reshape(b, self.di) * F.silu(z))                           # gated RMSNorm
        return self.out_proj(y), (conv_s, ssm_s)

class GQAttention(nn.Module):
    """위치 임베딩 없는 causal GQA decode step(Nemotron의 attention 층처럼)."""
    def __init__(self, d, hq=8, hkv=2, dh=64):
        super().__init__()
        self.hq, self.hkv, self.dh = hq, hkv, dh
        self.q = nn.Linear(d, hq * dh, bias=False)
        self.kv = nn.Linear(d, 2 * hkv * dh, bias=False)
        self.o = nn.Linear(hq * dh, d, bias=False)

    def init_state(self, b):
        return (torch.zeros(b, self.hkv, 0, self.dh), torch.zeros(b, self.hkv, 0, self.dh))

    def step(self, u, state):
        k_c, v_c = state
        b = u.shape[0]
        q = self.q(u).view(b, self.hq, 1, self.dh)
        k, v = self.kv(u).view(b, 2, self.hkv, 1, self.dh).unbind(1)
        k_c, v_c = torch.cat([k_c, k], 2), torch.cat([v_c, v], 2)               # T와 함께 자란다
        rep = self.hq // self.hkv
        o = F.scaled_dot_product_attention(q, k_c.repeat_interleave(rep, 1), v_c.repeat_interleave(rep, 1))
        return self.o(o.reshape(b, -1)), (k_c, v_c)

class ReLU2FFN(nn.Module):                        # '-'와 'E'를 모두 대신한다(MoE는 arch/moe 참고)
    def __init__(self, d, ff=4):
        super().__init__(); self.up = nn.Linear(d, ff * d, bias=False); self.down = nn.Linear(ff * d, d, bias=False)
    def forward(self, x): return self.down(F.relu(self.up(x)) ** 2)

class HybridLM(nn.Module):
    def __init__(self, pattern, vocab=1000, d=256):
        super().__init__()
        assert pattern[0] == "M", "Nemotron 규칙: 첫 층은 Mamba-2 (위치 임베딩은 어디에도 없다)"
        self.pattern = pattern
        make = {"M": lambda: Mamba2Mixer(d), "*": lambda: GQAttention(d), "-": lambda: ReLU2FFN(d), "E": lambda: ReLU2FFN(d)}
        self.emb = nn.Embedding(vocab, d)
        self.norms = nn.ModuleList(nn.RMSNorm(d) for _ in pattern)
        self.layers = nn.ModuleList(make[c]() for c in pattern)
        self.norm_f, self.head = nn.RMSNorm(d), nn.Linear(d, vocab, bias=False)

    def init_cache(self, b):
        return [l.init_state(b) if c in "M*" else None for c, l in zip(self.pattern, self.layers)]

    @torch.no_grad()
    def step(self, tok, cache):                   # tok: [b] -> logits [b, vocab]
        h = self.emb(tok)
        for i, (c, layer, norm) in enumerate(zip(self.pattern, self.layers, self.norms)):
            if c in "M*":
                out, cache[i] = layer.step(norm(h), cache[i])
            else:
                out = layer(norm(h))
            h = h + out
        return self.head(self.norm_f(h)), cache

def cache_bytes(cache, kind, pattern):
    return sum(t.numel() * t.element_size() for c, s in zip(pattern, cache) if c == kind for t in s)

def snapshot(cache):                              # 검증기가 draft 위치마다 들고 있어야 하는 것
    return [None if s is None else tuple(t.clone() for t in s) for s in cache]

def rollback(cache, snap, pattern, keep_len):
    """draft 거부: attention은 KV를 자르면 되고, Mamba는 저장해 둔 state로 되돌려야 한다."""
    out = []
    for c, s, sn in zip(pattern, cache, snap):
        if c == "*": out.append((s[0][:, :, :keep_len], s[1][:, :, :keep_len]))
        elif c == "M": out.append(sn)
        else: out.append(None)
    return out

torch.manual_seed(0)
pat = "MEMEM*EMEMEM*E"
lm = HybridLM(pat).eval()
cache = lm.init_cache(1)
for t in range(512):
    _, cache = lm.step(torch.tensor([t % 1000]), cache)
print("after 512 tokens  KV:", cache_bytes(cache, "*", pat), "B   SSM+conv:", cache_bytes(cache, "M", pat), "B")
snap = snapshot(cache)                            # 위치 512까지 수락됨
for t in range(4):                                # draft 토큰 4개, 그리고 전부 거부
    _, cache = lm.step(torch.tensor([7]), cache)
cache = rollback(cache, snap, pat, keep_len=512)
print("after rollback    KV:", cache_bytes(cache, "*", pat), "B   SSM+conv:", cache_bytes(cache, "M", pat), "B")
 

로컬에서 돌려 보면 KV 바이트는 토큰 수에 비례해 자라고 SSM 바이트는 그대로다. 거부된 draft 뒤에 KV는 slicing으로 잘리지만, Mamba 층은 draft 전에 snapshot()이 복사해 두었기 때문에만 되돌릴 수 있다. 실제 엔진(참조 구현 mamba_ssm, vLLM, TRT-LLM)에서는 검증 단계가 k+1k{+}1개 위치 전부를 chunked forward 한 번으로 계산하고 중간 state를 보관하며, step()을 반복 호출하지 않는다.

NVFP4, 그리고 그것을 거부하는 층

Nemotron 3는 NVFP4(FP4 E2M1 원소, 원소 16개마다 E4M3 scale, 텐서마다 FP32 scale; 2D weight block, wgrad 입력에 Random Hadamard Transform, 기울기에 stochastic rounding)로 학습하며, “최대 25T 토큰까지 안정적”이고 상대 loss 차이는 Nano에서 1% 미만, 활성 8B 모델에서 0.6% 미만이었다(white paper §2.4). 하이브리드에서 흥미로운 것은 예외 목록이다. 네트워크의 마지막 15%, QKV와 attention projection, latent projection, MTP 층은 BF16에 남고, Mamba output projection은 NVFP4가 Nano에서 최대 40%의 flush-to-zero를 일으켜 MXFP8을 쓴다. 같은 민감성이 학습 뒤에도 나타난다. Ultra의 사후 양자화에서 Four-Over-Six scale 선택은 원소당 5.03비트에서 정확도 중앙값 98.50%를 지켰지만, Mamba linear 층까지 FP4로 내린 설정에서는 84.71%로 떨어졌다(Ultra §4.2). 그러니 몇 개 안 되는 attention 층과 Mamba projection이 스택에서 정밀도에 민감한 부분이고, 파라미터 거의 전부를 가진 expert는 쉬운 부분이다. 형식 자체는 양자화 레슨에서 유도한다.

Nemotron 4: 실제로 발표된 것

2026-12-01(GTC Washington, D.C.)에 NVIDIA가 Nemotron 4 계열을 발표했다. 이 글을 쓰는 시점에 NVIDIA 공식 자료가 그에 대해 말하는 것은 다음이 전부다.

  • “오래 실행되는 코딩·지식 노동 agent를 위해 만든 공개 프론티어 멀티모달 모델 계열”(NVIDIA 보도자료, 2026-12-01).
  • “agent 작업에서 같은 급 최고의 효율을 낼 새 구조”, “컨텍스트가 자라도 agent가 빠르게 돌아가게 하는” 구조(같은 보도자료).
  • Nemotron 4 Super가 먼저 나오며 “2027년 초 출시 예정”, “이어서 Ultra와 Lightning 모델”이 나오고, 각각 “정확도·성능·계산 유연성에 맞춰 크기를 정했다”. Ultra와 Lightning의 시기는 없다.
  • “Nemotron 4 Super는 코딩·수학·다국어 벤치마크에서 최대 5배 높은 처리량을 낸다”. 비교 모델, 하드웨어, 시퀀스 길이는 없다.
  • Nemotron Coalition 파트너(보도자료는 Mistral, Perplexity, Nous Research 등을 든다)의 “데이터셋, agent trace, 학습 환경, 전문성”으로 개발하며, coalition의 첫 모델인 “Mistral AI와 NVIDIA가 공동 개발한 base 모델”(DGX Cloud에서 학습)이 “다가올 Nemotron 4 계열의 토대가 된다”(coalition 보도자료, 2026-03-16).

NVIDIA 블로그, 연구 사이트, Hugging Face, arXiv 어디에도 기술 보고서, 모델 카드, config, 파라미터 수는 없다. NVIDIA의 글은 Nemotron 4에 대해 “Mamba”, “hybrid”, “MoE”, “LatentMoE”, “MTP”, “NVFP4”라는 말을 한 번도 쓰지 않는다. 이런 특징(또는 “sparse attention”)을 붙이는 언론 보도는 추론이며, 보도끼리도 엇갈린다.

보고서가 나오면 이 레슨의 도구로 볼 것: (1) 층 배치. 여전히 mixer 5–8개 중 attention 1개인가, anchor는 여전히 KV head 2개의 GQA인가, 아니면 attention 자체가 sparse해졌는가. (2) state. Mamba-2인가, state 바이트당 recall이 더 높은 delta-rule 계열(Gated DeltaNet, KDA)인가. (3) FFN. LatentMoE 비율 d/ℓd/\ell와 top-K. (4) 공개 모델이 Transformer인 파트너와 만든 coalition base 모델이 하이브리드를 유지하는가. (5) “멀티모달”이 스택에 어떻게 들어오는가. (6) MTP 깊이와 NVFP4 예외. (7) “5배”의 비교 대상과 시퀀스 길이. 위의 M(T)M(T) 식이 있으면 config에서 그 주장을 예측할 수 있다.

확인 문제Check yourself

어떤 팀이 'Mamba state가 시퀀스당 400 MB나 되니 충분하다'며 attention이 0층인 Nemotron식 하이브리드를 제안한다. 이 레슨에서 가장 강한 반론은?

state 총량이 조회 한 번의 용량은 아니다. head 하나하나가 신호 대 잡음비 ≈N/n\approx\sqrt{N/n}인 선형 associative memory이고, 실험 기록도 이와 맞는다(순수 Mamba-2는 약 500토큰을 넘으면 phonebook 조회에 실패한다, Waleffe 등 §3.3.3). 하이브리드의 8–20% attention 층은 정확한 내용 기반 검색을 위해 있다. RoPE를 필요 없게 만드는 것이 Mamba 층이고(3번은 거꾸로다), NVFP4는 몇 가지 예외만 두면 하이브리드를 잘 학습하며, MTP는 (state snapshot과 함께) Mamba 층과도 동작한다.

정리

  • NVIDIA의 공개 모델 계열은 2025년부터 골격 하나를 유지했다. token mixing의 대부분은 Mamba-2 층, 위치 임베딩 없는 GQA attention 몇 층이 전역 anchor(mixer 5–8개 중 약 1개), FFN 칸은 dense → MoE → LatentMoE로 바뀌었다. 층 개수와 배치는 config에서 바로 읽을 수 있다.
  • decode 토큰 하나에 attention 층은 바이트와 FLOPs 모두 TT에 비례하고, Mamba-2 층은 HPNHPN에 비례하는 상수다. Super의 얇은 GQA-2 층과 비교하면 층 하나의 교차점은 약 8K 토큰에 불과하므로, 하이브리드의 이득은 긴 컨텍스트·긴 출력의 이득이며(처리량 주장이 모두 거기서 측정되었다) 대부분 더 큰 batch에서 온다.
  • attention이 남는 이유는 고정된 P×NP \times N state가 신호 대 잡음비 ≈N/n\approx\sqrt{N/n}의 associative memory이기 때문이다. ablation(약 8% attention에서 loss 최소, 고른 간격, Mamba로 시작, RoPE 없음)과 가지치기 연구(47B는 attention 10개 중 5개, 9B는 “KV cache 크기와 긴 컨텍스트 성능”을 위해 4개를 남김)는 필요한 수가 작지만 0은 아니라고 말한다.
  • Nemotron 3는 KV head를 2로 줄여 anchor 하나를 충분히 싸게 만들었고, 그 덕분에 attention 비율을 17–21%로 올리고도 1M 토큰 KV를 8–12 GiB로 유지했다. MTP(공유 head 하나), LatentMoE(d/ℓ=4d/\ell = 4), NVFP4(attention과 Mamba projection 주변은 BF16/MXFP8 예외)가 남은 decode 비용을 공략한다. recurrent state는 speculative decoding과 prefix caching을 복잡하게 만든다(snapshot).
  • Nemotron 4(2026-12-01 발표, Super는 2027년 초, 이어서 Ultra와 Lightning)는 아직 공개된 구조가 없다. “컨텍스트가 자라도 agent가 빠르게 돌아가게 하는” “새 구조”와 비교 대상 없는 “최대 5배” 처리량이 전부다. 비교 레슨이 이 계보를 attention 기반 대안들 옆에 놓는다.

더 읽을거리Further reading