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
Log in to track your progress

Comments

Leave a Reply

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