Encode Tokens to IDs & Decode Back to Text

Basics
BasicsTokenizationLLMOpenAIAnthropicGoogle

Problem

Implement two functions: encode_tokens(tokens, vocab) mapping each token to its integer ID (falling back to vocab['<UNK>'] for unseen words), and decode_ids(ids, vocab) converting integer IDs back into a space-joined string (falling back to '<UNK>' for unknown IDs).

Why It Matters: Every LLM inference pipeline encodes user prompts into integer IDs before the embedding lookup and decodes generated token IDs back into human-readable text.

Function Signature

def encode_tokens(tokens: list[str], vocab: dict[str, int]) -> list[int]:
    """Convert tokens to integer IDs using vocab['<UNK>'] for unknown words."""

def decode_ids(ids: list[int], vocab: dict[str, int]) -> str:
    """Convert integer IDs back to a space-joined string."""

Sample Input & Output

Example 1: Known & Unknown Words

Input:

vocab = {"<PAD>": 0, "<UNK>": 1, "cat": 2, "sat": 3}
encode_tokens(["cat", "flew", "sat"], vocab)

Expected Output:

[2, 1, 3]

Explanation: 'cat' -> 2, unseen 'flew' -> 1 (<UNK>), and 'sat' -> 3.

Example 2: Decoding Back to Text

Input:

vocab = {"<PAD>": 0, "<UNK>": 1, "cat": 2, "sat": 3}
decode_ids([2, 1, 3], vocab)

Expected Output:

"cat <UNK> sat"

Explanation: IDs map through the inverted dictionary and join with a single space.

Constraints & Edge Cases

  • Unknown tokens map to vocab['<UNK>'].
  • decode_ids joins decoded tokens with a single space.
  • Empty tokens returns []; empty ids returns ''.
  • Invert vocab once (id_to_tok = {v: k for k, v in vocab.items()}) for O(N)O(N) decoding.

Constraints & Evaluation Criteria

  • Unknown tokens map to `vocab['<UNK>']`.
  • `decode_ids` joins decoded tokens with a single space.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
['hi', 'mars'] -> [2, 1]
Expected Output / Criteria
decode([2, 3]) == 'hi ai'