MacroLens / code /experiments /probes /lightgbm_ablation.py
itouchz's picture
Duplicate from macrolens/MacroLens
ff4becd
Raw
History Blame Contribute Delete
10.1 kB
"""LightGBM A->E context-ablation driver (Phase 2.1).
Runs the canonical :class:`LightGBMRegressor` across the five ablation
settings (A: OHLCV; B: +Fundamentals; C: +Macro; D: +Scenario flags;
E: +SBERT filing embeddings) on the four ablation tasks (T1 at the
panel-default horizon, T2, T4, T5). Twenty cells in total at the primary
seed; library-default LightGBM hyperparameters with no per-cell tuning
(per project memory: every benchmark cell uses library defaults).
The driver writes per-cell prediction pickles under
``experiments/predictions/`` using the same tag convention as
:mod:`experiments.run_all` (``<method>_<task>_seed<seed>_set<setting>.pkl``)
so a subsequent ``re_evaluate.py`` pass aggregates LightGBM rows into the
same A->E table that already houses the LLM ablation cells. The driver
also writes a flat JSON summary report at
``experiments/probes_output/lightgbm_ablation.json`` with the primary
metric per cell and cluster-bootstrap 95% CIs.
Per-launch authorisation: this is CPU-only and ~20 fits at moderate
sample sizes (T1 ~5M panel rows, T2/T5 ~1.3k snapshots, T4 ~4M scenario
rows); wall-clock estimate is well under one hour on the shared host.
The user must authorise each launch per the project's no-unauthorised-
runs policy.
"""
from __future__ import annotations
import argparse
import json
import logging
import pickle
import time
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
import numpy as np
logger = logging.getLogger(__name__)
# Primary metric per ablation task (mirrors the convention used by
# `gen_tables.py` for the LLM ablation column).
_PRIMARY_METRIC: dict[str, str] = {
"T1": "mse",
"T2": "medape",
"T4": "mae",
"T5": "medape",
}
# Cluster-key column per task (cluster_keys argument to ml.score).
_CLUSTER_KEY: dict[str, str] = {
"T1": "ticker",
"T2": "ticker",
"T4": "scenario_id",
"T5": "ticker",
}
@dataclass
class _CellReport:
task: str
setting: str
horizon: int | None
seed: int
n_train: int
n_test: int
primary_metric: str
value: float
ci_lo: float
ci_hi: float
fit_sec: float
predict_sec: float
def _cluster_keys(task: str, meta_test: Any) -> Any:
key = _CLUSTER_KEY[task]
if hasattr(meta_test, "columns") and key in meta_test.columns:
return meta_test[key].values
if hasattr(meta_test, "get"):
keys = meta_test.get(key)
if keys is not None:
return np.asarray(keys)
return None
def _save_predictions(
*,
pred_dir: Path,
method_id: str,
task: str,
seed: int,
setting: str,
granularity: str,
y_pred: Any,
y_test: Any,
meta_test: Any,
) -> Path:
pred_dir.mkdir(parents=True, exist_ok=True)
tag = f"{method_id}_{task}_seed{seed}_set{setting}"
out_path = pred_dir / f"{tag}.pkl"
tmp = out_path.with_suffix(".pkl.tmp")
with open(tmp, "wb") as f:
pickle.dump({
"method_id": method_id,
"task": task,
"seed": seed,
"granularity": granularity,
"ablation_setting": setting,
"y_pred": y_pred,
"y_test": y_test,
"meta_test": meta_test,
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
}, f)
tmp.replace(out_path)
return out_path
def run_cell(
*,
task: str,
setting: str,
granularity: str,
horizon: int | None,
seed: int,
pred_dir: Path,
method_id: str = "lightgbm",
) -> _CellReport:
"""Fit + predict + score a single (task, setting) cell."""
import macrolens as ml
load_kwargs: dict[str, Any] = {"granularity": granularity, "setting": setting}
if task == "T1" and horizon is not None:
load_kwargs["horizon"] = horizon
train = ml.load(task, "train", **load_kwargs)
test = ml.load(task, "test", **load_kwargs)
model = ml.methods.LightGBMRegressor(task=task)
t0 = time.perf_counter()
model.fit(train.X, train.y, seed=seed)
fit_sec = time.perf_counter() - t0
t1 = time.perf_counter()
y_pred = model.predict(test.X)
predict_sec = time.perf_counter() - t1
_save_predictions(
pred_dir=pred_dir, method_id=method_id, task=task, seed=seed,
setting=setting, granularity=granularity,
y_pred=y_pred, y_test=test.y, meta_test=test.meta,
)
metrics = ml.score(
task, test.y, y_pred,
cluster_keys=_cluster_keys(task, test.meta),
resample="cluster",
n_boot="adaptive",
seed=seed,
)
primary = _PRIMARY_METRIC[task]
mv = metrics[primary]
return _CellReport(
task=task,
setting=setting,
horizon=horizon if task == "T1" else None,
seed=seed,
n_train=int(len(train.y)) if hasattr(train.y, "__len__") else -1,
n_test=int(len(test.y)) if hasattr(test.y, "__len__") else -1,
primary_metric=primary,
value=float("nan") if mv.value is None else float(mv.value),
ci_lo=float("nan") if mv.ci_lo is None else float(mv.ci_lo),
ci_hi=float("nan") if mv.ci_hi is None else float(mv.ci_hi),
fit_sec=fit_sec,
predict_sec=predict_sec,
)
def run_ablation(
*,
tasks: tuple[str, ...] | None = None,
settings: tuple[str, ...] | None = None,
granularity: str = "daily",
horizon: int | None = None,
seed: int | None = None,
pred_dir: Path | None = None,
) -> dict[str, Any]:
"""Drive the full LightGBM A->E ablation grid.
Defaults match :mod:`experiments.panel`: tasks = ABLATION_TASKS,
settings = list(ABLATION_SETTINGS), horizon = ABLATION_T1_HORIZON,
seed = PRIMARY_SEED.
"""
from projects.agent_builder.scripts.whatif_bench.experiments import panel
tasks = tasks or panel.ABLATION_TASKS
settings = settings or tuple(panel.ABLATION_SETTINGS.keys())
# DRAFT.md (Fig. 3 caption / §5.4.1) reports the ablation at T1 h=252,
# not at panel.ABLATION_T1_HORIZON=21. Default to 252 so this driver
# produces cells that align with the paper's figure.
horizon = horizon if horizon is not None else 252
seed = seed if seed is not None else panel.PRIMARY_SEED
pred_dir = pred_dir or Path(__file__).resolve().parents[1] / "predictions"
reports: list[_CellReport] = []
for task in tasks:
for setting in settings:
logger.info("lightgbm ablation: task=%s setting=%s seed=%d horizon=%s",
task, setting, seed, horizon if task == "T1" else "-")
try:
cell = run_cell(
task=task, setting=setting, granularity=granularity,
horizon=horizon, seed=seed, pred_dir=pred_dir,
)
reports.append(cell)
logger.info(" -> %s=%.6g [%.6g, %.6g]",
cell.primary_metric, cell.value, cell.ci_lo, cell.ci_hi)
except Exception as exc:
logger.exception("cell failed for task=%s setting=%s: %s",
task, setting, exc)
# Record the failure but keep going; selective per-cell
# failures (e.g., missing setting-E SBERT embeddings on a
# task) must surface in the JSON report rather than abort
# the whole grid.
reports.append(_CellReport(
task=task, setting=setting,
horizon=horizon if task == "T1" else None,
seed=seed, n_train=-1, n_test=-1,
primary_metric=_PRIMARY_METRIC[task],
value=float("nan"), ci_lo=float("nan"), ci_hi=float("nan"),
fit_sec=float("nan"), predict_sec=float("nan"),
))
return {
"probe": "lightgbm_ablation",
"method_id": "lightgbm",
"granularity": granularity,
"horizon_T1": horizon,
"seed": seed,
"tasks": list(tasks),
"settings": list(settings),
"n_cells": len(reports),
"cells": [asdict(r) for r in reports],
}
def _default_probe_dir() -> Path:
# Probe outputs live under experiments/ (experiment artifacts),
# never under data_small_caps/ (raw + derived benchmark data).
return Path(__file__).resolve().parents[1] / "probes_output"
def main() -> int:
parser = argparse.ArgumentParser(
description="LightGBM A->E context-ablation driver.",
)
parser.add_argument("--granularity", default="daily")
parser.add_argument("--tasks", nargs="+", default=None,
help="Tasks to run (default: panel.ABLATION_TASKS).")
parser.add_argument("--settings", nargs="+", default=None,
help="Ablation settings to run (default: A B C D E).")
parser.add_argument("--horizon", type=int, default=None,
help="T1 horizon (default: 252, matching DRAFT.md Fig. 3 caption).")
parser.add_argument("--seed", type=int, default=None,
help="Seed (default: panel.PRIMARY_SEED).")
parser.add_argument("--pred-dir", type=Path, default=None,
help="Override the per-cell predictions directory.")
parser.add_argument("--output", type=Path, default=None,
help="Path to the summary JSON report.")
args = parser.parse_args()
logging.basicConfig(
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
)
report = run_ablation(
tasks=tuple(args.tasks) if args.tasks else None,
settings=tuple(args.settings) if args.settings else None,
granularity=args.granularity,
horizon=args.horizon,
seed=args.seed,
pred_dir=args.pred_dir,
)
out_path = args.output or _default_probe_dir() / "lightgbm_ablation.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(report, indent=2, default=str))
logger.info("ablation report written to %s", out_path)
return 0
if __name__ == "__main__":
raise SystemExit(main())