Inferensys

Glossary

Beam Search

Beam search is a heuristic search algorithm that explores a graph by maintaining a fixed-size priority queue (the beam) of the most promising candidate nodes to visit next.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
GRAPH-BASED ANN ALGORITHM

What is Beam Search?

Beam search is a heuristic graph traversal algorithm used in approximate nearest neighbor (ANN) search to efficiently explore a vector graph index.

Beam search is a best-first search algorithm that maintains a fixed-size priority queue, called the beam, containing the most promising candidate nodes to visit next during graph traversal. Instead of exploring all possible paths, it prunes less promising candidates at each step, balancing exploration depth with computational efficiency. This makes it a core component for querying graph-based indexes like HNSW and Navigable Small World (NSW) graphs in vector databases.

The algorithm begins at one or more entry points and iteratively expands the beam by evaluating the neighbors of the current best candidates, using a distance metric like Euclidean distance or cosine similarity. It is defined by its beam width (k), which controls the trade-off between search latency and recall@K. A wider beam explores more paths for higher accuracy but increases computation, directly illustrating the recall-precision trade-off fundamental to ANN systems.

GRAPH-BASED ANN ALGORITHM

Key Characteristics of Beam Search

Beam search is a heuristic search algorithm used in graph-based Approximate Nearest Neighbor (ANN) search. It balances exploration and computational efficiency by maintaining a fixed-size priority queue of the most promising candidate nodes to visit next.

01

The Beam Width Parameter

The beam width (B) is the algorithm's core hyperparameter, defining the size of the priority queue (the "beam"). It controls the fundamental trade-off between search quality and speed.

  • A larger beam width explores more candidate nodes per step, increasing the probability of finding the true nearest neighbors (higher recall) but at a higher computational cost.
  • A smaller beam width is more aggressive in pruning the search space, leading to faster queries but a higher risk of getting trapped in a local minimum of the graph, potentially missing better neighbors. In practice, beam width is tuned based on latency requirements and desired recall levels for the application.
02

Priority Queue Dynamics

At each step of the traversal, beam search maintains a min-heap or max-heap priority queue (depending on the distance metric) containing the B most promising nodes discovered so far.

  • The queue is initialized with one or more entry points into the graph.
  • For each node in the current beam, its neighbors are examined, and their distances to the query vector are computed.
  • All candidate neighbors are pooled, and only the top-B closest nodes are retained to form the beam for the next iteration. This iterative refinement ensures the search progressively focuses on the region of the graph most likely to contain the nearest neighbors.
03

Termination Condition

The search terminates when no new, closer nodes are found, indicating convergence. Common stopping criteria include:

  • No improvement: The set of nodes in the beam remains unchanged between iterations.
  • Maximum iterations: A predefined limit on the number of search steps to prevent excessive traversal, especially in large or dense graphs.
  • Distance threshold: Stopping when the distance of the farthest node in the beam is below a certain threshold, indicating high confidence in the results. Upon termination, the nodes in the final beam are returned as the approximate nearest neighbors.
04

Contrast with Greedy Search

Beam search generalizes two simpler graph traversal strategies:

  • Greedy Search (Beam Width = 1): At each step, only the single closest neighbor to the query is selected for expansion. This is highly efficient but highly prone to following a suboptimal path and missing the global nearest neighbors.
  • Exhaustive Search (Beam Width = N): The beam encompasses the entire dataset, guaranteeing an exact result but requiring linear time complexity, defeating the purpose of ANN. Beam search operates in the middle ground, using a beam width 1 < B << N to mitigate the myopia of greedy search while maintaining sub-linear time complexity.
05

Role in HNSW Search

Beam search is the core traversal algorithm used in the Hierarchical Navigable Small World (HNSW) index, one of the most popular graph-based ANN methods.

  • In HNSW, search begins at a high layer of the graph with long-range connections, using a small beam width for fast, coarse navigation.
  • As the search descends to lower, denser layers, the beam width is often increased to refine the search in the localized neighborhood.
  • This layered application of beam search is key to HNSW achieving its logarithmic time complexity for high-recall queries.
06

Trade-offs and Tuning

Implementing beam search involves balancing several performance dimensions:

  • Recall vs. Latency: The primary trade-off governed by beam width. Higher recall requires a wider beam and more distance computations.
  • Graph Quality Dependency: The effectiveness of beam search is heavily dependent on the underlying graph's construction. A well-built graph (e.g., with good small-world properties) allows a narrower beam to achieve high recall.
  • Memory Overhead: Maintaining the beam and candidate lists requires O(B) memory per query, which is negligible compared to index size but must be considered for highly concurrent systems. Tuning involves benchmarking recall@K and query latency across a range of beam widths for a representative query set.
GRAPH-BASED ANN ALGORITHMS

Beam Search vs. Other Search Strategies

A comparison of heuristic search strategies used in graph-based Approximate Nearest Neighbor (ANN) indexes, focusing on their trade-offs between exploration, efficiency, and result quality.

Search CharacteristicBeam SearchGreedy SearchExhaustive Search (Brute-Force)

Algorithm Type

Heuristic, best-first

Heuristic, local optimum

Exact, global optimum

Core Mechanism

Maintains a fixed-size priority queue (beam) of candidate nodes

Always moves to the single nearest neighbor of the current node

Computes distance to every vector in the dataset

Time Complexity

Sub-linear, O(b * log N) typical

Sub-linear, O(log N) typical

Linear, O(N)

Guarantees Optimal Result?

Primary Risk

Pruning error: promising paths can be prematurely discarded

Local minima: can get stuck far from the global optimum

None (perfect accuracy)

Memory Overhead (During Search)

Moderate (stores 'b' candidates)

Minimal (stores path)

High (must access full dataset)

Typical Use Case in ANN

Balanced quality/speed in HNSW graph traversal

Fast, low-overhead traversal in simple graphs

Ground truth calculation for evaluating ANN recall

Query Latency (Scale: 1M vectors)

< 1 ms

< 0.5 ms

100 ms

BEAM SEARCH

Applications of Beam Search

Beam search is a heuristic graph traversal algorithm that maintains a fixed-size priority queue (the beam) of the most promising nodes to explore next. Its primary applications balance exploration efficiency with result quality in sequential decision and search problems.

01

Graph-Based ANN Search

In Hierarchical Navigable Small World (HNSW) and other graph-based ANN indices, beam search is the core traversal algorithm. It explores the graph from entry points by:

  • Maintaining a dynamic candidate list (the beam) of the most promising nodes to visit next, ranked by distance to the query.
  • Iteratively expanding the beam's neighbors, pruning the list to a fixed width B (beam width).
  • This balances exploration (visiting new regions) with efficiency, preventing the exponential growth of a naive breadth-first search while achieving high recall with sub-linear time complexity.
02

Sequence Generation in Language Models

Beam search is a standard decoding algorithm for autoregressive models like Large Language Models (LLMs) when generating text, code, or other sequences.

  • Instead of greedily choosing the single next most likely token, it keeps the top-B most probable partial sequences (hypotheses) at each step.
  • It scores sequences using the log probability of the sequence given the model.
  • This allows the model to recover from potential early errors made by a greedy approach, producing more fluent and higher-quality outputs, especially for tasks like machine translation, summarization, and code completion.
03

Speech Recognition

In Automatic Speech Recognition (ASR) systems, beam search decodes acoustic feature sequences into text.

  • The search space is a weighted finite-state transducer (WFST) that combines an acoustic model, a pronunciation lexicon, and a language model.
  • The beam prunes unlikely partial word hypotheses at each time step, managing the massive combinatorial space.
  • This application is critical for real-time systems, where search latency and accuracy are paramount. Modern end-to-end models like RNN-T also rely on beam search for efficient decoding.
04

Machine Translation Decoding

Historically foundational, beam search was the dominant decoding algorithm for statistical machine translation (SMT) and remains crucial for neural machine translation (NMT).

  • It searches through possible translations by sequentially adding target language words.
  • The beam maintains several partial translation hypotheses, scoring them with a combination of model probabilities (the translation model) and a language model for fluency.
  • The algorithm must handle reordering between languages (a major search challenge) and often incorporates length normalization to avoid bias towards shorter outputs.
05

Planning and Pathfinding

In robotics and game AI, beam search is applied to action planning and pathfinding in large state spaces.

  • Each node represents a state (e.g., a robot's configuration, a game board), and edges represent possible actions.
  • The beam width controls computational cost, allowing for real-time planning.
  • It is particularly useful when a cost function or heuristic can guide the search, but the state space is too large for exhaustive methods like A*. This makes it applicable for non-player character (NPC) behavior and logistics optimization.
06

Constraint Optimization Problems

Beam search can solve combinatorial optimization problems like scheduling, routing, and certain types of protein folding.

  • Solutions are constructed incrementally (e.g., assigning a time slot to a task, placing the next amino acid).
  • A heuristic function evaluates partial solutions, and the beam retains the most promising ones.
  • While not guaranteed to find the global optimum, it provides a high-quality approximate solution with predictable, controllable runtime, which is often necessary for NP-hard problems. It trades off against more exhaustive methods like branch and bound.
BEAM SEARCH

Frequently Asked Questions

Beam search is a heuristic search algorithm used in graph-based Approximate Nearest Neighbor (ANN) search to efficiently traverse a graph index by maintaining a fixed-size set of the most promising candidate nodes.

Beam search is a heuristic graph traversal algorithm that maintains a fixed-size priority queue, called the beam, of the most promising nodes to explore next. In the context of graph-based Approximate Nearest Neighbor (ANN) search, such as within HNSW or NSW indexes, it works by starting from one or more entry points. For each visited node, the algorithm computes the distance to its neighbors, adding them to a candidate list. This list is then sorted, and only the top B candidates (the beam width) are kept for the next iteration. This process repeats, greedily moving toward the query's neighborhood while pruning less promising paths, which balances exploration efficiency with search accuracy.

Key Mechanism:

  • Initialization: Start with entry point(s) in the beam.
  • Expansion: For each node in the current beam, explore its connected neighbors in the graph.
  • Selection: Pool all candidates, sort by distance (e.g., L2, cosine), and retain only the B best.
  • Termination: Stop when no better candidates are found or a maximum depth is reached.
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.