Tag: Data Eng

  • CD0017 Log Forensics Triage

    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
  • CD0013 KNN Array Query

    Mode B · Build & Trace 30 Min NumPy 4 Array Blanks

    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 A of shape (n_A,), B of shape (n_B,), and queries of shape (Q,), 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 (Q,): the kNN labels, the kNN vote margin (share of B votes minus share of A votes, in absolute value, so it lies in [0, 1]), the z-score labels, and the z-score gap |z_A - z_B|.

    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
    Operator contract for the two-source query classifier: an inputs box holding source arrays A and B plus the query stream feeds two question-marked branches, pairwise distances followed by a kNN vote with a tie rule, and a scale-aware score per source; both branches feed a question-marked step that returns labels and margins for every query. Below, boxes list the forbidden library calls, the allowed NumPy building blocks, and the test oracle

    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.

    Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the hidden kNN and z-score checks.

    Open in Colab ↗
    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)
    Shape trace for the two-source classifier: the top row marks the target shapes of Blanks 1 and 2, from the query and pool vectors to a question-marked (Q, N) distance matrix, a question-marked (Q, k) neighbor set, and per-query outputs; the bottom row marks the target shapes of Blanks 3 and 4, from the sources to per-query standardized distances, per-query margins, and four returned arrays of shape (Q,)

    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): queries is (Q,) and pool is (N,). Which axis must each array gain so the subtraction broadcasts to (Q, N), and what silently happens instead when Q == N? If both arrays arrive as uint8 sensor counts, what does 3 - 5 evaluate to?
    Blank 2 (kNN Vote + Tie Rule): Along which axis does argsort sort 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 with labels on line 25? What should happen when k exceeds n_A + n_B, and how many distinct values can the vote margin take for a fixed k?
    Answer
    Login to view more content
  • CD0010 K-Means From Scratch

    Mode B · Build & Trace 30 Min NumPy 4 Array Blanks

    Clustering prototypes show up constantly on Google and Waymo ML teams, and this screen (reported by candidates from both companies' coding rounds) rewards the same habit: writing a few lines of vectorized NumPy that stay correct when the data misbehaves. You must implement KMeans.fit(X, k) from scratch. It takes a float array of shape (n_samples, n_features) and returns integer cluster labels of shape (n_samples,) and centroids of shape (k, n_features). Calling sklearn.cluster.KMeans, scipy.cluster.vq, or scipy.spatial.distance.cdist is forbidden.

    Initialization is fixed for this round: k distinct rows of X drawn at random, with k-means++ left as a follow-up. The interviewer cares less about the happy path than about three edge cases. A cluster can come out empty mid-run, the loop needs a defensible stopping rule, and a correct implementation must preserve specific invariants on every iteration.

    Complete the 4 missing operations in the skeleton below and narrate the array shape after each line. Then state the algorithm's time complexity, explain how you would choose k, and write a test that checks invariants rather than one hand-picked output.

    Skeleton Code (Fill Blanks 1-4):

    01  import numpy as np
    02
    03
    04  class KMeans:
    05      def __init__(self, max_iter: int = 100, tol: float = 1e-6, seed: int = 0):
    06          self.max_iter, self.tol = max_iter, tol
    07          self.rng = np.random.default_rng(seed)
    08
    09      def fit(self, X: np.ndarray, k: int):
    10          n_samples, n_features = X.shape                    # X: (n_samples, n_features) float64
    11          centroids = X[self.rng.choice(n_samples, size=k, replace=False)]   # (k, n_features)
    12          self.inertia_history = []
    13          for it in range(self.max_iter):
    14              # TODO (Blank 1): squared distances from every point to every
    15              #                 centroid, shape (n_samples, k), no Python loops
    16              sq_dists = ...
    17              # TODO (Blank 2): index of the nearest centroid per point, (n_samples,)
    18              labels = ...
    19              self.inertia_history.append(sq_dists[np.arange(n_samples), labels].sum())
    20              prev_centroids = centroids.copy()
    21              # TODO (Blank 3): recompute each centroid as the mean of its
    22              #                 points; an empty cluster must stay finite
    23              ...
    24              # TODO (Blank 4): stop when the centroids have converged
    25              if ...:
    26                  break
    27          self.centroids_, self.labels_, self.n_iter_ = centroids, labels, it + 1
    28          return labels, centroids
    Operator contract for KMeans.fit: input X of shape (n_samples, n_features) with k random rows as initial centroids flows through four question-marked steps (Blank 1 distances, Blank 2 assignment, Blank 3 centroid update, Blank 4 stop check) with a loop back for the next iteration, ending at labels (n_samples,) and centroids (k, n_features); below, three boxes list the edge cases the interviewer probes

    Figure 1: the input and output contract is fixed, the random-row initialization is given, and the four steps inside the Lloyd loop are yours to write, with the interviewer probing empty clusters, the stopping rule, and the loop's invariants.

    Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the invariant checks.

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

    (1) Broadcast Geometry: Align the point axis of X and the centroid axis of centroids so one subtraction covers every pair, then reduce over the feature axis only.
    (2) Reduction Axis: The assignment must produce one label per point, and line 19 indexes sq_dists with exactly that shape.
    (3) Empty-Cluster Contract: Decide what a centroid with zero members should be before writing the update, and keep every centroid finite.
    (4) Stopping Rule: Compare the updated centroids with the snapshot on line 20 using an explicit tolerance, and remember that line 13 is the second guard.

    2Visual Review Map (Figure 2)
    Shape trace for KMeans.fit: X (n_samples, n_features) and centroids (k, n_features) feed question-marked blanks whose target shapes are an intermediate (n_samples, k, n_features), sq_dists (n_samples, k), labels (n_samples,), new centroids (k, n_features), and a boolean stop flag; the line 19 inertia and the line 20 prev_centroids snapshot are shown as given, with a loop back to Blank 1 for the next iteration

    Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shape it must produce; writing the operations that reach them is the exercise.

    3Interviewer Nudge & Line Focus

    Pin the input shape, output shape, and failure mode of each blank before writing the NumPy call:

    Blank 1 (Distance Matrix): X is (n_samples, n_features) and centroids is (k, n_features). Which singleton axes must you insert so the subtraction broadcasts to a 3-axis tensor, and which axis do you reduce? If n_samples == k, what does a plain X - centroids silently compute instead of raising?
    Blank 2 (Assignment): sq_dists is (n_samples, k). Does the reduction collapse the point axis or the centroid axis, what shape would the other choice produce, and which index wins when two centroids sit at exactly the same distance?
    Blank 3 (Centroid Update): If X contains duplicate rows, two initial centroids can be identical. What does averaging a (0, n_features) array return, what happens to the next distance matrix once one centroid holds that value, and which two finite choices could you make instead?
    Blank 4 (Convergence): Lloyd's algorithm visits finitely many partitions, so why still compare against a tolerance in the data's units, and why does line 13 keep its bound even when your stop check is correct?
    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
  • MSD0064 Notification Ranking System

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

  • MSD0057 LLM Training Data Pipeline

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

  • MSD0055 Netflix Watch Pause Prediction

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