CD0012 Debug Extra Trees

Mode A · Bug Hunt 30 Min Python 3 + NumPy 4 Silent Bugs

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 K 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 M 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.

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.

Interactive Python Workspace: Switch to the split-screen workspace to repair the listing in the live editor and run the behavioral test suite.

Open in Colab ↗
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 to fit creates, 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)
Review map of the 45-line listing split into eight stages, four inside _build and four at forest level, each marked with an identical question mark.

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

Comments

Leave a Reply

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