Prepare Q, K, V

Rotate by position

×

Rotate all 64 features of each head by the position, in 32 pairs.

K=RoPE⁡t(kh){\htmlData{light=keys k-rotate}{{\htmlClass{vl-stream-k}{K}}}}=\operatorname{RoPE}_{t}({\htmlData{light=k-take}{{\htmlClass{vl-stream-k}{k^{\mathrm h}}}}})
in
khk^{\mathrm h} [B batch, 8 heads, T positions, 64 d_h]RR [B batch, T positions, 64 rotary features]
out
KK [B batch, 8 heads, T positions, 64 d_h]

Feature i is paired with feature i + 32: the head’s first and second halves are rotated against each other (model.py 57–60). 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.

Sources

In codeself.rope(q, k) · 242; _apply_rotary_emb · 50–60

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

A rotation splits each head’s features into halves x1 and x2 and returns x1·cos − x2·sin joined with x2·cos + x1·sin.

model.py 50–60 ↗ · openai/gpt-oss @ 5681a6b65526

Excerpt
def _apply_rotary_emb(
    x: torch.Tensor,
    cos: torch.Tensor,
    sin: torch.Tensor,
) -> torch.Tensor:
    cos = cos.unsqueeze(-2).to(x.dtype)
    sin = sin.unsqueeze(-2).to(x.dtype)
    x1, x2 = torch.chunk(x, 2, dim=-1)
    o1 = x1 * cos - x2 * sin
    o2 = x2 * cos + x1 * sin
    return torch.cat((o1, o2), dim=-1)

The attention block’s forward: normalise; project; take the query, key and value features in that order; read queries as 8 groups of 8 heads of 64, keys and values as 8 heads of 64; rotate queries and keys; attend; project; add to the block’s input.

model.py 217–246 ↗ · openai/gpt-oss @ 5681a6b65526

Excerpt
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        t = self.norm(x)
        qkv = self.qkv(t)
        q = qkv[:, : self.num_attention_heads * self.head_dim].contiguous()
        k = qkv[
            :,
            self.num_attention_heads
            * self.head_dim : (self.num_attention_heads + self.num_key_value_heads)
            * self.head_dim,
        ].contiguous()
        v = qkv[
            :,
            (self.num_attention_heads + self.num_key_value_heads)
            * self.head_dim : (self.num_attention_heads + 2 * self.num_key_value_heads)
            * self.head_dim,
        ].contiguous()

        q = q.view(
            -1,
            self.num_key_value_heads,
            self.num_attention_heads // self.num_key_value_heads,
            self.head_dim,
        )
        k = k.view(-1, self.num_key_value_heads, self.head_dim)
        v = v.view(-1, self.num_key_value_heads, self.head_dim)
        q, k = self.rope(q, k)
        t = sdpa(q, k, v, self.sinks, self.sm_scale, self.sliding_window)
        t = self.out(t)
        t = x + t
        return t