MacroLens / code /experiments /run_all.py
itouchz's picture
Upload experiments/ (runner, predictions, results, paper artifacts)
029e02e verified
Raw
History Blame Contribute Delete
43.7 kB
"""Phase-4 unified-API experiment orchestrator.
Thin runner that ties together:
data (``ml.load``) -> method (``ml.methods.<Class>``)
-> eval (``ml.score``)
-> :class:`macrolens.RunRecord`
-> JSON via ``pydantic.TypeAdapter``.
Every choice mirrors the unified-API plan §6 (RunRecord), §7 (Determinism
flag), and Phase-4 Pipeline B pseudocode.
Hard rules:
* Zero benchmark-data IO outside ``ml.load`` (this file is a leaf consumer).
* Methods/eval are accessed strictly via :mod:`macrolens` (no reaching into
private internals).
* The runner does NOT override hyperparameters except for two cases:
(i) T1 + ``Persistence`` — the runner reads the actual ``close`` index
out of ``meta_test.attrs["feature_names"]`` and overrides
``PersistenceConfig.close_feature_idx``;
(ii) opt-in ``--config-override`` flag (e.g. ``lightgbm.n_estimators=20``)
for fast smoke tests.
* LLM/LLM-TS/LLM-FT method families require an externally-managed vLLM
HTTP endpoint (one ``vllm serve`` per HF model id). The runner reads the
endpoint URL from a per-method environment variable
(``MACROLENS_LLM_BASE_URL_<NAME>`` — see :func:`_resolve_llm_engine`),
constructs one :class:`methods._openai_engine.OpenAIChatEngine` per
``(method_id, model_id)`` pair, and injects it via the ``engine=``
ctor kwarg. If no endpoint is configured for an LLM-family method, the
runner emits ``status="skip"`` with a clear ``error`` message — there
is NO silent fallback to a dry-run engine.
Usage::
python -m projects.agent_builder.scripts.whatif_bench.experiments \\
--task T1 T2 \\
--method persistence log_size_ols lightgbm \\
--granularity daily --seeds 42 --no-checkpoint
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import logging
import os
import platform
import subprocess
import sys
import time
import traceback
import tracemalloc
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from typing import Any, Iterable
import pydantic
from .. import config
from .. import macrolens as ml
from ..macrolens import RunRecord
from . import panel as panel_module
logger = logging.getLogger(__name__)
# ── Constants ─────────────────────────────────────────────────────────────
# Method families that talk to an externally-managed vLLM HTTP endpoint.
# The runner resolves one ``OpenAIChatEngine`` per family member from
# ``MACROLENS_LLM_BASE_URL_<NAME>`` and injects it via ``engine=``.
_LLM_FAMILIES: frozenset[str] = frozenset({"llm", "llm_ts", "llm_ft"})
# Hard cap on how much traceback text is recorded on a failed RunRecord
# so the result JSON stays bounded even when stack traces are huge.
_TRACEBACK_TRUNCATE_BYTES: int = 4 * 1024
# ── LLM engine resolution (env-var → OpenAIChatEngine) ────────────────────
def _llm_endpoint_env_var(method_id: str) -> str:
"""Canonical env-var name for a given LLM-family method id.
Mapping rule: uppercase the method id and prefix with
``MACROLENS_LLM_BASE_URL_``. Examples::
llama_scout -> MACROLENS_LLM_BASE_URL_LLAMA_SCOUT
gemma4 -> MACROLENS_LLM_BASE_URL_GEMMA4
chattime -> MACROLENS_LLM_BASE_URL_CHATTIME
time_mqa -> MACROLENS_LLM_BASE_URL_TIME_MQA
llm_finetuned -> MACROLENS_LLM_BASE_URL_LLM_FINETUNED
"""
return f"MACROLENS_LLM_BASE_URL_{method_id.upper()}"
# Process-global cache: one OpenAIChatEngine per (env-var, model_id) pair
# so all (task, seed) cells reuse the same HTTP client.
_LLM_ENGINE_CACHE: dict[tuple[str, str], Any] = {}
def _resolve_llm_engine(
method_id: str, cls: type,
) -> tuple[Any | None, str | None]:
"""Return ``(engine, error)`` for one LLM-family method.
Reads the endpoint URL from ``MACROLENS_LLM_BASE_URL_<METHOD_ID>``.
If unset, returns ``(None, "<reason>")`` so the runner can emit a
``status="skip"`` record. If set, constructs (or returns the cached)
:class:`methods._openai_engine.OpenAIChatEngine` and returns it.
Exception: methods whose authors' inference code is fundamentally
incompatible with the OpenAI chat API (ChatTime's 10K-bin numeric
tokenisation; Time-MQA's LoRA prompt protocol) are loaded in-process
from the vendored authors' code via a dedicated engine wrapper. They
do not require an env-var endpoint.
"""
# In-process engines for methods that can't be served via vllm-serve.
if method_id == "chattime":
try:
cfg = cls.default_config()
model_id = getattr(cfg, "model_id", "") or "ChengsenWang/ChatTime-1-7B-Chat"
except Exception:
model_id = "ChengsenWang/ChatTime-1-7B-Chat"
cache_key = ("inprocess:chattime", model_id)
cached = _LLM_ENGINE_CACHE.get(cache_key)
if cached is not None:
return cached, None
try:
from ..methods._chattime_engine import ChatTimeEngine
engine = ChatTimeEngine(model_path=model_id)
except Exception as exc:
return None, f"ChatTimeEngine construction failed: {exc!r}"
_LLM_ENGINE_CACHE[cache_key] = engine
return engine, None
env_var = _llm_endpoint_env_var(method_id)
base_url = os.environ.get(env_var, "").strip()
if not base_url:
return (
None,
f"No endpoint configured for {method_id}; "
f"set {env_var}=http://<host>:<port>/v1",
)
# Pull the model_id from the method's default config so the engine
# can target the matching ``model`` field on the vLLM endpoint.
try:
cfg = cls.default_config()
model_id = getattr(cfg, "model_id", "") or method_id
except Exception:
model_id = method_id
cache_key = (base_url, model_id)
cached = _LLM_ENGINE_CACHE.get(cache_key)
if cached is not None:
return cached, None
try:
from ..methods._openai_engine import OpenAIChatEngine
except ImportError as exc: # pragma: no cover -- defensive
return None, f"OpenAI client import failed: {exc!r}"
api_key = os.environ.get("MACROLENS_LLM_API_KEY", "EMPTY") or "EMPTY"
n_workers = int(os.environ.get("MACROLENS_LLM_N_WORKERS", "8"))
timeout = float(os.environ.get("MACROLENS_LLM_TIMEOUT_SEC", "300"))
try:
engine = OpenAIChatEngine(
base_url=base_url, api_key=api_key, model_id=model_id,
n_workers=n_workers, request_timeout_sec=timeout,
)
except Exception as exc:
return None, f"OpenAIChatEngine construction failed: {exc!r}"
_LLM_ENGINE_CACHE[cache_key] = engine
return engine, None
# ── Provenance helpers ────────────────────────────────────────────────────
def _git_sha() -> str:
"""Return the current git SHA, or ``"unknown"`` if outside a git tree."""
try:
out = subprocess.check_output(
["git", "rev-parse", "HEAD"], stderr=subprocess.DEVNULL,
)
return out.decode().strip()
except Exception:
return "unknown"
def _detect_hardware() -> dict[str, str]:
"""Best-effort hardware fingerprint (CPU + GPU + CUDA)."""
hw: dict[str, str] = {
"cpu": platform.processor() or platform.machine(),
"platform": platform.platform(),
"python_version": platform.python_version(),
}
try:
import torch # type: ignore
hw["torch_version"] = torch.__version__
if torch.cuda.is_available():
hw["gpu"] = torch.cuda.get_device_name(0)
hw["n_gpus"] = str(torch.cuda.device_count())
hw["cuda_version"] = str(torch.version.cuda)
else:
hw["gpu"] = "none"
hw["n_gpus"] = "0"
hw["cuda_version"] = "n/a"
except Exception:
hw["gpu"] = "unknown"
hw["n_gpus"] = "0"
hw["cuda_version"] = "n/a"
return hw
def _truncate_traceback(exc: BaseException) -> str:
tb = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
if len(tb) > _TRACEBACK_TRUNCATE_BYTES:
tb = tb[: _TRACEBACK_TRUNCATE_BYTES - 16] + "\n... [truncated]"
return tb
def _checkpoint_path(
method_id: str, task: str, granularity: str, seed: int,
horizon: int | None = None,
) -> Path:
"""Canonical per-run checkpoint directory.
For T1, ``horizon`` is included in the path so multiple horizons
on the same (method, task, granularity, seed) tuple each get their
own fresh fit/save state and never collide.
"""
base = (
Path(__file__).resolve().parent
/ "checkpoints"
/ method_id
/ task
/ granularity
/ f"seed={seed}"
)
if task == "T1" and horizon is not None:
base = base / f"h={horizon}"
return base
def _apply_overrides(config_overrides: dict[str, dict[str, Any]], method_id: str) -> dict[str, Any]:
"""Return the kwarg dict for one method (post-override)."""
return dict(config_overrides.get(method_id, {}))
def _now_iso() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat()
# ── Inner per-(method, seed) execution ─────────────────────────────────────
def _make_failed_record(
*,
method_id: str,
method_family: str,
task: str,
granularity: str,
seed: int,
status: str,
error: str,
n_train: int | None,
n_test: int | None,
hyperparams: dict[str, Any],
artifact_sha256: dict[str, str],
deterministic_mode: bool,
fit_time_sec: float | None = None,
predict_time_sec: float | None = None,
peak_mem_mb: float | None = None,
ablation_setting: str | None = None,
) -> RunRecord:
return RunRecord(
method_id=method_id, method_family=method_family,
task=task, granularity=granularity, seed=seed,
status=status, error=error,
n_train=n_train, n_test=n_test,
hyperparams=hyperparams,
lib_versions={}, hardware=_detect_hardware(),
fit_time_sec=fit_time_sec, predict_time_sec=predict_time_sec,
peak_mem_mb=peak_mem_mb, metrics=None,
artifact_sha256=artifact_sha256,
timestamp=_now_iso(), git_sha=_git_sha(),
deterministic_mode=deterministic_mode,
ablation_setting=ablation_setting,
)
def _sanity_gate(
task: str,
X_test: Any,
y_test: Any,
y_pred: Any,
y_train: Any,
meta_test: Any,
) -> str | None:
"""Persistence-/constant-floor sanity gate for regression tasks.
Compares the model's primary metric on the eval set against a trivial
reference floor (persistence for T1, train-median/-mean constant for
T2/T4/T5/T7). If model_metric > 10× baseline_metric (100× for T1's
persistence floor — kept tight because persistence is itself non-trivial)
the cell is flagged "suspect" via a returned reason string. T3 and T6
are long-form per-field tasks; their per-field MAPE floor is implicitly
the SectorMedian baseline already in the panel, so they are skipped here.
The gate is best-effort: any internal exception or shape mismatch
yields ``None`` so the runner never crashes on a sanity probe.
"""
try:
import numpy as _np
except Exception: # pragma: no cover -- numpy is a hard dep
return None
try:
# ── T1: persistence MSE floor ────────────────────────────────────
if task == "T1":
y_t = _np.asarray(y_test, dtype=_np.float64)
y_p = _np.asarray(y_pred, dtype=_np.float64)
close_last = None
if hasattr(meta_test, "columns") and "close_last" in meta_test.columns:
close_last = _np.asarray(
meta_test["close_last"].values, dtype=_np.float64,
)
elif hasattr(X_test, "shape") and getattr(X_test, "ndim", 0) == 3:
close_last = _np.asarray(X_test[:, -1, -1], dtype=_np.float64)
if (close_last is None
or y_t.ndim != 2 or y_p.ndim != 2
or y_t.shape != y_p.shape):
return None
tile = _np.broadcast_to(close_last[:, None], y_t.shape)
pers_mse = float(_np.nanmean((tile - y_t) ** 2))
model_mse = float(_np.nanmean((y_p - y_t) ** 2))
if not (_np.isfinite(pers_mse) and _np.isfinite(model_mse)
and pers_mse > 0):
return None
if model_mse > 100.0 * pers_mse:
return (
f"T1 SUSPECT: model_MSE={model_mse:.4g} > 100x "
f"persistence_MSE={pers_mse:.4g} on the same eval set; "
"model likely emitting un-normalised raw close instead "
"of per-window log-returns."
)
return None
# ── T2 / T5: constant (train-median) MAPE floor ─────────────────
if task in ("T2", "T5"):
y_tr = _np.asarray(y_train, dtype=_np.float64).ravel()
y_t = _np.asarray(y_test, dtype=_np.float64).ravel()
y_p = _np.asarray(y_pred, dtype=_np.float64).ravel()
if y_t.size == 0 or y_t.shape != y_p.shape:
return None
const = float(_np.nanmedian(y_tr))
if not _np.isfinite(const):
return None
denom = _np.abs(y_t)
mask = _np.isfinite(y_t) & _np.isfinite(y_p) & (denom > 0)
if not mask.any():
return None
const_mape = 100.0 * float(_np.nanmean(
_np.abs(const - y_t[mask]) / denom[mask]
))
model_mape = 100.0 * float(_np.nanmean(
_np.abs(y_p[mask] - y_t[mask]) / denom[mask]
))
if not (_np.isfinite(const_mape) and _np.isfinite(model_mape)
and const_mape > 0):
return None
if model_mape > 10.0 * const_mape:
return (
f"{task} SUSPECT: model_MAPE={model_mape:.4g} > 10x "
f"baseline_MAPE={const_mape:.4g} on the same eval set; "
"check method implementation"
)
return None
# ── T4: constant (train-mean) MAE floor on return % ─────────────
if task == "T4":
y_tr = _np.asarray(y_train, dtype=_np.float64).ravel()
y_t = _np.asarray(y_test, dtype=_np.float64).ravel()
y_p = _np.asarray(y_pred, dtype=_np.float64).ravel()
if y_t.size == 0 or y_t.shape != y_p.shape:
return None
const = float(_np.nanmean(y_tr))
if not _np.isfinite(const):
return None
mask = _np.isfinite(y_t) & _np.isfinite(y_p)
if not mask.any():
return None
const_mae = float(_np.nanmean(_np.abs(const - y_t[mask])))
model_mae = float(_np.nanmean(_np.abs(y_p[mask] - y_t[mask])))
if not (_np.isfinite(const_mae) and _np.isfinite(model_mae)
and const_mae > 0):
return None
if model_mae > 10.0 * const_mae:
return (
f"T4 SUSPECT: model_MAE={model_mae:.4g} > 10x "
f"baseline_MAE={const_mae:.4g} on the same eval set; "
"check method implementation"
)
return None
# ── T7: per-target constant (train-median) MAPE floors ──────────
if task == "T7":
try:
import pandas as _pd
except Exception: # pragma: no cover
return None
if not (isinstance(y_train, _pd.DataFrame)
and isinstance(y_test, _pd.DataFrame)
and isinstance(y_pred, _pd.DataFrame)):
return None
if "address" not in y_test.columns or "address" not in y_pred.columns:
return None
merged = y_test.merge(
y_pred, on="address", how="inner",
suffixes=("_actual", "_pred"),
)
if merged.empty:
return None
for target, pred_col in (("rent", "pred_rent"),
("price", "pred_price")):
actual_col = target if target in merged.columns else f"{target}_actual"
if pred_col not in merged.columns or actual_col not in merged.columns:
continue
if target not in y_train.columns:
continue
y_tr = _pd.to_numeric(y_train[target], errors="coerce").to_numpy()
const = float(_np.nanmedian(y_tr))
if not _np.isfinite(const):
continue
actual = _pd.to_numeric(merged[actual_col], errors="coerce").to_numpy()
pred = _pd.to_numeric(merged[pred_col], errors="coerce").to_numpy()
denom = _np.abs(actual)
mask = _np.isfinite(actual) & _np.isfinite(pred) & (denom > 0)
if not mask.any():
continue
const_mape = 100.0 * float(_np.nanmean(
_np.abs(const - actual[mask]) / denom[mask]
))
model_mape = 100.0 * float(_np.nanmean(
_np.abs(pred[mask] - actual[mask]) / denom[mask]
))
if not (_np.isfinite(const_mape) and _np.isfinite(model_mape)
and const_mape > 0):
continue
if model_mape > 10.0 * const_mape:
return (
f"T7 SUSPECT: model_{target}_MAPE={model_mape:.4g} "
f"> 10x baseline_{target}_MAPE={const_mape:.4g} on "
"the same eval set; check method implementation"
)
return None
# T3, T6 (long-form per-field tasks): skipped by design.
return None
except Exception: # noqa: BLE001 -- gate is best-effort
return None
def _run_one(
*,
method_id: str,
cls: type,
task: str,
granularity: str,
seed: int,
X_train: Any, y_train: Any, meta_train: Any,
X_test: Any, y_test: Any, meta_test: Any,
no_checkpoint: bool,
deterministic: bool,
extra_kwargs: dict[str, Any],
) -> RunRecord:
"""Run a single (method, seed) cell on already-loaded data."""
method_family = getattr(cls, "family", "unknown")
artifact_sha256: dict[str, str] = {
**(meta_train.attrs.get("data_sha256") or {}),
**(meta_test.attrs.get("data_sha256") or {}),
}
n_train, n_test = len(X_train), len(X_test)
ablation_setting = (
meta_test.attrs.get("ablation_setting")
if meta_test is not None else None
)
# T1 + Persistence: discover the close-feature index from train meta.
ctor_kwargs: dict[str, Any] = dict(extra_kwargs)
if task == "T1" and method_id == "persistence":
feat_names = meta_test.attrs.get("feature_names") or []
if "close" in feat_names:
ctor_kwargs["close_feature_idx"] = int(feat_names.index("close"))
# Ctor.
try:
model = cls(task=task, **ctor_kwargs)
except Exception as exc: # pragma: no cover -- defensive
return _make_failed_record(
method_id=method_id, method_family=method_family,
task=task, granularity=granularity, seed=seed,
status="fit_failed",
error=f"ctor: {_truncate_traceback(exc)}",
n_train=n_train, n_test=n_test,
hyperparams=ctor_kwargs, artifact_sha256=artifact_sha256,
deterministic_mode=deterministic,
ablation_setting=ablation_setting,
)
# For T1, derive horizon from y_test/y_train shape so the checkpoint path
# is horizon-specific. Without this, multiple horizons on the same
# (method, task, granularity, seed) tuple share one checkpoint dir; the
# first horizon's manifest gets loaded by every subsequent horizon and
# the runner silently emits wrong-shape predictions.
t1_horizon = None
if task == "T1":
try:
import numpy as _np # noqa: F401
y_ref = y_test if hasattr(y_test, "shape") else y_train
if hasattr(y_ref, "shape") and len(y_ref.shape) == 2:
t1_horizon = int(y_ref.shape[1])
except Exception:
t1_horizon = None
ckpt = _checkpoint_path(method_id, task, granularity, seed, horizon=t1_horizon)
manifest_path = ckpt / "manifest.json"
fit_time_sec: float | None = None
predict_time_sec: float | None = None
peak_mem_mb: float | None = None
# Fit (or load from checkpoint).
try:
if manifest_path.exists() and not no_checkpoint:
model = cls.load(ckpt) # type: ignore[attr-defined]
fit_time_sec = 0.0
# cls.load reconstructs state from disk and does NOT preserve
# injected runtime resources (the LLM-family engine, etc.).
# Re-attach any kwargs the runner originally injected so
# ``predict`` does not hit "no engine" failures on a checkpoint
# round-trip.
for k, v in ctor_kwargs.items():
if k in ("task",):
continue
setattr(model, k, v)
# Also propagate the X_train cache for LLM in-context fitting.
if method_family in _LLM_FAMILIES:
if hasattr(model, "_X_train"):
model._X_train = X_train
if hasattr(model, "_y_train"):
model._y_train = y_train
else:
tracemalloc.start()
t0 = time.perf_counter()
model.fit(X_train, y_train, seed=seed)
fit_time_sec = time.perf_counter() - t0
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
peak_mem_mb = peak / (1024.0 * 1024.0)
# Skip writing checkpoint state under ``--no-checkpoint`` —
# those files would never be loaded back (the load branch is
# gated on ``not no_checkpoint``) and just accumulate.
if not no_checkpoint:
try:
ckpt.mkdir(parents=True, exist_ok=True)
model.save(ckpt)
except Exception: # save failure is non-fatal for the run
logger.warning("checkpoint save failed for %s/%s/%s", method_id, task, seed)
except Exception as exc:
return _make_failed_record(
method_id=method_id, method_family=method_family,
task=task, granularity=granularity, seed=seed,
status="fit_failed",
error=_truncate_traceback(exc),
n_train=n_train, n_test=n_test,
hyperparams=model.hyperparams() if hasattr(model, "hyperparams") else ctor_kwargs,
artifact_sha256=artifact_sha256,
deterministic_mode=deterministic,
fit_time_sec=fit_time_sec, peak_mem_mb=peak_mem_mb,
ablation_setting=ablation_setting,
)
# Predict.
try:
t1 = time.perf_counter()
y_pred = model.predict(X_test)
predict_time_sec = time.perf_counter() - t1
# Save y_pred + y_test + meta to parquet/npz so eval can be RE-RUN
# later without re-doing the expensive predict step. One file per
# (method, task, seed, ablation_setting). Failures are non-fatal.
try:
import pickle
# Predictions are experimental outputs, not dataset content.
# Live alongside experiments/results/, not under data_small_caps/.
pred_dir = Path(__file__).parent / "predictions"
pred_dir.mkdir(parents=True, exist_ok=True)
tag = f"{method_id}_{task}_{granularity}_seed{seed}"
if task == "T1" and t1_horizon is not None:
tag += f"_h{t1_horizon}"
if ablation_setting:
tag += f"_set{ablation_setting}"
pred_path = pred_dir / f"{tag}.pkl"
tmp = pred_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": ablation_setting,
"y_pred": y_pred,
"y_test": y_test,
"meta_test": meta_test,
"timestamp": _now_iso(),
}, f)
tmp.replace(pred_path)
except Exception:
logger.warning("save predictions failed for %s/%s", method_id, task)
except Exception as exc:
return _make_failed_record(
method_id=method_id, method_family=method_family,
task=task, granularity=granularity, seed=seed,
status="predict_failed",
error=_truncate_traceback(exc),
n_train=n_train, n_test=n_test,
hyperparams=model.hyperparams(), artifact_sha256=artifact_sha256,
deterministic_mode=deterministic,
fit_time_sec=fit_time_sec, peak_mem_mb=peak_mem_mb,
ablation_setting=ablation_setting,
)
# Score.
try:
# Cluster keys: ticker for T1/T2/T3/T5/T6, scenario_id for T4,
# address for T7. Loader ``meta`` always carries the right column.
if task == "T4":
cluster_keys = (
meta_test["scenario_id"].values
if "scenario_id" in meta_test.columns
else None
)
elif task == "T7":
cluster_keys = (
meta_test["address"].values
if "address" in meta_test.columns
else None
)
elif "ticker" in meta_test.columns:
cluster_keys = meta_test["ticker"].values
else:
cluster_keys = None
score_kwargs: dict[str, Any] = {"cluster_keys": cluster_keys}
if task == "T1" and "close_last" in meta_test.columns:
score_kwargs["close_last"] = meta_test["close_last"].values
metrics = ml.score(task, y_test, y_pred, **score_kwargs)
except Exception as exc:
return _make_failed_record(
method_id=method_id, method_family=method_family,
task=task, granularity=granularity, seed=seed,
status="score_failed",
error=_truncate_traceback(exc),
n_train=n_train, n_test=n_test,
hyperparams=model.hyperparams(), artifact_sha256=artifact_sha256,
deterministic_mode=deterministic,
fit_time_sec=fit_time_sec, predict_time_sec=predict_time_sec,
peak_mem_mb=peak_mem_mb,
ablation_setting=ablation_setting,
)
# If eval returned a primary metric of None (NaN-only signal — happens
# when an LLM emits non-canonical field names so the inner-join finds
# 0 valid (ticker, FY, field) tuples), surface the cell as
# ``score_failed`` rather than ``status=ok`` with a None metric. This
# keeps the no-silent-NaN rule honest at the runner level.
_PRIMARY_METRIC = {
"T1": "mse", "T2": "median_ape", "T3": "overall_mape",
"T4": "return_mae_pct", "T5": "median_ape", "T6": "overall_mape",
"T7": "rent_MAPE",
}
primary_key = _PRIMARY_METRIC.get(task)
primary_mv = (metrics or {}).get(primary_key) if primary_key else None
primary_value = (
primary_mv.value if primary_mv is not None
and hasattr(primary_mv, "value") else None
)
if primary_value is None:
return _make_failed_record(
method_id=method_id, method_family=method_family,
task=task, granularity=granularity, seed=seed,
status="score_failed",
error=(
f"primary metric '{primary_key}' is None on {task}; "
"predictions did not produce any valid (canonical) "
"match against y_true (e.g. all preds NaN, or non-canonical "
"field names). Refusing to record status=ok."
),
n_train=n_train, n_test=n_test,
hyperparams=model.hyperparams(), artifact_sha256=artifact_sha256,
deterministic_mode=deterministic,
fit_time_sec=fit_time_sec, predict_time_sec=predict_time_sec,
peak_mem_mb=peak_mem_mb,
ablation_setting=ablation_setting,
)
# ── Per-task persistence/constant-floor sanity gate ─────────────────
# Blow-up guard: when a regression model's primary metric is
# >> the trivial-baseline floor on the same eval set it is emitting
# nonsense (e.g. T1 trained on raw close instead of log-returns —
# MSE 1e10-1e16; T2/T5 mis-scaled valuations; T4 wrong sign on
# returns; T7 unit-mixed rent/price). The gate covers T1, T2, T4,
# T5, T7. T3 / T6 are long-form per-field tasks whose floor is
# implicitly the SectorMedian baseline and are skipped here.
suspect_reason: str | None = _sanity_gate(
task, X_test, y_test, y_pred, y_train, meta_test,
)
if suspect_reason is not None:
logger.warning(suspect_reason)
return RunRecord(
method_id=method_id, method_family=method_family,
task=task, granularity=granularity, seed=seed,
status="ok", error=suspect_reason,
n_train=n_train, n_test=n_test,
hyperparams=model.hyperparams(),
lib_versions=model.lib_versions(),
hardware=_detect_hardware(),
fit_time_sec=fit_time_sec, predict_time_sec=predict_time_sec,
peak_mem_mb=peak_mem_mb, metrics=metrics,
artifact_sha256=artifact_sha256,
timestamp=_now_iso(), git_sha=_git_sha(),
deterministic_mode=deterministic,
ablation_setting=meta_test.attrs.get("ablation_setting") if meta_test is not None else None,
)
def _seed_dispatch(args_tuple: tuple) -> RunRecord:
"""Process-pool entry point — unpack args and call :func:`_run_one`."""
return _run_one(**args_tuple)
# ── Public API ────────────────────────────────────────────────────────────
def run_all(
tasks: list[str],
methods_list: list[str],
granularity: str = "daily",
*,
seeds: Iterable[int] = (42,),
deterministic: bool = False,
no_checkpoint: bool = False,
multi_seed_parallel: bool = False,
config_overrides: dict[str, dict[str, Any]] | None = None,
output_path: Path | None = None,
setting: str | None = None,
horizon: int | None = None,
lookback: int | None = None,
) -> list[RunRecord]:
"""Run every (task, method, seed) cell and persist :class:`RunRecord` JSON.
Parameters
----------
tasks
Task ids in ``{"T1","T2","T3","T4","T5","T6","T7"}``.
methods_list
Registry ids (matching ``ml.methods.ALL_METHODS`` keys).
granularity
``"daily"`` (default) | ``"weekly"`` | ``"monthly"``.
seeds
Iterable of integer seeds. Default ``(42,)``.
deterministic
When True, set ``MACROLENS_DETERMINISTIC=1`` and call
``torch.use_deterministic_algorithms(True)`` once before any
method runs.
no_checkpoint
When True, ignore any existing checkpoint and re-train; new
checkpoints are still written.
multi_seed_parallel
When True, dispatch one process per seed via
:class:`concurrent.futures.ProcessPoolExecutor`.
config_overrides
Mapping ``{method_id: {kwarg: value, ...}}`` forwarded to the
method ctor (single-step override path used by the runner-side
``--config-override`` flag).
output_path
When supplied, write the JSON list to this exact path; otherwise
write to ``<data_root>/results/<git_sha>_<utc_timestamp>.json``.
Returns
-------
list[RunRecord]
Every emitted record (including ``status != "ok"`` failures and
deferred-LLM ``status == "skip"`` placeholders).
"""
if deterministic:
os.environ["MACROLENS_DETERMINISTIC"] = "1"
try:
import torch # type: ignore
torch.use_deterministic_algorithms(True)
if hasattr(torch.backends, "cudnn"):
torch.backends.cudnn.deterministic = True
except Exception:
pass
overrides = config_overrides or {}
seed_list = list(seeds)
records: list[RunRecord] = []
adapter = pydantic.TypeAdapter(list[RunRecord])
# Resolve the output path eagerly so we can checkpoint after every cell.
if output_path is None:
ts = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
sha_short = _git_sha()[:8] if _git_sha() != "unknown" else "nogit"
# Experiment outputs live under experiments/, NOT under
# data_small_caps/ (raw + derived benchmark data only).
results_dir = Path(__file__).resolve().parent / "results"
results_dir.mkdir(parents=True, exist_ok=True)
output_path = results_dir / f"{sha_short}_{ts}.json"
else:
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
def _flush() -> None:
"""Atomic-rename incremental write so a SIGTERM mid-run loses ~0 records."""
tmp = output_path.with_suffix(".json.tmp")
tmp.write_bytes(adapter.dump_json(records, indent=2))
tmp.replace(output_path)
def _log_cell(method_id: str, task_id: str, family: str, status: str,
fit_s: float | None, pred_s: float | None,
metrics: dict | None) -> None:
m_str = ""
if metrics:
primary_keys = ("mse", "mape", "median_ape", "return_mae_pct",
"rent_MAPE", "overall_mape", "n_predictions")
for k in primary_keys:
if k in metrics and hasattr(metrics[k], "value"):
v = metrics[k].value
m_str = f" {k}={'None' if v is None else f'{v:.4g}'}"
break
ft = f"{fit_s:.1f}s" if fit_s is not None else "-"
pt = f"{pred_s:.1f}s" if pred_s is not None else "-"
print(f" [{len(records):>3d}] {family:10s} {method_id:18s} {task_id} "
f"status={status:14s} fit={ft:>6s} predict={pt:>6s}{m_str}",
flush=True)
print(f"output_path={output_path}", flush=True)
if setting is not None:
valid = {"A", "B", "C", "D", "E"}
if setting not in valid:
raise ValueError(f"setting must be in {valid} or None, got {setting!r}")
print(f"ablation setting={setting}", flush=True)
for task in tasks:
print(f"\n=== task={task} === loading data...", flush=True)
t0 = time.perf_counter()
load_kwargs: dict[str, Any] = {"granularity": granularity}
if horizon is not None and task == "T1":
load_kwargs["horizon"] = horizon
if lookback is not None and task in ("T1", "T4"):
load_kwargs["lookback"] = lookback
if setting is not None:
if task in ("T3", "T6", "T7"):
print(f" skipping task={task} for ablation (not in ABLATION_TASKS)",
flush=True)
continue
load_kwargs["setting"] = setting
X_train, y_train, meta_train = ml.load(task, "train", **load_kwargs)
X_test, y_test, meta_test = ml.load(task, "test", **load_kwargs)
print(f" loaded in {time.perf_counter()-t0:.1f}s "
f"(n_train={len(X_train)}, n_test={len(X_test)})", flush=True)
for method_name in methods_list:
cls = ml.methods.ALL_METHODS.get(method_name)
if cls is None:
logger.warning("method '%s' not registered; skipping", method_name)
continue
if task not in cls.tasks:
continue # silent skip per plan
method_family = getattr(cls, "family", "unknown")
extra_kwargs = _apply_overrides(overrides, method_name)
# LLM/LLM-TS/LLM-FT families require an externally-managed vLLM
# HTTP endpoint. Missing endpoint is a hard error — fail loudly
# rather than emitting a silent placeholder.
if method_family in _LLM_FAMILIES:
engine, err = _resolve_llm_engine(method_name, cls)
if engine is None:
raise RuntimeError(
f"{method_name} requires an LLM endpoint but "
f"{_llm_endpoint_env_var(method_name)} is unset. "
f"Reason: {err}. Either serve the endpoint and set "
f"the env var, or omit this method from --method."
)
# Engine resolved — inject via the ctor kwarg path.
extra_kwargs = {**extra_kwargs, "engine": engine}
if multi_seed_parallel and len(seed_list) > 1:
payloads = [
{
"method_id": method_name, "cls": cls,
"task": task, "granularity": granularity, "seed": seed,
"X_train": X_train, "y_train": y_train, "meta_train": meta_train,
"X_test": X_test, "y_test": y_test, "meta_test": meta_test,
"no_checkpoint": no_checkpoint,
"deterministic": deterministic,
"extra_kwargs": extra_kwargs,
}
for seed in seed_list
]
with ProcessPoolExecutor(max_workers=len(seed_list)) as ex:
futs = [ex.submit(_seed_dispatch, p) for p in payloads]
for fut in as_completed(futs):
rec = fut.result()
records.append(rec)
_log_cell(method_name, task, method_family, rec.status,
rec.fit_time_sec, rec.predict_time_sec,
rec.metrics)
_flush()
else:
for seed in seed_list:
rec = _run_one(
method_id=method_name, cls=cls,
task=task, granularity=granularity, seed=seed,
X_train=X_train, y_train=y_train, meta_train=meta_train,
X_test=X_test, y_test=y_test, meta_test=meta_test,
no_checkpoint=no_checkpoint,
deterministic=deterministic,
extra_kwargs=extra_kwargs,
)
records.append(rec)
_log_cell(method_name, task, method_family, rec.status,
rec.fit_time_sec, rec.predict_time_sec, rec.metrics)
_flush()
_flush()
logger.info("Wrote %d records to %s", len(records), output_path)
print(f"\n=== {len(records)} records written to {output_path} ===", flush=True)
return records
# ── CLI plumbing (kept here for `python -m experiments.run_all` callers) ──
def _parse_overrides(raw: list[str]) -> dict[str, dict[str, Any]]:
"""Parse ``--config-override 'method.key=value'`` flags into a dict."""
overrides: dict[str, dict[str, Any]] = {}
for spec in raw:
if "=" not in spec or "." not in spec.split("=", 1)[0]:
raise ValueError(
f"--config-override expects 'method.key=value', got {spec!r}"
)
lhs, value = spec.split("=", 1)
method_id, key = lhs.split(".", 1)
# Coerce value: try int, then float, then bool, else str.
casted: Any = value
for caster in (int, float):
try:
casted = caster(value)
break
except ValueError:
continue
if isinstance(casted, str) and casted.lower() in ("true", "false"):
casted = casted.lower() == "true"
overrides.setdefault(method_id, {})[key] = casted
return overrides
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--task", nargs="+", required=True,
choices=["T1", "T2", "T3", "T4", "T5", "T6", "T7"])
parser.add_argument("--method", nargs="+", required=True,
help="Registry method ids (e.g. persistence lightgbm)")
parser.add_argument("--granularity", default="daily",
choices=["daily", "weekly", "monthly"])
parser.add_argument("--seeds", type=int, nargs="+", default=[42])
parser.add_argument("--deterministic", action="store_true")
parser.add_argument("--no-checkpoint", action="store_true")
parser.add_argument("--multi-seed-parallel", action="store_true")
parser.add_argument(
"--config-override", action="append", default=[],
help=("Override a single method ctor kwarg, e.g. "
"'lightgbm.n_estimators=20'. Repeatable."),
)
parser.add_argument("--output", type=Path, default=None,
help="Optional explicit output path.")
parser.add_argument(
"--setting", choices=["A", "B", "C", "D", "E"], default=None,
help=("Ablation feature-tier (A: OHLCV; B: +Fundamentals; "
"C: +Macro; D: +Scenario flags; E: D + filing text in prompt). "
"Applies to T1, T2, T4, T5 only; T3/T6/T7 silently skipped."),
)
parser.add_argument(
"--horizon", type=int, default=None,
help=("Forecast horizon for T1; ignored for T2-T7. Default: longest "
"canonical horizon for the granularity "
"(daily=252, weekly=52, monthly=12)."),
)
parser.add_argument(
"--lookback", type=int, default=None,
help=("Lookback window length for T1/T4; ignored for non-sequence "
"tasks. Default: shortest canonical lookback for the granularity "
"(daily=63, weekly=13, monthly=3). Use a longer value (e.g. "
"monthly=12) for architectures whose downsample stack needs "
"more timesteps."),
)
args = parser.parse_args(argv)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
datefmt="%H:%M:%S",
)
overrides = _parse_overrides(args.config_override)
run_all(
tasks=args.task, methods_list=args.method,
granularity=args.granularity, seeds=args.seeds,
deterministic=args.deterministic,
no_checkpoint=args.no_checkpoint,
multi_seed_parallel=args.multi_seed_parallel,
config_overrides=overrides,
output_path=args.output,
setting=args.setting,
horizon=args.horizon,
lookback=args.lookback,
)
return 0
if __name__ == "__main__": # pragma: no cover
sys.exit(main())