In computer science, quadratic complexity is a computational scaling property where an algorithm's execution time or memory usage increases with the square of its input size (n). This O(n²) relationship means processing an input twice as large requires roughly four times the resources. It is a defining characteristic of the self-attention mechanism in standard transformer architectures, where each element in a sequence must attend to every other element, creating an n x n interaction matrix.
Glossary
Quadratic Complexity

What is Quadratic Complexity?
Quadratic complexity, denoted as O(n²), describes an algorithm whose resource requirements grow proportionally to the square of its input size, becoming a critical bottleneck in large-scale machine learning systems.
This scaling is a primary engineering challenge in cross-encoder reranking for RAG systems. When a reranker jointly encodes a query and a long document, the sequence length (n) is the sum of both, making the attention computation prohibitively expensive for long contexts. Consequently, quadratic complexity drives the need for multi-stage retrieval pipelines, sparse attention mechanisms, and model distillation to maintain practical latency and cost in production environments.
Key Characteristics of Quadratic Complexity
Quadratic complexity, denoted as O(n²), describes algorithms where processing time grows proportionally to the square of the input size. In cross-encoder reranking, this is the fundamental bottleneck for scaling.
The n² Self-Attention Bottleneck
The self-attention mechanism in a standard transformer encoder has quadratic complexity because it computes pairwise interactions between all tokens in the input sequence. For a sequence of length n, it generates an n x n attention matrix.
- Core Operation: Each token attends to every other token.
- Cost: The number of computations scales as O(n²).
- Reranking Impact: In a cross-encoder, the query and document are concatenated into a single sequence. A long document (e.g., 1000 tokens) with a short query creates a sequence where
nis large, making the attention calculation prohibitively expensive for real-time applications.
Sequence Length Sensitivity
Processing time doesn't just double when sequence length doubles; it quadruples. This makes cross-encoders acutely sensitive to document and chunk sizes.
- Example: If processing a 500-token sequence takes 100ms, a 1000-token sequence will take approximately 400ms (4x longer), not 200ms.
- Practical Constraint: This forces strict limits on the reranking depth (k) and the maximum document chunk size that can be feasibly processed in a latency-sensitive pipeline like RAG.
Contrast with Linear & Sub-Quadratic Models
Quadratic complexity is the key differentiator between cross-encoders and more scalable architectures.
- Bi-Encoders (O(n)): Encode queries and documents independently with linear complexity relative to total text length, enabling pre-computation of document embeddings.
- Late-Interaction Models (e.g., ColBERT): Use sub-quadratic token-level late interaction, providing deeper matching than bi-encoders without the full O(n²) cost.
- Sparse-Attention Models: Architectures like Longformer or BigBird use engineered attention patterns to reduce complexity to O(n) or O(n log n), enabling longer contexts.
Direct Impact on RAG Latency & Cost
The O(n²) cost translates directly to operational metrics that concern CTOs and engineers.
- Latency: The dominant factor in reranking latency, often making it the slowest stage in a multi-stage retrieval pipeline.
- Compute Cost: Requires more GPU memory (to hold the large attention matrix) and higher FLOPs, increasing cloud inference costs.
- Throughput Limitation: Limits the number of query-document pairs that can be processed per second, constraining system scalability.
Mitigation Strategies in Production
Engineering teams employ specific techniques to manage quadratic complexity.
- Input Truncation: Aggressively truncating documents to a fixed token limit (e.g., 512) before feeding to the cross-encoder.
- Cascading Architectures: Using a fast bi-encoder first-stage to narrow candidates to a small
k(e.g., 100) before applying the costly cross-encoder on the topk. - Model Distillation: Training a smaller, more efficient student model (like a bi-encoder) to mimic the ranking behavior of the large cross-encoder teacher.
- Hardware Optimization: Using inference-optimized runtimes (e.g., ONNX, TensorRT) and techniques like quantization to speed up the core matrix operations.
The Accuracy vs. Efficiency Trade-off
Quadratic complexity is the price paid for the highest accuracy. The full cross-attention in a cross-encoder allows for deep, nuanced understanding of query-document relevance that linear models often cannot match.
- Benchmark Result: On tasks like MS MARCO passage ranking, cross-encoders consistently outperform bi-encoders in terms of NDCG and MRR.
- Design Decision: Choosing a cross-encoder reranker is an explicit decision to prioritize precision and ranking quality over throughput and low latency. This trade-off must be evaluated based on application-specific SLAs.
Quadratic vs. Other Complexity Classes
A comparison of the computational complexity, latency characteristics, and scalability trade-offs between the quadratic self-attention mechanism in standard cross-encoders and other common complexity classes in retrieval and reranking architectures.
| Complexity Metric | Quadratic O(n²) (Standard Cross-Encoder) | Linear O(n) (Bi-Encoder / BM25) | Log-Linear O(n log n) (Late Interaction / ColBERT) | Constant O(1) (Cached Retrieval) |
|---|---|---|---|---|
Asymptotic Scaling | n² | n | n log n | 1 |
Primary Use Case | Precise reranking of short candidate lists | Initial high-recall retrieval from large corpora | Balanced retrieval & reranking with token-level interaction | Serving pre-computed results for frequent queries |
Typical Sequence Length (n) Limit | 512 tokens |
| ~ 512-4096 tokens per doc | N/A (pre-computed) |
Latency for n=512 | ~100-500 ms | ~5-50 ms | ~20-100 ms | < 1 ms |
Memory Complexity | O(n²) for attention matrix | O(d) for embeddings (d=dimension) | O(n * d) for token embeddings | O(1) for lookup |
Parallelizability | Limited (attention is sequential) | High (embeddings computed independently) | Moderate (token similarities computed in parallel) | Perfect (direct key-value access) |
Interaction Between Query & Document | Full, deep cross-attention | None (independent encoding) | Token-level, late interaction (MaxSim) | None (static scoring) |
Accuracy / Precision Trade-off | ✅ Highest precision for reranking | ❌ Lower precision, higher recall | ✅ Good balance of precision & recall | ❌ Static, cannot adapt to novel queries |
Suitable for First-Stage Retrieval? | ❌ No (prohibitively slow) | ✅ Yes (core function) | ⚠️ Possible but often used as second stage | ✅ Yes, for known-query caching |
Handles Long Documents (n > 2048)? | ❌ No (memory & compute explode) | ✅ Yes (embedding fixed cost) | ⚠️ Yes, with chunking or efficient attention | ✅ Yes (if pre-computed) |
Training Cost | ✅ High (requires full fine-tuning) | ✅ Moderate (contrastive learning) | ✅ High (contrastive + fine-tuning) | N/A |
Inference Cost (FLOPs) | Very High | Low | Moderate to High | Negligible |
AI Systems Impacted by Quadratic Complexity
Quadratic complexity (O(n²)) is a fundamental scaling constraint in transformer-based models, where computational cost grows with the square of the input sequence length. This creates severe bottlenecks in systems that process long sequences or require exhaustive pairwise comparisons.
Cross-Encoder Rerankers
These models, which jointly encode a query and a candidate document into a single sequence, are acutely affected. The quadratic cost scales with the combined length of the query + document sequence. In a multi-stage retrieval pipeline, reranking just 100 candidates, each 512 tokens long, requires the model to process over 50,000 tokens with quadratic interactions, creating a major latency bottleneck. This cost forces pragmatic limits on reranking depth and document chunk size.
Dense Retrieval with Full Interaction
Early neural ranking models that performed full cross-attention between queries and all documents in a corpus were rendered impractical by quadratic complexity. Comparing a query to M documents of length n would incur O(M * n²) cost, making real-time search over large corpora impossible. This limitation drove the adoption of more efficient two-tower bi-encoder architectures for first-stage retrieval.
Multiple Sequence Alignment in Bioinformatics
In computational biology, aligning N biological sequences (like DNA or protein strings) of length L using dynamic programming often involves O(N² * L²) operations. While not a transformer, this is a classic example of quadratic (and quartic) scaling that limits the analysis of large datasets. AI models applied to this domain must contend with similar pairwise comparison challenges.
Graph Neural Networks on Dense Graphs
Message-passing in Graph Neural Networks (GNNs) can exhibit quadratic complexity in the number of nodes when applied to densely connected graphs, as each node may aggregate information from all others. Processing large, dense graphs (e.g., representing social networks or interaction matrices) becomes computationally prohibitive, requiring sampling techniques or simplified aggregation functions.
Frequently Asked Questions
Quadratic complexity, denoted as O(n²), is a critical computational bottleneck in transformer-based cross-encoder reranking models. This section addresses common technical questions about its origins, impact, and mitigation strategies for enterprise RAG systems.
Quadratic complexity is a computational scaling property where the time or memory required by an algorithm grows proportionally to the square of its input size, formally denoted as O(n²). In the context of cross-encoder reranking, this arises from the self-attention mechanism in standard transformer architectures. When a model jointly encodes a query and a candidate document into a single sequence of length n, the attention mechanism computes pairwise interactions between all n tokens, resulting in n² operations. This becomes a severe performance bottleneck when processing long sequences or large candidate sets, as doubling the input length quadruples the computational cost.
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
Quadratic complexity is a defining constraint in transformer-based cross-encoder reranking. These related concepts detail the architectural trade-offs, optimization techniques, and evaluation frameworks that engineers use to manage this computational cost in production systems.
Cross-Encoder Reranker
A reranking model that jointly encodes a query and a candidate document into a single sequence using a transformer encoder. This architecture enables full cross-attention between every token in the query and every token in the document, which is the source of its high accuracy and its O(n²) quadratic complexity. It is the most computationally intensive component in a multi-stage retrieval pipeline.
Bi-Encoder vs. Cross-Encoder
A fundamental architectural comparison in neural retrieval.
- Bi-Encoder: Encodes the query and document independently into dense vector embeddings. Relevance is computed via a simple, fast similarity function (e.g., cosine). Complexity is O(n), enabling large-scale search.
- Cross-Encoder: Performs joint encoding, allowing deep token-level interaction. This yields superior accuracy for reranking but at quadratic cost O(n²), limiting its use to reordering a small candidate set (e.g., top 100 documents).
Multi-Stage Retrieval
The standard pipeline architecture designed to mitigate the cost of quadratic models. It employs a cascade of models with increasing accuracy and computational cost:
- First Stage (Recall): A fast, high-recall retriever (e.g., BM25, bi-encoder) fetches a large candidate set (e.g., 1000 documents).
- Second Stage (Reranking): A precise, computationally expensive cross-encoder reranks a much smaller subset (e.g., top 100). This confines the quadratic complexity operation to a manageable scale, optimizing the trade-off between latency and precision.
Late Interaction Model (e.g., ColBERT)
An intermediate architecture that balances the efficiency of bi-encoders with the expressive power of cross-encoders. Models like ColBERT encode queries and documents independently but compute relevance via a sum of maximum similarity (MaxSim) across all token embeddings. This allows for deeper interaction than simple vector similarity without the full O(n²) pairwise attention of a cross-encoder, offering a favorable performance-cost trade-off.
Sparse Attention Reranking
A class of optimization techniques that modify the transformer's self-attention mechanism to reduce quadratic complexity. Models like Longformer or BigBird use pattern-based sparse attention, where each token only attends to a subset of other tokens (e.g., a local window + global tokens). This reduces complexity from O(n²) to O(n) or O(n log n), enabling the reranking of much longer query-document sequences that would be prohibitive for standard cross-encoders.
Reranking Latency
The critical operational metric directly impacted by quadratic complexity. It is the end-to-end time delay introduced by applying a reranking model to a candidate set. For a cross-encoder, latency scales quadratically with total sequence length (query + document). Engineers manage this through:
- Controlling reranking depth (k)
- Implementing inference optimizations (quantization, GPU batching)
- Using model distillation to replace large cross-encoders with faster student models Latency is the primary constraint determining the feasibility of a reranker in a real-time system.

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