Generate RoPE coefficients

×

Construct rotations for the 64-feature rotary parts.

Rt,j=eitωj{\htmlData{light=model-rotations frequencies}{{\htmlClass{vl-stream-context}{R_{t,j}}}}}=e^{\mathrm i t\omega_j}
in
pp [T positions]
out
RR [T positions, 32 pairs]
Explanation

tt is the position and j<32j<32 the pair.

The frequencies are ωj=θ−2j/64\omega_j=\theta^{-2j/64} with θ=8,000,000\theta=8,000,000. The configuration’s RoPE type is default, so they are not rescaled for longer contexts; the maximum length is 1,048,576 positions.

Sources

In codeself.rotary_emb(hidden_states, position_ids=position_ids)

Open pinned code ↗

Direct evidence

Rotary coefficients: default RoPE, inverse frequencies θ^(−2j/d) over the rotary slice, cosine and sine computed in float32 for the current positions and cast to the activations’ type, with no rescaling (the attention factor is 1).

modeling_glm_moe_dsa.py 67–111 ↗ · huggingface/transformers @ c4c4605f9618

Excerpt
class GlmMoeDsaRotaryEmbedding(nn.Module):
    def __init__(self, config: GlmMoeDsaConfig):
        super().__init__()
        self.max_seq_len_cached = config.max_position_embeddings
        self.original_max_seq_len = config.max_position_embeddings

        self.config = config

        self.rope_type = self.config.rope_parameters["rope_type"]
        rope_init_fn: Callable = self.compute_default_rope_parameters
        if self.rope_type != "default":
            rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
        inv_freq, self.attention_scaling = rope_init_fn(self.config)

        self.inv_freq = nn.Buffer(inv_freq, persistent=False)
        self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False)

    @staticmethod
    def compute_default_rope_parameters(config: GlmMoeDsaConfig, **kwargs) -> tuple[torch.Tensor, float]:
        """
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        """
        base = config.rope_parameters["rope_theta"]
        dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads

        attention_factor = 1.0  # Unused in this type of RoPE
        # Compute the inverse frequencies
        inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
        return inv_freq, attention_factor

    @torch.no_grad()
    @dynamic_rope_update  # power user: used with advanced RoPE types (e.g. dynamic rope)
    def forward(self, x, position_ids):
        freqs = position_ids[..., None].float() * self.inv_freq.to(device=x.device, dtype=torch.float)
        emb = torch.cat((freqs, freqs), dim=-1)
        cos = emb.cos() * self.attention_scaling
        sin = emb.sin() * self.attention_scaling

        return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)

The implementation’s configuration: an explicit indexer_types list is used as given (otherwise it is derived from index_topk_freq and index_skip_topk_offset), RoPE covers only the 64-feature rotary slice (head_dim is pointed at qk_rope_head_dim), and, where no mlp_layer_types list is given, the first first_k_dense_replace layers use the dense MLP (GLM-5.3’s configuration gives the list).

configuration_glm_moe_dsa.py 136–156 ↗ · huggingface/transformers @ c4c4605f9618

Excerpt
        # Per-layer indexer mode: a pattern (e.g. `"FSSF..."`) overrides the freq/offset schedule.
        if self.indexer_types is None:
            pattern = kwargs.get("index_topk_pattern")
            if pattern is not None:
                self.indexer_types = (
                    [{"F": "full", "S": "shared"}[c] for c in pattern] if isinstance(pattern, str) else list(pattern)
                )
            else:
                freq = max(kwargs.get("index_topk_freq", 1), 1)
                offset = kwargs.get("index_skip_topk_offset", 2)
                self.indexer_types = [
                    "full" if (max(i - offset + 1, 0) % freq) == 0 else "shared" for i in range(self.num_hidden_layers)
                ]
        self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
        # RoPE applies only to the rope slice, so point `head_dim` at it: the inherited (Llama) rotary
        # embedding reads `config.head_dim` and then computes the right frequencies with no override needed.
        self.head_dim = self.qk_rope_head_dim
        # MLP layer types: the first `first_k_dense_replace` layers are dense, the rest are MoE.
        if self.mlp_layer_types is None:
            n_dense = min(self.first_k_dense_replace, self.num_hidden_layers)
            self.mlp_layer_types = ["dense"] * n_dense + ["sparse"] * (self.num_hidden_layers - n_dense)