Inferensys

Glossary

Quadratic Complexity

Quadratic complexity, denoted as O(n²), is a computational scaling property where the time or resources required by an algorithm grow proportionally to the square of its input size, creating a fundamental performance bottleneck in systems like transformer-based cross-encoders.
Developer building agentic RAG system, retrieval pipeline diagram on laptop, technical workspace with notes.
COMPUTATIONAL 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.

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.

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.

COMPUTATIONAL COMPLEXITY

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.

01

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 n is large, making the attention calculation prohibitively expensive for real-time applications.
02

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.
03

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.
04

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.
05

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 top k.
  • 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.
06

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.
COMPUTATIONAL COST COMPARISON

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 MetricQuadratic 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 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

100k documents

~ 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

COMPUTATIONAL BOTTLENECKS

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.

02

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.

03

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.

05

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.

06

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.

QUADRATIC COMPLEXITY

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 operations. This becomes a severe performance bottleneck when processing long sequences or large candidate sets, as doubling the input length quadruples the computational cost.

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.