The Longformer is a modified transformer architecture designed to overcome the quadratic memory and computational complexity of standard self-attention. It achieves this through a combination of sliding window attention for local context and global attention on pre-selected task-specific tokens, such as the [CLS] token. This hybrid mechanism allows the model to process sequences of up to 4,096 tokens or more, making it uniquely suited for long-form legal documents like contracts and case law.
Glossary
Longformer

What is Longformer?
Longformer is a transformer model employing a sparse attention mechanism that scales linearly with sequence length, enabling the processing of lengthy legal documents without truncation.
By scaling linearly with input length, Longformer eliminates the need for aggressive text truncation that destroys cross-clause legal reasoning. The architecture's dilated sliding window further expands its receptive field without increasing compute, enabling the model to capture distant dependencies across lengthy legal provisions. This makes it a foundational encoder for legal embedding models and Retrieval-Augmented Generation (RAG) systems that require full-document semantic understanding.
Key Features of Longformer
The Longformer introduces a sparse attention mechanism that scales linearly with sequence length, enabling the processing of lengthy legal documents without truncation.
Sliding Window Attention
The core innovation replacing full self-attention. Each token attends only to a fixed-size window of w neighboring tokens on each side, reducing complexity from O(n²) to O(n*w).
- Fixed Context Radius: Typically 512 tokens on each side
- Stacked Layers: Receptive field grows with depth, eventually covering the entire document
- Legal Relevance: Captures local syntactic structures and clause boundaries without quadratic cost
Global Attention on Special Tokens
Designated tokens—such as [CLS] for classification or question tokens in QA tasks—receive global attention, attending to all other tokens in the sequence.
- Task-Specific Flexibility: Configure which tokens operate globally based on the downstream task
- Information Bottleneck: Global tokens aggregate document-level context for sequence-level predictions
- Legal Application: Enables a [CLS] token to synthesize an entire 50-page contract for clause classification
Dilated Sliding Window
To increase the receptive field without increasing computation, the sliding window can be dilated—introducing gaps between attended tokens.
- Exponential Growth: Dilation doubles at certain layers, rapidly expanding coverage
- Multi-Scale Patterns: Captures both fine-grained local context and broader document structure
- Efficiency: Achieves large effective context with minimal overhead, critical for multi-document legal reasoning
Linear Scaling with Sequence Length
Unlike standard transformers where doubling the input length quadruples computation, Longformer's cost grows linearly. This makes processing full-length legal documents computationally feasible.
- Memory Efficiency: GPU memory usage scales linearly, preventing out-of-memory errors on long texts
- Practical Limits: Can process sequences up to 4,096 tokens (base) or beyond with custom configurations
- Benchmarking: Demonstrated on tasks like document classification and coreference resolution over entire long texts
Pre-Trained on Long Documents
Longformer was pre-trained from RoBERTa checkpoints with continued training on long document corpora, combining the rich linguistic knowledge of a robust encoder with the ability to handle extended context.
- Warm-Start Strategy: Initialized from RoBERTa weights, then adapted with sparse attention
- Gradual Length Increase: Sequence length increased during pre-training to stabilize learning
- Legal Fine-Tuning: The pre-trained checkpoint serves as an ideal starting point for domain-specific legal adaptation using LoRA or full fine-tuning
Autoregressive Language Modeling Variant
Beyond the encoder-only model, Longformer also offers an autoregressive variant (Longformer-Encoder-Decoder) for sequence-to-sequence tasks like long-form summarization.
- LED Architecture: Combines a Longformer encoder with a standard decoder for generation
- Global Encoder Tokens: Decoder cross-attends to global tokens in the encoder for efficient access to full source context
- Legal Summarization: Enables abstractive summarization of entire legal opinions or multi-contract analyses without truncation
Longformer vs. Standard Transformer vs. Other Long-Context Models
A technical comparison of the Longformer's sparse attention mechanism against the standard Transformer and other long-context architectures for processing lengthy legal documents.
| Feature | Longformer | Standard Transformer | Other Long-Context Models |
|---|---|---|---|
Attention Complexity | O(n) | O(n²) | O(n log n) to O(n) |
Max Effective Sequence Length | 4,096+ tokens | 512-1,024 tokens | 8,192-1,000,000 tokens |
Attention Pattern | Sliding window + global | Full self-attention | Sparse, recurrence, or linearized |
Memory Footprint Scaling | Linear | Quadratic | Linear to sub-quadratic |
Pre-training Corpus Size | Books, Wiki, RealNews, Stories | BooksCorpus, Wikipedia | Varies by model (C4, Pile, custom) |
Global Token Support | |||
Dilated Sliding Window | |||
Fine-tuning on Long Documents | |||
Inference Speed (4K tokens) | Fast | Prohibitively slow | Fast to moderate |
Legal Document Suitability | High | Low (truncation required) | High |
Frequently Asked Questions
Answers to common questions about the Longformer's sparse attention mechanism and its application to processing lengthy legal documents without truncation.
The Longformer is a modified Transformer architecture designed to process long documents by replacing the standard self-attention mechanism with a sparse attention pattern that scales linearly with sequence length. Standard Transformers exhibit quadratic complexity (O(n²)) because every token attends to every other token. The Longformer introduces a combination of sliding window attention, where each token attends only to a fixed number of neighboring tokens on either side, and global attention on pre-selected tokens like [CLS] or question tokens. This hybrid approach allows the model to capture both local context (within a clause or paragraph) and global document structure (the relationship of a clause to the overall contract) without exceeding memory constraints. For legal documents that can span hundreds of pages, this means the model can ingest an entire merger agreement or multi-year case history in a single pass rather than truncating it, preserving the cross-references and long-range dependencies critical to legal reasoning.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Explore the core components and complementary techniques that form the Longformer ecosystem for processing lengthy legal documents.
Sparse Attention Mechanism
The core innovation enabling linear scaling with sequence length. Unlike standard self-attention (O(n²)), Longformer uses a combination of sliding window attention for local context and global attention on pre-selected tokens (like [CLS]) to capture long-range dependencies without quadratic memory blowup. This allows processing entire contracts or briefs in a single pass.
Global-Local Attention Pattern
Longformer's hybrid attention pattern combines two distinct mechanisms:
- Sliding Window: Each token attends to a fixed number of neighboring tokens (e.g., ±256), capturing local syntax and clause structure.
- Global Attention: A small set of task-specific tokens attend to all positions, acting as information highways for document-level understanding. This dual approach is critical for legal tasks requiring both clause-level precision and cross-document reasoning.
Dilated Sliding Windows
To increase the receptive field without increasing computation, Longformer employs dilated sliding windows—introducing gaps between attended tokens. This geometrically expands the context coverage while maintaining the same computational budget. For legal documents with hierarchical structure, this helps the model connect distant sections (e.g., a definition in §1.1 and its usage in §12.3) without attending to every intermediate token.
Pre-training Objectives
Longformer is pre-trained using a masked language modeling (MLM) objective adapted for long sequences. The model learns to predict masked tokens using both local window context and global attention signals. For legal domain adaptation, continued pre-training on corpora like PACER dockets or EDGAR filings teaches the sparse attention patterns to recognize legal-specific long-range dependencies, such as cross-referenced statutory definitions.
Comparison with Alternative Architectures
Longformer vs. BigBird: Both use sparse attention, but Longformer's sliding window is conceptually simpler and often faster. Longformer vs. Reformer: Reformer uses LSH-based hashing; Longformer avoids hash collisions and is more deterministic. Longformer vs. Mamba/SSMs: State-space models offer linear scaling but lack the pre-trained ecosystem of Longformer for legal NLP. For legal document processing, Longformer remains the most battle-tested long-context transformer.

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us