Coding Advice

This is the section that makes the artifact useful. Below is the actual committed train.py — the only mutable surface in a Klein v2 study — followed by the pitfalls that bit this study and the seven pieces of transferable advice they earned.

The winning train.py, verbatim

Read it for its shape first. It is 114 lines and it contains no model code at all: constructors live in the frozen study library pipeline.py, the metric lives in the framework registry, and the per-experiment surface is a nine-line CONFIG block. That is the point — a 5–15 line diff per candidate is only possible if everything else is already immovable.



Annotated: the five things this file does that matter

  1. The CONFIG block is the entire experiment surface. Seven named configs, a seed, three capacity knobs and an INTERACTIONS tuple. Every one of the twelve ledger rows is a diff inside those nine lines. The comment on INTERACTIONS — "surrogate-derived only" — is the data-card's lookahead directive written where the person editing the file will see it.
  2. It refuses to run outside the harness. KLEIN_EVALUATION_KIND, KLEIN_EXPERIMENT_ID and KLEIN_TRACK must all be present or it raises. A file that can be run by hand is a file whose results can end up unlogged.
  3. The split-identity anchor fires before any model fits. On every development run it recomputes the intercept-only deviance and compares it to the frozen reference cell at 1e−9. If the split, the prep or the weights ever drift, the study stops immediately rather than producing plausible-looking numbers on different data.
  4. wall_seconds is passed explicitly through extra. It looks decorative. It is load-bearing — friction F1 below.
  5. The sealed branch exports per-row predictions. A sealed access is spent once, so it must yield everything downstream analysis will ever need: the joined prediction tables are what the off-ledger sealed-gap and paired-SE computation ran on, and what a pricing-eval double-lift card would consume.

War stories — the traps that actually fired

F1 — a guardrail metric that is written but not printed

E0001 printed the anchor-exact 0.454861 and was still dispositioned discard: "guardrail metric wall_seconds missing". evaluate_regression writes wall_seconds to aux_metrics.tsv, but the runner's guardrail check reads the printed canonical block. One experiment slot, gone.

# the one-line fix that un-burned the slot (E0002's candidate diff):
extra={"model_config": MODEL, "wall_seconds": time.time() - t0}
#                              ^^^^^^^^^^^^^^ not decorative

Transferable rule: a declared guardrail must appear in whatever surface the checker actually reads. If your harness reads stdout, write it to stdout.

F2 — per-track state that was derived once, at scaffold time

E0012 was refused: "sealed final-test state is missing for track 'gbdt'". klein new scaffolds a single track, and the initial state derives its final_holdout_access keys from the tracks that existed then. Adding a second track by editing study.yaml — the only way to build a two-track study today — leaves that map stale, and state loading performs no reconciliation.

Transferable rule: any state map derived from a contract must be topped up from the contract at load time, not frozen at creation. Both frictions are filed as framework fixes in section 7 — each one cost a real experiment slot.

The CatBoost prediction-space trap

CatBoostRegressor.predict returns RawFormulaVal — a log — for most losses, and Exponent only for Poisson and Tweedie if you ask. Handing raw scores to a Poisson deviance produces a nonsense number, or gets rejected by the positivity guard, which is the lucky outcome. The call site is frozen in the study library and never inlined in train.py:

class CatBoostPoisson:
    """CatBoost with Poisson loss on the raw frame (native categoricals).
    predict() must return expected counts (exp space), not the raw score."""

    def predict(self, X: pd.DataFrame) -> np.ndarray:
        return np.asarray(self.model.predict(X, prediction_type="Exponent"), dtype=float)

The registry refuses non-positive predictions — by contract

Poisson deviance needs strictly positive μ, and the metric registry raises rather than silently clipping. That is the right contract, but it means every estimator needs a wrapper — which is also the natural place to replay the stateless frame-level transform at predict time, so that fit and predict can never diverge:

class ClippedRegressor:
    def predict(self, X: pd.DataFrame) -> np.ndarray:
        X = _transform_frame(X, shaped=self.shaped, interactions=self.interactions)
        return np.clip(np.asarray(self.inner.predict(X), dtype=float), MIN_PRED, None)

Scoping the spline basis — the study-04 fix, in three lines

Study 04 splined everything the transformer was handed, including the one-hot dummies. The scoped version puts the spline pipeline on the three continuous rating factors only:

("spline", Pipeline([("scale", StandardScaler()),
                     ("spline", SplineTransformer(n_knots=6, degree=3))]), SPLINED),
("num",    StandardScaler(), rest + inter_cols),
("cat",    OneHotEncoder(handle_unknown="ignore", min_frequency=20), CATEGORICAL),

The punchline from section 5 is worth repeating here: this fix was correct, hygienic, and changed the answer by −0.8 percentage points. Splining a 0/1 column is a no-op in expressiveness. Fix it because it is right, not because you expect it to buy signal.

Monotone constraints index the input columns

The constraint vector is one entry per input feature, categoricals must be 0, and the whole config therefore has to switch to the native-categorical encoder so the index order is the raw NUMERIC + CATEGORICAL order the vector assumes. That is two changes at once, which is exactly why RQ7 needed a same-encoding control:

pre = build_preprocessor(NUMERIC, CATEGORICAL, kind="native")
cst = [1 if c == "BonusMalus" else 0 for c in NUMERIC] + [0] * len(CATEGORICAL)

The effective-capacity probe

Three libraries, three different attributes, one aux column. Without this the RQ2 verdict would have compared 67 trees to 200 and called it "matched capacity":

def effective_trees(clipped) -> float:
    if isinstance(est, HistGradientBoostingRegressor): return float(est.n_iter_)
    if isinstance(inner, CatBoostPoisson):             return float(inner.model.tree_count_)
    if hasattr(est, "booster_"):                       return float(est.booster_.num_trees())
    return float("nan")   # deterministic GLMs: no tree count

The seven transferable rules

  1. [C8] Run the translate-back programme as a screen with a budget, not as a search. Distil the black box on the train fold only into an interpretable surrogate, rank candidate structure by residual explanation, then adopt on development only above the measured floor — and publish screened / adopted either way. Here that was 10 screened, 0 adopted, and the honest zero is a stronger result than any of the ten "improvements" a floor-free search would have reported.
  2. [C9] Report the GAP, never the levels. 26.54% of development rows and 26.37% of sealed-test rows have a feature-identical twin in train, and the three partitions differ in exposure-weighted frequency by ±1.3%. Both effects hit both tracks identically, so the difference survives what the levels do not — as the A/E flip demonstrates, with no model change whatsoever.
  3. [C10] Log EFFECTIVE capacity on every boosted row before you claim a library difference — or a library tie. max_iter / n_estimators / iterations are nominal; n_iter_, booster_.num_trees(), tree_count_ are what you fitted. HGBT early-stops above 10,000 samples by default and delivered 67 of a nominal 200. Match on the effective number and re-run before writing the verdict.
  4. [C11] Measure the paired floor that governs YOUR comparison before believing any gap. There is more than one floor and they differ by a factor of five or more: a GLM fit-seed std of exactly 0 (deterministic solver — quoting a seed floor for a GLM is meaningless), a GBDT fit-seed std of 0.000210, within-track paired SEs of 0.000270 / 0.000287, and a cross-track paired SE of 0.000963 — 4.6× the GBDT seed floor and the only one that legitimately bands the headline gap. Use common random numbers and bootstrap the difference, not the two levels.
  5. [C12] Size-gate the model class before you spend a week on it. Refit both candidates on nested subsamples of your own train fold and plot the gap against n: seven fits, 14 seconds here, and it tells you whether the boosted model is worth its governance overhead at all. Below the crossover a filed additive GLM is not a concession — it is the better model.
  6. [C13] Price a shape constraint against a control that differs ONLY by the constraint, and check the MARGINAL shape first so you know what you are pricing. Differencing against a differently-encoded incumbent measures constraint plus encoding (4.8× floor); the same-encoding control isolates the constraint (3.7×). And confirm the empirical direction before interpreting: a constraint that is true on the margin can still be expensive, because it is the conditional version the library enforces.
  7. [C14] Start the next study from checklist.md, not from findings.md. The transferable product of this study is a seven-row dataset-characteristics → method-choice checklist shipped alongside the findings; each row names the measurable property of your data, the cheap way to measure it, the method choice it implies, and the claim ID that earned it. Read the checklist to decide; read the findings to audit the decision.

And one rule the harness enforces for you

Every candidate is committed before it runs, and a non-keep restores train.py to the pre-candidate base commit while leaving the candidate commit resolvable. This study's most-cited rows — E0007 and E0008 at 0.43× and 0.45× floor, E0009's 3.7×-floor constraint cost — are all discards. Negative evidence is evidence, and it is only citable if the loop kept it.