This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.
Tag: Data Eng
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 contentCD0013 KNN Array Query
A Google data-quality job runs two measurement pipelines that log integer readings of the same quantity — a source-attribution task reported from a Google AI/ML coding round in November 2025. Source A is a tightly calibrated sensor, while source B is a cheap sensor with a much wider spread. A stream of new readings arrives without provenance, and for each one you must decide which source more likely produced it. Naive nearest-distance reasoning picks the wrong source, so the brief asks you to handle ties explicitly and to compare at least two assignment strategies.
You receive
Aof shape,
Bof shape, and
queriesof shape, all integer arrays whose dtype is not guaranteed to be signed. Label 0 means source A and label 1 means source B. You may use NumPy only: scikit-learn neighbors,
scipy.spatial.distance.cdist, and a Python loop over queries are all off limits. The batched driver returns four arrays of shape: the kNN labels, the kNN vote margin (share of B votes minus share of A votes, in absolute value, so it lies in
), the z-score labels, and the z-score gap
.
Complete the 4 missing pieces in the skeleton below and trace the exact array shape after each line. Then argue which strategy is more defensible when one source is much noisier than the other, and verify your module on a synthetic two-source fixture with known ground truth.
Skeleton Code (Fill Blanks 1-4):
01 import numpy as np 02 03 04 def pairwise_dist(queries, pool): 05 # TODO (Blank 1): |queries_i - pool_j| for every query/pool pair, float (Q, N) 06 dists = ... 07 return dists 08 09 10 def knn_vote(dists, pool_labels, k): 11 # TODO (Blank 2): majority label among the k nearest pool points per row; 12 # a tied vote falls back to the single nearest label 13 pred, frac_b = ... 14 return pred, frac_b # (Q,) int, (Q,) share of B votes 15 16 17 def zscore_assign(queries, A, B, eps=1e-12): 18 # TODO (Blank 3): |queries - mean| per source, scaled by that source std (ddof=0) 19 z_A, z_B = ... 20 return (z_A > z_B).astype(int), z_A, z_B # 1 = source B, z tie goes to A 21 22 23 def classify(queries, A, B, k=5): 24 A, B = np.asarray(A, float), np.asarray(B, float) 25 pool_labels = np.concatenate([np.zeros(len(A)), np.ones(len(B))]).astype(int) 26 # TODO (Blank 4): all queries at once (no Python loop), labels + margins 27 knn_pred, knn_margin, z_pred, z_margin = ... 28 return knn_pred, knn_margin, z_pred, z_margin
Figure 1: the inputs and the four returned arrays are fixed, and the two assignment strategies run side by side. Every question-marked step is yours to write in plain NumPy.
Progressive Hints (Free · Zero Spoilers)1Inspection Checklist (Where to Look)
(1) Broadcast Axes: Decide which axis indexes queries and which indexes pool points before you subtract, and check what integer dtype the readings arrive in.
(2) Row-Wise Neighbors: The k nearest points must be chosen independently for every query row, and equal distances need an order that is identical on every run.
(3) Scale Contract: Each source distance must be measured in that source’s own spread, including a source whose readings never vary.
(4) Batch Contract: One vectorized pass over all queries, labels aligned with the pool order, a neighbor count that may exceed the pool, and margins computed per query.2Visual Review Map (Figure 2)

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce, and writing the NumPy ops that reach them is the exercise.
3Interviewer Nudge & Line Focus
Pin the input shape, output shape, and dtype of each blank before writing the NumPy op:
Blank 1 (Pairwise Distances):queriesis(Q,)andpoolis(N,). Which axis must each array gain so the subtraction broadcasts to(Q, N), and what silently happens instead whenQ == N? If both arrays arrive asuint8sensor counts, what does3 - 5evaluate to?Blank 2 (kNN Vote + Tie Rule): Along which axis doesargsortsort a(Q, N)matrix by default, and does slicing its result with[:k]keep the first k rows or the first k columns? With k = 4 and a 2-2 split, which single neighbor should decide, and which sort kind keeps equal integer distances in pool order on every run?Blank 3 (Scale-Aware Score): Source A has std 2 and source B has std 15. A query sits 8 units from mean A and 12 units from mean B: what are the two standardized distances, and does the winner differ from the raw-distance winner? What does your expression return when every reading of a source is identical?Blank 4 (Batched Driver + Margins): In which order must A and B be concatenated so the pool lines up withlabelson line 25? What should happen when k exceedsn_A + n_B, and how many distinct values can the vote margin take for a fixed k?Answer
Login to view more content











