This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.
Category: Bug Hunt
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
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 overintent classes. The CI fixtures pad every row to
with pad id 0, and the fixture files store labels as
, 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 onlabels.jsonldiffers 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)
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.
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 inaccuracy(); both directions must agree.2Visual Review Map (Figure 2)

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 toT = 32. What fraction of the line-21 vector is contributed by real tokens, and should that fraction change when the same sentence is padded toT = 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 callspredict(), 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 contentCD0015 Debug Left-Padded LM Loss
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 longermax_lenchanges 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
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.
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.
2Visual Review Map (Figure 2)

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
) and answer each Socratic check before editing:
Label Contract: After line 23, what value sits in a label slot whose token is padding, and doesF.cross_entropytreat 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 fromto
. Which of
nllanddenomchanges, and which one should?Answer
Login to view more contentCD0012 Debug Extra Trees
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
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
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.](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjc1IiBoZWlnaHQ9IjUyOCIgdmlld0JveD0iMCAwIDEyNzUgNTI4Ij48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBzdHlsZT0iZmlsbDojY2ZkNGRiO2ZpbGwtb3BhY2l0eTogMC4xOyIvPjwvc3ZnPg==)
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.
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 tofitcreates, 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)

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




![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.](https://intvml.com/wp-content/uploads/2026/11/CD0012-debug-extra-trees-implementation-problem.jpg)








