Harden a Messy Text Ingestor and Triage a Broken ML Training Repo
Machine LearningModel answerLast updated
Design a fault-tolerant parser for noisy text records, hunt down three hidden bugs in a training codebase, and plan how to verify everything within a one-hour budget.
You are given a small machine learning project and a pile of raw text files that feed it. You have 60 minutes. The work has three parts.
Part 1: Ingest messy text
The raw files contain delimited records with inconsistent formatting. Design and implement a parser that turns them into structured examples. It must cope with:
- Delimiters and quoted fields, including delimiters that appear inside quotes.
- Escaping (doubled quotes and backslash escapes) and newlines inside quoted fields.
- Mixed encodings and Unicode quirks (BOMs, invalid byte sequences, combining characters, mixed line endings).
- Missing fields, extra fields, trailing delimiters, blank lines, and repeated header rows.
- Malformed lines, which must not crash the run and must not vanish silently.
Explain the output format, how you distinguish a missing value from an explicitly empty one, and how you would test the parser.
Part 2: Fix three defects
The project has a data loader, a preprocessing/tokenization step, a training loop, and an evaluation script. Three defects are hidden in it. Typical culprits include an off-by-one in tokenization or indexing, train/test leakage, a wrong loss reduction, nondeterministic seeding, and tensor shape mismatches.
Describe how you would find and fix them quickly in code you have never seen: how you would use stack traces, assertions, binary-search logging, and minimal reproductions.
Part 3: Prove it works
Explain how you would validate your fixes within the time limit: unit tests, an end-to-end run, metric sanity checks, and regression guards.
Provide a structured answer with concrete code for the parser and specific checks for the debugging and validation phases.
Hints
Hint 1
Split the parser into three stages (decode bytes, tokenize into fields, validate against a schema) so every failure mode lives in exactly one place and can be tested alone.
Hint 2
Never let a bad line raise. Collect it in an error list with line number, reason, and a truncated snippet, and cap how many lines a quoted field may span so one stray quote cannot swallow the file.
Hint 3
For debugging, shrink first: tiny batch, one step, no worker processes. Then assert invariants at stage boundaries (id range vs vocab size, logits vs label shapes, disjoint train/test ids).
Hint 4
Sanity metrics catch what asserts miss: overfit a handful of examples to near-zero loss, check initial loss is near log(num_classes), and confirm two runs with the same seed match.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
Interviewers care about process as much as the final code. The strategy is to isolate failures, make them observable, and prove fixes with cheap, targeted checks.
Part 1: Robust parser
Design
Use three stages so each failure mode is isolated.
- Decode. Try
utf-8-sig(strips a BOM). Useutf-16only if a UTF-16 BOM is present. Fall back tolatin-1, which cannot fail. Then normalize CRLF/CR to LF, drop NUL bytes, and apply Unicode NFC so equivalent strings compare equal. - Tokenize. A per-record state machine tracks in-quote, out-of-quote, and escape. Delimiters inside quotes are never split points.
""inside quotes yields a literal quote. If a quote is still open at end of line, append the next line (a newline inside a quoted field), but cap continuation at a few lines. On overflow, record an error for the starting line and resume at the next physical line, which guarantees forward progress. - Validate. Map tokens to a schema:
- Short rows are padded with
None. - Trailing empty extras (from a trailing delimiter) are trimmed.
- Genuinely extra fields are an error.
- Missing required fields are an error.
- Unquoted empty means
None(missing); quoted""means an explicit empty string. - A row equal to the header is skipped, which handles repeated headers.
- Short rows are padded with
Bad lines go to an errors list as (line_no, reason, snippet). In production, also emit an error-rate metric and alert above a threshold.
Code
import unicodedata
def decode_bytes(data: bytes) -> str:
if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
text = data.decode("utf-16")
else:
try:
text = data.decode("utf-8-sig")
except UnicodeDecodeError:
text = data.decode("latin-1")
text = text.replace("\r\n", "\n").replace("\r", "\n").replace("\x00", "")
return unicodedata.normalize("NFC", text)
def _finish(buf, quoted):
s = "".join(buf)
if not quoted:
s = s.strip()
return s or None
return s
def split_record(s, delim=",", quote='"', esc="\\"):
fields, buf, in_q, quoted, i = [], [], False, False, 0
while i < len(s):
c = s[i]
if c == esc and i + 1 < len(s):
buf.append(s[i + 1]); i += 2; continue
if in_q:
if c == quote:
if i + 1 < len(s) and s[i + 1] == quote:
buf.append(quote); i += 2; continue
in_q = False
else:
buf.append(c)
elif c == quote and all(ch.isspace() for ch in buf):
buf, in_q, quoted = [], True, True
elif c == delim:
fields.append(_finish(buf, quoted)); buf, quoted = [], False
else:
buf.append(c)
i += 1
if in_q:
return None # quote still open
fields.append(_finish(buf, quoted))
return fields
def parse(data, schema, required, max_cont=5):
lines = decode_bytes(data).split("\n")
records, errors, i = [], [], 0
while i < len(lines):
start, rec = i, lines[i]
if not rec.strip():
i += 1; continue
fields = split_record(rec)
while fields is None and i + 1 < len(lines) and i - start < max_cont:
i += 1
rec += "\n" + lines[i]
fields = split_record(rec)
if fields is None:
errors.append((start + 1, "unterminated quote", lines[start][:200]))
i = start + 1
continue
i += 1
if [f.lower() if f else f for f in fields] == [h.lower() for h in schema]:
continue
while len(fields) > len(schema) and fields[-1] is None:
fields.pop()
if len(fields) > len(schema):
errors.append((start + 1, "too many fields", rec[:200])); continue
fields += [None] * (len(schema) - len(fields))
row = dict(zip(schema, fields))
missing = [k for k in required if row[k] is None]
if missing:
errors.append((start + 1, f"missing {missing}", rec[:200])); continue
records.append(row)
return records, errors
Complexity: time is O(N·K) for input size N and continuation cap K (effectively linear); space is O(N) for output.
Testing the parser
- Table-driven unit tests, one per edge case, asserting exact records and exact errors.
- Round-trip property test: generate random rows containing delimiters, quotes, newlines, and emoji; write with
csv.writer; parse; compare. - Fuzz test with random bytes: must never raise, and
len(records) + len(errors)must not exceed the non-blank line count. - A golden file of real messy data with checked-in expected output.
Part 2: Finding three defects fast
Workflow
- Reproduce small. One batch of about 32 examples, one step,
num_workers=0. Fast runs and clean stack traces. - Read the trace bottom-up, then print
.shapeand.dtypeof every tensor at the failing line. - Assert invariants at stage boundaries:
ids.max() < vocab_sizelogits.shape[:-1] == labels.shapenot set(train_ids) & set(test_ids)
- Binary-search the pipeline. Log shape, mean, NaN count, and a few decoded tokens at the midpoint of load, preprocess, train, eval; then narrow to the first stage where the data looks wrong.
- Minimal repro per bug, which later becomes its regression test.
Typical defects and tells
| Defect | Symptom | Fix |
|---|---|---|
| Off-by-one in tokenization or label shift | Last token dropped, labels misaligned, id equal to vocab size | Correct slice or shift; assert id range |
| Train/test leakage (fit scaler/vocab on all data, overlapping ids, split after augmentation) | Suspiciously high eval metric | Split first, fit on train only, assert disjointness |
Wrong loss reduction (sum vs mean, averaging over padding) | Loss scale changes with batch size, unstable training | Use mean, mask padding via ignore_index |
| Nondeterministic seeding | Two runs differ | Seed Python, NumPy, torch, and DataLoader workers; seed the shuffle generator |
| Shape mismatch with silent broadcasting | Loss runs but is wrong | Explicit view/squeeze and shape asserts |
Prioritize bugs that fail loudly first (they unblock the run), then silent ones, which are found by sanity checks rather than errors.
Part 3: Validating within 60 minutes
Suggested budget: 20 min parser, 25 min debugging, 15 min validation.
- Unit tests for each fix, using the minimal repros. They must fail before the fix and pass after.
- Metric sanity checks:
- Initial loss is near
log(num_classes). - The model can overfit 10 to 20 examples to near-zero loss. If not, something is broken in the data or loss.
- Eval metric is plausible. A huge jump after the fix is a warning, and a drop after removing leakage is expected.
- Shuffled-label training should stay near chance.
- Initial loss is near
- Determinism check: two runs with the same seed produce identical loss curves.
- End-to-end smoke run on a small subset, covering load through eval.
- Regression guards: keep the asserts in the code, add tests to CI, and add a leakage check plus a parser error-rate threshold.
Common mistakes
- Guessing at fixes instead of reproducing first.
- Fixing the symptom (clipping an index) rather than the cause.
- Letting the parser silently drop bad rows.
- Treating a higher metric after a fix as success without considering leakage.
- Spending the entire hour on parser polish and leaving no time for validation.
Trade-offs to mention
Strict parsing preserves correctness but loses rows. Lenient parsing keeps rows but risks bad data. The compromise is lenient parsing with a quarantined error list and an alert threshold. In debugging, asserts add small runtime cost, but they are cheap insurance and can be gated behind a debug flag if needed.