CD0019 AI-Assisted Tokenizer Fix

Mode D · AI-Assisted 60 Min Python 3.10+ 1 Warm-Up Bug + 3 AI Flaws

Inside Meta’s text-preprocessing layer in front of a byte-level text classifier sits a small multi-file repository with a red test suite and an AI assistant in the editor sidebar; the exercise is how you split the work between yourself and the model. tokenizer.py defines ByteTokenizer, whose vocab maps 96 byte values (printable ASCII plus newline) to ids 4 to 99, with PAD = 0, BOS = 1, EOS = 2, UNK = 3. batching.py defines encode_batch, a legacy chunked encoder that was written for a cross-chunk merge pass, and that merge pass has since been removed.

CI reports one failing test, test_encode_batch_lengths, run with chunk size 4. It prints len 4: expected 5 ids, got 4 and len 8: expected 9 ids, got 8, while lengths 0, 1, 2, 3, 5, 6, and 7 pass. Phase 1 (unaided, with the assistant switched off): make that test green. Phase 2: steer the assistant to add a streaming API. Phase 3: the assistant’s first draft contains 3 subtle flaws. Audit it, repair it, and write a verification suite that covers batch/streaming equivalence and vocab integrity.

Phase 2 Target Contract: encode_iter(text, *, add_bos=False, add_eos=True, special_map=None) is a generator method on ByteTokenizer. It walks text.encode("utf-8") in self.chunk-byte slices and yields one id at a time.
(1) Stream Equals Batch: With default flags, list(tok.encode_iter(t)) == encode_batch(tok, [t])[0] must hold for every text and every chunk size n \geq 1.
(2) Framing Flags: add_bos=True prepends BOS, and add_eos=False drops the trailing EOS.
(3) Per-Call Specials: special_map routes chosen byte values (for example newline) to special ids for that call only, and tok.vocab stays unchanged.
(4) Unknown Bytes: A byte outside the vocab keeps its position in the stream and becomes unk_id.

Starter Code (tokenizer.py + batching.py):

01  # ---- tokenizer.py ----
02  class ByteTokenizer:
03      def __init__(self, vocab, pad_id, bos_id, eos_id, unk_id, chunk=4):
04          self.vocab = vocab  # byte value -> token id
05          self.pad_id, self.bos_id = pad_id, bos_id
06          self.eos_id, self.unk_id = eos_id, unk_id
07          self.chunk = chunk
08
09      def encode_chunk(self, chunk: bytes) -> list:
10          return [self.vocab.get(b, self.unk_id) for b in chunk]
11
12
13  # ---- batching.py ----
14  def encode_batch(tok, texts, add_eos=True):
15      n, out = tok.chunk, []
16      for text in texts:
17          data = text.encode("utf-8")
18          ids, pending = [], None
19          for i in range(0, len(data), n):
20              row = tok.encode_chunk(data[i:i + n])
21              if pending is not None:
22                  ids.append(pending)
23              if len(row) < n:  # tail chunk
24                  ids.extend(row)
25                  pending = None
26              else:
27                  ids.extend(row[:-1])
28                  pending = row[-1]
29          if add_eos:
30              ids.append(tok.eos_id)
31          out.append(ids)
32      return out
Three-phase flow of the round: Phase 1 is an unaided fix of encode_batch where some input lengths fail, marked with a question mark; Phase 2 is choosing one of three prompts for encode_iter; Phase 3 is auditing the AI draft for three subtle flaws, marked with question marks. Below are three contract boxes: the stream must equal the batch output, tok.vocab must never change, and unknown bytes become unk_id in place while ids are yielded one at a time

Figure 1: The round has three graded phases. Every phase is checked against the same Phase 2 Target Contract, and the question marks show what you have to find.

Interactive Python Workspace: Switch to the split-screen workspace to run all three phases. First fix encode_batch unaided, then pick a steering prompt, then audit the assistant’s draft against the hidden checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Tail-Chunk Contract: For every byte length L, including 0, n, and 2n, the output holds exactly L byte ids followed by EOS.
(2) Deferred-Id Ownership: Any id held back at a chunk boundary must be written exactly once, and by exactly one code path.
(3) Shared-State Contract: A per-call option may change what one call yields. It must never change the tokenizer object that other callers share.
(4) Unknown-Byte Contract: An OOV byte keeps its position in the stream and carries the id the tokenizer designates for unknowns.

2Visual Review Map (Figure 2)
Review map of the two files with identical question-mark markers. In batching.py, the marker sits next to the tail-chunk test with its deferred boundary id. In the AI draft of encode_iter in tokenizer.py, markers sit next to the lookup table setup, the per-byte id lookup, and the chunk loop with its tail flush

Figure 2: Each question mark labels a stage worth a hand trace. Working out what is wrong there is the exercise.

3Interviewer Nudge & Line Focus

Work the three phases in order using the stage checks below:

Phase 1 (Tail-Chunk Predicate): Trace L = 4 and L = 5 with n = 4 by hand. On each iteration, where does the deferred id end up? For which length is there no later iteration left to write it?
Phase 2 (Spotting Flawed Prompts): Do not judge prompts by keyword coverage. Check whether the spec pins every contract clause: a per-call vocab copy, the unk policy, stream-equals-batch at every length, and the batch oracle’s own tail flush. A clause left unpinned comes back broken in the regenerated draft.
Phase 3 (Auditing the Stream Loop): Dry-run the stream twice — once with special_map={10: 100}, then again on plain text: which table did the update mutate? Feed a byte outside the vocab: which id does the stream emit versus encode_chunk? And at a byte length of exactly 2n, how many times does the final id come out?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *