Deep architectures
Position, Masking, and Sequence Geometry
Design positional information and masks for ordered, cyclic, two-dimensional, packed, and causal data without leaking unavailable evidence.
By the end you can
- Explain why plain self-attention is permutation equivariant without position information
- Compare absolute, relative, rotary, and learned positional schemes
- Design causal, padding, segment, local, and cross-attention masks
- Diagnose extrapolation, packing, and boundary failures in sequence geometry
Content alone does not define order
Feed a self-attention layer the same set of vectors in a different order and its outputs come back permuted the same way. Position or structure has to be injected; the mechanism compares content, not chronology. That is not a rule of thumb about attention. It is a published property, with a formal definition and a named proposition behind it.
The Set Transformer paper wrote both down in 2019. Its Definition 1 is exact: a function f : X^n -> Y^n is permutation equivariant iff f(pi x) = pi f(x) for every permutation pi in S_n. The paper then applies that definition to the two positionless self-attention operations it builds, the Set Attention Block (SAB) and the Induced Set Attention Block (ISAB). The sentence immediately before Property 1: “We also emphasize that both of our set operations (SAB and ISAB) are permutation equivariant”. Shuffle the encoder's input and its output arrives shuffled in exactly the same way. Nothing else about it changes. Nothing else in it knows the order changed.
A second group, working on an unrelated problem, states the same fact in its own words. The T5 paper, 2020: “Since self-attention is order-independent (i.e. it is an operation on sets), it is common to provide an explicit position signal to the Transformer.”
So the architecture has to supply the geometry — sequence order, spatial coordinates, graph distance, whatever the task runs on. Equivariance is the default. The design has to overturn it deliberately.
Position is not metadata around attention; it is part of the model’s definition of relationship.
Comparison
Ways to encode position
Each scheme chooses different assumptions about distance, length, and extrapolation. Four of the rows below come with published measurements. Three come with a verdict from the authors who ran the experiment.
The original Transformer chose sinusoids in 2017, for a stated reason: “we hypothesized it would allow the model to easily learn to attend by relative positions”. The same paragraph records the control they ran. They “also experimented with using learned positional embeddings instead, and found that the two versions produced nearly identical results”. So the measurement did not decide it. The sinusoidal form survived on a second argument instead — “because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training”. That is a hypothesis about a regime they had not measured.
A 2018 follow-up measured what the relative row is worth. In the big configuration, relative position representations gained 1.3 BLEU on WMT 2014 English-to-German over absolute ones, and 0.3 BLEU on English-to-French. Base and big gains were 0.3 and 1.3 BLEU for EN-DE, 0.5 and 0.3 BLEU for EN-FR. The sharper number is the clipping-distance ablation, scored on the English-to-German development set newstest2013. Remove relative position information entirely, at clipping distance k = 0, and BLEU collapses to 12.5. Restore the crudest possible relation, k = 1, and it returns to 25.5. Every larger clip lands between 25.8 and 25.9 (k = 2: 25.8, k = 4: 25.9, k = 16: 25.8, k = 64: 25.9, k = 256: 25.8). The base model used k = 16, the big model k = 8. Almost all of the value is in knowing that a neighbour is a neighbour. Stacking a second scheme on top buys nothing: “Notably, we observe that combining relative and absolute position representations yields no further improvement in translation quality.”
The relative row also has production numbers. T5 dropped absolute position embeddings for a simplified relative scheme. Each "embedding" is a single scalar added to the attention logit, shared across all layers but distinct per head. The 2020 paper states the sizing: “In this work, we use 32 embeddings for all of our models with ranges that increase in size logarithmically up to an offset of 128 beyond which we assign all relative positions to the same embedding.” The consequence is structural. Past an offset of 128 tokens, a single layer cannot tell one distance from another. Only stacked layers recover longer offsets.
Rotary encoding came later. RoPE encodes “the absolute position with a rotation matrix”, while incorporating “the explicit relative position dependency in self-attention formulation”. It was posted in 2021 and later published in Neurocomputing.
The warning in the coordinate row — that a scheme may expose unwanted absolute cues — has been measured too. Swin Transformer, in 2021, was built on a learned relative position bias over the (2M-1) x (2M-1) grid of within-window offsets. Its ablation: “Swin-T with relative position bias yields +1.2%/+0.8% top-1 accuracy on ImageNet-1K, +1.3/+1.5 box AP and +1.1/+1.3 mask AP on COCO, and +2.3/+2.9 mIoU on ADE20K in relation to those without position encoding and with absolute position embedding, respectively, indicating the effectiveness of the relative position bias.” On the same backbone, absolute position embedding helps ImageNet classification by +0.4% top-1 while hurting localisation: -0.2 box and mask AP on COCO, -0.6 mIoU on ADE20K. One added cue, two opposite signs. Which sign you get is decided by which invariances the task has.
Absolute embeddings
Associate each index with a vector added or combined with content.
- Simple implementation
- Direct index identity
- Fixed or learned tables
- May extrapolate poorly beyond trained lengths
Relative position bias
Modify interactions using distance or relation between elements.
- Emphasizes pairwise geometry
- Can share across locations
- Supports local or bucketed distances
- Needs a rule for unseen ranges
Rotary-style encoding
Rotate query and key components according to position.
- Injects relative phase into dot products
- Compatible with causal attention
- Scaling choices affect long context
- Does not solve retrieval alone
Coordinate or structural features
Use multidimensional, graph, temporal, or domain-specific positions.
- Matches non-text geometry
- Can encode axes and boundaries
- Requires task-specific design
- May expose unwanted absolute cues
Visual
Masks define legal information flow
Several masks may be combined before normalization, and the combination can be the architecture. Big Bird is made of exactly three composable masks: g global tokens attending to the whole sequence, a sliding window of w local neighbours, and r random tokens. Eleven authors at Google Research published it in 2020. That sum is not a heuristic. They report it is a universal approximator of sequence functions and Turing complete, and they run it at sequence length 4096. What the sparsity buys is in the abstract: “The proposed sparse attention can handle sequences of length up to 8x of what was previously possible using similar hardware.”
Each layer below is a set of permitted edges. A real system is their intersection.
- 01
Causal access
Disallow a position from reading future targets.
- 02
Padding validity
Remove artificial padded elements from attention.
- 03
Segment isolation
Prevent packed examples or documents from contaminating one another.
- 04
Local or sparse pattern
Restrict routing to windows, blocks, or selected global elements.
- 05
Application constraints
Encode visibility, permissions, or modality-specific access.
Example
Geometry bugs that produce suspiciously good metrics
Many mask failures are silent because tensor shapes remain valid. The first of them is a deliberate design decision at a frontier lab. Llama 3 masks attention across document boundaries inside a packed sequence, and Meta's July 2024 report says why: “We use an attention mask that prevents self-attention between different documents within the same sequence. We find that this change had limited impact during in standard pre-training, but find it to be important in continued pre-training on very long sequences.” The typo is in the original.
The cost of omitting that mask has been measured independently. An ACL 2024 study found that plain causal masking over concatenated documents admits distracting information from previous documents. Its related-document packing method, BM25Chunk, improves in-context learning by 11.6%, knowledge memorisation by 9.8% and context utilisation by 7.2%. None of that shows up as a shape error.
- Packed training: tokens from one example attend to another because segment boundaries were omitted. This is the leak Llama 3's document mask prevents, and the one the ACL 2024 study priced at 11.6% of in-context learning performance.
- Causal forecasting: the target timestamp reads features computed from later observations through a side channel.
- Image patches: row and column coordinates are flattened incorrectly, swapping neighborhood relationships. Swin's post-shift sub-window mask blocks that failure, confining self-attention so that patches which are not spatial neighbours cannot attend to one another.
- Variable-length batches: padded keys are masked, but padded queries still contribute to the loss.
- Cross-attention: a decoder receives source positions that should be hidden by user permissions or temporal availability.
Analogy
Seating plans and access badges
At a conference, seat numbers describe location and badges determine which rooms each attendee may enter. Content describes the people; position and masks define the interaction geometry.
A badge gives a hard yes or no at the door. Neural access is soft after masking, and representations change through layers. Order and permission enter the architecture as two separate inputs.
Positional encoding says where an element is; masking says which interactions are legal.
Steps
Unit-test sequence geometry before training
A small synthetic batch can reveal most access-control errors. The edge sets worth asserting are the ones the published architectures name explicitly: document boundaries inside a packed sequence; the g global tokens, the w-wide local window and the r random tokens of a sparse pattern; the sub-window partition a cyclic shift creates. Each of those is an adjacency matrix. You can write it down before training and compare against it.
1. Label every token by source
Use distinct numeric values for examples, segments, and positions.
2. Enumerate permitted edges
Write the expected attention adjacency matrix explicitly.
3. Test boundary lengths
Include empty padding, one-token sequences, maximum length, and packed segments.
4. Shift or extend positions
Measure whether outputs change according to the intended geometry.
5. Verify loss masking
Ensure invalid query positions contribute neither prediction nor gradient.
Key idea
Longer context is not only a larger mask
Position schemes may behave differently outside their training range. Attention can underuse middle or distant evidence even when access is legal. Numerical and cache costs grow as well.
Extrapolation is a measured trade, not a caution. ALiBi, presented at ICLR 2022, adds no positional embeddings at all. It penalises query-key attention scores in proportion to distance. The abstract states the result: “We show that this method trains a 1.3 billion parameter model on input sequences of length 1024 that extrapolates to input sequences of length 2048, achieving the same perplexity as a sinusoidal position embedding model trained on inputs of length 2048 but training 11% faster and using 11% less memory.” Training length and usable length came apart, and cheaper.
Accepting more tokens is a different property again. A 2024 study ran that experiment. It moved one decisive document through a multi-document question-answering context. It moved it through a key–value retrieval task as well. It found that “performance is often highest when relevant information occurs at the beginning or end of the input context”. It “significantly degrades when models must access relevant information in the middle of long contexts, even for explicitly long-context models”. Access was legal at every position tested. Use was not uniform across them.
So evaluate controlled retrieval by distance, location, and distractor density. A model accepting more tokens does not prove that it uses them reliably.
Context capacity, positional extrapolation, and effective retrieval are separate properties.
The correct geometry depends on the invariances of the task
Absolute time can matter in seasonality. Relative intervals matter in event dynamics. Two-dimensional images need both axes. Graphs may require shortest-path, edge, or spectral information.
The strongest evidence that this is a design decision, rather than a component to install, is a controlled comparison in which the brand names lose to nothing at all. A 2023 study trained roughly 107M-weight decoder-only Transformers from scratch on ten tasks in three groups. Two were primitive: copy and reverse. Six were mathematical and reasoning tasks: addition, polynomial evaluation, sorting, summation, parity and LEGO. Two were the classical length-generalization datasets, SCAN and PCFG. Five position treatments ran across all ten: sinusoidal absolute position embedding (APE), T5's relative bias, ALiBi, rotary, and no positional encoding at all (NoPE). The learnable APE variant was left out deliberately, “as the learnable variant cannot produce embeddings for unseen positions”.
On the aggregate mean-reciprocal-rank across the ten tasks, NoPE ranks first at 0.69. T5's relative bias follows at 0.55, ALiBi at 0.50, rotary at 0.33, APE at 0.22. NoPE also requires no additional computation. The authors' own summary, at NeurIPS 2023: “Our findings reveal that the most commonly used positional encoding methods, such as ALiBi, Rotary, and APE, are not well suited for length generalization in downstream tasks.”
Do not import a text positional scheme merely because the backbone is a Transformer. State which transformations should preserve behavior and which should change it. Then check that the scheme you picked was measured under those conditions, and not others.
Positional design is an inductive-bias decision, not a required brand-name component.
Key takeaways
- Positionless self-attention is permutation equivariant by proof, not by habit: f(pi x) = pi f(x) for every permutation pi in S_n. That is Property 1 of the Set Attention Block and the Induced Set Attention Block.
- Schemes encode different assumptions, and the differences are measured: 12.5 BLEU with no relative position against 25.5 at k = 1 on newstest2013, and T5's 32 log-spaced buckets going flat past an offset of 128 tokens.
- Causal, padding, segment, and application masks solve distinct access-control problems. Summing three of them — g global, w local, r random — is what carried Big Bird to sequence length 4096.
- Packed examples require explicit isolation. Llama 3 masks self-attention between documents in one sequence, and omitting that boundary cost 11.6% of in-context learning performance in an ACL 2024 measurement.
- Long accepted context does not guarantee reliable use of it. ALiBi extrapolated from length 1024 to 2048 at equal perplexity, while attention still degrades on evidence placed in the middle of a long context.
- Verify position and mask behavior with explicit adjacency and boundary tests before training, and choose the scheme for the task's invariances. In a ten-task comparison, no positional encoding ranked first at 0.69, against rotary's 0.33 and APE's 0.22.