Build a reproducible parallel random forest with flattened vectorized inference
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement three functions for a bagged forest of scikit-learn `DecisionTreeClassifier` trees. `fit_forest(X, y, n_trees, seed, max_features="sqrt", max_depth=None, n_jobs=1)` trains the trees with one random stream per tree. `flatten_forest(forest)` packs every tree into shared global node arrays. `predict_proba_flat(flat, X)` walks all trees at once with vectorized NumPy and returns averaged class probabilities of shape `(n_samples, n_classes)`.
Fitting rules:
- Tree `i` uses `rng = np.random.default_rng(np.random.SeedSequence(seed).spawn(n_trees)[i])`. Its first draw is the bootstrap `rng.integers(0, n, size=n)`, and the tree's `random_state` also comes from this stream. `max_features` and `max_depth` pass through to every tree.
- Results are identical for any `n_jobs`, and adding trees leaves the earlier trees unchanged.
- Return a dict with keys `trees`, `bootstrap_indices` and `classes` (equal to `np.unique(y)`).
Flattening rules:
- Return a dict with keys `feature`, `threshold`, `left`, `right`, `value` and `roots`. Trees are concatenated in order, child indices are global positions in the concatenated arrays, and `roots[i]` is the offset where tree `i` starts.
- Leaves have `left = right = -1`, `feature = -2` and `threshold = -2.0`.
- `value` has one row per node and one column per forest class. For nodes of a fitted tree each row sums to 1, and classes missing from that tree's bootstrap get 0.
Prediction rules:
- At a split node, go left when `x[feature] <= threshold`, otherwise right.
- The output must match the average of the trees' own `predict_proba` outputs aligned to the forest's classes. scikit-learn compares split values with `X` in `float32`.
Example with a hand-built flat forest of two stumps:
```python
flat = {"feature": [0, -2, -2, 1, -2, -2], "threshold": [0.5, -2, -2, 2.0, -2, -2],
"left": [1, -1, -1, 4, -1, -1], "right": [2, -1, -1, 5, -1, -1],
"value": [[0, 0], [1, 0], [.2, .8], [0, 0], [.5, .5], [0, 1]], "roots": [0, 3]}
predict_proba_flat(flat, [[0.0, 1.0], [1.0, 3.0]])
# [[0.75, 0.25], [0.1, 0.9]]
```
Tree 0 (nodes 0 to 2) splits on feature 0 at 0.5, and tree 1 (nodes 3 to 5) splits on feature 1 at 2.0. The first sample reaches leaves 1 and 4, so its output is the mean of `[1, 0]` and `[0.5, 0.5]`. The second reaches leaves 2 and 5, giving the mean of `[0.2, 0.8]` and `[0, 1]`. Prediction never reads the rows of internal nodes, so the example leaves them at 0.
```hint Both reproducibility rules
The tree's own `random_state` has to come from the tree's stream too. Check what a shared global generator, or one seed reused for every tree, would do to each of the two reproducibility rules.
```
```hint Ties on a threshold
A sample whose feature value lies very close to a threshold can go the other way if your comparison runs at a different precision than the library's.
```
```hint When the loop can stop
Picture a 2-D array of current node indices, one per sample and tree. Work out what must be true of it before you can read off the leaf values.
```
### Constraints & Assumptions
- `X` is a numeric array of shape `(n_samples, n_features)` and `y` holds one sortable label per row.
- NumPy, scikit-learn and the Python standard library are available.
- `n_jobs` of `None` or 1 runs serially, a larger value sets the number of worker threads, and a negative value means all cores.
- The traversal is vectorized over samples and trees. A Python loop over tree depth is fine; a loop over samples is not.
### What a Strong Answer Covers
- How per-tree random streams make results independent of the worker count and stable when trees are added.
- Index bookkeeping during flattening: global child offsets, leaf markers and tree roots.
- Normalized node values aligned to the forest's classes when a bootstrap misses a class.
- A traversal vectorized over samples and trees that compares at scikit-learn's precision and stops once every cursor sits on a leaf.
- The time and memory cost of inference.
### Follow-up Questions
- How would you use the bootstrap indices to compute an out-of-bag score?
- How does the vectorized traversal scale, and how would you reduce its memory use?
- Why not seed tree `i` with `default_rng(seed + i)` instead of spawning children?
Overview: Build a bagged random forest whose results do not depend on the number of worker threads, then flatten every tree into shared node arrays for vectorized prediction. It tests SeedSequence streams, global index bookkeeping, class alignment and exact agreement with scikit-learn's predict_proba.