RoPE coefficients

×

Compute the cos and sin of every position’s angle for the 32 frequencies of a head, YaRN-blended, scaled by the concentration.

Why

131,072 positions. The rotary positions are extended with YaRN so that the global layers, the model card’s dense layers, read a context of 131,072 tokens. gpt-oss model card §2.2

Rt=c (cos⁡ptωj,  sin⁡ptωj){\htmlData{light=model-rotations frequencies}{{\htmlClass{vl-stream-context}{R_{t}}}}}=c\,\big(\cos {\htmlData{light=positions}{p_t}}\omega_j,\;\sin {\htmlData{light=positions}{p_t}}\omega_j\big)
ωj=(mj+1−mj32) 150,000−2j/64\omega_j=\big(m_j+\tfrac{1-m_j}{32}\big)\,150{,}000^{-2j/64}
in
pp [B batch, T positions]
out
RR [B batch, T positions, 64 rotary features]
Explanation

jj runs over the 32 pairs of a head’s 64 features, θ=150,000\theta=150{,}000. YaRN keeps the original frequency where mj=1m_j=1 and divides it by 32 where mj=0m_j=0: mj=1−clip⁡((j−ℓ)/(u−ℓ),0,1)m_j=1-\operatorname{clip}\big((j-\ell)/(u-\ell),0,1\big) with ℓ≈8.09\ell\approx 8.09 and u≈17.40u\approx 17.40, from the original context of 4,096 and β = 32, α = 1 (model.py 96–118).

The cos and sin carry the concentration c=0.1ln⁡32+1≈1.3466c=0.1\ln 32+1\approx 1.3466 (model.py 92–94, 129–130), so a rotated query or key is cc times as long as a plain rotation leaves it, and every score is c2≈1.813c^2\approx 1.813 times larger.

Every attention block builds the same coefficients from the same settings (model.py 206–215, 242); the atlas draws them once, here, and hands them to every layer.

Sources

In codeself.rope._compute_cos_sin(num_tokens) · 125–131

Open pinned code ↗

Direct evidence

The rotary embedding: frequencies base^(−2j/64); with a scaling factor above 1, YaRN: a concentration 0.1·ln(factor) + 1, and per frequency pair a blend of the original (extrapolated) and the factor-divided (interpolated) frequency by a ramp between two pair indices set by α and β; cos and sin of position × frequency, both multiplied by the concentration, for positions 0 to T − 1; queries and keys rotated in every head.

model.py 63–150 ↗ · openai/gpt-oss @ 5681a6b65526

Excerpt
class RotaryEmbedding(torch.nn.Module):
    def __init__(
        self,
        head_dim: int,
        base: int,
        dtype: torch.dtype,
        initial_context_length: int = 4096,
        scaling_factor: float = 1.0,
        ntk_alpha: float = 1.0,
        ntk_beta: float = 32.0,
        device: torch.device | None = None,
    ) -> None:
        super().__init__()
        self.head_dim = head_dim
        self.base = base
        self.dtype = dtype
        self.initial_context_length = initial_context_length
        self.scaling_factor = scaling_factor
        self.ntk_alpha = ntk_alpha
        self.ntk_beta = ntk_beta
        self.device = device

    def _compute_concentration_and_inv_freq(self) -> torch.Tensor:
        """See YaRN paper: https://arxiv.org/abs/2309.00071"""
        freq = self.base ** (
            torch.arange(0, self.head_dim, 2, dtype=torch.float, device=self.device)
            / self.head_dim
        )
        if self.scaling_factor > 1.0:
            concentration = (
                0.1 * math.log(self.scaling_factor) + 1.0
            )  # YaRN concentration

            d_half = self.head_dim / 2
            # NTK by parts
            low = (
                d_half
                * math.log(self.initial_context_length / (self.ntk_beta * 2 * math.pi))
                / math.log(self.base)
            )
            high = (
                d_half
                * math.log(self.initial_context_length / (self.ntk_alpha * 2 * math.pi))
                / math.log(self.base)
            )
            assert 0 < low < high < d_half - 1

            interpolation = 1.0 / (self.scaling_factor * freq)
            extrapolation = 1.0 / freq

            ramp = (
                torch.arange(d_half, dtype=torch.float32, device=freq.device) - low
            ) / (high - low)
            mask = 1 - ramp.clamp(0, 1)

            inv_freq = interpolation * (1 - mask) + extrapolation * mask
        else:
            concentration = 1.0
            inv_freq = 1.0 / freq

        return concentration, inv_freq

    def _compute_cos_sin(self, num_tokens: int):
        concentration, inv_freq = self._compute_concentration_and_inv_freq()
        t = torch.arange(num_tokens, dtype=torch.float32, device=self.device)
        freqs = torch.einsum("i,j->ij", t, inv_freq)
        cos = freqs.cos() * concentration
        sin = freqs.sin() * concentration
        return cos, sin

    def forward(
        self,
        query: torch.Tensor,
        key: torch.Tensor,
    ) -> tuple[torch.Tensor, torch.Tensor]:
        num_tokens = query.shape[0]
        cos, sin = self._compute_cos_sin(num_tokens)

        query_shape = query.shape
        query = query.view(num_tokens, -1, self.head_dim)
        query = _apply_rotary_emb(query, cos, sin)
        query = query.reshape(query_shape)

        key_shape = key.shape
        key = key.view(num_tokens, -1, self.head_dim)
        key = _apply_rotary_emb(key, cos, sin)
        key = key.reshape(key_shape)
        return query, key

The attention block: a window on the layers whose index, counted from zero, is even; one sink per query head, bfloat16; an RMSNorm; one fused query–key–value projection with bias to 64·(64 + 2·8) features; an output projection with bias from 64·64 features to the width; the scale 1/√64; its own rotary embedding with the configuration’s base, YaRN factor and NTK α and β.

model.py 176–215 ↗ · openai/gpt-oss @ 5681a6b65526

Excerpt
class AttentionBlock(torch.nn.Module):
    def __init__(
        self,
        config: ModelConfig,
        layer_idx: int = 0,
        device: torch.device | None = None,
    ):
        super().__init__()
        self.head_dim = config.head_dim
        self.num_attention_heads = config.num_attention_heads
        self.num_key_value_heads = config.num_key_value_heads
        # Only apply sliding window to every other layer
        self.sliding_window = config.sliding_window if layer_idx % 2 == 0 else 0
        self.sinks = torch.nn.Parameter(
            torch.empty(config.num_attention_heads, device=device, dtype=torch.bfloat16)
        )
        self.norm = RMSNorm(config.hidden_size, device=device)
        qkv_dim = config.head_dim * (
            config.num_attention_heads + 2 * config.num_key_value_heads
        )
        self.qkv = torch.nn.Linear(
            config.hidden_size, qkv_dim, device=device, dtype=torch.bfloat16
        )
        self.out = torch.nn.Linear(
            config.head_dim * config.num_attention_heads,
            config.hidden_size,
            device=device,
            dtype=torch.bfloat16,
        )
        self.sm_scale = 1 / math.sqrt(config.head_dim)
        self.rope = RotaryEmbedding(
            config.head_dim,
            config.rope_theta,
            torch.float32,
            initial_context_length=config.initial_context_length,
            scaling_factor=config.rope_scaling_factor,
            ntk_alpha=config.rope_ntk_alpha,
            ntk_beta=config.rope_ntk_beta,
            device=device,
        )

The configuration the reference implementation reads: 36 layers of width 2,880; 128 experts, 4 per token, each of 2,880 inner features; swiglu_limit 7.0; 64 query and 8 key–value heads of 64; a sliding window of 128; RoPE base 150,000 over an initial context of 4,096, scaled by 32 with NTK α 1 and β 32; a vocabulary of 201,088.

config.json 1 ↗ · openai/gpt-oss-120b @ b5c939de8f75

Excerpt
{"num_hidden_layers": 36, "num_experts": 128, "experts_per_token": 4, "vocab_size": 201088, "hidden_size": 2880, "intermediate_size": 2880, "swiglu_limit": 7.0, "head_dim": 64, "num_attention_heads": 64, "num_key_value_heads": 8, "sliding_window": 128, "initial_context_length": 4096, "rope_theta": 150000, "rope_scaling_factor": 32.0, "rope_ntk_alpha": 1, "rope_ntk_beta": 32}