Implement Beam Search


Beam Search is a heuristic search algorithm widely used in sequence generation tasks such as machine translation, text generation, and speech recognition. Unlike greedy search, which selects the highest probability token at each step, Beam Search keeps track of multiple candidate sequences to improve accuracy. Your task is to implement the Beam Search algorithm for sequence prediction. Given a starting token and a function that predicts the probability of the next token, your algorithm should return the most probable sequence.

Inputs :
  • A function model(sequence) which returns a list of possible next tokens along with their probabilities.
  • beam_width : k which determines how many candidate sequences to maintain at each step.
  • max_length : n which defines the maximum length of the generated sequence
  • start_token : START that marks the beginning of the sequence
  • end_token : END if encountered, should terminate the sequence early.
Output :
  • The most probable sequence generated using beam search.

Code Output