Category: Bug Hunt

  • CD0026 Debug Scheduler FSM

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0021 Debug GPT Train Step

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0016 Debug Classifier Tests

    Mode A · Bug Hunt 30 Min PyTorch 2.x 4 Silent Bugs

    An OpenAI intent-classification service runs on a teammate’s 40-line PyTorch wrapper, TextClassifier: a Transformer encoder layer over token ids, hidden states pooled two ways, and a linear head over K intent classes. The CI fixtures pad every row to T = 32 with pad id 0, and the fixture files store labels as 1, \ldots, K, the same convention as the offline evaluation report. Nothing crashes, and the encoder layer is unchanged from the version that produced the offline report. Yet the wrapper fails its own test suite in three ways.

    (1) test_padded_f1: macro-F1 on the heavy-padding fixture is 0.54, against 0.91 in the offline report.
    (2) test_deterministic_predict: two identical runs over the same weights and the same inputs report different accuracy.
    (3) test_label_fixture: every prediction on labels.jsonl differs from its fixture label by the same constant class index.

    Read the pooling, head, and label-handling code in order. Find the 4 silent bugs (one of them is invisible to all three failing tests), state which assertion each one would trip in an honest test, patch them in place, and write a deterministic verification test that locks the behavior.

    Buggy Code (Find 4 Silent Bugs):

    01  import torch
    02  import torch.nn as nn
    03  import torch.nn.functional as F
    04
    05  LABEL_BASE = 1  # fixture files store classes as 1..K
    06
    07
    08  class TextClassifier(nn.Module):
    09      def __init__(self, vocab: int, d: int, K: int, pad_id: int = 0):
    10          super().__init__()
    11          self.pad_id = pad_id
    12          self.embed = nn.Embedding(vocab, d, padding_idx=pad_id)
    13          self.encoder = nn.TransformerEncoderLayer(
    14              d, nhead=4, dim_feedforward=4 * d, dropout=0.1, batch_first=True)
    15          self.score = nn.Linear(d, 1)  # attention-pooling scorer
    16          self.head = nn.Sequential(nn.Dropout(0.1), nn.Linear(2 * d, K))
    17
    18      def forward(self, ids: torch.Tensor) -> torch.Tensor:
    19          mask = ids.ne(self.pad_id)  # (B, T), True = real token
    20          hidden = self.encoder(self.embed(ids), src_key_padding_mask=~mask)
    21          mean_pool = hidden.mean(dim=1)  # (B, d)
    22          scores = self.score(hidden).squeeze(-1)  # (B, T)
    23          scores = scores.masked_fill(~mask, torch.finfo(scores.dtype).min)
    24          w = F.softmax(scores, dim=0)  # pooling weights
    25          attn_pool = (w.unsqueeze(-1) * hidden).sum(dim=1)  # (B, d)
    26          feats = torch.cat([mean_pool, attn_pool], dim=-1)  # (B, 2d)
    27          return self.head(feats)  # (B, K) logits
    28
    29      def encode_labels(self, raw) -> torch.Tensor:
    30          return torch.as_tensor(raw, dtype=torch.long) - LABEL_BASE
    31
    32      def loss(self, ids: torch.Tensor, raw_labels) -> torch.Tensor:
    33          return F.cross_entropy(self(ids), self.encode_labels(raw_labels))
    34
    35      def predict(self, ids: torch.Tensor) -> list:
    36          pred = self(ids).argmax(dim=-1)  # (B,)
    37          return pred.tolist()
    38
    39  def accuracy(clf: TextClassifier, ids: torch.Tensor, raw_labels) -> float:
    40      return sum(p == y for p, y in zip(clf.predict(ids), raw_labels)) / len(raw_labels)
    Three symptom panels from the failing CI run: macro-F1 of 0.91 in the offline report and 0.88 on a short-text fixture but 0.54 on a heavy-padding fixture; test accuracy varying between 0.69 and 0.74 across six identical runs; and 0.00 exact label match on the label fixture versus 1.00 match after a constant shift

    Figure 1: The three failing tests as CI reports them. Every number is wrong in a different, reproducible pattern, and no exception is raised anywhere in the run.

    Interactive PyTorch Workspace: Switch to the split-screen workspace to patch the classifier in the live editor and run the hidden behavioral checks.

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

    (1) Pooling Contract: Decide which positions may contribute to a sentence vector, then check that every pooled statistic honors the mask built on line 19.
    (2) Normalization Axis: For each softmax, name the axis whose entries must sum to one for a single example, and compare it with the axis in the code.
    (3) Inference State: List the module-level state an inference entry point depends on, and find the line that sets it.
    (4) Label Space: Trace one fixture label from the file into the loss, and one class id from the logits back to the comparison in accuracy(); both directions must agree.

    2Visual Review Map (Figure 2)
    Review map of the classifier: token ids (B, T) flow through embedding and encoder layer to (B, T, d), branch into a mean-pool stage and an attention-pool stage, merge in concat plus head to (B, K) logits, then pass through predict and label-space stages; the mean-pool, attention-pool, predict, and label-space stages each carry a uniform question mark

    Figure 2: The forward and predict path with its shape contract. The four “?” stages are where to look; deciding what is wrong at each one is the exercise.

    3Interviewer Nudge & Line Focus

    Walk each stage and answer the Socratic check before editing:

    Pooling Contract: Take a fixture row with 6 real tokens padded to T = 32. What fraction of the line-21 vector is contributed by real tokens, and should that fraction change when the same sentence is padded to T = 128?
    Inference State: The constructor creates dropout inside the encoder layer and inside the head. In which mode is the module when a training loop calls predict(), and does anything on lines 35-37 change that mode or stop autograd from recording?
    Label Space: Push a fixture label of 2 through line 30: which class id does the loss train on? Now push that class id back out through line 37 and compare it with the raw label that line 40 expects.
    Normalization Axis: Line 24 normalizes a (B, T) matrix. Pick one row: do its weights sum to one? Would that row’s pooled vector change if you scored it alone instead of inside a batch of 4?
    Answer
    Login to view more content
  • CD0015 Debug Left-Padded LM Loss

    Mode A · Bug Hunt 30 Min PyTorch 2.x 4 Silent Bugs

    On an OpenAI supervised fine-tuning pipeline, the data collator left-pads variable-length chat transcripts because the same batching code also feeds batched generation, where left padding keeps every row’s newest token in the last column. A teammate’s loss function written on top of those batches never crashes; a unit test that scores a single unpadded sequence against a hand-written reference matches to six decimal places.

    On real batches, three anomalies show up in the training telemetry:
    (1) Perplexity on padded batches is dramatically lower than when the same sequences are scored one at a time, and per-position dumps show padding tokens among the scored targets.
    (2) Re-padding the identical validation rows to a longer max_len changes the reported loss.
    (3) On the longest rows of a batch, the opening real tokens never appear among the scored targets.

    Trace the label-construction and loss-reduction lines below. Identify the 4 silent bugs, explain how each one interacts with left padding, and patch the function in place. Then write a verification test proving the loss is identical whether the same sequences are left-padded, right-padded, or unpadded.

    Code Under Review (38 Lines):

    01  import torch
    02  import torch.nn.functional as F
    03
    04
    05  def causal_lm_loss(logits: torch.Tensor,
    06                     input_ids: torch.Tensor,
    07                     attention_mask: torch.Tensor) -> torch.Tensor:
    08      """Mean next-token NLL over real (context, target) token pairs.
    09
    10      logits:         (B, T, V) model outputs for input_ids
    11      input_ids:      (B, T) left-padded token ids, each row starts with BOS
    12      attention_mask: (B, T) 1 = real token, 0 = padding
    13      Contract: the same sequences give the same loss under any padding.
    14      """
    15      B, T, V = logits.shape
    16      real = attention_mask.bool()  # (B, T)
    17
    18      # trim leading columns that are padding in every row
    19      n_lead = int(real.any(dim=0).int().argmax())
    20      n_lead = (n_lead + 7) // 8 * 8  # trim in multiples of 8 for tensor cores
    21      logits = logits[:, n_lead:]  # (B, T', V)
    22      real = real[:, n_lead:]  # (B, T')
    23      labels = input_ids[:, n_lead:].clone()  # (B, T')
    24      labels[:, 0] = -100  # BOS has no left context
    25
    26      # next-token shift: slot t predicts token t + 1
    27      logits = logits[:, :-1]  # (B, T'-1, V)
    28      labels = labels[:, 1:]  # (B, T'-1)
    29
    30      nll = F.cross_entropy(
    31          logits.reshape(-1, V).float(),
    32          labels.reshape(-1),
    33          reduction="sum",
    34      )
    35
    36      # average over every next-token slot in the batch
    37      denom = B * (T - 1)
    38      return nll / denom
    A left-padded batch of three rows with real lengths 11, 7 and 4 laid out over 14 columns, showing pad cells, a BOS cell and content tokens; below it the padding-invariance contract and three symptom boxes: low padded perplexity, a loss that moves with max_len, and opening tokens of the longest rows never scored

    Figure 1: A left-padded batch as the collator emits it, the padding-invariance contract the loss must honor, and the three symptoms observed in training telemetry.

    Interactive PyTorch Workspace: Switch to the split-screen workspace to hunt the 4 silent bugs in the live editor and run the padding-invariance checks.

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

    (1) Trim Contract: Compare the promise in the comment on line 18 with the number of columns actually removed, using the row that has the least padding.
    (2) Label Contract: List which label slots should be prediction targets, then check whether anything in the function marks the other slots so cross-entropy skips them.
    (3) Column Assumptions: Any hard-coded column index is a left-padding red flag. Ask where each row’s BOS actually sits after the trim and after the shift.
    (4) Reduction Contract: The docstring promises a mean over real pairs. Check what the divisor counts and whether it depends on T.

    2Visual Review Map (Figure 2)
    Review map of the loss function: five stages in order (leading-column trim, label construction, next-token shift, cross-entropy call, reduction divisor), each marked with the same question mark and an open question beneath it

    Figure 2: The five stages a strong candidate walks aloud. Every stage carries the same question mark, so answer each open question before deciding which lines to edit.

    3Interviewer Nudge & Line Focus

    Trace one concrete batch (real lengths 21, 14, 9 and 5, left-padded to T = 24) and answer each Socratic check before editing:

    Label Contract: After line 23, what value sits in a label slot whose token is padding, and does F.cross_entropy treat that value as a class to predict or as a slot to skip?
    Trim Stage: Line 18 promises to remove only columns that are padding in every row. With 3, 10, 15 and 19 leading pads, how many columns do lines 19-20 remove, and where does the longest row’s BOS end up?
    BOS Target: Line 24 writes into column 0 before the shift on line 28. Which (context, target) pair does that write remove after the shift, and which pair is left behind for a row whose BOS sits in column 10?
    Reduction Divisor: Re-pad the same four rows from T = 24 to T = 32. Which of nll and denom changes, and which one should?
    Answer
    Login to view more content
  • CD0012 Debug Extra Trees

    Mode A · Bug Hunt 30 Min Python 3 + NumPy 4 Silent Bugs

    Anthropic’s evaluation tooling keeps repair tasks dependency-free: a 45-line pure NumPy implementation of an Extremely Randomized Trees (ExtraTrees) classifier sits behind a hidden test suite it currently fails, and the rules forbid rewriting the file, a format candidates have publicly described from Anthropic’s online assessment. The file fits, it predicts, and it beats a coin flip on a toy dataset whose features lie in [0, 1], so nothing crashes and no warning fires.

    The spec is the original ExtraTrees algorithm. Every tree is grown on the full training set without bootstrap, and each node scores K candidate splits (one randomly chosen feature with one random cut-point each), keeps the candidate with the highest Gini gain, and recurses. A node that stops splitting becomes a leaf that predicts for every sample reaching it, and the forest takes a majority vote over its M trees.

    The hidden suite reports three failing behaviors: (1) the learned trees are suspiciously deterministic across seeds, (2) accuracy collapses on a fixture where cut-points must be drawn between the observed feature values rather than across a fixed range, and (3) leaf predictions are wrong whenever the first sample reaching a leaf is not the majority class. Find the 4 planted bugs in the split-selection and leaf-aggregation code, explain which part of the ExtraTrees contract each one breaks, apply minimal in-place fixes, and describe the test that would have caught each bug.

    Code Under Review (Lines 01-45):

    01  import numpy as np
    02
    03  class ExtraTreesClassifier:
    04      def __init__(self, n_estimators=30, max_features=2, max_depth=12, seed=0):
    05          self.n_estimators, self.max_features = n_estimators, max_features
    06          self.max_depth, self.seed = max_depth, seed
    07
    08      def _gini(self, y):
    09          p = np.bincount(y, minlength=self.n_classes_) / len(y)
    10          return 1.0 - np.sum(p * p)
    11
    12      def _build(self, X, y, depth, rng):
    13          best, parent = None, self._gini(y)
    14          if depth < self.max_depth and parent > 0:
    15              feats = np.argsort(X.var(axis=0))[-self.max_features:]
    16              for j in feats:
    17                  t = rng.uniform(0.0, 1.0)
    18                  left = X[:, j] <= t
    19                  if left.all() or not left.any():
    20                      continue
    21                  w = left.mean()
    22                  gain = parent - w * self._gini(y[left]) - (1 - w) * self._gini(y[~left])
    23                  if best is None or gain > best[0]:
    24                      best = (gain, j, t, left)
    25          if best is None:
    26              return ("leaf", int(y[0]))
    27          _, j, t, left = best
    28          return ("node", j, t, self._build(X[left], y[left], depth + 1, rng),
    29                  self._build(X[~left], y[~left], depth + 1, rng))
    30
    31      def fit(self, X, y):
    32          self.n_classes_, self.trees_ = int(y.max()) + 1, []
    33          for _ in range(self.n_estimators):
    34              rng = np.random.RandomState(0)
    35              self.trees_.append(self._build(X, y, 0, rng))
    36          return self
    37
    38      def _predict_one(self, node, x):
    39          while node[0] == "node":
    40              node = node[3] if x[node[1]] <= node[2] else node[4]
    41          return node[1]
    42
    43      def predict(self, X):
    44          votes = np.array([[self._predict_one(t, x) for t in self.trees_] for x in X])
    45          return np.array([np.bincount(v, minlength=self.n_classes_).argmax() for v in votes])
    Top row: the ExtraTrees spec as six steps, from fit on the full data through K candidate features, one random cut-point per feature, best Gini gain, a leaf label, and a vote over M trees. Bottom row: three observed hidden-suite failures: identical forests across seeds, one label for every row when features lie in [3, 5], and leaf labels that change when rows are reordered.

    Figure 1: the spec contract every tree must follow (top) and the three behaviors the hidden suite reports (bottom); mapping each failure to the lines that cause it is the exercise.

    Interactive Python Workspace: Switch to the split-screen workspace to repair the listing in the live editor and run the behavioral test suite.

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

    (1) Cut-Point Support: For each candidate feature, compare the interval the cut-point is sampled from with the values that actually reach the current node.
    (2) Randomness Lifecycle: Count how many random generators one call to fit creates, and check which constructor argument, if any, controls them.
    (3) Candidate Feature Set: The spec randomizes some node-level choices and optimizes others; mark the line that makes each choice and ask whether it depends on the seed.
    (4) Leaf Aggregation: A leaf summarizes a set of samples; check whether its stored label would change if those samples arrived in a different order.
    (5) Decoy Stages: Gini (L08-10), the weighted gain (L21-22), routing (L38-41), and the vote (L43-45) deserve a quick audit too, because not every stage hides a bug.

    2Visual Review Map (Figure 2)
    Review map of the 45-line listing split into eight stages, four inside _build and four at forest level, each marked with an identical question mark.

    Figure 2: The listing split into eight inspection stages, each with the same “?” marker. Four stages hide a silent bug and four are correct; deciding which is which is the exercise.

    3Interviewer Nudge & Line Focus

    Walk each stage and answer the Socratic check before editing:

    Cut-Point Draw: Feed the forest a feature whose values all lie in [3, 5]. For a cut-point drawn on line 17, what fraction of draws sends at least one sample left and at least one sample right?
    Randomness Lifecycle: Every tree here sees the same full training set. If two trees consume exactly the same random stream, can they differ at all, and how many distinct streams does this loop produce for seed 0 versus seed 1?
    Candidate Features: Multiply one feature by 1000 without changing the information it carries. Should the set of features a node considers change, and does it change in this code?
    Leaf Label: A node stops splitting while holding labels [0, 1, 1, 1]. What label should it store, and would your answer change if those four rows arrived shuffled?
    Answer
    Login to view more content
  • CD0008 Debug Eval Metrics Script

    Mode A · Bug Hunt 30 Min Python 3 (stdlib only) 4 Silent Bugs

    In a Google code-comprehension round, the interviewer shares a 42-line pure-Python scorer that a teammate wrote for a review-moderation classifier with three labels: ok, spam, and the rare abuse. It reads two CSV exports of example_id,label rows, one from the batch inference job and one from the labeling pipeline. It then prints overall accuracy and one row per class with its confusion counts (tp, fp, fn), precision P, and recall R. The script uses only the standard library and never raises.

    Three reviewers still flag the output. (1) On a review fixture where two predictions have no gold row and the gold export carries two ids the inference job never scored, accuracy prints 1.250. (2) On the same fixture, the rare-class row prints abuse tp=1 fp=2 fn=0 P=1.000, a precision that cannot coexist with two false positives. (3) On a four-row file where every prediction is wrong, one class still reports P=1.000.

    Read the script in data-flow order (load → pair → count → divide → print). Identify the 4 silent bugs in the metric computations and explain why each yields a plausible number instead of an exception. Patch them in place without restructuring the functions, then write a verification test on a hand-computable fixture that pins accuracy and every tp, fp, fn, P, and R value.

    Evaluation Script (Find 4 Silent Bugs):

    01  import csv
    02
    03
    04  def load_labels(lines):
    05      """Parse 'example_id,label' CSV lines into {example_id: label}."""
    06      return {ex_id: label.strip() for ex_id, label in csv.reader(lines)}
    07
    08
    09  def safe_div(num, den):
    10      try:
    11          return num / den
    12      except ZeroDivisionError:
    13          return 1.0
    14
    15
    16  def accuracy(pred, gold):
    17      scored = [ex_id for ex_id in pred if ex_id in gold]
    18      correct = sum(p == y for p, y in zip(pred.values(), gold.values()))
    19      return correct / len(scored)
    20
    21
    22  def per_class(pred, gold):
    23      rows = [(pred[ex_id], gold[ex_id]) for ex_id in pred if ex_id in gold]
    24      classes = sorted(set(row[0] for row in rows))
    25      report = {}
    26      for c in classes:
    27          tp = sum(1 for p, y in rows if p == c and y == c)
    28          fp = sum(1 for p, y in rows if p == c and y != c)
    29          fn = sum(1 for p, y in rows if p != c and y == c)
    30          precision = safe_div(tp, tp + fn)
    31          recall = safe_div(tp, tp + fp)
    32          report[c] = (tp, fp, fn, precision, recall)
    33      return report
    34
    35
    36  def evaluate(pred_lines, gold_lines):
    37      pred, gold = load_labels(pred_lines), load_labels(gold_lines)
    38      acc, report = accuracy(pred, gold), per_class(pred, gold)
    39      print(f"accuracy {acc:.3f}")
    40      for c, (tp, fp, fn, prec, rec) in report.items():
    41          print(f"{c:>6} tp={tp} fp={fp} fn={fn} P={prec:.3f} R={rec:.3f}")
    42      return acc, report
    Review fixture for the eval script: a predictions.csv table with ten rows r01 to r10 and a gold.csv table with ten rows in labeling-export order, shaded where an id appears in only one file; on the right, the unpatched script's printed output for the review fixture and for a four-row all-wrong file, with tags (1) to (3) marking the three reviewer flags

    Figure 1: the two exports of the review fixture (shaded ids exist in only one file) and what the unpatched script prints for that fixture and for a four-row all-wrong file. Tags (1) to (3) mark the three reviewer flags.

    Interactive Python Workspace: Switch to the split-screen workspace to patch the scorer in the live editor and run the behavioral check suite on the review fixtures.

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

    (1) Example Pairing: Check how each prediction meets its gold label, and confirm the accuracy numerator and denominator count the same population of examples.
    (2) Ratio Denominators: Precision divides by the predicted-positive count and recall by the gold-positive count; check each printed ratio against the counts on its own row.
    (3) Class Universe: A per-class report should contain a row for every class that appears in the gold labels.
    (4) Undefined Ratios: Decide what a 0/0 ratio should report so that an all-wrong prediction file can never look good.

    2Visual Review Map (Figure 2)
    Data-flow review map of the scorer: CSV files feed load_labels, which branches into the accuracy path and the per-class path (rows, class list, tp fp fn counts, P and R ratios that call safe_div); four stages carry a uniform question-mark marker with their line ranges

    Figure 2: The data-flow order a strong candidate reads aloud. Each of the four stages marked ? hides one silent bug, and the line ranges match the numbered listing.

    3Interviewer Nudge & Line Focus

    Walk each stage and answer the Socratic check before editing:

    Accuracy Stage: Lines 17 and 18 each build their own view of which examples get scored. On the review fixture, how many (prediction, gold) pairs does the numerator iterate over, and how many examples does the denominator count? What invariant would make accuracy at most 1 by construction?
    Per-Class Ratios: Take the abuse row with tp=1, fp=2, fn=0 and compute precision and recall by hand. Which of the two counts belongs in each denominator, and does the printed P agree with your number?
    Class List: Each element of rows is a two-field tuple. If the model never predicts a class that gold contains, should that class still get a recall row? Which field decides whether it appears?
    Division Guard: When a ratio’s denominator is zero, the metric is undefined. What does a reader of the report assume a printed 1.000 means, and what score should any class get on a file where every prediction is wrong?
    Answer
    Login to view more content
  • CD0007 Debug QA Data Pipeline

    Mode A · Bug Hunt 30 Min Python 3.10 · json + csv 4 Silent Bugs

    Scale AI’s annotation pipelines turn human-labeled tasks into training data for LLM customers, and small pieces of glue code sit between the labeled JSON exports and the files a training job actually ingests. In this coding round you are handed one of those pieces: extract_qa.py, a 40-line script that walks a directory of annotation files, pulls question-answer pairs, deduplicates them, and writes a two-column CSV used as LLM fine-tuning data.

    The nightly run reads annotations/, which holds 64 task files and 15,872 items. The script exits with status 0, but the data QA report on qa_train.csv flags three anomalies: (1) only 198 data rows were written, (2) 6 rows parse to more than two columns, with answer text bleeding into a third or fourth field, and (3) a reviewer’s spot check finds approved QA pairs missing from the CSV even though their source files load cleanly with json.load.

    The vendor exporter was upgraded last quarter. Items reviewed after the upgrade are re-emitted in the new shape, so a single task file can mix both item shapes. The data contract you are given is below.

    FieldSchema v1 (Legacy Exporter)Schema v2 (Current Exporter)
    File envelope{"task_id": str, "items": [...]}Same envelope
    Item idid: int, the item’s position within its task file (0, 1, 2, …)Same as v1
    Questionquestion: strquestion: str
    Answeranswer: str at the item’s top levelresponse: object holding answer (str) and rater_id (str)
    RedeliveryA task may be re-sent as a second file with the same task_id; each item must reach the CSV onceSame as v1

    Walk the script the way a record flows from disk to CSV. Find the 4 silent bugs, state exactly which line drops or corrupts each class of record, patch them in place with a minimal diff, and write a verification test on a mixed edge-case fixture that proves both row counts and CSV escaping.

    Script Under Review (40 Lines):

    01  import json
    02  from pathlib import Path
    03
    04
    05  def load_items(src_dir):
    06      """Return (task_id, item) pairs from every annotation file."""
    07      paths = sorted(Path(src_dir).glob("*.json"))
    08      items = []
    09      for path in paths:
    10          with open(path, encoding="utf-8") as f:
    11              doc = json.load(f)
    12          for item in doc["items"]:
    13              items.append((doc["task_id"], item))
    14          return items
    15
    16
    17  def extract_pairs(src_dir):
    18      """Deduplicated (question, answer) pairs, in file order."""
    19      pairs, seen = [], set()
    20      for task_id, item in load_items(src_dir):
    21          try:
    22              question = item["question"].strip()
    23              answer = item["answer"].strip()
    24          except KeyError:
    25              continue
    26          key = item["id"]
    27          if key in seen:
    28              continue
    29          seen.add(key)
    30          pairs.append((question, answer))
    31      return pairs
    32
    33
    34  def write_csv(pairs, out_csv):
    35      """Write a two-column CSV with a header row."""
    36      with open(out_csv, "w", encoding="utf-8") as f:
    37          f.write("question,answer\n")
    38          for question, answer in pairs:
    39              f.write('"' + '","'.join([question, answer]) + '"\n')
    40      return len(pairs)
    Data QA report for qa_train.csv: a bar chart comparing 15,872 annotation items on disk with 198 CSV data rows, and a second bar chart of fields per parsed CSV row showing 192 rows with 2 fields, 4 rows with 3 fields, and 2 rows with 4 fields

    Figure 1: the data QA report. Only about 1.2% of the items on disk reach the CSV, and 6 of 198 rows read back with more than two columns, yet the script never raised.

    Interactive Python Workspace: Switch to the split-screen workspace to patch the script in the live editor and run the hidden fixture checks.

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

    (1) File Coverage: Compare how many paths the glob returns with how many files the loop actually opens before load_items returns.
    (2) Schema Contract: For each item shape in the schema table, trace which keys lines 22-23 read and what the except branch does on a miss.
    (3) Identity Contract: Decide what uniquely identifies one annotation across the whole directory, then compare it with the key built on line 26.
    (4) Serialization Contract: List the characters that RFC 4180 says force quoting or escaping inside a field, and test each one against line 39.

    2Visual Review Map (Figure 2)
    Pipeline review map: annotations on disk flow through four stages, the file loop at lines 05-14, the field read at lines 20-25, the dedup key at lines 26-29, and serialization at lines 34-40, each marked with a question mark, into qa_train.csv; a second row lists the count to reconcile at each stage

    Figure 2: the four stages a record crosses between disk and CSV. Each ? marks a stage to inspect; reconcile the count beneath it before you edit any line.

    3Interviewer Nudge & Line Focus

    Answer each Socratic check on paper before touching the editor:

    File Loop: paths holds 64 files. Trace control flow through one full iteration: after line 13 appends the first file’s items, which line executes next, and how many times does line 10 run in total?
    Field Read: Hand-feed one item of each schema version through lines 22-23. Which one raises, which exception is it, and does any counter or log record that the item was skipped?
    Dedup Key: Take item 0 of two different task files and compute the line-26 key for each by hand. If every file numbers its 248 items from 0, how many distinct keys can 64 tasks produce?
    Serialization: Write the row for the answer He said "stop", then left. by hand exactly as line 39 would. Then read it back character by character as a CSV parser would: how many fields come out?
    Answer
    Login to view more content
  • CD0001 Debug PyTorch Training Loop

    Mode A · Bug Hunt 30 Min PyTorch 2.x 4 Silent Bugs

    Meta’s PyTorch org maintains the training stack behind its ranking and recommendation models, and its interviews like to probe whether you can read a loop the way a profiler does. In a coding round for that team, the interviewer hands you a 36-line PyTorch training and validation script. An AI coding assistant generated it for fine-tuning a 10-class classifier with BatchNorm and Dropout layers. The script runs without a single syntax or runtime exception. The small build_model() head is the minimal reproduction, and the production job plugs a pretrained encoder into the same loop.

    Code Under Review (Spot the 4 Silent Bugs):

    01  import torch
    02  import torch.nn as nn
    03  import torch.nn.functional as F
    04
    05  def build_model(in_dim=32, hidden=64, num_classes=10):
    06      return nn.Sequential(
    07          nn.Linear(in_dim, hidden), nn.BatchNorm1d(hidden), nn.ReLU(),
    08          nn.Dropout(p=0.3), nn.Linear(hidden, num_classes))
    09
    10  def fit(model, train_loader, val_loader, epochs=5, device="cuda"):
    11      model.to(device)
    12      criterion = nn.CrossEntropyLoss()
    13      optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
    14      history = []
    15      for epoch in range(epochs):
    16          for x, y in train_loader:
    17              x, y = x.to(device), y.to(device)
    18              logits = model(x)
    19              probs = F.softmax(logits, dim=-1)
    20              loss = criterion(probs, y)
    21              loss.backward()
    22              optimizer.step()
    23          train_loss = loss.item()
    24
    25          batch_losses = []
    26          for x, y in val_loader:
    27              x, y = x.to(device), y.to(device)
    28              logits = model(x)
    29              batch_losses.append(criterion(logits, y))
    30          val_loss = sum(batch_losses) / len(val_loader)
    31          history.append(val_loss)
    32          print(f"epoch {epoch}: train {train_loss:.3f} "
    33                f"val {val_loss.item():.3f}")
    34      return history
    35
    36  # usage: history = fit(build_model(), train_dl, val_dl)

    Three things go wrong in practice. (1) Training loss starts near 2.30, falls to about 1.65 within the first few dozen steps, and then stops improving. (2) GPU memory climbs by roughly 10 GB on every validation pass until a CUDA out-of-memory error kills the job during epoch 4 on a 40 GB card. (3) The validation set has 1,030 samples and the loader uses batch size 128, so the final batch holds only 6 samples, and the reported epoch validation loss jumps erratically whenever that short batch is present.

    Walk through the script in the order data and gradients flow. Identify the 4 silent bugs planted in the training and validation loops, and explain the exact mathematical or autograd reason each one triggers its symptom. Then provide the corrected training and validation code, and write a compact verification test that proves every fix works.

    Three symptom panels: a training loss curve that drops from 2.3 and flattens near 1.65, GPU memory stepping up about 10 GB per epoch until a CUDA OOM at the 40 GB limit in epoch 4, and bars showing different reported validation losses for the same weights at batch sizes 103, 128, and 256

    Figure 1: Illustrative telemetry from the run. Training loss stalls near 1.65, memory steps up every epoch until the 40 GB limit, and identical weights report different validation losses as the batch size changes.

    Interactive PyTorch Workspace: Switch to the split-screen workspace to patch the 4 silent bugs in the live PyTorch editor and run the behavioral test suite.

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

    (1) Loss Contract: Check what tensor reaches the loss function and whether that loss already normalizes its input.
    (2) Gradient Lifecycle: Check what happens to every parameter’s .grad buffer between one step and the next.
    (3) Evaluation Context: Validation must neither mutate layer statistics nor keep autograd graphs alive across epochs.
    (4) Metric Aggregation: An epoch metric is a statement about samples, not batches; check how unequal batch sizes are weighted.

    2Visual Review Map (Figure 2)
    Data and gradient flow through the script: a training row of batch, model, loss, backward, and optimizer step with a dashed gradient path back to the model, a validation row of batch, model forward, aggregate loss, history, and report, and question-mark markers on the suspect stages a reviewer inspects

    Figure 2: The data path (solid) and gradient path (dashed) through the script. The question-mark markers flag the stages a reviewer inspects next.

    3Interviewer Nudge & Line Focus

    Walk the script in execution order and answer the interviewer’s Socratic check at each stage:

    Loss Contract: What normalization does nn.CrossEntropyLoss already apply internally, and what happens to logit gradients when its input is pre-squashed into [0, 1]?
    Step Lifecycle: loss.backward() accumulates into .grad via +=; where in the inner loop is that buffer cleared before the next batch?
    Eval Context: Layer mode (BatchNorm/Dropout) and autograd graph recording are two independent switches. Why does history.append(val_loss) pin ~10 GB per epoch?
    Epoch Metric: With 1,030 samples at batch_size=128, batch 9 has 6 samples. How much weight does sum(batch_losses) / len(val_loader) give those 6 samples?
    Answer
    Login to view more content

  • CD0002 Debug Causal Attention Mask

    Mode A · Bug Hunt 30 Min PyTorch 2.x · FP16 4 Masking Bugs

    OpenAI’s serving stack runs batched causal attention over left-padded, variable-length prompts, where a mask that is off by one diagonal quietly leaks future tokens. In an LLM engineering interview there, you are handed an AI-generated PyTorch module for batched causal self-attention. It must support variable-length sequences with left-padding and run under FP16 autocast. Its unit test passes on a single unpadded sequence in FP32, and in that setting the code never throws.

    Code Under Review (Spot the 4 Silent Bugs):

    01  import math
    02  import torch
    03  import torch.nn as nn
    04  import torch.nn.functional as F
    05
    06  NEG_INF = -1e9
    07
    08  class CausalSelfAttention(nn.Module):
    09      def __init__(self, d_model, n_head, p_drop=0.1):
    10          super().__init__()
    11          assert d_model % n_head == 0
    12          self.h, self.d = n_head, d_model // n_head
    13          self.qkv = nn.Linear(d_model, 3 * d_model)
    14          self.proj = nn.Linear(d_model, d_model)
    15          self.p_drop = p_drop
    16
    17      def forward(self, x, attn_mask):
    18          # x: (B, T, C); attn_mask: (B, T) with 1 = real token, 0 = left pad
    19          B, T, C = x.shape
    20          q, k, v = self.qkv(x).split(C, dim=-1)
    21          q, k, v = (t.view(B, T, self.h, self.d).transpose(1, 2) for t in (q, k, v))
    22          scores = q @ k.transpose(-2, -1) / math.sqrt(self.d)  # (B, H, T, T)
    23          causal = torch.triu(torch.ones(T, T, device=x.device), diagonal=0)
    24          scores = scores.masked_fill(causal == 0, NEG_INF)
    25          pad = torch.zeros(B, T, device=x.device, dtype=scores.dtype)
    26          pad = pad.masked_fill(attn_mask == 0, float("-inf"))
    27          scores = scores + pad.view(B, 1, T, 1)
    28          scores = F.dropout(scores, p=self.p_drop, training=self.training)
    29          attn = F.softmax(scores, dim=-1)
    30          out = attn @ v  # (B, H, T, D)
    31          out = out.transpose(1, 2).contiguous().view(B, T, C)
    32          return self.proj(out)

    Once the module is deployed in a batched evaluation harness, it fails in three ways. (1) On unpadded sequences, teacher-forced perplexity on held-out text collapses toward 1 (loss near zero), yet free-running generation produces gibberish. (2) Whenever a batch contains left-padded sequences, the attention output fills with NaN at the padded positions and contaminates every later layer. (3) Under FP16 autocast, the forward pass crashes with a RuntimeError: value cannot be converted to type at::Half without overflow.

    Inspect the numbered attention module and pinpoint the 4 silent masking and broadcasting bugs. Explain how each one corrupts the attention weight matrix or the softmax denominator. Then write the corrected implementation and a unit test that verifies causal invariance and padding safety.

    A unit test box marked PASS and an eval harness box with left-padded FP16 batches both feed an AI-generated causal self-attention module marked with a question mark, which fans out to three symptom boxes: perplexity near 1 with gibberish generation, NaN at padded positions, and an FP16 overflow RuntimeError

    Figure 1: the same attention module passes a single-sequence FP32 test but fails three different ways once it meets left-padded batches and FP16 autocast.

    Interactive PyTorch Workspace: Switch to the split-screen workspace to fix all 4 masking bugs in the live editor and run causal, left-padding, and FP16 checks.

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

    (1) Causal Direction: Confirm which triangle blocks keys with j > i while preserving the diagonal.
    (2) Broadcast Axes: Decide whether a (B, T) padding mask should block query rows or key columns of (B, H, T, T).
    (3) Dtype-Aware Fill: Every constant written into scores must fit IEEE-754 FP16 as well as FP32/BF16.
    (4) Post-Mask Ops: Check every operation between masking and attn @ v to ensure masked entries stay zero.

    2Visual Review Map (Figure 2)
    Snake-shaped data flow of the attention module: input, QKV projection, scores of shape B H T T, causal mask, padding mask, then dropout, softmax, attention times V, merge heads and projection, and output; the four mask-sensitive stages carry question-mark markers

    Figure 2: The score tensor passes through four mask-sensitive stages between the matmul and the softmax; the stages marked “?” are where a reviewer digs next.

    3Interviewer Nudge & Line Focus

    Trace a 4 x 4 score matrix with 2 left-pad tokens and answer each check below:

    Causal Triangle & Range: Write out torch.triu(ones(4, 4), diagonal=0): which triangle is zeroed when masking causal == 0? Also check whether every fill constant fits IEEE-754 float16 (max 65,504).
    Padding Broadcast Axis: In scores of shape (B, H, T_q, T_k), does pad.view(B, 1, T, 1) mask padded key columns or entire padded query rows? What does softmax([-inf, -inf, -inf, -inf]) evaluate to?
    Fill Constant vs Dtype Range: NEG_INF = -1e9 (line 6) is consumed by masked_fill inside autocast at line 24. What happens when the fill must cast into a float16 tensor whose max finite is 65,504? Would torch.finfo(scores.dtype).min fit every dtype, and what does a fully masked row softmax to under it?
    Dropout vs Softmax Order: If F.dropout randomly zeroes a large negative masked logit before F.softmax, what probability weight does exp(0.0) assign to that forbidden token?
    Answer
    Login to view more content