Skip to content

← Tokenization & Embeddings step 2 of 15

Medium Primitives

BPE Merge Step

Merge a specified pair of adjacent tokens in one left-to-right pass. This is the basic operation used by the simplified BPE encoder in the next exercise. BPE stands for Byte-Pair Encoding; here, tokens are Python strings.

Your task

Implement bpe_merge_step(tokens, pair).

  • tokens is a list of token strings. A token may contain more than one character.
  • pair is a two-element list of strings to match exactly, in that order.
  • Return a new list of strings. Leave both input lists unchanged.

Read the original sequence from left to right. When two adjacent tokens match pair, append their concatenation and consume both tokens. Otherwise, append the current token and move forward by one. Do not scan the newly created output again during this step.

For tokens ["l", "o", "w", "e", "r"] and pair ["l", "o"], return ["lo", "w", "e", "r"]. A later step could merge ["lo", "w"], treating "lo" as one token.

Matches cannot overlap. For ["a", "a", "a"] and pair ["a", "a"], return ["aa", "a"]: the first two tokens are consumed, leaving the third. Four a tokens produce ["aa", "aa"], not one "aaaa" token.

Matching is case-sensitive and uses whole tokens, not substrings inside them. If the pair is absent, return a new list with the original contents. An empty input returns []; a single token remains unchanged.

This task applies one supplied rule. It does not count pair frequencies, learn merge rules or assign vocabulary IDs. Ordinary Python list and string operations are sufficient in both framework modes.