Howwise RSS
AI & Automation8 min read

Why Transformer Fixed Input Length Exists and How to Fix It

Short answer

Why transformer fixed input length limits exist: not because of self-attention itself, but because of learned position embedding tables, quadratic attention memory, the length seen in training, and static shapes in batching and export.

Key takeaways
  • Q/K/V projections, feed-forward and layer norm are per-token, so the math accepts any length; the limit comes from position tables, memory and training.
  • Learned absolute position embeddings (BERT's 512) are the hard error: indices past the table raise an index-out-of-range error.
  • Attention score memory grows with n squared: going from 512 to 4096 tokens means 64 times more score entries per head per layer.
  • Going past the trained length without a length-robust method degrades quality even when nothing crashes.
  • For long text, pad and mask for batching, chunk with overlap, or use RoPE scaling, ALiBi, sliding-window attention or a long-context model.

Is the fixed input length really part of the transformer?

No. Every core layer acts on each token independently or through a softmax over whatever keys exist. The Q, K and V projections are matrices of shape (d_model, d_model), the feed-forward network is applied position-wise, and layer norm normalizes over the feature dimension. None of these weights has a dimension tied to sequence length n.

So a trained transformer can, in principle, take a tensor of shape (batch, n, d_model) for any n. The limit shows up in the pieces around the layers: the position table, the n x n score matrix, what the model saw in training, and how tensors are batched, compiled and cached.

This is why the answer 'because of positional encoding' is only partly right. It explains one hard error, but not the out-of-memory crashes or the quality collapse on inputs that run without errors.

Where does the limit actually come from? Hard vs soft limits

Some limits crash your program and some quietly make outputs worse. Telling them apart tells you which fix to reach for.

CauseHard error or quality dropSymptomFix
Learned absolute position tableHard errorIndexError: index out of range in self (embedding lookup), or CUDA device-side assertTruncate, chunk, interpolate the table and fine-tune, or switch to a relative or rotary model
Quadratic attention memoryHard error (OOM)torch.cuda.OutOfMemoryError as n growsFlashAttention or SDPA, smaller batch, sliding-window attention, gradient checkpointing
Quadratic attention computeSlowdownLatency grows about 4x when length doublesSparse or windowed attention, shorter inputs
Training length mismatchQuality dropPerplexity jumps, repetition or gibberish past the trained lengthRoPE scaling (PI, NTK, YaRN), ALiBi, or fine-tune on longer data
Rectangular batchesNot an error, wasted computeShort items padded to the longestDynamic padding, length bucketing, attention mask
Static shapes (export, XLA, compile)Hard error or recompilesShape mismatch in ONNX or TorchScript; repeated recompiles in torch.compile or XLADynamic axes, padding to a few bucket sizes
Causal mask and KV cache preallocationHard error at inferenceShape errors or cache overflow past max lengthRaise max_seq_len or max_new_tokens budget when allocating

Why do learned position embeddings cause the index error?

Absolute position embeddings in BERT, GPT-2 and similar models are an nn.Embedding(max_positions, d_model) table, for example 512 rows in BERT. Token i adds row i to its embedding. A sequence of 600 tokens asks for row 512 to 599 that do not exist.

Sinusoidal encodings avoid the crash because position p is computed from a formula, so any p works. But the model only learned to use the frequencies and phases that appeared in training, so quality still degrades far past the trained length.

The tokenizer's max length is a separate setting from the model's table. Setting tokenizer.model_max_length higher does not add rows, so you get the crash later in the forward pass.

from transformers import AutoConfig, AutoTokenizer

cfg = AutoConfig.from_pretrained("bert-base-uncased")
tok = AutoTokenizer.from_pretrained("bert-base-uncased")
print(cfg.max_position_embeddings)   # 512
print(tok.model_max_length)          # 512

enc = tok(long_text, truncation=True, max_length=512, return_tensors="pt")
# Without truncation=True, a 700 token input raises:
# IndexError: index out of range in self
Warning: Truncation is silent. If you pass truncation=True, everything after the limit is discarded with no warning. Check enc['input_ids'].shape or use return_overflowing_tokens to see what was dropped.

Why is attention quadratic in sequence length?

Each of the n queries is compared with each of the n keys, producing an n x n score matrix per head per layer, then softmax and a multiplication with V. Time and memory both scale as O(n^2 * d) for the scores.

Worked example: at n = 512 there are 512 x 512 = 262,144 scores per head per layer. At n = 4096 there are 16,777,216, which is 64 times more (8 times the length, squared). In fp16 at 2 bytes each, that is about 32 MB per head per layer for one sequence, so 12 heads is about 400 MB per layer, and a batch of 8 multiplies that again, before counting the saved activations for backprop.

FlashAttention computes attention in tiles and never materializes the full n x n matrix in GPU memory, so memory becomes linear in n. It does not reduce the arithmetic: compute is still quadratic, it is just faster because it avoids slow memory traffic. In PyTorch, torch.nn.functional.scaled_dot_product_attention picks such a kernel automatically when conditions allow.

import torch.nn.functional as F
# q, k, v: (batch, heads, n, head_dim)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
# Hugging Face: from_pretrained(..., attn_implementation="sdpa")

How do I batch variable length input and what about static shapes?

Transformers handle variable length fine per batch, but PyTorch tensors must be rectangular. Shorter sequences are padded to the longest in the batch (or to max_length), and an attention mask makes real tokens ignore pad tokens. In torch.nn.MultiheadAttention this is key_padding_mask, where True means ignore; in Hugging Face, attention_mask uses 1 for real tokens and 0 for padding.

Padding to a global max_length wastes compute, and since cost is quadratic, one long outlier inflates the whole batch. Use dynamic padding and group similar lengths together.

  1. Tokenize without padding: tok(texts, truncation=True, max_length=512).
  2. Sort or bucket examples by length so each batch has similar sizes.
  3. Pad per batch with DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8), which keeps tensor-core friendly shapes.
  4. Pass attention_mask to the model, and ignore pad positions in the loss (label -100).
  5. For export, declare dynamic axes so ONNX does not freeze the trace length.
torch.onnx.export(
    model, (input_ids, attention_mask), "m.onnx",
    input_names=["input_ids", "attention_mask"],
    output_names=["logits"],
    dynamic_axes={"input_ids": {0: "batch", 1: "seq"},
                  "attention_mask": {0: "batch", 1: "seq"},
                  "logits": {0: "batch"}},
)
Tip: TorchScript tracing, XLA/TPU and torch.compile specialize on shapes, so each new length can trigger a recompile. Padding to a handful of bucket sizes (128, 256, 512) keeps the number of compiled graphs small. torch.compile(dynamic=True) is another option. At inference, causal masks and KV caches are also allocated for a maximum length, so the cache size must cover prompt plus generated tokens.

How does Transformer-XL overcome the fixed context length?

A vanilla transformer language model is trained on fixed segments, say 512 tokens, with no information passing between them. The first tokens of each segment have almost no context, which is called context fragmentation. At evaluation it must either use non-overlapping chunks (poor context) or slide one token at a time (very slow).

Transformer-XL adds segment-level recurrence: hidden states from the previous segment are cached (with gradients stopped) and attended to as extra keys and values when processing the next segment. Stacking layers lets the effective context grow roughly with segment length times number of layers. Evaluation is also much faster because cached states are reused rather than recomputed.

Cached states from an earlier segment have different absolute positions, so absolute embeddings would be ambiguous. Transformer-XL therefore uses relative positional encodings, where attention depends on the distance i - j between query and key. This idea carries into most modern designs.

How do I run a transformer on text longer than max length?

Pick by whether you can change the model. If not, chunk with overlap. If so, prefer a position scheme that extends well.

Sliding-window chunking with Hugging Face tokenizers keeps context at the boundaries. Aggregate per-chunk outputs afterwards (max or mean of logits for classification, or merge spans for QA and NER).

enc = tok(
    long_text,
    max_length=512,
    stride=128,                      # overlap in tokens
    truncation=True,
    return_overflowing_tokens=True,
    return_offsets_mapping=True,
    padding=True,
    return_tensors="pt",
)
enc.pop("overflow_to_sample_mapping"); enc.pop("offset_mapping")
logits = model(**enc).logits          # (n_chunks, labels)
doc_logits = logits.mean(0)

# Extending a learned position table by linear interpolation
import torch, torch.nn as nn
old = model.embeddings.position_embeddings.weight.data   # (512, d)
new_len = 1024
new = nn.functional.interpolate(
    old.T.unsqueeze(0), size=new_len, mode="linear", align_corners=True
).squeeze(0).T.contiguous()
model.embeddings.position_embeddings = nn.Embedding.from_pretrained(new, freeze=False)
model.config.max_position_embeddings = new_len
# Also resize the registered position_ids buffer, then fine-tune.
Warning: Interpolated tables are only a starting point. Without fine-tuning on longer sequences, quality is usually poor. Model-specific attributes also differ (for example, BERT keeps a position_ids buffer and token_type handling that must match the new length).

Which modern methods remove or soften the limit?

Most current approaches change how position enters attention, or limit which tokens attend to which.

Common mistake: confusing the context window with the output limit. The window covers prompt plus generated tokens together, and many APIs cap output separately, so a long prompt leaves less room for the answer.

MethodIdeaTrade-off
Relative position (T5 bias, Transformer-XL)Attention depends on distance, not absolute indexBetter transfer, still weaker far beyond trained range
RoPERotates Q and K by position-dependent angles so scores depend on relative offsetUnscaled RoPE degrades past training length
Position interpolation, NTK scaling, YaRNRescale RoPE positions or frequencies to fit a longer range into the trained oneShort fine-tune recommended; some tuning of the scale factor
ALiBiAdds a distance-proportional penalty to attention scores, no position embeddingsExtrapolates modestly; locality bias
Sliding window, Longformer, BigBirdEach token attends to a local window plus a few global or random tokensLinear cost; long-range links are indirect
Long-context pretrained modelsTrained or extended on long sequencesStill quadratic compute unless sparse; memory for KV cache
# Hugging Face: RoPE scaling on a Llama-style model (linear / position interpolation)
from transformers import AutoConfig, AutoModelForCausalLM
cfg = AutoConfig.from_pretrained("your/model")
cfg.rope_scaling = {"type": "linear", "factor": 2.0}   # 4k -> 8k
model = AutoModelForCausalLM.from_pretrained("your/model", config=cfg)
# Newer versions may name keys differently (rope_type); fine-tune for best quality.

Common questions

Can transformers handle variable length input?

Yes. Within a batch, shorter sequences are padded and masked, and across batches the length can differ freely. The only requirements are that the length stays within the position table and memory, and that your export or compile path allows dynamic shapes.

Does sinusoidal positional encoding remove the length limit?

It removes the crash, because any position can be computed from the formula. It does not remove the quality drop, since the model never trained on those positions and attention patterns beyond the training length.

Will FlashAttention let me use any length?

It makes memory for attention scores linear in n, which allows much longer inputs on the same GPU. Compute remains quadratic, and the KV cache and activations still grow with length, and quality still depends on what length the model was trained for.

Why does my model run out of memory before reaching max_length?

Memory scales with batch size times heads times n squared for naive attention, plus activations kept for backprop. Reduce the batch size, enable SDPA or FlashAttention, use gradient checkpointing, or use mixed precision.

Is raising tokenizer model_max_length enough to accept longer input?

No. That only changes the tokenizer's truncation default. The model's position table or RoPE configuration still defines what it can process, so longer ids will crash or degrade unless the model itself is extended.

Related topics:transformerspositional-encodingattentionpytorchlong-context