Track VI · Frontier Tech Reports · 16/20

gpt-oss — attention sink, MXFP4, harmonygpt-oss — attention sink, MXFP4, harmony

OpenAI의 오픈 웨이트 추론 모델 gpt-oss-120b/20b 모델 카드를 읽는다. 교대 sliding-window/dense attention과 학습된 attention sink, MXFP4 block 양자화, harmony 채팅 형식과 reasoning effort를 수식·그림·NumPy로 재현하고, 카드가 밝히지 않은 것을 구분한다.Reading the model card of OpenAI's open-weight reasoning models gpt-oss-120b/20b. We reproduce alternating sliding-window/dense attention with a learned attention sink, MXFP4 block quantization, the harmony chat format and reasoning effort with equations, figures and NumPy, and separate what the card does not disclose.

55 분min gpt-oss · OpenAI · MoE · attention sink · sliding window · MXFP4 · quantization · harmony · reasoning effort · open weights 먼저 볼 것:Before this: Attention: query·key·valueAttention: query, key, value, 추론 최적화Inference optimisation, RLVR과 추론 — GRPO, RLOO, Dr. GRPO, DAPO, GSPORLVR and reasoning — GRPO, RLOO, Dr. GRPO, DAPO, GSPO

In August 2025 OpenAI released two open-weight reasoning models, gpt-oss-120b and gpt-oss-20b, under Apache 2.0. The accompanying document calls itself a model card rather than a “system card”: once the weights are public, OpenAI cannot control the systems the model ends up in. So the document reads less like a technical report and more like an architecture summary + evaluations + safety evaluations, and it says almost nothing about the data mix or the RL algorithm.

There is still plenty to read. The released reference implementation (openai/gpt-oss) and the harmony format documentation fill the card’s gaps with code. This lesson runs three things directly: (1) the learned sink attached to attention that alternates between sliding window and dense, (2) MXFP4, which shrinks the MoE weights to 4.25 bits, and (3) reasoning effort, with which the same model changes how long it thinks across low/medium/high. Every number comes from the model card (table numbers given) or the official code.

At a glance

gpt-oss-120bgpt-oss-20b
Lab · releaseOpenAI · 2025-08 (model card, arXiv 2508.10925)same
Parameters (total / active)116.83B / 5.13B (Table 1)20.91B / 3.61B (Table 1)
ArchitectureMoE Transformer, 36 layers, top-4 of 128 expertsMoE Transformer, 24 layers, top-4 of 32 experts
Residual width · attention2880 · GQA with 64 query heads / 8 KV heads, 64-dim headssame
Attention patternbanded window (128 tokens) alternating with dense across layers + a learned sink per headsame
Contextdense layers extended to 131,072 tokens with YaRNsame
Pre-trainingtext only, “trillions of tokens”, knowledge cutoff 2024-06same
Training compute2.1M H100 GPU-hoursless than 1/10 of that (“almost 10x fewer”)
Weight format · sizeMoE weights in MXFP4 (4.25 bit/param), 60.8 GiB checkpoint12.8 GiB
LicenseApache 2.0 + gpt-oss usage policysame
Tokenizero200k_harmony, 201,088 tokenssame

What is new

  • The attention sink is built into the architecture. A single learned scalar per head is added to the softmax denominator, so attention can “pay attention to nothing”. This matters most in layers whose window is only 128 tokens (see the architecture section below).
  • Trained, then shipped, in MXFP4: the MoE weights, more than 90% of all parameters, were quantized to MXFP4 during post-training. That is why 120b fits on a single 80GB GPU and 20b fits in 16GB of memory (§2.1).
  • The harmony chat format: a role hierarchy (system > developer > user > assistant > tool) and channels (analysis / commentary / final) separate the CoT, tool calls and the answer shown to the user.
  • Three reasoning-effort levels are selected with Reasoning: low|medium|high in the system message. Accuracy rises smoothly (roughly log-linearly) with CoT length (Figure 3).
  • No direct optimization pressure on the CoT (§4.4). This was chosen to support research on CoT monitoring, and the price is that the CoT may contain hallucinations or policy-violating text.

Architecture

One block

Putting card §2.2 together with the reference implementation, the block is a GPT-2-style Pre-LN structure. For an input hh,

h←h+Attn⁡(RMSNorm⁡(h))h←h+MoE⁡(RMSNorm⁡(h))\begin{aligned} h &\leftarrow h + \operatorname{Attn}(\operatorname{RMSNorm}(h)) \\ h &\leftarrow h + \operatorname{MoE}(\operatorname{RMSNorm}(h)) \end{aligned}

The card does not mention it, but the reference implementation shows that the qkv and output projections, the router and the experts all have biases. That differs from most recent LLMs, which drop biases. (Compare with Anatomy of a Transformer block.)

MoE. The router is a linear map g=Wrh+br∈REg = W_r h + b_r \in \mathbb{R}^{E} (EE = 128 or 32). It picks the set of top-4 experts T=top4⁡(g)\mathcal{T} = \operatorname{top4}(g), then takes a softmax over the chosen four only and forms a weighted sum.

MoE⁡(h)=∑e∈Tege∑e′∈Tege′ fe(h).\operatorname{MoE}(h) = \sum_{e\in\mathcal{T}} \frac{e^{g_e}}{\sum_{e'\in\mathcal{T}} e^{g_{e'}}}\, f_e(h).

There is no shared expert. Each expert fef_e is a SwiGLU. The card’s footnote says only “unconventional, including clamping and a residual connection”; in the code it looks like this (xgx_g and xℓx_\ell are the even and odd columns of the first projection’s output).

swiglu⁡(xg,xℓ)=x~g σ(1.702 x~g)⏟sigmoid approx. of GELU⋅(x~ℓ+1),x~g=min⁡(xg,7),x~ℓ=clip⁡(xℓ,−7,7).\begin{aligned} \operatorname{swiglu}(x_g, x_\ell) &= \underbrace{\tilde x_g\,\sigma(1.702\,\tilde x_g)}_{\text{sigmoid approx. of GELU}}\cdot(\tilde x_\ell + 1), \\ \tilde x_g &= \min(x_g, 7),\quad \tilde x_\ell = \operatorname{clip}(x_\ell, -7, 7). \end{aligned}

The +1+1 gives glu⁡(xg)⋅xℓ+glu⁡(xg)\operatorname{glu}(x_g)\cdot x_\ell + \operatorname{glu}(x_g), i.e. a residual path through which the gate output passes unchanged, and the clamp prevents activations from blowing up. In a model used with low-precision (MXFP4) weights it reads as a device for keeping activations within a bounded range. The card, however, does not give the reason.

Attention: alternating windows + sink

Every layer is GQA with 64 query heads and 8 KV heads, and the head dimension is 64. The pattern alternates from layer to layer. In the reference implementation, layers with layer_idx % 2 == 0 use banded (sliding) attention with window 128, and the rest use dense causal attention. The set of keys that query ii can see is

N(i)={{ j:i−128<j≤i }sliding layer{ j:j≤i }dense layer\mathcal{N}(i) = \begin{cases}\{\, j : i-128 < j \le i \,\} & \text{sliding layer} \\ \{\, j : j \le i \,\} & \text{dense layer}\end{cases}

On top of this, a learned scalar bhb_h per head hh is added to the softmax denominator. With scores sij=qi⊤kj/64s_{ij} = q_i^\top k_j/\sqrt{64},

aij=esijebh+∑k∈N(i)esik,pisink=ebhebh+∑k∈N(i)esika_{ij} = \frac{e^{s_{ij}}}{e^{b_h} + \sum_{k\in\mathcal{N}(i)} e^{s_{ik}}}, \qquad p^{\text{sink}}_i = \frac{e^{b_h}}{e^{b_h} + \sum_{k\in\mathcal{N}(i)} e^{s_{ik}}}

and the output is oi=∑j∈N(i)aijvjo_i = \sum_{j\in\mathcal{N}(i)} a_{ij} v_j. The total mass the tokens receive is ∑jaij=1−pisink\sum_{j} a_{ij} = 1 - p^{\text{sink}}_i, less than 1. In other words, the sink is the same as attaching one virtual key whose value vector is 0 and whose logit is fixed at bhb_h. The reference implementation’s sdpa() does exactly that: it appends a sink column to the right of the score matrix, takes the softmax, and then discards that column. Fixing bh=0b_h = 0 gives Miller’s proposal of “adding 1 to the denominator” (softmax1_1).

Why is it needed? An ordinary softmax must distribute a mass of 1 somewhere. If no token is relevant to this query, attention outputs noise such as the average of the values in the window. The StreamingLLM paper observed that trained LLMs solve this problem by piling attention onto the first tokens (the attention sink). In window attention, however, the first tokens soon slide out of the window, and at that point the model collapses. Their fixes were to keep the KV of the initial tokens around, or to add a dedicated sink token during pre-training. gpt-oss’s bhb_h turns that “dedicated sink” into a per-head scalar instead of a token, so “looking at nothing” is possible even when the BOS token is not inside the 128-token window.

2025년 8월 OpenAI는 두 개의 오픈 웨이트 추론 모델, gpt-oss-120b와 gpt-oss-20b를 Apache 2.0으로 공개했다. 함께 나온 문서는 스스로를 “system card”가 아니라 model card라고 부른다. 가중치가 공개되면 그 모델이 들어갈 시스템을 OpenAI가 통제할 수 없기 때문이다. 그래서 이 문서는 기술 보고서라기보다 구조 요약 + 평가 + 안전성 평가에 가깝고, 데이터 구성이나 RL 알고리즘은 거의 말하지 않는다.

그래도 읽을 거리는 많다. 공개된 참조 구현(openai/gpt-oss)과 harmony 형식 문서가 카드의 빈칸을 코드로 메운다. 이 레슨은 세 가지를 직접 돌려 본다. (1) sliding window와 dense를 번갈아 쓰는 attention에 붙은 학습된 sink, (2) MoE 가중치를 4.25비트로 줄인 MXFP4, (3) 같은 모델이 low/medium/high로 생각 길이를 바꾸는 reasoning effort. 숫자는 모두 모델 카드(표 번호 표기)나 공식 코드에서 가져왔다.

한눈에

gpt-oss-120bgpt-oss-20b
연구소 · 공개OpenAI · 2025-08 (모델 카드, arXiv 2508.10925)같음
파라미터 (total / active)116.83B / 5.13B (Table 1)20.91B / 3.61B (Table 1)
구조MoE Transformer, 36층, 128 expert 중 top-4MoE Transformer, 24층, 32 expert 중 top-4
residual 폭 · attention2880 · GQA 64 query head / 8 KV head, head 64차원같음
attention 패턴banded window(128 토큰)와 dense를 층마다 교대 + head마다 학습된 sink같음
contextdense 층을 YaRN으로 131,072 토큰까지 확장같음
사전학습텍스트 전용, “trillions of tokens”, knowledge cutoff 2024-06같음
학습 연산H100 2.1M GPU-hours그 1/10 미만 (“almost 10x fewer”)
가중치 형식 · 크기MoE 가중치 MXFP4(4.25 bit/param), 체크포인트 60.8 GiB12.8 GiB
라이선스Apache 2.0 + gpt-oss usage policy같음
tokenizero200k_harmony, 201,088 토큰같음

무엇이 새로운가

  • attention sink를 구조에 넣었다. head마다 학습되는 스칼라 하나를 softmax 분모에 더해, attention이 “어디에도 주의를 주지 않을” 수 있게 했다. window가 128 토큰뿐인 층에서 특히 의미가 있다(아래 아키텍처 절).
  • MXFP4로 학습 후 배포: 전체 파라미터의 90% 이상인 MoE 가중치를 post-training 단계에서 MXFP4로 양자화했다. 그래서 120b가 80GB GPU 한 장에, 20b가 16GB 메모리에 들어간다(§2.1).
  • harmony 채팅 형식: 역할 위계(system > developer > user > assistant > tool)와 채널(analysis / commentary / final)로 CoT, 도구 호출, 사용자에게 보일 답을 분리한다.
  • reasoning effort 3단계를 system 메시지의 Reasoning: low|medium|high로 고른다. 정확도가 CoT 길이에 대해 매끄럽게(대략 로그-선형으로) 오른다(Figure 3).
  • CoT에 직접 최적화 압력을 주지 않았다(§4.4). CoT 감시(monitoring) 연구를 위한 선택이고, 그 대가로 CoT에 환각이나 정책 위반 문장이 섞일 수 있다.

아키텍처

블록 하나

카드 §2.2와 참조 구현을 합치면 블록은 GPT-2식 Pre-LN 구조다. 입력 hh에 대해

h←h+Attn⁡(RMSNorm⁡(h))h←h+MoE⁡(RMSNorm⁡(h))\begin{aligned} h &\leftarrow h + \operatorname{Attn}(\operatorname{RMSNorm}(h)) \\ h &\leftarrow h + \operatorname{MoE}(\operatorname{RMSNorm}(h)) \end{aligned}

카드는 언급하지 않지만 참조 구현을 보면 qkv·출력 projection, router, expert 모두 bias가 있다. 요즘 LLM이 대부분 bias를 빼는 것과 다르다. (Transformer 블록 해부와 비교해 보자.)

MoE. router는 선형 사상 g=Wrh+br∈REg = W_r h + b_r \in \mathbb{R}^{E}이고(EE = 128 또는 32), 상위 4개 expert 집합 T=top4⁡(g)\mathcal{T} = \operatorname{top4}(g)를 고른 뒤 고른 4개에 대해서만 softmax를 취해 가중합한다.

MoE⁡(h)=∑e∈Tege∑e′∈Tege′ fe(h).\operatorname{MoE}(h) = \sum_{e\in\mathcal{T}} \frac{e^{g_e}}{\sum_{e'\in\mathcal{T}} e^{g_{e'}}}\, f_e(h).

shared expert는 없다. 각 expert fef_e는 SwiGLU인데, 카드 각주가 “unconventional, including clamping and a residual connection”이라고만 적은 부분을 코드에서 보면 다음과 같다(xgx_g, xℓx_\ell은 첫 projection 출력의 짝수·홀수 열).

swiglu⁡(xg,xℓ)=x~g σ(1.702 x~g)⏟GELU의 sigmoid 근사⋅(x~ℓ+1),x~g=min⁡(xg,7),x~ℓ=clip⁡(xℓ,−7,7).\begin{aligned} \operatorname{swiglu}(x_g, x_\ell) &= \underbrace{\tilde x_g\,\sigma(1.702\,\tilde x_g)}_{\text{GELU의 sigmoid 근사}}\cdot(\tilde x_\ell + 1), \\ \tilde x_g &= \min(x_g, 7),\quad \tilde x_\ell = \operatorname{clip}(x_\ell, -7, 7). \end{aligned}

+1+1 덕분에 glu⁡(xg)⋅xℓ+glu⁡(xg)\operatorname{glu}(x_g)\cdot x_\ell + \operatorname{glu}(x_g), 즉 gate 출력이 그대로 지나가는 잔차 경로가 생기고, clamp는 활성값 폭주를 막는다. 저정밀(MXFP4) 가중치와 함께 쓰는 모델에서 활성값 범위를 묶어 두는 장치로 읽힌다. 다만 이유는 카드에 적혀 있지 않다.

attention: window 교대 + sink

각 층은 64개 query head와 8개 KV head를 쓰는 GQA이고 head 차원은 64다. 층마다 패턴이 번갈아 바뀐다. 참조 구현에서는 layer_idx % 2 == 0인 층이 window 128의 banded(sliding) attention, 나머지가 dense causal attention이다. query ii가 볼 수 있는 key 집합은

N(i)={{ j:i−128<j≤i }sliding 층{ j:j≤i }dense 층\mathcal{N}(i) = \begin{cases}\{\, j : i-128 < j \le i \,\} & \text{sliding 층} \\ \{\, j : j \le i \,\} & \text{dense 층}\end{cases}

여기에 head hh마다 학습되는 스칼라 bhb_h를 softmax 분모에 더한다. score sij=qi⊤kj/64s_{ij} = q_i^\top k_j/\sqrt{64}에 대해

aij=esijebh+∑k∈N(i)esik,pisink=ebhebh+∑k∈N(i)esika_{ij} = \frac{e^{s_{ij}}}{e^{b_h} + \sum_{k\in\mathcal{N}(i)} e^{s_{ik}}}, \qquad p^{\text{sink}}_i = \frac{e^{b_h}}{e^{b_h} + \sum_{k\in\mathcal{N}(i)} e^{s_{ik}}}

이고 출력은 oi=∑j∈N(i)aijvjo_i = \sum_{j\in\mathcal{N}(i)} a_{ij} v_j다. 토큰들이 받는 질량의 합은 ∑jaij=1−pisink\sum_{j} a_{ij} = 1 - p^{\text{sink}}_i로 1보다 작다. 즉 sink는 값 벡터가 0이고 logit이 bhb_h로 고정된 가상의 key 하나를 붙인 것과 같다. 참조 구현의 sdpa()도 정확히 그렇게, score 행렬 오른쪽에 sink 열을 이어 붙여 softmax한 뒤 그 열을 버린다. bh=0b_h = 0으로 고정하면 Miller가 제안한 “분모에 1 더하기”(softmax1_1)가 된다.

왜 필요한가. 일반 softmax는 질량 1을 반드시 어딘가에 나눠 줘야 한다. 이 query에 관련된 토큰이 없으면 attention은 window 안 값들의 평균 같은 잡음을 내보낸다. StreamingLLM 논문은 학습된 LLM이 이 문제를 첫 토큰들에 attention을 몰아주는 방식(attention sink)으로 해결한다는 것을 관찰했다. 그런데 window attention에서는 첫 토큰이 곧 window 밖으로 밀려나고, 그때 모델이 무너진다. 그들은 초기 토큰의 KV를 계속 유지하거나, 사전학습 때 전용 sink 토큰을 넣는 해법을 제시했다. gpt-oss의 bhb_h는 그 “전용 sink”를 토큰 대신 head별 스칼라로 만든 것이라, 128 토큰 window 안에 BOS가 없어도 “아무것도 보지 않기”가 가능하다.

query 위치query position – sink 질량sink mass – 토큰에 간 질량mass on tokens – 유효 key 수effective keys 1/Σw² – 출력output ‖o‖ –
Click the matrix on the left to choose a query position. Each row is one query's attention distribution, and the leftmost cell (∅) is the mass taken by the sink. In a sliding-window layer only the W keys next to the diagonal remain (real gpt-oss uses W = 128). Choose "no relevant token" and turn the sink off: the distribution spreads evenly over the window and the output ‖o‖ cannot go to 0. Raise the sink logit b and the mass drains into ∅ so that ‖o‖ → 0 — "attending to nothing" becomes possible. 왼쪽 행렬을 클릭해 query 위치를 고른다. 각 행은 한 query의 attention 분포이고, 맨 왼쪽 칸(∅)은 sink가 가져간 질량이다. sliding window 층에서는 대각선 근처 W개 key만 남는다(실제 gpt-oss는 W = 128). "관련 토큰이 없음"을 고르고 sink를 끄면 분포가 window 안에 고르게 퍼져 출력 ‖o‖가 0이 되지 못한다. sink logit b를 올리면 질량이 ∅로 빠지며 ‖o‖ → 0, 즉 "아무것도 보지 않기"가 가능해진다.

Things to check in the figure:

  1. With “no relevant token” + “no sink”, the distribution spreads evenly over the window (the effective number of keys is close to W). ‖o‖ stays near the typical size of an average of W random value vectors.
  2. In the same situation, raise bb and the mass drains into ∅ and ‖o‖ goes to 0. The layer becomes a no-op that adds nothing to the residual stream.
  3. With “a relevant token exists”, the relevant key’s logit is large, so the sink takes almost no mass. The sink is a safety valve that acts “only when there is nothing to look at”.
  4. In a sliding layer, if the old relevant token (red outline) is outside the window, this layer cannot see its information. Switch to a dense layer and it is visible again. The alternating layout is designed so that the dense layers pass this information along.

A feel for the sink’s size: if all logits are similarly near 0, psink≈eb/(eb+W)p^{\text{sink}} \approx e^{b}/(e^{b} + W). For the sink to take half the mass with a window of 128 you need b≈ln⁡128≈4.85b \approx \ln 128 \approx 4.85. The NumPy block below reproduces exactly this number.

KV cache: why alternate

A sliding layer only needs to hold the K and V of the last 128 tokens. The KV per token per layer is 2 (K,V)×8 head×64×2 B=2 KiB2\,(\text{K,V}) \times 8\,\text{head} \times 64 \times 2\,\text{B} = 2\,\text{KiB} (assuming bf16), so for length nn and LL layers

KV(n)=2 KiB×(L2 n+L2min⁡(n,128))\text{KV}(n) = 2\,\text{KiB} \times \Big(\tfrac{L}{2}\, n + \tfrac{L}{2}\min(n, 128)\Big)

and for n≫128n \gg 128 this approaches half of 2 KiB×Ln2\,\text{KiB}\times L n, the value when every layer is dense.

For 120b at n=131,072n = 131{,}072 that is about 4.5 GiB instead of 9.0 GiB all-dense. Attention compute is also O(nW)O(nW) in the sliding layers, so it drops by nearly half in long prefills. Since the dense layers handle part of the long context, the quality loss is reduced. The card only says this alternating design “follows GPT-3”, and later models such as Gemma 3 lean further toward local attention, with five local layers per global layer. (See KV cache and inference optimization.)

→ Go deeper: Attention and KV — sliding windows, sinks and local/global layouts across models.

그림에서 확인할 것:

  1. “관련 토큰이 없음” + “sink 없음”이면 분포가 window 안에 고르게 퍼진다(유효 key 수가 W에 가깝다). ‖o‖는 무작위 값 벡터 W개의 평균 크기 근처에 머문다.
  2. 같은 상황에서 bb를 올리면 질량이 ∅로 빠지고 ‖o‖가 0으로 간다. 이 층은 잔차 스트림에 아무것도 더하지 않는 no-op이 된다.
  3. “관련 토큰이 있음”에서는 관련 key의 logit이 커서 sink가 질량을 거의 빼앗지 못한다. sink는 “볼 것이 없을 때만” 작동하는 안전판이다.
  4. sliding 층에서 오래된 관련 토큰(빨간 테두리)이 window 밖이면 그 정보는 이 층에서 볼 수 없다. dense 층으로 바꾸면 다시 보인다. 교대 배치는 이 정보를 dense 층이 넘겨 주도록 한 설계다.

sink의 크기 감각: 모든 logit이 비슷하게 0 근처면 psink≈eb/(eb+W)p^{\text{sink}} \approx e^{b}/(e^{b} + W)이다. window 128에서 sink가 질량의 절반을 가져가려면 b≈ln⁡128≈4.85b \approx \ln 128 \approx 4.85가 필요하다. 아래 NumPy 블록이 이 숫자를 그대로 재현한다.

KV cache: 왜 교대인가

sliding 층은 마지막 128개 토큰의 K, V만 들고 있으면 된다. 토큰·층당 KV는 2 (K,V)×8 head×64×2 B=2 KiB2\,(\text{K,V}) \times 8\,\text{head} \times 64 \times 2\,\text{B} = 2\,\text{KiB}(bf16 가정)이므로, 길이 nn, 층 수 LL에서

KV(n)=2 KiB×(L2 n+L2min⁡(n,128))\text{KV}(n) = 2\,\text{KiB} \times \Big(\tfrac{L}{2}\, n + \tfrac{L}{2}\min(n, 128)\Big)

이고, n≫128n \gg 128이면 이 값은 모든 층이 dense일 때 2 KiB×Ln2\,\text{KiB}\times L n의 절반으로 간다.

120b에서 n=131,072n = 131{,}072이면 all-dense 9.0 GiB 대신 약 4.5 GiB다. attention 연산도 sliding 층은 O(nW)O(nW)라 긴 prefill에서 절반 가까이 줄어든다. 긴 context 일부는 dense 층이 맡으므로 품질 손해를 줄인다. 이 교대 설계는 카드가 “GPT-3를 따랐다”고만 적었고, 이후 Gemma 3처럼 local 층 다섯에 global 층 하나를 두는, 더 local 쪽으로 기운 모델도 나왔다. (KV cache와 추론 최적화 참고.)

→ 더 깊이: Attention과 KV — sliding window, sink, local/global 배치를 여러 모델에 걸쳐 본다.

━ 모두 denseall dense ━ gpt-oss: sliding/dense 교대alternating sliding/dense ┅ 모두 sliding (참고)all sliding (reference)
gpt-oss 방식gpt-oss layout – 모두 dense라면if all dense – 비율ratio – 토큰·층당per token·layer –
The strip at the top is the layer layout (violet = sliding window, blue = dense; a layer is sliding when layer_idx % 2 == 0). Below is the KV-cache size of one sequence as a function of context length (log–log). Shrink n and the three curves coincide while the context is shorter than W. Once n exceeds W the cost of the sliding layers stops at W, so at long context the gpt-oss layout comes to almost exactly half of all-dense. The other half (the dense layers) still grows in proportion to n. 위 띠는 층 배치다(보라 = sliding window, 파랑 = dense; layer_idx % 2 == 0이면 sliding). 아래는 한 시퀀스의 KV cache 크기를 context 길이에 따라 그린 것이다(로그–로그). n을 줄이면 W보다 짧은 구간에서는 세 곡선이 겹친다. n이 W를 넘으면 sliding 층의 비용은 W에서 멈추므로, 긴 context에서 gpt-oss 방식은 all-dense의 거의 정확히 절반이 된다. 나머지 절반(dense 층)은 그대로 n에 비례한다.

Positional encoding and context

The model uses RoPE and extends the dense layers’ context to 131,072 with YaRN (§2.2). The reference implementation’s config shows this as arithmetic: initial_context_length = 4096, rope_scaling_factor = 32, and 4096×32=131,0724096 \times 32 = 131{,}072. The RoPE base is 150,000. YaRN mixes interpolation and extrapolation per frequency component (NTK-by-parts) and corrects the temperature of the attention logits. In the code this is implemented as a “concentration” c=0.1ln⁡s+1c = 0.1\ln s + 1 (ss = 32, c≈1.35c \approx 1.35) that multiplies cos/sin. Since it multiplies both qq and kk, the logits are scaled by c2c^2.

NumPy Recomputing Table 1 parameter counts and checkpoint sizes from the config
import numpy as np

# gpt-oss config (ModelConfig in openai/gpt-oss gpt_oss/torch/model.py)
cfg = dict(d=2880, ff=2880, heads=64, kv=8, hd=64, vocab=201088)

def count(layers, experts, topk=4, **c):
    d, ff, H, KV, hd, V = c['d'], c['ff'], c['heads'], c['kv'], c['hd'], c['vocab']
    expert = (2 * ff * d + 2 * ff) + (d * ff + d)        # mlp1 (SwiGLU, 2x width)+bias, mlp2+bias
    router = d * experts + experts
    mlp_layer = experts * expert + router + d             # + RMSNorm before the MLP
    attn_layer = d * hd * (H + 2 * KV) + hd * (H + 2 * KV) \
               + hd * H * d + d + H + d                   # qkv, out(+bias), sinks, norm
    mlp, attn = layers * mlp_layer, layers * attn_layer
    emb = 2 * V * d                                       # embedding + unembedding (untied)
    active = layers * (topk * expert + router + d) + attn + V * d + d
    total = mlp + attn + emb + d
    # checkpoint: only expert weights (excluding biases) in MXFP4 (4.25 bit), the rest bf16
    q_params = layers * experts * (2 * ff * d + d * ff)
    ckpt = q_params * 4.25 / 8 + (total - q_params) * 2
    return mlp, attn, emb, active, total, ckpt

for name, L, E in [("120b", 36, 128), ("20b", 24, 32)]:
    mlp, attn, emb, act, tot, ck = count(L, E, **cfg)
    print(f"gpt-oss-{name}: MLP {mlp/1e9:.2f}B  Attn {attn/1e9:.2f}B  Emb+Unemb {emb/1e9:.2f}B  "
          f"active {act/1e9:.2f}B  total {tot/1e9:.2f}B  ckpt {ck/2**30:.1f} GiB")
print("Model card Table 1: 120b MLP 114.71B / Attn 0.96B / Emb 1.16B / active 5.13B / total 116.83B / 60.8GiB")
print("                    20b  MLP  19.12B / Attn 0.64B / Emb 1.16B / active 3.61B / total  20.91B / 12.8GiB")
 

From the config values alone, all six numbers in Table 1 match to two decimal places. The card’s convention of excluding the embedding but including the unembedding in the active parameters is reflected as well. The checkpoint sizes of 60.8 GiB and 12.8 GiB come out under the assumption “only the expert matrices at 4.25 bits, everything else (biases, attention, embeddings, router) in bf16”. Of 120b’s 5.13B active parameters, the experts account for about 3.6B, so the compute a single token passes through is similar to that of a 5B-class dense model — which is why this model is fast.

→ Go deeper: Design choices compared — gpt-oss’s block side by side with MiMo-V2, MiniMax-M2, GLM-5 and MAI-Base-2.

Data

The card says little about data. It is better to separate what it says from what it does not.

ItemIn the cardNot in the card
Pre-training scale“trillions of tokens”, text onlyexact token count, epochs
Compositionfocus on STEM, coding and general knowledgeper-source ratios, language ratios, whether synthetic data is used
Filteringreused GPT-4o’s CBRN pre-training filters to remove harmful data, especially hazardous biosecurity knowledgequality filters, deduplication method
Knowledge cutoff2024-06–
Tokenizero200k_harmony (o200k plus harmony special tokens), 201,088 tokens, released via TikToken–
Post-training dataa broad range of problems in coding, math, science, etc. (§2.5), role-conflict examples (instruction hierarchy), safety-refusal datanumber of problems, sources, kinds of verifiers, synthetic ratio

In the end gpt-oss is open weights, not open data. To compare against a model that releases its data recipe too, a fully open model such as AI2’s OLMo 3 is the right reference (OLMo 3 lesson). Incidentally, one can try to back out the token count from the compute the card reports (2.1M H100-hours), but MFU remains an unknown (see “Reading critically” below).

Training

Pre-training

The model was trained on H100s with PyTorch, Triton kernels for the experts and FlashAttention, and 120b took 2.1M H100-hours (§2.4). The optimizer, learning-rate schedule, batch size, precision and training stages (e.g. when the context was extended) are not disclosed. The “pre-training recipe” section that other reports take for granted is missing entirely.

Post-training: CoT RL + effort + tools

Card §2.5 describes it in one sentence: “post-trained with CoT RL techniques similar to OpenAI o3.” The RL algorithm, rewards, KL handling and number of rollouts are not given. So all this lesson can use is the generic form in this site’s notation.

max⁡θ  Ex∼D,  y∼πθ(⋅∣x)[r(x,y)]−β DKL ⁣(πθ ∥ πref)\max_\theta\; \mathbb{E}_{x\sim\mathcal{D},\; y\sim\pi_\theta(\cdot\mid x)}\big[r(x,y)\big] - \beta\, \mathbb{D}_{\mathrm{KL}}\!\big(\pi_\theta \,\|\, \pi_{\text{ref}}\big)

With a verifiable reward rr and a GRPO-style objective, the contribution of token tt takes the form min⁡(ρtA^,clip⁡(ρt,1−ε,1+ε)A^)\min(\rho_t \hat A, \operatorname{clip}(\rho_t, 1-\varepsilon, 1+\varepsilon)\hat A), ρt=πθ(yt∣⋅)/πold(yt∣⋅)\rho_t = \pi_\theta(y_t\mid\cdot)/\pi_{\text{old}}(y_t\mid\cdot). The card offers no evidence that gpt-oss used this form. The following three things, however, the card states directly.

Variable effort reasoning (§2.5.2). The model was trained to select one of three levels from a keyword in the system message such as Reasoning: low, and raising the level increases the average CoT length. How it was trained is not given, but it can be viewed as learning a conditional policy πθ(y∣x,e)\pi_\theta(y \mid x, e) that attaches an effort marker ee to the same prompt and gives it a different length budget. One possibility, for example, is a different length cost per effort level, as in r(x,y)−λe∣y∣r(x,y) - \lambda_e |y| (this formula is an assumption made for illustration).

Agentic tool use (§2.5.3). The model was trained on three kinds of tools: (1) a browsing tool that handles the web with search/open, (2) a python tool in a stateful Jupyter environment, and (3) arbitrary functions defined by a schema in the developer message. The model can interleave CoT, function calls, function results, intermediate messages to the user (preambles) and the final answer, and it was trained both with and without tools, specified through the system prompt.

Safety training (§3, §4.3). Deliberative alignment teaches refusals and jailbreak robustness, and supervised training on collected examples of conflicting roles teaches the model to follow system > developer > user in that order (instruction hierarchy).

The harmony format: a conversation split into channels

A chat template usually marks only “who spoke”. harmony adds on which channel, and to whom a message is addressed. According to the harmony docs the special tokens are <|start|>(200006), <|end|>(200007), <|message|>(200008), <|channel|>(200005), <|return|>(200002), <|call|>(200012), and one message has the form <|start|>{header}<|message|>{content}<|end|>.

  • Channel analysis: the CoT. It does not follow the same safety standards as the final answer, so the docs warn not to show it to users as is.
  • Channel commentary: function tool calls (and preambles before calling several tools).
  • Channel final: the answer shown to the user.

A shortened version of the function-call example from the harmony docs follows. The effort goes in the system message, and the function definitions, in TypeScript-like syntax, go in the developer message.

<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.
Knowledge cutoff: 2024-06
Current date: 2025-06-28

Reasoning: high

# Valid channels: analysis, commentary, final. Channel must be included for every message.
Calls to these tools must go to the commentary channel: 'functions'.<|end|>
<|start|>developer<|message|># Instructions
Use a friendly tone.
# Tools
## functions
namespace functions {
// Gets the current weather in the provided location.
type get_weather = (_: { location: string, format?: "celsius" | "fahrenheit" }) => any;
} // namespace functions<|end|>
<|start|>user<|message|>What is the weather like in SF?<|end|>
<|start|>assistant<|channel|>analysis<|message|>Need to use function get_weather.<|end|>
<|start|>assistant<|channel|>commentary to=functions.get_weather <|constrain|>json<|message|>{"location":"San Francisco"}<|call|>
<|start|>functions.get_weather to=assistant<|channel|>commentary<|message|>{"sunny": true, "temperature": 20}<|end|>
<|start|>assistant

(Line breaks between messages were added for readability; in practice they are concatenated. The original example defines the function as get_current_weather and calls get_weather; here the names were made consistent.) When the model stops at <|call|>, the harness runs the tool, appends the result as a message from the functions.get_weather role, and samples again. Two rules matter.

  1. Erase the CoT of past, completed turns. If a previous assistant turn ended with final, that turn’s analysis messages are dropped from the next input (card §2.5.1 also says explicitly to “remove reasoning traces from past assistant turns”).
  2. Keep the CoT of a turn whose tool call is still in progress. When inserting a function result and sampling again, as in the example above, the preceding CoT (“Need to use function get_weather.”) must be included so the model can continue its thought.

The decision not to pressure the CoT

§4.4 cites prior OpenAI work. Monitoring the CoT helps catch misbehaviour, but putting pressure on the CoT itself (“don’t think bad thoughts”) can train the model to hide its thoughts while continuing to misbehave (Baker et al., 2025). The card therefore states that no direct optimization pressure was applied to the CoT of either model. As a result the CoT may contain hallucinations or language that does not comply with OpenAI’s safety policies, and developers should not show the CoT to users without filtering or summarizing it. From the perspective of the over-optimization lesson on reward hacking, this is the choice “do not put the monitoring signal into the reward”.

Core methods in depth

1. MXFP4: 32 values share one exponent

MX (microscaling) formats are block formats in which kk elements share one scale. MXFP4 has k=32k = 32, elements in FP4 E2M1 (1 sign, 2 exponent, 1 mantissa bit), and a shared scale in E8M0 (an 8-bit exponent-only number, i.e. a power of two). The magnitudes an element can represent are only the eight values

{0, 0.5, 1, 1.5, 2, 3, 4, 6}\{0,\ 0.5,\ 1,\ 1.5,\ 2,\ 3,\ 4,\ 6\}

(16 codes with sign, FP4_VALUES in the reference implementation). The cost per element is 4+8/32=4.254 + 8/32 = 4.25 bits, which is exactly the card’s “4.25 bits per parameter”.

The conversion in the Microscaling paper (Algorithm 1) aligns the exponent of the block’s maximum absolute value with FP4’s largest binade. E2M1’s largest normal number is 6=1.5⋅226 = 1.5\cdot 2^2, so emax⁡=2e_{\max} = 2 and

X=2⌊log⁡2max⁡i∣vi∣⌋−2,Pi=round⁡FP4 ⁣(clip⁡(vi/X,−6,6)),v^i=X Pi.X = 2^{\lfloor \log_2 \max_i |v_i| \rfloor - 2}, \qquad P_i = \operatorname{round}_{\text{FP4}}\!\big(\operatorname{clip}(v_i / X, -6, 6)\big), \qquad \hat v_i = X\,P_i .

Two consequences follow.

  • Because of the floor, max⁡∣v∣/X∈[4,8)\max|v|/X \in [4, 8). A quotient above 6 (when the largest element lies between 6X6X and 8X8X) is clamped to 6. The largest value can shrink by up to 25%.
  • Since there is one scale for the whole block, when a single outlier inflates the block’s scale, the small values in the same block fall below 0.5X and are flushed to 0. The smaller the block, the narrower the damage. 32 is a compromise between the metadata cost (8/k bits) and this locality.

위치 인코딩과 context

RoPE를 쓰고 dense 층의 context를 YaRN으로 131,072까지 늘렸다(§2.2). 참조 구현의 설정이 이를 산수로 보여 준다. initial_context_length = 4096, rope_scaling_factor = 32이고 4096×32=131,0724096 \times 32 = 131{,}072다. RoPE 밑은 150,000이다. YaRN은 주파수 성분별로 보간과 외삽을 섞고(NTK-by-parts), attention logit의 온도를 보정한다. 코드에서는 c=0.1ln⁡s+1c = 0.1\ln s + 1(ss = 32, c≈1.35c \approx 1.35)을 cos/sin에 곱하는 “concentration”으로 구현했다. qq와 kk 모두에 곱해지므로 logit은 c2c^2배가 된다.

NumPy Table 1 파라미터 수와 체크포인트 크기를 설정에서 다시 계산
import numpy as np

# gpt-oss 설정 (openai/gpt-oss gpt_oss/torch/model.py 의 ModelConfig)
cfg = dict(d=2880, ff=2880, heads=64, kv=8, hd=64, vocab=201088)

def count(layers, experts, topk=4, **c):
    d, ff, H, KV, hd, V = c['d'], c['ff'], c['heads'], c['kv'], c['hd'], c['vocab']
    expert = (2 * ff * d + 2 * ff) + (d * ff + d)        # mlp1(SwiGLU 2배 폭)+bias, mlp2+bias
    router = d * experts + experts
    mlp_layer = experts * expert + router + d             # + MLP 앞 RMSNorm
    attn_layer = d * hd * (H + 2 * KV) + hd * (H + 2 * KV) \
               + hd * H * d + d + H + d                   # qkv, out(+bias), sinks, norm
    mlp, attn = layers * mlp_layer, layers * attn_layer
    emb = 2 * V * d                                       # embedding + unembedding (untied)
    active = layers * (topk * expert + router + d) + attn + V * d + d
    total = mlp + attn + emb + d
    # 체크포인트: expert weight(=bias 제외)만 MXFP4(4.25 bit), 나머지는 bf16
    q_params = layers * experts * (2 * ff * d + d * ff)
    ckpt = q_params * 4.25 / 8 + (total - q_params) * 2
    return mlp, attn, emb, active, total, ckpt

for name, L, E in [("120b", 36, 128), ("20b", 24, 32)]:
    mlp, attn, emb, act, tot, ck = count(L, E, **cfg)
    print(f"gpt-oss-{name}: MLP {mlp/1e9:.2f}B  Attn {attn/1e9:.2f}B  Emb+Unemb {emb/1e9:.2f}B  "
          f"active {act/1e9:.2f}B  total {tot/1e9:.2f}B  ckpt {ck/2**30:.1f} GiB")
print("모델 카드 Table 1: 120b MLP 114.71B / Attn 0.96B / Emb 1.16B / active 5.13B / total 116.83B / 60.8GiB")
print("                   20b  MLP  19.12B / Attn 0.64B / Emb 1.16B / active 3.61B / total  20.91B / 12.8GiB")
 

설정값만으로 Table 1의 여섯 숫자가 소수 둘째 자리까지 맞는다. active 파라미터에 embedding은 빼고 unembedding은 넣는다는 카드의 규칙도 그대로 반영했다. 체크포인트 크기는 “expert 행렬만 4.25비트, 나머지(bias, attention, embedding, router)는 bf16”이라는 가정으로 60.8 GiB와 12.8 GiB가 나온다. 120b의 active 5.13B 중 expert 몫은 3.6B 정도라, 토큰 하나가 지나가는 연산은 5B급 dense 모델과 비슷하다는 점이 이 모델이 빠른 이유다.

→ 더 깊이: 설계 선택 비교 — gpt-oss의 블록을 MiMo-V2, MiniMax-M2, GLM-5, MAI-Base-2와 나란히 놓는다.

데이터

카드가 밝힌 데이터 정보는 짧다. 무엇을 말했고 무엇을 말하지 않았는지 나눠 두는 편이 낫다.

항목카드에 있는 것없는 것
사전학습 규모“trillions of tokens”, 텍스트 전용정확한 토큰 수, epoch
구성STEM, 코딩, 일반 지식에 초점출처별 비율, 언어 비율, 합성 데이터 여부
필터링GPT-4o의 CBRN 사전학습 필터를 재사용해 유해 데이터, 특히 생물보안 위험 지식을 걸렀다품질 필터, 중복 제거 방법
knowledge cutoff2024-06–
tokenizero200k_harmony(o200k에 harmony 특수 토큰 추가), 201,088 토큰, TikToken으로 공개–
사후학습 데이터코딩·수학·과학 등 넓은 범위의 문제(§2.5), 역할 충돌 예시(instruction hierarchy), 안전 거절 데이터문제 수, 출처, 검증기 종류, 합성 비율

결국 gpt-oss는 오픈 웨이트이지 오픈 데이터가 아니다. 데이터 레시피까지 공개한 모델과 비교하려면 AI2의 OLMo 3 같은 완전 공개 모델 쪽이 맞다(OLMo 3 레슨). 참고로 카드가 밝힌 연산량(2.1M H100-hours)에서 토큰 수를 거꾸로 짐작해 볼 수는 있지만 MFU라는 미지수가 하나 남는다(아래 “비판적으로 읽기”).

학습

사전학습

H100에서 PyTorch와 expert용 Triton 커널, FlashAttention으로 학습했고 120b에 2.1M H100-hours가 들었다(§2.4). optimizer, 학습률 스케줄, batch, 정밀도, 학습 단계(context 확장 시점 등)는 공개되지 않았다. 다른 보고서에서 당연히 있는 “사전학습 레시피” 절이 통째로 없는 셈이다.

사후학습: CoT RL + effort + 도구

카드 §2.5의 설명은 한 문장이다. “OpenAI o3와 비슷한 CoT RL 기법으로 사후학습했다.” RL 알고리즘, 보상, KL 처리, 롤아웃 수는 나오지 않는다. 따라서 이 레슨에서 쓸 수 있는 것은 이 사이트 표기의 일반형뿐이다.

max⁡θ  Ex∼D,  y∼πθ(⋅∣x)[r(x,y)]−β DKL ⁣(πθ ∥ πref)\max_\theta\; \mathbb{E}_{x\sim\mathcal{D},\; y\sim\pi_\theta(\cdot\mid x)}\big[r(x,y)\big] - \beta\, \mathbb{D}_{\mathrm{KL}}\!\big(\pi_\theta \,\|\, \pi_{\text{ref}}\big)

검증 가능한 보상 rr에 대해 GRPO류 목적을 쓰면 토큰 tt의 기여는 min⁡(ρtA^,clip⁡(ρt,1−ε,1+ε)A^)\min(\rho_t \hat A, \operatorname{clip}(\rho_t, 1-\varepsilon, 1+\varepsilon)\hat A), ρt=πθ(yt∣⋅)/πold(yt∣⋅)\rho_t = \pi_\theta(y_t\mid\cdot)/\pi_{\text{old}}(y_t\mid\cdot) 꼴이다. gpt-oss가 이 형태를 썼다는 증거는 카드에 없다. 다만 아래 세 가지는 카드가 직접 말한다.

Variable effort reasoning(§2.5.2). system 메시지에 Reasoning: low처럼 키워드를 넣어 세 단계를 고르도록 학습했고, 단계를 올리면 평균 CoT 길이가 늘어난다. 어떻게 학습했는지는 없지만, 같은 프롬프트에 effort 표식 ee를 붙여 길이 예산을 다르게 주는 조건부 정책 πθ(y∣x,e)\pi_\theta(y \mid x, e)를 배운 것으로 볼 수 있다. 예컨대 r(x,y)−λe∣y∣r(x,y) - \lambda_e |y|처럼 effort별로 길이 비용을 달리 주는 방식이 한 가지 가능성이다(이 식은 설명을 위한 가정이다).

Agentic tool use(§2.5.3). 세 종류의 도구를 학습했다. (1) search/open으로 웹을 다루는 browsing 도구, (2) 상태가 유지되는 Jupyter 환경의 python 도구, (3) developer 메시지에 스키마로 정의한 임의 함수. 모델은 CoT, 함수 호출, 함수 결과, 사용자용 중간 메시지(preamble), 최종 답을 섞어 낼 수 있고, 도구가 있는 경우와 없는 경우 모두 system 프롬프트로 지정해 학습했다.

안전 학습(§3, §4.3). deliberative alignment로 거절과 jailbreak 강건성을 가르치고, 역할끼리 충돌하는 예시를 모아 system > developer > user 순으로 따르도록 지도학습했다(instruction hierarchy).

harmony 형식: 채널로 나눈 대화

chat template은 보통 “누가 말했는가”만 표시한다. harmony는 여기에 어느 채널로, 누구에게 말하는지를 더한다. 특수 토큰은 harmony 문서 기준 <|start|>(200006), <|end|>(200007), <|message|>(200008), <|channel|>(200005), <|return|>(200002), <|call|>(200012)이고, 메시지 하나는 <|start|>{header}<|message|>{content}<|end|> 꼴이다.

  • 채널 analysis: CoT. 최종 답과 같은 안전 기준을 따르지 않으므로 사용자에게 그대로 보이지 말라고 문서가 경고한다.
  • 채널 commentary: 함수 도구 호출(그리고 여러 도구를 부르기 전의 preamble).
  • 채널 final: 사용자에게 보일 답.

harmony 문서의 함수 호출 예를 줄이면 다음과 같다. system 메시지에 effort가, developer 메시지에 TypeScript 비슷한 문법의 함수 정의가 들어간다.

<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.
Knowledge cutoff: 2024-06
Current date: 2025-06-28

Reasoning: high

# Valid channels: analysis, commentary, final. Channel must be included for every message.
Calls to these tools must go to the commentary channel: 'functions'.<|end|>
<|start|>developer<|message|># Instructions
Use a friendly tone.
# Tools
## functions
namespace functions {
// Gets the current weather in the provided location.
type get_weather = (_: { location: string, format?: "celsius" | "fahrenheit" }) => any;
} // namespace functions<|end|>
<|start|>user<|message|>What is the weather like in SF?<|end|>
<|start|>assistant<|channel|>analysis<|message|>Need to use function get_weather.<|end|>
<|start|>assistant<|channel|>commentary to=functions.get_weather <|constrain|>json<|message|>{"location":"San Francisco"}<|call|>
<|start|>functions.get_weather to=assistant<|channel|>commentary<|message|>{"sunny": true, "temperature": 20}<|end|>
<|start|>assistant

(가독성을 위해 메시지 사이에 줄바꿈을 넣었다. 실제로는 이어 붙인다. 원문 예제는 함수를 get_current_weather로 정의하고 get_weather를 호출하는데, 여기서는 이름을 하나로 맞췄다.) 모델이 <|call|>에서 멈추면 하니스가 도구를 실행하고, 결과를 functions.get_weather 역할의 메시지로 붙여 다시 샘플링한다. 다음 두 규칙이 중요하다.

  1. 턴이 끝난 과거의 CoT는 지운다. 이전 assistant 턴이 final로 끝났다면 그 턴의 analysis 메시지는 다음 입력에서 뺀다(카드 §2.5.1도 “past assistant turns의 reasoning trace를 제거하라”고 명시한다).
  2. 도구 호출이 진행 중인 턴의 CoT는 남긴다. 위 예처럼 함수 결과를 넣고 다시 샘플링할 때는 직전 CoT(“Need to use function get_weather.”)를 함께 넣어야 모델이 생각을 이어 간다.

CoT에 압력을 주지 않는다는 결정

§4.4는 OpenAI의 이전 연구를 인용한다. CoT를 감시하면 오작동을 잡는 데 도움이 되지만, CoT 자체에 “나쁜 생각을 하지 말라”는 압력을 주면 모델이 생각은 숨기고 오작동은 계속하는 쪽으로 학습될 수 있다(Baker et al., 2025). 그래서 두 모델 모두 CoT에 직접적인 최적화 압력을 주지 않았다고 밝힌다. 결과로 CoT에는 환각이나 OpenAI 안전 정책에 맞지 않는 표현이 섞일 수 있으며, 개발자는 CoT를 필터링·요약 없이 사용자에게 보여 주면 안 된다. 보상 해킹을 다룬 과최적화 레슨의 관점에서 보면 “감시 신호를 보상에 넣지 않는다”는 선택이다.

핵심 method 깊게 보기

1. MXFP4: 32개가 지수 하나를 나눠 쓴다

MX(microscaling) 형식은 kk개 원소가 공유 scale 하나를 쓰는 block 형식이다. MXFP4는 k=32k = 32, 원소는 FP4 E2M1(부호 1, 지수 2, 가수 1비트), 공유 scale은 E8M0(지수만 있는 8비트, 즉 2의 거듭제곱)이다. 원소가 표현할 수 있는 크기는

{0, 0.5, 1, 1.5, 2, 3, 4, 6}\{0,\ 0.5,\ 1,\ 1.5,\ 2,\ 3,\ 4,\ 6\}

의 여덟 개(부호 포함 16개 코드, 참조 구현 FP4_VALUES)뿐이다. 원소당 비용은 4+8/32=4.254 + 8/32 = 4.25비트이고, 카드가 말한 “4.25 bits per parameter”가 바로 이것이다.

Microscaling 논문의 변환(Algorithm 1)은 block의 최대 절댓값의 지수를 FP4의 최대 binade에 맞춘다. E2M1의 최대 정규수 6=1.5⋅226 = 1.5\cdot 2^2이라 emax⁡=2e_{\max} = 2이고

X=2⌊log⁡2max⁡i∣vi∣⌋−2,Pi=round⁡FP4 ⁣(clip⁡(vi/X,−6,6)),v^i=X Pi.X = 2^{\lfloor \log_2 \max_i |v_i| \rfloor - 2}, \qquad P_i = \operatorname{round}_{\text{FP4}}\!\big(\operatorname{clip}(v_i / X, -6, 6)\big), \qquad \hat v_i = X\,P_i .

두 가지 귀결이 있다.

  • floor 때문에 max⁡∣v∣/X∈[4,8)\max|v|/X \in [4, 8)이다. 6을 넘는 몫(최대 원소가 6X6X와 8X8X 사이)은 6으로 clamp된다. 가장 큰 값이 최대 25% 줄어들 수 있다.
  • scale이 block 전체에서 하나라, outlier 하나가 block의 scale을 키우면 같은 block의 작은 값들이 0.5X보다 작아져 0으로 뭉개진다. block이 작을수록 피해 범위가 좁다. 32는 메타데이터 비용(8/k비트)과 이 국소성 사이의 타협이다.
bits/원소bits/element – 이 block의 scale Xscale X of this block – 상대 RMSE(전체 4096개)relative RMSE (all 4096) – 0으로 뭉개진 비율flushed to zero – clamp된 비율clamped –
Left: the original values of one block (grey dots) and their MXFP4 reconstruction (blue); the horizontal lines are the values representable in that block, X·{0, ±0.5, ±1, ±1.5, ±2, ±3, ±4, ±6} (at most 64 elements shown). Right: overall relative error versus block size. Raise the outlier scale and the block containing the outlier gets a larger scale, so the small values in the same block are flushed to 0. The larger the block, the wider the damage. Because of the floor, the E8M0 scale puts max/X in [4, 8), and values above 6 are clamped to 6. An FP32 scale (absmax/6) has no clamping but spends 32 bits on a single scale. 왼쪽: 한 block의 원래 값(회색 점)과 MXFP4로 되돌린 값(파랑), 가로선은 그 block에서 표현 가능한 값 X·{0, ±0.5, ±1, ±1.5, ±2, ±3, ±4, ±6}이다(최대 64개만 표시). 오른쪽: block 크기에 따른 전체 상대 오차. outlier 배율을 올리면 outlier가 든 block의 scale이 커져 같은 block의 작은 값들이 0으로 뭉개진다. block이 클수록 피해 범위가 넓다. E8M0 scale은 floor 때문에 max/X가 [4, 8)에 놓이고, 6을 넘는 값은 6으로 clamp된다. FP32 scale(absmax/6)은 clamp가 없지만 scale 하나에 32비트를 쓴다.

In the checkpoint, two 4-bit codes are packed into one byte (blocks), and the scale is stored as a uint8 with a bias of 127 added (scales). The reference implementation looks values up with lut[idx] and restores them with ldexp(value, scale - 127). Let us port the same process to NumPy.

NumPy MXFP4 quantization, packing, reconstruction and a block-size experiment
import numpy as np

# FP4 E2M1 codes 0..15 → values (same order as FP4_VALUES in gpt_oss/torch/weights.py)
FP4_VALUES = np.array([+0.0, +0.5, +1.0, +1.5, +2.0, +3.0, +4.0, +6.0,
                       -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0], dtype=np.float32)
EMAX_ELEM = 2          # largest normal number in E2M1: 6 = 1.5 * 2^2

def mxfp4_quantize(w, k=32):
    """Microscaling Algorithm 1: one E8M0 scale + 4-bit codes per block. w.size must be a multiple of k."""
    b = w.reshape(-1, k)
    amax = np.abs(b).max(axis=1, keepdims=True)
    shared_exp = np.floor(np.log2(np.maximum(amax, 2.0**-126))) - EMAX_ELEM
    r = np.clip(b / 2.0**shared_exp, -6, 6)                  # clamp anything outside the normal range
    mags = FP4_VALUES[:8]
    idx = np.abs(np.abs(r)[..., None] - mags).argmin(-1)     # nearest magnitude
    code = (idx + 8 * (r < 0)).astype(np.uint8)              # top bit = sign
    packed = code[:, 0::2] | (code[:, 1::2] << 4)            # two elements per byte (lo, hi)
    scale_u8 = (shared_exp[:, 0] + 127).astype(np.uint8)     # E8M0: store only the exponent, bias 127
    return packed, scale_u8

def mxfp4_dequantize(packed, scale_u8):
    lo, hi = packed & 0x0F, packed >> 4
    codes = np.stack([lo, hi], -1).reshape(packed.shape[0], -1)
    exp = scale_u8.astype(np.int32) - 127                    # weights.py: scales.to(int32) - 127
    return np.ldexp(FP4_VALUES[codes.astype(np.intp)], exp[:, None])

rng = np.random.default_rng(0)
w = rng.standard_normal(1 << 16).astype(np.float32) * 0.02
packed, sc = mxfp4_quantize(w)
wq = mxfp4_dequantize(packed, sc).ravel()
bits = (packed.nbytes + sc.nbytes) * 8 / w.size
print(f"stored bits/element = {bits:.3f}  (4 + 8/32 = 4.25)")
print(f"relative RMSE = {np.linalg.norm(w - wq) / np.linalg.norm(w):.4f}")

# does re-quantizing leave the values unchanged? (points on the grid must be fixed points)
p2, s2 = mxfp4_quantize(wq)
print("invariant under re-quantization:", np.array_equal(mxfp4_dequantize(p2, s2).ravel(), wq))

# effect of block size and outliers
w_out = w.copy(); w_out[5::256] *= 30                       # one outlier every 256 values
print("\n k    bits   relRMSE(normal)  relRMSE(outlier)  zeroed fraction(outlier)")
for k in [8, 16, 32, 64, 256, 1 << 16]:
    row = []
    for x in (w, w_out):
        q = mxfp4_dequantize(*mxfp4_quantize(x, k)).ravel()
        row.append(np.linalg.norm(x - q) / np.linalg.norm(x))
    qz = mxfp4_dequantize(*mxfp4_quantize(w_out, k)).ravel()
    zero = np.mean((qz == 0) & (w_out != 0))
    print(f"{k:6d}  {4 + 8 / k:5.3f}  {row[0]:.4f}        {row[1]:.4f}          {zero:.3f}")

# side effect of the floor scale: max/X lies in [4, 8), so elements above 6 are clamped
blk = np.array([7.5] + [0.1] * 31, dtype=np.float32)
q = mxfp4_dequantize(*mxfp4_quantize(blk)).ravel()
print(f"\nblock with max=7.5: X=2^{int(np.floor(np.log2(7.5))) - 2}, 7.5 → {q[0]} (clamp), 0.1 → {q[1]}")
 

For normally distributed weights the relative error is about 11% and is almost insensitive to block size. The error does not fall much even for small blocks because of the E8M0 scale. Every block has one largest element, which is clamped whenever max⁡∣v∣/X∈(6,8)\max|v|/X \in (6, 8), and the smaller the block, the larger the fraction of “largest elements”. In the figure, switching the scale to FP32 (absmax/6) removes the clamping and the error of small blocks drops sharply. The price is that spending 32 bits on the scale makes it 5 bits per element at block size 32. Mixing in outliers changes the story. At block size 32 about 14% of elements are flushed to 0, but with a per-tensor scale (the bottom row) nearly all of them become 0. That is why MX formats insist on “one scale per block”. Keeping quality with 4-bit weights usually requires quantization-aware training, but the card only says the MoE weights were “post-trained while quantized to MXFP4”. What form of quantization-aware training was used is not disclosed.

확인 문제Check yourself

In MXFP4 (block 32, E8M0 scale) the largest absolute value in a block is 7.0. What are this block's scale X and the reconstructed value of 7.0?

⌊log⁡27⌋=2\lfloor\log_2 7\rfloor = 2, so X=22−2=1X = 2^{2-2} = 1. 7/X=77/X = 7 exceeds E2M1’s maximum of 6, so it is clamped to 6 and the reconstructed value is 6.0. Because the scale must be a power of two, you cannot pick a “perfect” scale such as absmax/6 = 7/6, and the floor rule means the largest element can be cut by up to 25%. In exchange, the scale is stored as a single 8-bit exponent, so the per-element metadata is only 8/32=0.258/32 = 0.25 bits.

2. Implementing attention with a sink

We port the reference implementation’s sdpa() to a single head. There are three things to check: (1) the token weights of each row + the sink mass = 1, (2) the window mask removes i−j≥128i - j \ge 128, and (3) the sink is exactly the same as “attaching one key whose value is 0”. Then we check whether the output shrinks as bb grows for queries with no relevant token.

NumPy Attention sink + sliding window (a NumPy version of sdpa in model.py)
import numpy as np

def sdpa_sink(Q, K, V, sink, window=0):
    """Causal attention for one head + a learned sink logit (model.py sdpa() ported to 1 head)."""
    n, d = Q.shape
    S = Q @ K.T / np.sqrt(d)
    mask = np.triu(np.full((n, n), -np.inf), 1)               # block the future
    if window > 0:
        mask += np.tril(np.full((n, n), -np.inf), -window)    # block i - j >= window
    S = S + mask
    S = np.concatenate([S, np.full((n, 1), sink)], axis=1)    # append the sink column to the logits
    S -= S.max(axis=1, keepdims=True)
    P = np.exp(S); P /= P.sum(axis=1, keepdims=True)
    W, p_sink = P[:, :-1], P[:, -1]                           # discard the sink column (no value vector)
    return W @ V, W, p_sink

rng = np.random.default_rng(1)
n, d = 300, 64
Q, K, V = (rng.standard_normal((n, d)) for _ in range(3))

o, W, ps = sdpa_sink(Q, K, V, sink=2.0, window=128)
print("row sum + sink mass = 1 :", np.allclose(W.sum(1) + ps, 1))
i, j = np.nonzero(W)
print("range of (i-j) for nonzero weights:", (i - j).min(), "~", (i - j).max(), " (window 128 → 0~127)")
print(f"mean sink mass = {ps.mean():.3f}")

# equivalence: the sink = one virtual key with value 0 whose logit is fixed at b
b = 2.0
S = Q @ K.T / 8 + np.triu(np.full((n, n), -np.inf), 1) + np.tril(np.full((n, n), -np.inf), -128)
S2 = np.concatenate([S, np.full((n, 1), b)], 1)
P2 = np.exp(S2 - S2.max(1, keepdims=True)); P2 /= P2.sum(1, keepdims=True)
o2 = P2 @ np.vstack([V, np.zeros((1, d))])
print("same output as a zero-value key:", np.allclose(o, o2))

# no-op case: output size when no key is relevant (all logits similar)
Qz = rng.standard_normal((n, d)) * 0.05                       # a query that asks for almost nothing
print("\n sink b   mean sink mass   mean ‖o‖  (query positions 128+)")
for bb in [None, 0.0, 3.0, np.log(128), 6.0]:
    o, W, ps = sdpa_sink(Qz, K, V, -1e9 if bb is None else bb, 128)
    name = "  none" if bb is None else f"{bb:6.2f}"
    print(f"{name}   {ps[128:].mean():.3f}            {np.linalg.norm(o, axis=1)[128:].mean():.3f}")
print(f"reference: norm of the mean of 128 V vectors in the window ≈ √(d/128) = {np.sqrt(d / 128):.3f}")

# KV cache: per token per layer 2(K,V) × 8 heads × 64 dim × 2 bytes
per = 2 * 8 * 64 * 2
for name, L in [("120b", 36), ("20b", 24)]:
    for ctx in [8192, 131072]:
        mix = per * (L // 2 * ctx + L // 2 * min(ctx, 128))
        dense = per * L * ctx
        print(f"gpt-oss-{name} n={ctx:6d}: alternating {mix / 2**30:6.3f} GiB  vs all dense {dense / 2**30:6.3f} GiB  ({mix / dense:.3f})")
 

Without a sink, even a query that “asks for nothing” adds to the residual stream the average of the 128 value vectors in the window, a vector of size about 64/128≈0.71\sqrt{64/128} \approx 0.71. At b=ln⁡128b = \ln 128 the sink takes exactly half of the mass, and at b=6b = 6 the output shrinks to a quarter or less of the original. The learned bhb_h is a threshold that decides, per head, “how readily it rests”.

In PyTorch you can use the reference implementation almost as is. Because of GQA, K and V are expanded across the query groups, and the sink is appended as a per-head column.

PyTorch PyTorch: sink + window attention and clamped SwiGLU (condensed from openai/gpt-oss torch/model.py) 로컬에서 실행run locally (pip install torch)
import torch

def sdpa(Q, K, V, S, sm_scale, sliding_window=0):
    # Q: (n, n_kv_heads, q_per_kv, d)  K, V: (n, n_kv_heads, d)  S: (n_heads,) learned sinks
    n, h_kv, q_mult, d = Q.shape
    K = K[:, :, None, :].expand(-1, -1, q_mult, -1)          # GQA: share each KV head across its query group
    V = V[:, :, None, :].expand(-1, -1, q_mult, -1)
    S = S.reshape(h_kv, q_mult, 1, 1).expand(-1, -1, n, -1)  # one sink-logit column per head
    mask = torch.triu(Q.new_full((n, n), -float("inf")), diagonal=1)
    if sliding_window > 0:                                    # block keys with i - j >= W
        mask += torch.tril(mask.new_full((n, n), -float("inf")), diagonal=-sliding_window)
    QK = torch.einsum("qhmd,khmd->hmqk", Q, K) * sm_scale + mask[None, None]
    W = torch.softmax(torch.cat([QK, S], dim=-1), dim=-1)[..., :-1]   # discard the sink column
    return torch.einsum("hmqk,khmd->qhmd", W, V).reshape(n, -1)

def swiglu(x, alpha: float = 1.702, limit: float = 7.0):
    x_glu, x_lin = x[..., ::2], x[..., 1::2]                 # split into even and odd columns
    x_glu = x_glu.clamp(max=limit)
    x_lin = x_lin.clamp(min=-limit, max=limit)
    return x_glu * torch.sigmoid(alpha * x_glu) * (x_lin + 1)

# window of layer i: only even layers are sliding (AttentionBlock: layer_idx % 2 == 0)
window_of = lambda layer_idx: 128 if layer_idx % 2 == 0 else 0
 
확인 문제Check yourself

For gpt-oss-120b, roughly how large is the KV cache (bf16) of one 131,072-token sequence compared with making every layer dense?

Of the 36 layers, 18 are sliding layers with window 128, and they hold the KV of only min⁡(n,128)\min(n, 128) tokens. The other 18 are dense and grow in proportion to nn. At n=131,072n = 131{,}072 the sliding layers’ share is negligibly small (about 4.5 MiB), so the total is about 4.5 GiB, half of the 9.0 GiB all-dense figure. The sink is a single scalar per head, so it does not add to the KV.

Results

All of the card’s evaluations are pass@1, reasoning level high, with the default system prompt (§2.6). The only comparisons are OpenAI’s own o3, o3-mini and o4-mini.

Main benchmarks (Figures 1, 2; high)

o3o3-minio4-minigpt-oss-120bgpt-oss-20b
AIME 2024 (with tools)95.287.3*98.796.696.0
AIME 2025 (with tools)98.486.5*99.597.998.7
GPQA Diamond (no tools)83.377.081.480.171.5
MMLU93.487.093.090.085.3
SWE-Bench Verified69.149.368.162.460.7
Tau-Bench Retail70.457.665.667.854.8
Codeforces Elo (with tools)27062073 (no tools)271926222516

* o3-mini was evaluated on AIME without tools (Figure 1 note). On HLE: o3 24.9 (tools), o4-mini 17.7 (tools), gpt-oss-120b 19.0 (tools) / 14.9 (no tools), 20b 17.3 / 10.9.

The card’s summary is “120b surpasses o3-mini and approaches o4-mini; 20b is surprisingly competitive despite being 6x smaller”. In math 20b is nearly level with 120b (on AIME 2025 with tools 20b is even higher), while the size gap shows on knowledge-heavy tasks such as GPQA and MMLU. The card attributes the strong math results to “using very long CoTs effectively (20b uses over 20k tokens per AIME problem on average)”.

Reasoning effort (Table 3, Figure 3). How much the same model changes across low/medium/high is the most useful table in this card.

체크포인트에서는 4비트 코드 두 개를 한 바이트에 담고(blocks), scale은 bias 127을 더한 uint8로 저장한다(scales). 참조 구현은 lut[idx]로 값을 찾고 ldexp(값, scale - 127)로 되돌린다. 같은 과정을 NumPy로 옮겨 보자.

NumPy MXFP4 양자화·패킹·복원과 block 크기 실험
import numpy as np

# FP4 E2M1 코드 0..15 → 값 (gpt_oss/torch/weights.py 의 FP4_VALUES와 같은 순서)
FP4_VALUES = np.array([+0.0, +0.5, +1.0, +1.5, +2.0, +3.0, +4.0, +6.0,
                       -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0], dtype=np.float32)
EMAX_ELEM = 2          # E2M1에서 가장 큰 정규수 6 = 1.5 * 2^2

def mxfp4_quantize(w, k=32):
    """Microscaling Algorithm 1: block마다 E8M0 scale + 4비트 코드. w.size는 k의 배수."""
    b = w.reshape(-1, k)
    amax = np.abs(b).max(axis=1, keepdims=True)
    shared_exp = np.floor(np.log2(np.maximum(amax, 2.0**-126))) - EMAX_ELEM
    r = np.clip(b / 2.0**shared_exp, -6, 6)                  # 정규수 범위 밖은 clamp
    mags = FP4_VALUES[:8]
    idx = np.abs(np.abs(r)[..., None] - mags).argmin(-1)     # 가장 가까운 크기
    code = (idx + 8 * (r < 0)).astype(np.uint8)              # 최상위 비트 = 부호
    packed = code[:, 0::2] | (code[:, 1::2] << 4)            # 바이트 하나에 두 원소 (lo, hi)
    scale_u8 = (shared_exp[:, 0] + 127).astype(np.uint8)     # E8M0: bias 127인 지수만 저장
    return packed, scale_u8

def mxfp4_dequantize(packed, scale_u8):
    lo, hi = packed & 0x0F, packed >> 4
    codes = np.stack([lo, hi], -1).reshape(packed.shape[0], -1)
    exp = scale_u8.astype(np.int32) - 127                    # weights.py: scales.to(int32) - 127
    return np.ldexp(FP4_VALUES[codes.astype(np.intp)], exp[:, None])

rng = np.random.default_rng(0)
w = rng.standard_normal(1 << 16).astype(np.float32) * 0.02
packed, sc = mxfp4_quantize(w)
wq = mxfp4_dequantize(packed, sc).ravel()
bits = (packed.nbytes + sc.nbytes) * 8 / w.size
print(f"저장 비트/원소 = {bits:.3f}  (4 + 8/32 = 4.25)")
print(f"상대 RMSE = {np.linalg.norm(w - wq) / np.linalg.norm(w):.4f}")

# 재양자화해도 값이 그대로인가 (격자 위의 점은 고정점이어야 한다)
p2, s2 = mxfp4_quantize(wq)
print("재양자화 불변:", np.array_equal(mxfp4_dequantize(p2, s2).ravel(), wq))

# block 크기 · outlier의 영향
w_out = w.copy(); w_out[5::256] *= 30                       # 256개마다 outlier 하나
print("\n k    bits   relRMSE(정규)  relRMSE(outlier)  0이 된 비율(outlier)")
for k in [8, 16, 32, 64, 256, 1 << 16]:
    row = []
    for x in (w, w_out):
        q = mxfp4_dequantize(*mxfp4_quantize(x, k)).ravel()
        row.append(np.linalg.norm(x - q) / np.linalg.norm(x))
    qz = mxfp4_dequantize(*mxfp4_quantize(w_out, k)).ravel()
    zero = np.mean((qz == 0) & (w_out != 0))
    print(f"{k:6d}  {4 + 8 / k:5.3f}  {row[0]:.4f}        {row[1]:.4f}          {zero:.3f}")

# floor 스케일의 부작용: max/X 가 [4, 8) 이므로 6을 넘는 원소는 clamp된다
blk = np.array([7.5] + [0.1] * 31, dtype=np.float32)
q = mxfp4_dequantize(*mxfp4_quantize(blk)).ravel()
print(f"\nmax=7.5 인 block: X=2^{int(np.floor(np.log2(7.5))) - 2}, 7.5 → {q[0]} (clamp), 0.1 → {q[1]}")
 

정규분포 가중치에서 상대 오차는 약 11%로, block 크기에 거의 둔감하다. 작은 block에서도 오차가 잘 줄지 않는 것은 E8M0 scale 탓이다. block마다 최대 원소가 하나씩 있고 그 원소는 max⁡∣v∣/X∈(6,8)\max|v|/X \in (6, 8)이면 clamp되는데, block이 작을수록 “최대 원소”의 비율이 커진다. 그림에서 scale을 FP32(absmax/6)로 바꾸면 clamp가 사라져 작은 block의 오차가 크게 내려가는 것이 보인다. 대신 scale에 32비트를 쓰면 block 32에서 원소당 5비트가 된다. outlier를 섞으면 이야기가 달라진다. block 32에서는 원소의 약 14%가 0으로 뭉개지지만 per-tensor scale(맨 아래 행)에서는 거의 전부가 0이 된다. MX 형식이 “block마다 scale”을 고집하는 이유다. 4비트 가중치로 품질을 유지하려면 대개 양자화를 고려한 학습이 따라야 하는데, 카드는 “MoE 가중치를 MXFP4로 양자화한 상태로 post-train했다”고만 적었다. 어떤 형태의 quantization-aware training인지는 공개되지 않았다.

확인 문제Check yourself

MXFP4(블록 32, E8M0 scale)에서 블록의 최대 절댓값이 7.0이다. 이 블록의 scale X와 7.0이 복원된 값은?

⌊log⁡27⌋=2\lfloor\log_2 7\rfloor = 2이므로 X=22−2=1X = 2^{2-2} = 1이다. 7/X=77/X = 7은 E2M1의 최대값 6을 넘으므로 6으로 clamp되어 복원값은 6.0이다. scale이 2의 거듭제곱이라는 제약 때문에 absmax/6 = 7/6 같은 “딱 맞는” scale을 고를 수 없고, floor 규칙 탓에 최대 원소가 최대 25%까지 잘릴 수 있다. 대신 scale을 8비트 지수 하나로 저장해 원소당 메타데이터가 8/32=0.258/32 = 0.25비트로 끝난다.

2. sink가 있는 attention을 직접 구현하기

참조 구현의 sdpa()를 한 head로 옮긴다. 확인할 것은 세 가지다. (1) 각 행의 토큰 가중치 합 + sink 질량 = 1, (2) window 마스크는 i−j≥128i - j \ge 128을 지운다, (3) sink는 “값이 0인 key 하나를 붙인 것”과 정확히 같다. 그리고 관련 토큰이 없는 query에서 bb를 키우면 출력이 줄어드는지 본다.

NumPy attention sink + sliding window (model.py sdpa의 NumPy 판)
import numpy as np

def sdpa_sink(Q, K, V, sink, window=0):
    """한 head의 causal attention + 학습된 sink logit (model.py sdpa()를 1-head로 옮김)."""
    n, d = Q.shape
    S = Q @ K.T / np.sqrt(d)
    mask = np.triu(np.full((n, n), -np.inf), 1)               # 미래 차단
    if window > 0:
        mask += np.tril(np.full((n, n), -np.inf), -window)    # i - j >= window 차단
    S = S + mask
    S = np.concatenate([S, np.full((n, 1), sink)], axis=1)    # sink 열을 logit에 붙이고
    S -= S.max(axis=1, keepdims=True)
    P = np.exp(S); P /= P.sum(axis=1, keepdims=True)
    W, p_sink = P[:, :-1], P[:, -1]                           # sink 열은 버린다 (값 벡터 없음)
    return W @ V, W, p_sink

rng = np.random.default_rng(1)
n, d = 300, 64
Q, K, V = (rng.standard_normal((n, d)) for _ in range(3))

o, W, ps = sdpa_sink(Q, K, V, sink=2.0, window=128)
print("행 합 + sink 질량 = 1 :", np.allclose(W.sum(1) + ps, 1))
i, j = np.nonzero(W)
print("0이 아닌 가중치의 (i-j) 범위:", (i - j).min(), "~", (i - j).max(), " (window 128 → 0~127)")
print(f"평균 sink 질량 = {ps.mean():.3f}")

# 등가성: sink = '값이 0인 가상 key' 하나를 붙이고 그 logit을 b로 고정한 것과 같다
b = 2.0
S = Q @ K.T / 8 + np.triu(np.full((n, n), -np.inf), 1) + np.tril(np.full((n, n), -np.inf), -128)
S2 = np.concatenate([S, np.full((n, 1), b)], 1)
P2 = np.exp(S2 - S2.max(1, keepdims=True)); P2 /= P2.sum(1, keepdims=True)
o2 = P2 @ np.vstack([V, np.zeros((1, d))])
print("zero-value key와 같은 출력:", np.allclose(o, o2))

# no-op 상황: 관련 있는 key가 없을 때(모든 logit이 비슷) 출력 크기
Qz = rng.standard_normal((n, d)) * 0.05                       # 거의 아무것도 묻지 않는 query
print("\n sink b   평균 sink 질량   평균 ‖o‖  (query 위치 128 이후)")
for bb in [None, 0.0, 3.0, np.log(128), 6.0]:
    o, W, ps = sdpa_sink(Qz, K, V, -1e9 if bb is None else bb, 128)
    name = "  없음" if bb is None else f"{bb:6.2f}"
    print(f"{name}   {ps[128:].mean():.3f}            {np.linalg.norm(o, axis=1)[128:].mean():.3f}")
print(f"참고: window 128개 V의 평균 벡터 크기 ≈ √(d/128) = {np.sqrt(d / 128):.3f}")

# KV cache: 토큰·층당 2(K,V) × 8 head × 64 dim × 2 byte
per = 2 * 8 * 64 * 2
for name, L in [("120b", 36), ("20b", 24)]:
    for ctx in [8192, 131072]:
        mix = per * (L // 2 * ctx + L // 2 * min(ctx, 128))
        dense = per * L * ctx
        print(f"gpt-oss-{name} n={ctx:6d}: 교대 {mix / 2**30:6.3f} GiB  vs 모두 dense {dense / 2**30:6.3f} GiB  ({mix / dense:.3f})")
 

sink가 없으면 “묻는 것이 없는” query도 window 안 128개 값 벡터의 평균, 크기 약 64/128≈0.71\sqrt{64/128} \approx 0.71인 벡터를 잔차 스트림에 더한다. b=ln⁡128b = \ln 128에서 sink가 질량의 정확히 절반을 가져가고, b=6b = 6이면 출력이 원래의 1/4 이하로 준다. 학습된 bhb_h는 head마다 “얼마나 쉽게 쉬는가”를 정하는 문턱이다.

PyTorch로는 참조 구현을 거의 그대로 쓰면 된다. GQA라 K, V를 query 그룹 수만큼 펼치고, sink를 head별 열로 붙인다.

PyTorch PyTorch: sink + window attention과 clamp SwiGLU (openai/gpt-oss torch/model.py 요약) 로컬에서 실행run locally (pip install torch)
import torch

def sdpa(Q, K, V, S, sm_scale, sliding_window=0):
    # Q: (n, n_kv_heads, q_per_kv, d)  K, V: (n, n_kv_heads, d)  S: (n_heads,) 학습된 sink
    n, h_kv, q_mult, d = Q.shape
    K = K[:, :, None, :].expand(-1, -1, q_mult, -1)          # GQA: KV head를 query 그룹에 공유
    V = V[:, :, None, :].expand(-1, -1, q_mult, -1)
    S = S.reshape(h_kv, q_mult, 1, 1).expand(-1, -1, n, -1)  # head마다 sink logit 한 열
    mask = torch.triu(Q.new_full((n, n), -float("inf")), diagonal=1)
    if sliding_window > 0:                                    # i - j >= W 인 key 차단
        mask += torch.tril(mask.new_full((n, n), -float("inf")), diagonal=-sliding_window)
    QK = torch.einsum("qhmd,khmd->hmqk", Q, K) * sm_scale + mask[None, None]
    W = torch.softmax(torch.cat([QK, S], dim=-1), dim=-1)[..., :-1]   # sink 열은 버린다
    return torch.einsum("hmqk,khmd->qhmd", W, V).reshape(n, -1)

def swiglu(x, alpha: float = 1.702, limit: float = 7.0):
    x_glu, x_lin = x[..., ::2], x[..., 1::2]                 # 짝수·홀수 열로 나눈다
    x_glu = x_glu.clamp(max=limit)
    x_lin = x_lin.clamp(min=-limit, max=limit)
    return x_glu * torch.sigmoid(alpha * x_glu) * (x_lin + 1)

# 층 i의 window: 짝수 층만 sliding (AttentionBlock: layer_idx % 2 == 0)
window_of = lambda layer_idx: 128 if layer_idx % 2 == 0 else 0
 
확인 문제Check yourself

gpt-oss-120b에서 context 131,072 토큰짜리 시퀀스 하나의 KV cache(bf16)는 모든 층이 dense일 때와 비교해 대략 얼마인가?

36층 중 18층이 window 128의 sliding 층이라 그 층들은 min⁡(n,128)\min(n, 128)개 토큰의 KV만 들고 있다. 나머지 18층은 dense라 nn에 비례한다. n=131,072n = 131{,}072이면 sliding 층의 몫은 무시할 만큼 작아(약 4.5 MiB) 전체는 all-dense 9.0 GiB의 절반인 약 4.5 GiB다. sink는 head당 스칼라 하나라 KV를 늘리지 않는다.

실험 결과

카드의 평가는 모두 pass@1, reasoning level high, 기본 system 프롬프트다(§2.6). 비교 대상은 OpenAI의 o3, o3-mini, o4-mini뿐이다.

주요 벤치마크 (Figure 1, 2; high)

o3o3-minio4-minigpt-oss-120bgpt-oss-20b
AIME 2024 (도구 사용)95.287.3*98.796.696.0
AIME 2025 (도구 사용)98.486.5*99.597.998.7
GPQA Diamond (도구 없음)83.377.081.480.171.5
MMLU93.487.093.090.085.3
SWE-Bench Verified69.149.368.162.460.7
Tau-Bench Retail70.457.665.667.854.8
Codeforces Elo (도구 사용)27062073 (도구 없음)271926222516

* o3-mini는 AIME를 도구 없이 평가했다(Figure 1 주석). HLE는 o3 24.9(도구), o4-mini 17.7(도구), gpt-oss-120b 19.0(도구)/14.9(도구 없음), 20b 17.3/10.9다.

카드의 요약은 “120b는 o3-mini를 넘고 o4-mini에 근접, 20b는 6배 작지만 놀랄 만큼 경쟁력 있다”이다. 수학에서는 20b가 120b와 거의 같고(AIME 2025 도구 사용은 20b가 더 높다), GPQA·MMLU처럼 지식형 과제에서 크기 차이가 드러난다. 카드는 수학이 강한 이유를 “매우 긴 CoT를 효과적으로 쓴다(20b는 AIME에서 문제당 평균 20k 토큰 이상)“로 설명한다.

reasoning effort (Table 3, Figure 3). 같은 모델이 low/medium/high에서 얼마나 달라지는지가 이 카드에서 가장 쓸모 있는 표다.

120b low→high – 20b low→high –
Scores are the model card's Table 3 values (pass@1 at each effort level). Switch the benchmark: on math (AIME) low→high gains tens of points, but knowledge-heavy tasks such as MMLU and HealthBench Consensus stay nearly flat, and for 20b, high scores below medium on Tau-Bench Airline and HealthBench Hard. Switch the x axis to "length" (AIME 2025 and GPQA, with tools) and, as in Figure 3, the curves become nearly straight in log length. The lengths are approximate values read off the figure by eye. 점수는 모델 카드 Table 3(pass@1, 각 effort 단계)의 값이다. benchmark를 바꿔 보면 수학(AIME)은 low→high에서 수십 점이 오르지만 MMLU·HealthBench Consensus처럼 지식형 과제는 거의 평평하고, 20b는 Tau-Bench Airline·HealthBench Hard에서 high가 medium보다 낮다. x축을 "길이"로 바꾸면(AIME 2025·GPQA, 도구 사용) Figure 3처럼 로그 길이에 대해 거의 직선이 된다. 길이는 그림에서 눈으로 읽은 근사값이다.
  • On AIME 2025 (no tools), 120b goes 50.4 → 80.0 → 92.5 and 20b goes 37.1 → 72.1 → 91.7. The smaller the model, the more it depends on effort.
  • MMLU (85.9 → 90.0) and HealthBench Consensus (90.6 → 89.9) are nearly flat. Thinking longer does not create knowledge the model lacks.
  • For 20b, high scores below medium on Tau-Bench Airline (42.6 → 38.0) and HealthBench Hard (12.9 → 10.8). Raising effort is not always a gain.
  • In Figure 3, accuracy is almost a straight line against the log of the average CoT length. The card also notes “log-linear returns on most tasks”.

Hallucination and instruction hierarchy (Tables 7–9). The card also shows directly where the open models are weaker.

Evaluationgpt-oss-120bgpt-oss-20bo4-mini
SimpleQA accuracy / hallucination rate0.168 / 0.7820.067 / 0.9140.234 / 0.750
PersonQA accuracy / hallucination rate0.298 / 0.4910.155 / 0.5320.356 / 0.361
System prompt extraction0.8320.8810.993
Prompt injection hijacking0.7800.6390.917

Being small models, they have less world knowledge (the card recommends compensating with browsing), and their ability to block user instructions via the system message is weaker than o4-mini’s. On the StrongReject jailbreak evaluation, on the other hand, the card reports them as on par with o4-mini.

There are no ablations. The card contains not a single experiment showing how much the sink, the window alternation, MXFP4 or the clamped SwiGLU each contributes. The only justification for the architectural choices is the cited papers and the statement that the design “follows” them.

Safety evaluations. The other half of the card is the Preparedness evaluation. Emulating an attacker, OpenAI maliciously fine-tuned 120b in the biology and cyber domains (helpful-only RL + domain data and environments), and the SAG reviewed the conclusion that even then it did not reach the High capability threshold (§5.1). This is an example of evaluating the risk of an open-weight release not “as released” but “after someone has trained it further”.

Reading critically

  • There is no recipe. The pre-training token count, data mix, optimizer, schedule and precision, and the post-training algorithm, rewards and data scale are all undisclosed. “CoT RL similar to o3” is not a reproducible description. The RL formula in this lesson is likewise only the generic form.
  • Guessing the token count from compute (an estimate). The card’s numbers alone do not give the token count. As an exercise, plugging Nactive=5.13N_{\text{active}} = 5.13B, a peak H100 bf16 dense throughput of about 989 TFLOPS and 2.1M GPU-hours into C≈6NactiveDC \approx 6 N_{\text{active}} D gives DD in the range of a few tens of T tokens at 20–40% MFU. Since the actual MFU of the MoE and whether the 2.1M includes post-training are unknown, it means nothing beyond the order of magnitude.
  • The only comparisons are in-house models. There is no comparison with other open models of the same period (MoEs of the same size class), and o3-mini is compared under different conditions on some evaluations (AIME without tools). The Preparedness section says its SWE-bench Verified evaluation used a fixed subset of 477 tasks (§5.2.3.1), but it does not say whether the Figure 2 score uses the same set.
  • The meaning of the effort levels is not pinned down. Whether low/medium/high is a length budget, a reward design or a mere prompt condition is unknown. The lengths in Figure 3 are given only as a plot, so the length values in this lesson are also approximations read off the figure.
  • The quality loss from MXFP4 was not measured. There is no comparison with the bf16 original. Only the MXFP4-quantized model was released, so a baseline cannot be built externally either.
  • Not supervising the CoT cuts both ways. It is a choice to preserve monitorability, but it hands the risk of exposing the CoT to users over to developers. A product that shows the analysis channel as is carries exactly the risk the card warns about.
  • Open questions. How the sink values bhb_h are distributed across heads, how the roles of the sliding and dense layers divide after training, and how the clamp (7.0) interacts with MXFP4 are questions that can be studied externally with the released weights.

Summary

  • gpt-oss-120b/20b are MoEs (128/32 experts, top-4) with 116.83B/5.13B and 20.91B/3.61B active parameters, and the config values alone reproduce the parameter counts and checkpoint sizes in the card’s Table 1 exactly.
  • Attention alternates between sliding layers with window 128 and dense layers, and each head adds a learned sink logit bhb_h to the softmax denominator. The sink is equivalent to a virtual key with value 0 and allows “looking at nothing”; the alternating layout cuts the long-context KV cache almost in half.
  • The MoE weights are MXFP4 (32 elements share one E8M0 exponent, 4.25 bit/param), which lets 120b fit on a single 80GB GPU. Clamping from the floor scale and outliers within a block are the main sources of error.
  • The harmony format separates the CoT, tool calls and the answer through a role hierarchy and the analysis/commentary/final channels. The rule of erasing the CoT of finished turns while keeping the CoT of an in-progress tool call must be followed identically in agent RL harnesses too.
  • From reasoning effort low→high, math accuracy rises by tens of points while knowledge-heavy tasks stay nearly unchanged. Accuracy is roughly linear in the log of the average CoT length.
  • The card discloses no data, no training recipe and no ablations. It is open weights, not an open recipe, and architectural details have to be checked in the official reference implementation.
  • AIME 2025(도구 없음)에서 120b는 50.4 → 80.0 → 92.5, 20b는 37.1 → 72.1 → 91.7이다. 작은 모델일수록 effort 의존도가 크다.
  • MMLU(85.9 → 90.0)나 HealthBench Consensus(90.6 → 89.9)는 거의 평평하다. 생각을 오래 해도 모르는 지식이 생기지는 않는다.
  • 20b는 Tau-Bench Airline(42.6 → 38.0)과 HealthBench Hard(12.9 → 10.8)에서 high가 medium보다 낮다. effort를 올리는 것이 항상 이득은 아니다.
  • Figure 3에서 정확도는 평균 CoT 길이의 로그에 대해 거의 직선이다. 카드도 “대부분의 과제에서 log-linear returns”라고 적는다.

환각과 instruction hierarchy (Table 7–9). 오픈 모델이 약한 쪽도 카드가 직접 보여 준다.

평가gpt-oss-120bgpt-oss-20bo4-mini
SimpleQA 정확도 / 환각률0.168 / 0.7820.067 / 0.9140.234 / 0.750
PersonQA 정확도 / 환각률0.298 / 0.4910.155 / 0.5320.356 / 0.361
System prompt extraction0.8320.8810.993
Prompt injection hijacking0.7800.6390.917

작은 모델이라 세계 지식이 적고(카드는 browsing으로 보완하라고 권한다), system 메시지로 사용자 지시를 막는 능력은 o4-mini보다 약하다. 반면 StrongReject jailbreak 평가는 o4-mini와 비슷하다고 적었다.

ablation은 없다. sink, window 교대, MXFP4, clamp SwiGLU 각각이 얼마나 기여했는지 보여 주는 실험은 카드에 하나도 없다. 구조 선택의 근거는 인용 논문과 “따랐다”는 서술뿐이다.

안전성 평가. 카드의 나머지 절반은 Preparedness 평가다. 공격자를 흉내 내 120b를 생물·사이버 영역으로 악의적 fine-tuning(helpful-only RL + 도메인 데이터·환경)한 뒤에도 High 능력 문턱에 이르지 않았다는 결론을 SAG가 검토했다(§5.1). 오픈 웨이트 공개의 위험을 “공개된 그대로”가 아니라 “누군가 더 학습한 뒤”로 평가한 사례다.

비판적으로 읽기

  • 레시피가 없다. 사전학습 토큰 수·데이터 구성·optimizer·스케줄·정밀도, 사후학습 알고리즘·보상·데이터 규모가 모두 비공개다. “o3와 비슷한 CoT RL”은 재현 가능한 서술이 아니다. 이 레슨의 RL 수식도 일반형일 뿐이다.
  • 연산량으로 토큰 수 짐작하기(추정). 카드 숫자만으로는 토큰 수를 알 수 없다. 연습 삼아 C≈6NactiveDC \approx 6 N_{\text{active}} D에 Nactive=5.13N_{\text{active}} = 5.13B, H100 bf16 dense 최고 성능 약 989 TFLOPS, 2.1M GPU-hours를 넣으면 MFU 20–40%에서 DD는 대략 수십 T 토큰 범위가 나온다. MoE의 실제 MFU, 2.1M에 사후학습이 포함되는지 여부를 모르므로 자릿수 이상의 의미는 없다.
  • 비교 대상이 자사 모델뿐이다. 같은 시기의 다른 오픈 모델(같은 크기급 MoE)과의 비교가 없고, o3-mini는 일부 평가를 다른 조건(AIME 도구 없음)으로 비교했다. Preparedness 절의 SWE-bench Verified 평가는 477개 고정 부분집합을 썼다고 밝히는데(§5.2.3.1), Figure 2의 점수도 같은 집합인지는 적혀 있지 않다.
  • effort 단계의 의미가 고정되어 있지 않다. low/medium/high가 길이 예산인지, 보상 설계인지, 단순 프롬프트 조건인지 알 수 없다. Figure 3의 길이는 그림으로만 주어져 있어, 이 레슨의 길이 값도 그림에서 읽은 근사다.
  • MXFP4 품질 손실을 측정하지 않았다. bf16 원본 대비 성능 차이가 없다. 공개된 것은 MXFP4로 양자화된 모델뿐이라 비교 기준도 외부에서 만들 수 없다.
  • CoT 비감독의 양면. 감시 가능성을 지키려는 선택이지만 사용자 노출 위험을 개발자에게 넘긴다. analysis 채널을 그대로 보여 주는 제품은 카드가 경고한 위험을 그대로 진다.
  • 열린 질문. sink 값 bhb_h가 head별로 어떻게 분포하는지, sliding 층과 dense 층의 역할이 학습 후 어떻게 나뉘는지, clamp(7.0)가 MXFP4와 어떻게 상호작용하는지는 공개 가중치로 외부에서 연구할 수 있는 문제다.

정리

  • gpt-oss-120b/20b는 116.83B/5.13B, 20.91B/3.61B active의 MoE(128/32 expert, top-4)이고, 설정값만으로 카드 Table 1의 파라미터 수와 체크포인트 크기가 그대로 재현된다.
  • attention은 window 128 sliding 층과 dense 층을 교대하고, head마다 학습된 sink logit bhb_h를 softmax 분모에 더한다. sink는 값이 0인 가상 key와 같아 “아무것도 보지 않기”를 허용하고, 교대 배치는 긴 context의 KV cache를 거의 절반으로 줄인다.
  • MoE 가중치는 MXFP4(32개 원소가 E8M0 지수 하나를 공유, 4.25 bit/param)라 120b가 80GB GPU 한 장에 들어간다. floor scale의 clamp와 block 안 outlier가 오차의 주된 원천이다.
  • harmony 형식은 역할 위계와 analysis/commentary/final 채널로 CoT·도구 호출·답을 분리한다. 끝난 턴의 CoT는 지우고 진행 중인 도구 호출의 CoT는 남기는 규칙은 agent RL 하니스에서도 똑같이 지켜야 한다.
  • reasoning effort low→high에서 수학 정확도는 수십 점 오르고 지식형 과제는 거의 그대로다. 정확도는 평균 CoT 길이의 로그에 대해 대략 선형이다.
  • 카드는 데이터·학습 레시피·ablation을 공개하지 않는다. 오픈 웨이트이지 오픈 레시피가 아니며, 구조 세부는 공식 참조 구현에서 확인해야 한다.

더 읽을거리Further reading