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 intent 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 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)
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.
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)

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:
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?
predict(), and does anything on lines 35-37 change that mode or stop autograd from recording?
(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?
Leave a Reply