Inferensys

Glossary

Context Window

The maximum span of preceding tokens that a language model can access and attend to when generating the next token in a sequence.
Engineer optimizing context window usage on laptop, token usage charts visible, technical work session.
FOUNDATIONAL ARCHITECTURE

What is Context Window?

The context window defines the maximum span of preceding tokens a language model can access when generating the next token, serving as the model's working memory for a single inference.

A context window is the fixed-length span of preceding tokens—measured in tokens, not words—that a large language model (LLM) can attend to when predicting the next token in a sequence. It functions as the model's transient working memory, defining the upper boundary of information available for a single inference pass. Tokens falling outside this window are irretrievably lost for that generation step, making the window size a critical architectural constraint that directly governs the complexity of tasks a model can perform, from long-document summarization to multi-turn agentic reasoning.

Expanding the context window involves overcoming the quadratic computational complexity of the standard self-attention mechanism, which scales O(n²) with sequence length. Techniques like FlashAttention, Ring Attention, and positional interpolation (such as RoPE scaling) have enabled windows to grow from 4K tokens to 1M+ tokens in frontier models. However, effective utilization does not scale linearly with size; research reveals a 'lost-in-the-middle' phenomenon where model recall accuracy degrades significantly for information positioned in the center of long contexts, making context engineering and strategic content placement essential for reliable performance.

FUNDAMENTAL MECHANICS

Core Characteristics of Context Windows

The context window defines the operational memory of a language model, dictating how much prior information it can consider when generating the next token. Understanding its characteristics is critical for engineering reliable AI systems.

01

Token-Based Capacity

A context window's size is measured in tokens, not words or characters. A token is a subword unit generated by a tokenizer like Byte-Pair Encoding (BPE). A single English word averages ~1.3 tokens, but complex or agglutinative words can fragment into many more. The model's attention mechanism computes pairwise relationships across all tokens in this window, making the computational cost scale quadratically with window size.

  • GPT-4 Turbo: 128,000 tokens (~96,000 words)
  • Claude 3 Opus: 200,000 tokens (~150,000 words)
  • Gemini 1.5 Pro: Up to 1,000,000 tokens in research preview
  • Mistral Large: 32,000 tokens
O(n²)
Attention Complexity
02

The Lost Middle Problem

A well-documented failure mode where models exhibit degraded recall for information positioned in the middle of a long context window. Performance follows a U-shaped curve: the model best remembers the beginning (primacy bias) and the end (recency bias) of the prompt, while the central portion suffers significant attention dropout.

  • This is not a token limit issue but an attention distribution failure
  • Mitigation strategies include reordering documents by relevance and placing critical instructions at the extremes
  • Evaluated using the Needle-in-a-Haystack benchmark, where a random fact is inserted at varying depths
03

Positional Encoding

Since the Transformer architecture is permutation-invariant, it requires a mechanism to inject sequence order into token representations. Positional encodings assign each token a unique vector based on its absolute or relative position in the context window.

  • Absolute Positional Encoding: Uses sinusoidal functions or learned embeddings tied to fixed indices (original Transformer)
  • Rotary Position Embedding (RoPE): Encodes relative position by rotating query and key vectors, enabling better length extrapolation (used in LLaMA, Mistral, PaLM)
  • ALiBi: Adds a linear bias to attention scores based on token distance, penalizing far-away tokens without learned embeddings
04

Attention Masking

The mechanism that controls which tokens can attend to which other tokens. In autoregressive (causal) language models, a triangular mask is applied to the attention matrix, preventing each token from attending to future tokens. This enforces the left-to-right generation constraint.

  • Causal Mask: Token at position i can only attend to positions 0 through i
  • Padding Mask: Ignores filler tokens in batched inputs of unequal length
  • Custom Masks: Can enforce document boundaries, speaker turns, or other structural constraints within the window
  • Masking is implemented by adding negative infinity to prohibited attention scores before the softmax
05

Context Window Extension Techniques

Methods to increase the effective context length of a pre-trained model beyond its original training window without full retraining. These techniques modify the attention mechanism or positional encoding to generalize to longer sequences.

  • Position Interpolation: Linearly scales down all position indices to fit within the original trained range, then fine-tunes on longer sequences
  • NTK-Aware Scaling: Modifies the base frequency of RoPE to prevent high-frequency information loss during interpolation
  • YaRN (Yet another RoPE extensioN): Combines NTK-aware interpolation with a temperature factor on attention logits to maintain perplexity at extended lengths
  • Self-Extend: Prompts the model to group tokens into chunks, using the original window size for local attention and a larger stride for global context
06

KV-Cache Management

During autoregressive generation, the Key and Value tensors computed for all previous tokens are cached in GPU memory to avoid redundant recomputation. The size of this KV-cache grows linearly with the context window and batch size, becoming the primary memory bottleneck for long-context inference.

  • Memory formula: 2 * num_layers * hidden_dim * context_length * batch_size * precision_bytes
  • Multi-Query Attention (MQA) and Grouped-Query Attention (GQA) reduce KV-cache size by sharing key/value heads across query heads
  • PagedAttention (vLLM) manages KV-cache in non-contiguous memory blocks, analogous to virtual memory paging, to minimize fragmentation
  • Sliding Window Attention (Mistral) restricts attention to a fixed local window, capping KV-cache growth regardless of total context length
CONTEXT WINDOW

Frequently Asked Questions

Clear, technically precise answers to the most common questions about context windows in large language models, covering mechanics, limitations, and optimization strategies.

A context window is the maximum span of preceding tokens—words, subwords, or characters—that a language model can access and attend to when generating the next token in a sequence. It defines the model's working memory during inference. For example, a model with a 128,000-token context window can "see" and reason over approximately 96,000 words of preceding text before its oldest input is truncated. This window includes the system prompt, conversation history, retrieved documents, and any user input. The mechanism is rooted in the self-attention computation, where each token computes relevance scores against every other token within the window. Tokens outside this boundary are permanently invisible to the model, making the context window a hard architectural constraint that directly governs the complexity of tasks the model can handle—from multi-document summarization to long-form code generation.

TOKEN CAPACITY COMPARISON

Context Window Sizes Across Major Models

A comparison of maximum context window sizes for prominent large language models, measured in tokens.

ModelMax TokensApprox. WordsRelease YearOpen Source

GPT-4o

128,000

~96,000

2024

Claude 3.5 Sonnet

200,000

~150,000

2024

Gemini 1.5 Pro

1,000,000

~750,000

2024

Llama 3.1 405B

128,000

~96,000

2024

Mistral Large 2

128,000

~96,000

2024

Command R+

128,000

~96,000

2024

GPT-3.5 Turbo

16,385

~12,000

2023

Claude 2.1

200,000

~150,000

2023

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.