Sequence Length, Context and Memory in LLM Fine-Tuning

JS
Jai Singh
12 Nov, 2026 4 min read 44 views

The maximum sequence length you train with is one of the biggest levers on memory and speed. Doubling it more than doubles activation memory in many setups, so choose the shortest length that keeps your examples intact. This post explains why and how to pick it.

Context window vs training length

A model's context window is the longest input it was built to handle. Your training sequence length is how long the sequences are in your fine-tuning batches. You can, and usually should, train on shorter sequences than the full context window. A model with a very long window can still be tuned on examples of 1,024 tokens, as long as your real use cases are of similar size.

Where memory goes

Training memory has four main parts:

  • Weights: the model parameters. A 1 billion parameter model in 16-bit takes about 2 GB.
  • Gradients: one per trainable parameter. With LoRA this is tiny; with full fine-tuning it matches the weights.
  • Optimizer state: AdamW keeps two extra values per trainable parameter, typically in 32-bit.
  • Activations: intermediate values kept for the backward pass. These scale with batch size and sequence length.

Only the last one depends on the length of your data. That is why a run can fit at length 512 and run out of memory at 2,048.

Attention cost

Standard self-attention compares every token with every other token, so its compute grows with the square of the sequence length. Memory-efficient kernels such as FlashAttention avoid storing the full attention matrix, which removes the quadratic memory term but not the quadratic compute. Other parts of the network scale linearly with length. So very long sequences get expensive quickly, though not always exactly quadratically.

Choose a length from your data

import numpy as np

# lengths = token counts per example, computed as in the tokenizer post
lengths = [212, 340, 198, 1020, 415, 377, 260, 305, 288, 1500]

for cap in [256, 512, 1024, 2048]:
    truncated = sum(1 for n in lengths if n > cap)
    print(f"max_len={cap}: {truncated / len(lengths):.0%} truncated")

print("p90:", np.percentile(lengths, 90))

The output shows what share of examples a given cap would cut. Pick the smallest cap that truncates almost nothing, or filter out the rare very long examples. Silent truncation of the answer part is a real quality bug, because the model sees prompts with no completions.

Setting length in TRL

from trl import SFTConfig

args = SFTConfig(
    output_dir="out",
    max_length=1024,                 # tokens kept per example
    per_device_train_batch_size=2,
    gradient_accumulation_steps=8,
)

In recent TRL versions the argument is called max_length; older releases used max_seq_length. If you get an unexpected-argument error, check the version you installed and its documentation.

Ways to cut memory

  1. Reduce sequence length or drop outlier examples.
  2. Lower the per-device batch size and raise gradient accumulation to keep the effective batch size (post 46).
  3. Turn on gradient checkpointing (post 48).
  4. Use LoRA or QLoRA instead of full fine-tuning.
  5. Use bf16 where the hardware supports it (post 47).
  6. Use an efficient attention implementation.

Long contexts need extra care

If your task truly needs long inputs, such as whole documents, training on short sequences may not transfer. Test on realistic lengths. Post 89 covers long-context tuning in detail.

Takeaways

  • Measure token lengths, then set the cap near the 95th percentile or higher.
  • Memory problems are almost always fixed by length, batch size and checkpointing before anything exotic.
  • Shorter sequences train faster, so every unnecessary token costs time.
  • Watch for truncation that removes the answer.

Worked example: sizing a run

Suppose you tuned for a 7B-class model with QLoRA, sequences of 1,024 tokens, and a batch of 4. You run out of memory. Work through the list: drop the batch to 2 and set gradient accumulation to 8, which keeps the effective batch of 16 but halves activation memory. If it still fails, enable gradient checkpointing, which recomputes activations during the backward pass and often cuts activation memory by a large factor at the cost of roughly a third more compute time. As a last step, lower the maximum length to 768 after checking that few examples are affected. Make one change at a time and record the memory reported by torch.cuda.max_memory_allocated() so you learn which change did the work.

The same thinking applies to speed. Padding wastes compute: if one example in a batch is long, every other example is padded to match. Sorting or grouping examples by length, or packing several short examples into one sequence (post 32), recovers that waste.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.