Implement a Median Pruner for Intermediate Trial Values
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `MedianPruner` with `report(trial_id, step, value)` to record intermediate values and `should_prune(trial_id, step)` returning a `bool`. A trial is pruned when its value at a step is worse than the median of all other trials' values at that exact step.
The constructor is `MedianPruner(n_startup_trials=5, n_warmup_steps=0, direction="maximize")`, and the pruner follows these rules:
- Re-reporting the same `(trial_id, step)` overwrites the previous value.
- Return `False` if `step < n_warmup_steps` or the trial has no value at `step`.
- The reference set is the values at `step` from other trials only. Return `False` if it is empty or smaller than `n_startup_trials`.
- Compute the median with `np.median`. With `"maximize"`, prune if and only if `value < median`. With `"minimize"`, prune if and only if `value > median`. Ties are never pruned.
- Any other `direction` raises `ValueError` in `__init__`.
Example:
```python
p = MedianPruner(n_startup_trials=2)
p.report(0, 0, 10.0); p.report(1, 0, 20.0); p.report(2, 0, 14.0)
p.should_prune(2, 0) # True: median of others {10, 20} = 15.0 > 14.0
```
```hint Data layout
Think about which lookup `should_prune` needs on every call. Indexing the stored values by step first turns the reference set into a single dictionary access.
```
```hint Order of the checks
Handle every early `False` case before computing a median. Watch that the trial's own value stays out of the reference set and that a value equal to the median is never pruned.
```
### What a Strong Answer Covers
- A storage layout where re-reporting overwrites and the values at one step come from a single lookup.
- The guard checks (warmup, missing value, empty or undersized reference set) applied before the median is computed.
- A reference set that excludes the trial being judged, and strict comparisons so ties survive in both directions.
- Direction validation in `__init__` and a plain Python `bool` as the return value.
- The cost of each call: constant per report and linear in the number of trials at that step per `should_prune`.
### Follow-up Questions
- How would you make the pruner less sensitive to noisy learning curves?
- How does a percentile pruner generalize this rule, and what does moving the percentile trade off?
- What changes if trials report at different, non-aligned steps?
Overview: Implement a median pruner for hyperparameter search that records intermediate trial values and decides whether a trial should stop early. It tests warmup and startup guards, building a reference set from the other trials at the same step, strict tie handling, and direction validation.