Bird
Raised Fist0
NLPml~10 mins

Beam search decoding in NLP - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the beam width for beam search decoding.

NLP
beam_width = [1]
Drag options to blanks, or click blank then click option'
A5
B1
C0
D10
Attempts:
3 left
💡 Hint
Common Mistakes
Setting beam width to 0 disables beam search.
Using 1 makes beam search behave like greedy search.
2fill in blank
medium

Complete the code to select the top scoring sequences at each decoding step.

NLP
top_sequences = sorted(all_candidates, key=lambda x: x.score, reverse=[1])[:beam_width]
Drag options to blanks, or click blank then click option'
ANone
B0
CTrue
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using reverse=False sorts ascending, which keeps worst sequences.
Using None or 0 causes errors or unexpected sorting.
3fill in blank
hard

Fix the error in the code that updates the beam with new candidates.

NLP
beam = [1]
Drag options to blanks, or click blank then click option'
Atop_sequences
Ball_candidates
Cbeam + all_candidates
D[]
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning beam to all_candidates keeps too many sequences.
Using beam + all_candidates duplicates sequences.
Assigning beam to [] empties the beam.
4fill in blank
hard

Fill both blanks to complete the loop that expands sequences and applies beam search.

NLP
for step in range(max_length):
    all_candidates = []
    for seq in beam:
        next_tokens = model.predict(seq.sequence)
        for token, score in next_tokens.items():
            candidate = seq.sequence + [token]
            candidate_score = seq.score [1] score
            all_candidates.append(Candidate(candidate, candidate_score))
    beam = sorted(all_candidates, key=lambda x: x.score, reverse=[2])[:beam_width]
Drag options to blanks, or click blank then click option'
A+
B-
CTrue
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Subtracting scores instead of adding.
Sorting ascending (reverse=False) loses best sequences.
5fill in blank
hard

Fill all three blanks to complete the beam search decoding function.

NLP
def beam_search_decode(model, start_token, beam_width, max_length):
    beam = [Candidate([start_token], 0.0)]
    for _ in range(max_length):
        all_candidates = []
        for seq in beam:
            next_tokens = model.predict(seq.sequence)
            for token, score in next_tokens.items():
                candidate = seq.sequence + [[1]]
                candidate_score = seq.score [2] score
                all_candidates.append(Candidate(candidate, candidate_score))
        beam = sorted(all_candidates, key=lambda x: x.score, reverse=[3])[:beam_width]
    return beam
Drag options to blanks, or click blank then click option'
Atoken
B+
CTrue
Dseq
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names for token or sequence.
Subtracting scores instead of adding.
Sorting ascending loses best sequences.

Practice

(1/5)
1. What is the main purpose of beam search decoding in natural language processing?
easy
A. To keep track of multiple best candidate sequences during prediction
B. To randomly select words for output generation
C. To generate only one possible output sequence
D. To speed up training by skipping steps

Solution

  1. Step 1: Understand beam search goal

    Beam search keeps multiple candidate sequences to explore more options than greedy search.
  2. Step 2: Compare options

    Only To keep track of multiple best candidate sequences during prediction describes keeping multiple best guesses; others describe random choice, single output, or unrelated speed-up.
  3. Final Answer:

    To keep track of multiple best candidate sequences during prediction -> Option A
  4. Quick Check:

    Beam search = multiple best sequences [OK]
Hint: Beam search tracks several top guesses, not just one [OK]
Common Mistakes:
  • Confusing beam search with random sampling
  • Thinking beam search outputs only one sequence
  • Assuming beam search speeds up training
2. Which of the following is the correct way to describe the beam width in beam search decoding?
easy
A. The size of the vocabulary used for prediction
B. The number of candidate sequences kept at each decoding step
C. The length of the output sequence generated
D. The number of layers in the neural network

Solution

  1. Step 1: Define beam width

    Beam width is how many top sequences the algorithm keeps at each step to explore.
  2. Step 2: Eliminate incorrect options

    Output length, vocabulary size, and network layers are unrelated to beam width.
  3. Final Answer:

    The number of candidate sequences kept at each decoding step -> Option B
  4. Quick Check:

    Beam width = candidate count per step [OK]
Hint: Beam width = how many sequences you keep each step [OK]
Common Mistakes:
  • Mixing beam width with output length
  • Confusing beam width with vocabulary size
  • Thinking beam width relates to model architecture
3. Consider a beam search with beam width 2 decoding a sequence. At step 1, the top 2 tokens have scores [0.6, 0.4]. At step 2, each token expands to two tokens with scores: from first token [0.5, 0.3], from second token [0.7, 0.2]. Which two sequences will beam search keep after step 2?
medium
A. [First token + second expansion (0.6*0.3), Second token + second expansion (0.4*0.2)]
B. [First token + first expansion (0.6*0.5), First token + second expansion (0.6*0.3)]
C. [Second token + first expansion (0.4*0.7), Second token + second expansion (0.4*0.2)]
D. [First token + first expansion (0.6*0.5), Second token + first expansion (0.4*0.7)]

Solution

  1. Step 1: Calculate scores for all expansions

    Calculate combined scores: 0.6*0.5=0.3, 0.6*0.3=0.18, 0.4*0.7=0.28, 0.4*0.2=0.08.
  2. Step 2: Select top 2 sequences by score

    Top two scores are 0.3 and 0.28, corresponding to first token + first expansion and second token + first expansion.
  3. Final Answer:

    [First token + first expansion (0.6*0.5), Second token + first expansion (0.4*0.7)] -> Option D
  4. Quick Check:

    Top scores = 0.3 and 0.28 [OK]
Hint: Multiply scores, pick top beam width sequences [OK]
Common Mistakes:
  • Choosing expansions only from one token
  • Not multiplying scores correctly
  • Picking lower scoring sequences
4. You implemented beam search decoding but notice it always returns the same output sequence regardless of input. What is the most likely bug?
medium
A. The vocabulary size is too large
B. The model is not trained
C. Beam width is set to 1, making it greedy search
D. The beam search is not normalizing scores

Solution

  1. Step 1: Analyze symptom of identical outputs

    Always same output suggests no exploration of multiple sequences.
  2. Step 2: Identify beam width effect

    If beam width = 1, beam search reduces to greedy search, always picking highest scoring token only.
  3. Final Answer:

    Beam width is set to 1, making it greedy search -> Option C
  4. Quick Check:

    Beam width 1 = greedy search [OK]
Hint: Check beam width; 1 means no beam search [OK]
Common Mistakes:
  • Blaming vocabulary size for output sameness
  • Ignoring beam width setting
  • Assuming model training causes identical outputs
5. In a machine translation task, you want to balance output quality and decoding speed. You have a beam search decoder with beam width 5. What happens if you increase the beam width to 20?
hard
A. Output quality may improve but decoding will be slower
B. Output quality will decrease and decoding will be faster
C. Output quality and decoding speed remain the same
D. Decoding speed improves but output quality is unpredictable

Solution

  1. Step 1: Understand beam width effect on quality

    Larger beam width explores more sequences, often improving output quality.
  2. Step 2: Understand beam width effect on speed

    More sequences to track means more computation, slowing decoding speed.
  3. Final Answer:

    Output quality may improve but decoding will be slower -> Option A
  4. Quick Check:

    Higher beam width = better quality, slower speed [OK]
Hint: Bigger beam = better results but slower decoding [OK]
Common Mistakes:
  • Assuming bigger beam always speeds decoding
  • Thinking quality decreases with bigger beam
  • Believing beam width doesn't affect speed