Blog

  • Enough RoPE

    Unlike RNNs, which read one token at a time, Transformers get their whole context window at once. So, it’s pretty intuitive that we need to give them some kind of signal about the ordering of those tokens so they don’t just devolve to treating their input as a bag of words.1 Seb Raschka recently did an in-depth breakdown on positional encodings, including how the industry largely aligned around RoPE for providing this information.

    But RoPE is… kinda weird? It encodes the position in the query and key projection heads in attention. It splits the head into pairs of values, treats each pair as a 2D vector, then rotates it (like a hand on a clock) based on the token position. When a query is compared with a key the difference between their rotations gives how far apart the two tokens are. Each pair is rotated at a different rate: a 64-dimension head gives you 32 pairs with the fastest completing a rotation every 6 tokens, the slowest every ~47k. The models learn to stick this together to understand overall position.

    That positional information also makes the dimensions somewhat useless for learning other kinds of rules: if you put some semantic comparison into the pairs and they get rotated 180 degrees after 3 tokens, you lose that information.

    Unlike rotations, we don’t tell the model to put semantic information into a channel though, they learn it. Specifically, they appear to learn to leverage the dimensions in three ways: a precise count within the last few tokens for the fast rotating pairs, a general sense of how far back something is for the medium pairs, and mostly semantic content that ignores the rotation for the slow pairs.2

    It is not a tremendous leap to think that rotating parts of the head then training the model to ignore it may not be the optimal route.

    Gemma 4 used “p-RoPE” (partial RoPE), only rotating the fastest quarter of the pairs. A recent ETH paper, HiSA, stopped counting pairs in the attention score if two entries are more than 90° apart, which covered about 2 tokens on the fast pairs to around 12k tokens on the slow pairs. Surprisingly, doing this seemed to result in slightly better models. They concluded that the larger angles are mostly noise the model has to learn to ignore.

    I tried this out with SmolLM-135M, fine-tuning it on “what is the token D steps back” in a non-repeating context window. The model solves this completely (out to 1,024 tokens at least). Taking the fine-tuned model and masking out each pair’s contribution where it had done 2 or more rotations nuked exact recall past D = 32, but the same change on the base model made hardly any difference to the model’s performance on regular prose-type tasks (0.0007 nats). So distance positional information isn’t quite noise, but it only impact capabilities the model mostly never needs.3

    Put this together and it looks like RoPE gets used in three chunks: fast pairs for exact offsets, something in the middle that acts as a general distance signal, and slow pairs that are mostly content.

    RoPE isn’t the only option, though.4 Thinky’s Inkling models instead have specific mechanisms for each of those chunks. For local navigation they use a sconv, a short convolution. Each layer has 4 depthwise 1D convolutions with window size W=4. They don’t mix channels, just neighboring tokens, so the model can learn what represents 1, 2 or 3 tokens ago without having to figure out a rotation.

    For the middle distance Inkling adds a relative-position bias to the attention logits, prior to the softmax. This is an additional term, not a transform of the query and key.5 It’s implemented as a lookup table that has one value per distance. Each head learns 16 different versions of those tables during training, and each token’s query value picks its own mix of the 16, so how much attention it pays to different distances depends on what the token is. They use this to cover the whole sliding window on local layers, and the most recent 1k tokens on global ones. Beyond that they skip positional encoding entirely.

    How much RoPE do you actually need? Some for the local distance, and some for the last thousand or so tokens, but you, probably, don’t need it much further out. And, if you start with that premise, maybe you don’t need RoPE at all!

    1. Mostly! A causal model can still work out roughly where it is from the mask, which is why NoPE/going without any encoding works at all. Meta’s iRoPE, for example, dispenses with RoPE entirely on the global (non-sliding window) layers. ↩︎
    2. Barbero et al. suggested that in Gemma 7B, the fast-moving pairs act as local positional heads, while the slow pairs get reused as semantic channels rather than positional ones: they move so slowly they are almost position-free. ↩︎
    3. This was a lot less aggressive than the HiSA cut, which in my test reduced performance by 0.22 nats on prose. This was much worse than in the paper, but 1) I didn’t retrain from scratch 2) the performance seemed specific to one layer which had learned what amounted to a fixed penalty on keys a long way back. ↩︎
    4. Back in April, Jane Street published a math-heavy post arguing that a good positional encoding should be linear, depend only on relative distance, be the identity at distance zero, and be continuous. Those constraints pretty much force you into a few valid options: no encoding, a decay term, or rotation. They concluded all the sensible choices are already in production, though their “linear” constrain excludes exactly what Thinky did below! ↩︎
    5. This isn’t new, T5 did it, and Shaw et al. had a query-dependent version back in 2018, but I don’t know anyone shipping it at this scale. ↩︎
  • ML compiler eng, your job is NP-hard

    I mean, sorta. From the Tensor Seeks Layout paper from Amazon:

    Layout Selection is NP-hard even when each operator has only a constant number of inputs and each tensor admits only a small number of layouts, and hardness persists in restricted settings that resemble common matmul-heavy graphs.

    The paper is very focused on formal analysis of the layout problem, for Trainium workloads. They build a layout selection exact solver, and on ResNet-50 they find the proven optimum using their cost model takes 63.9M cycles. In contrast, the awkward heuristic rules take… 20.9M cycles. The authors attribute this to a wonky cost model, which we will come back to.

    There has been a lot of work in recent months on what layouts actually are, but this paper is about where and when you do conversions between them.

    To jump down a level of granularity, in the Triton compiler this decision is mainly handled by the RemoveLayoutConversions pass: during compilation, Triton throws in layout conversions every time one might be needed, and this pass prunes them. It has the very sophisticated rule that conversions either cost 0 or 32xbytes. “0” means the conversion is a register permute, where everything happens locally. The higher value is for shuffles and shared memory round trips.

    This made me wonder how wrong the rule actually was, versus the more structured approach in Amazon’s paper. I ran some experiments and found, yeah, the heuristic is pretty wrong. Relative to an elementwise add, the heuristic overestimates by about 4x for fp32, 19x for fp16, and sometimes even more for fp8. If you update to use the proper cost model though, not a lot changes. No tutorial kernels shift, and in general the performance changes are a bit of a wash: in testing 8 were slower, 4 were faster, 9 didn’t change at all.

    The main reason is rematerialization: instead of converting the layout, walk back up the chain and recompute or load in the format you actually need. Conversions are mostly about cases where you can only emit one way, and then consume a different way. In those cases, the layout picks are arbitrary1, but they are mostly fine: the majority of kernels didn’t require a choice, and where they did, the default pick seemed to be the right one the vast majority of times.

    We talked earlier about OpenAI’s effort to remove heuristics from the compiler, but this seems like an area where a heuristic is doing a reasonable job. If you dig into the cases where there is a performance mismatch though, you will find that the problem is also a compiler, but in this case a different one.

    The pass exists to cut down layout conversions, which is generally good! But the output is then fed into another compiler, ptxas. That can be sensitive: in one case we found a matmul that got 15–26x faster, purely because of the instruction ordering. ptxas decides register allocation, and if it decides there aren’t enough it will spill to memory, significantly impacting performance2.

    The finding that layout search is computationally hard in Amazon’s paper is valid, and good to share with your executives3 . But, in reality, you don’t have to check all that many options: there are generally just a few places to put a conversion in a specific kernel4. Picking an option requires relying a potentially inaccurate model of how expensive those ops are given the subsequent (closed-source!) software stack and the hardware itself. And that seems to be the really tricky part.

    1. And the pass is commented“TODO: add a proper heuristic”, so it’s not like this was a surprise ↩︎
    2. in this case it moved one local_load 6 ops earlier, which caused ptxas to drop from 255 registers to 40. I don’t know why! ↩︎
    3. We have to take these wins in the brief time before someone puts out 150M lines of Lean to prove that NP isn’t that hard at all. ↩︎
    4. To be fair, the Amazon paper is doing the same thing for entire graphs of 10k+ operators, but it seems like it is somewhat analogous ↩︎

Earlier posts

All posts in the archive →