Download code/experiments/panel.py from DeepAuto-AI/MacroLens: direct link, hf CLI and curl.
- Browser
- Download file 21.2 kB
-
https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/experiments/panel.py
- Command line
-
hf download hf://datasets/DeepAuto-AI/MacroLens/code/experiments/panel.py
-
curl -L -o panel.py https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/experiments/panel.py
21.2 kB
| """Canonical MacroLens baseline panel for the NeurIPS 2026 D&B submission. | |
| Single source of truth for: | |
| - Which methods are in the panel (18 method classes across 7 families) | |
| - Which tasks each method covers (T1..T7) | |
| - HuggingFace model IDs for LLM/TSFM checkpoints (FP8 native MLLMs) | |
| - GPU parallelism hints (tensor-parallel size) | |
| - Seed strategy (primary seed vs headline T1 subset) | |
| - Ablation subset (5 models x 5 settings on T1 h=21 + T4) | |
| Any change to the panel MUST happen here first; all family runners import from | |
| this module. If a method is not in `ALL_METHODS`, the orchestrators will not | |
| run it. If a HuggingFace ID changes, update this file only. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| from typing import Literal | |
| # ── Task IDs ────────────────────────────────────────────────────────────── | |
| Task = Literal["T1", "T2", "T3", "T4", "T5", "T6", "T7"] | |
| ALL_TASKS: tuple[Task, ...] = ("T1", "T2", "T3", "T4", "T5", "T6", "T7") | |
| TASK_METADATA: dict[Task, dict] = { | |
| "T1": {"name": "TSF", "long": "Contextual Time-Series Forecasting", | |
| "primary_metric": "MSE"}, | |
| "T2": {"name": "Val-PT", "long": "Point-in-Time Equity Valuation", | |
| "primary_metric": "MedAPE"}, | |
| "T3": {"name": "Stmt-Gen", "long": "Statement Generation", | |
| "primary_metric": "per-field MAPE"}, | |
| "T4": {"name": "Scen-Ret", "long": "Scenario-Conditioned Return Forecasting", | |
| "primary_metric": "Return MAE"}, | |
| "T5": {"name": "Priv-Val", "long": "Private-Company Valuation", | |
| "primary_metric": "MedAPE"}, | |
| "T6": {"name": "Gen-Eval", "long": "Generator Evaluation", | |
| "primary_metric": "per-field MAPE"}, | |
| "T7": {"name": "RE-Val", "long": "Real-Estate Valuation", | |
| "primary_metric": "Rent + Price MAPE"}, | |
| } | |
| # ── Method definitions ──────────────────────────────────────────────────── | |
| Family = Literal[ | |
| "naive", "classical", "sequence", | |
| "tsfm", | |
| "llm_ts", | |
| "llm", | |
| ] | |
| class Method: | |
| """Single entry in the baseline panel.""" | |
| id: str # e.g. "persistence", "chronos2_zs" | |
| name: str # display name, e.g. "Persistence" | |
| family: Family | |
| tasks: frozenset[Task] # tasks this method runs on | |
| hf_id: str | None = None # HuggingFace repo id (for LLM/TSFM) | |
| notes: str = "" # free-form context (size, quant, TP) | |
| # ── Family 1: Naive (4 methods) ─────────────────────────────────────────── | |
| # Deterministic heuristics and non-parametric lookups (no fitted parameters). | |
| NAIVE_METHODS: tuple[Method, ...] = ( | |
| Method("persistence", "Persistence", "naive", | |
| frozenset({"T1"}), | |
| notes="Repeat last close (T1); repeat pre-event level (T4)."), | |
| Method("sector_median", "Sector-Median", "naive", | |
| frozenset({"T3", "T6"}), | |
| notes="Predict each XBRL field as its sector median."), | |
| Method("metro_median", "Metro-Median", "naive", | |
| frozenset({"T7"}), | |
| notes="Median rent/price in the same metro."), | |
| Method("historical_analogue", "Historical Analogue", "naive", | |
| frozenset({"T4"}), | |
| notes="Find nearest past scenario by type; reuse its post-event return."), | |
| ) | |
| # ── Family 2: Classical ML (2 methods) ──────────────────────────────────── | |
| # Fitted parametric models (OLS regression, gradient-boosted trees). | |
| CLASSICAL_METHODS: tuple[Method, ...] = ( | |
| Method("random_forest", "RandomForest", "classical", | |
| frozenset(ALL_TASKS), | |
| notes="200 trees, max_depth=16, min_samples_leaf=5; sklearn RandomForestRegressor with per-task adapters mirroring LightGBM (log-return target on T1, log-target pipeline on T2/T5/T7, sparse field one-hot on T3/T6, flatten+event-type one-hot on T4)."), | |
| Method("lightgbm", "LightGBM", "classical", | |
| frozenset(ALL_TASKS), | |
| notes=( | |
| "300 trees, num_leaves=63, histogram binning; trained on " | |
| "137-feature panel. Chosen over XGBoost for 2-5x training " | |
| "speedup with essentially identical accuracy on financial " | |
| "tabular data." | |
| )), | |
| ) | |
| # ── Family 3: Deep Sequence (3 methods) ─────────────────────────────────── | |
| SEQUENCE_METHODS: tuple[Method, ...] = ( | |
| Method("dlinear", "DLinear", "sequence", | |
| frozenset({"T1", "T4"}), | |
| notes="Linear decomposition baseline."), | |
| Method("itransformer", "iTransformer", "sequence", | |
| frozenset({"T1", "T4"}), | |
| notes=( | |
| "Inverted transformer (variables-as-tokens); d=128, 4 heads. " | |
| "Chosen over PatchTST as the transformer representative: " | |
| "its cross-variable attention matches the 137-feature " | |
| "multivariate structure of MacroLens better than PatchTST's " | |
| "channel-independent formulation." | |
| )), | |
| Method("moderntcn", "ModernTCN", "sequence", | |
| frozenset({"T1", "T4"}), | |
| notes="Modern pure-convolution backbone."), | |
| ) | |
| # ── Family 4: TSFM Zero-Shot (3 methods) ────────────────────────────────── | |
| # Sundial was dropped from the panel because its modeling code (HF Hub | |
| # `thuml/sundial-base-128m`, vendored via `trust_remote_code`) requires | |
| # transformers==4.40.x and is incompatible with transformers>=4.45 (used here | |
| # for vLLM 0.20 + Llama-4 / Gemma-4 / Qwen-3.5 FP8 LLMs); the cascade includes | |
| # DynamicCache.get_usable_length removal, _prepare_4d_causal_attention_mask | |
| # shape mismatch under Sundial's patching, apply_rotary_pos_emb position-id | |
| # scale mismatch, and TSGenerationMixin._extract_past_from_model_output | |
| # removal in GenerationMixin >=4.45. Documented and removed rather than | |
| # patched into a parallel transformers env. | |
| TSFM_ZS_METHODS: tuple[Method, ...] = ( | |
| Method("chronos2", "Chronos-2", "tsfm", | |
| frozenset({"T1"}), | |
| hf_id="amazon/chronos-2", | |
| notes="Probabilistic multivariate; frozen checkpoint."), | |
| Method("moirai2", "Moirai 2.0", "tsfm", | |
| frozenset({"T1"}), | |
| hf_id="Salesforce/moirai-2.0-R-small", | |
| notes="Any-variate universal forecaster."), | |
| Method("timesfm", "TimesFM", "tsfm", | |
| frozenset({"T1"}), | |
| hf_id="google/timesfm-1.0-200m-pytorch", | |
| notes=( | |
| "Decoder-only foundation; TimesFM 1.0 (200M, 20 transformer " | |
| "layers). The 2.0 checkpoint (500M, 50 layers) requires a " | |
| "newer `timesfm` package version than the one currently " | |
| "installed; revisit once upgraded." | |
| )), | |
| ) | |
| # ── Family 5: LLM-TS Multi-Task (2 methods) ─────────────────────────────── | |
| # Note: "LLM-TS Forecasting" family (CALF, TimeReasoner) was removed from the | |
| # panel; the LLM-TS Multi-Task family covers the "LLM adapted for time-series" | |
| # story across all 7 tasks, subsuming the forecast-only variants. | |
| LLM_TS_MULTITASK_METHODS: tuple[Method, ...] = ( | |
| Method("chattime", "ChatTime", "llm_ts", | |
| frozenset(ALL_TASKS), | |
| notes="LLaMA-2-7B + 10K-bin tokenisation."), | |
| Method("time_mqa", "Time-MQA", "llm_ts", | |
| frozenset(ALL_TASKS), | |
| notes="Mistral-7B + LoRA r=16; 192,843 QA pairs."), | |
| ) | |
| # ── LLM models ──────────────────────────────────────────────────────────── | |
| # Paper-canonical Family-6 LLM panel (matches DRAFT.md §5.4 and the | |
| # canon RunRecord JSONs under experiments/results/). Two of the four | |
| # entries are OpenRouter-hosted closed-source models; the third | |
| # (gpt-oss-120B) is open-weights routed via OpenRouter for compute | |
| # economy; the fourth (Qwen-3.5-27B-FP8) runs locally on 4xA100-40GB. | |
| # Local-vLLM fields (tensor_parallel_size, quant, prequantized) are | |
| # meaningful only when ``provider == "local"``; for OpenRouter entries | |
| # they carry placeholder values. | |
| class LLMModel: | |
| id: str | |
| name: str | |
| provider: Literal["local", "openrouter"] | |
| hf_id: str | None = None | |
| tensor_parallel_size: int = 1 | |
| quant: Literal["fp8", "bf16"] = "fp8" | |
| multimodal: bool = False | |
| total_params_b: float | None = None | |
| active_params_b: float | None = None | |
| ft_strategy: str = "none" | |
| prequantized: bool = False | |
| LLM_MODELS: tuple[LLMModel, ...] = ( | |
| LLMModel( | |
| id="gpt51", | |
| name="GPT-5.1", | |
| provider="openrouter", | |
| hf_id="openai/gpt-5.1", | |
| ft_strategy="none", | |
| ), | |
| LLMModel( | |
| id="gemini3_flash", | |
| name="Gemini-3-Flash-Preview", | |
| provider="openrouter", | |
| hf_id="google/gemini-3-flash-preview", | |
| ft_strategy="none", | |
| ), | |
| LLMModel( | |
| id="exaone", | |
| name="EXAONE-4.5 32B", | |
| provider="local", | |
| hf_id="LGAI-EXAONE/EXAONE-4.5-32B-FP8", | |
| tensor_parallel_size=4, | |
| quant="fp8", | |
| total_params_b=32.0, | |
| active_params_b=32.0, | |
| ft_strategy="qlora_nf4", | |
| prequantized=True, | |
| ), | |
| LLMModel( | |
| id="llama_scout", | |
| name="Llama-4 Scout 109B", | |
| provider="local", | |
| hf_id="meta-llama/Llama-4-Scout-17B-16E-Instruct", | |
| tensor_parallel_size=4, | |
| quant="fp8", | |
| multimodal=True, | |
| total_params_b=109.0, | |
| active_params_b=17.0, | |
| ft_strategy="qlora_nf4_zero2", | |
| prequantized=False, | |
| ), | |
| LLMModel( | |
| id="qwen35", | |
| name="Qwen-3.5-27B-FP8", | |
| provider="local", | |
| hf_id="Qwen/Qwen3.5-27B-FP8", | |
| tensor_parallel_size=1, | |
| quant="fp8", | |
| multimodal=False, | |
| total_params_b=27.0, | |
| active_params_b=27.0, | |
| ft_strategy="qlora_nf4", | |
| prequantized=True, | |
| ), | |
| ) | |
| LLM_MODELS_BY_ID: dict[str, LLMModel] = {m.id: m for m in LLM_MODELS} | |
| # ── Family 6: LLM Zero-Shot (4 methods) ─────────────────────────────────── | |
| # Method ids match the canon RunRecord JSON ``method_id`` field (no | |
| # ``_zs`` suffix); family is ``llm`` (not ``llm_zs``). | |
| def _llm_notes(m: LLMModel) -> str: | |
| if m.provider == "openrouter": | |
| return "OpenRouter API; reasoning tokens disabled." | |
| return f"vLLM {m.quant.upper()} inference, TP={m.tensor_parallel_size}." | |
| LLM_ZS_METHODS: tuple[Method, ...] = tuple( | |
| Method( | |
| id=m.id, | |
| name=m.name, | |
| family="llm", | |
| tasks=frozenset(ALL_TASKS), | |
| hf_id=m.hf_id, | |
| notes=_llm_notes(m), | |
| ) | |
| for m in LLM_MODELS | |
| ) | |
| # ── Aggregation ─────────────────────────────────────────────────────────── | |
| # Paper-canonical 18 methods x 6 families. The legacy ``Method`` | |
| # dataclass list aligns with the canon RunRecord JSON ``method_id`` and | |
| # ``method_family`` fields under ``experiments/results/``. | |
| ALL_METHODS: tuple[Method, ...] = ( | |
| NAIVE_METHODS | |
| + CLASSICAL_METHODS | |
| + SEQUENCE_METHODS | |
| + TSFM_ZS_METHODS | |
| + LLM_TS_MULTITASK_METHODS | |
| + LLM_ZS_METHODS | |
| ) | |
| METHODS_BY_ID: dict[str, Method] = {m.id: m for m in ALL_METHODS} | |
| METHODS_BY_FAMILY: dict[Family, tuple[Method, ...]] = { | |
| "naive": NAIVE_METHODS, | |
| "classical": CLASSICAL_METHODS, | |
| "sequence": SEQUENCE_METHODS, | |
| "tsfm": TSFM_ZS_METHODS, | |
| "llm_ts": LLM_TS_MULTITASK_METHODS, | |
| "llm": LLM_ZS_METHODS, | |
| } | |
| def methods_for_task_panel(task: Task) -> tuple[Method, ...]: | |
| """All legacy panel ``Method`` dataclasses applicable to a task. | |
| Retained under a renamed handle so the new registry-driven | |
| :func:`methods_for_task` (returning ``list[str]`` of registry ids) is | |
| the canonical Phase-4 entry point. Callers that need the panel | |
| dataclass (display name, ``hf_id``, ``notes``) keep using this. | |
| """ | |
| return tuple(m for m in ALL_METHODS if task in m.tasks) | |
| def methods_for_family(family: Family) -> tuple[Method, ...]: | |
| return METHODS_BY_FAMILY[family] | |
| # ── Phase-4 unified-API panel helpers ───────────────────────────────────── | |
| # The orchestrator (``experiments/run_all.py``) consumes the registry-driven | |
| # 18-method panel rather than the legacy ``Method`` dataclasses above. The | |
| # helpers below mirror the registry surface so the runner never reaches into | |
| # ``methods._registry`` directly. | |
| from ..methods._registry import ALL_METHODS as _REGISTRY_METHODS | |
| def methods_for_task(task: str) -> list[str]: | |
| """Return the sorted list of registered method ids that support ``task``. | |
| Single source of truth for the Phase-4 runner's "skip methods that do | |
| not support this task" filter. Reads directly from | |
| :data:`methods._registry.ALL_METHODS`. | |
| """ | |
| return sorted(name for name, cls in _REGISTRY_METHODS.items() if task in cls.tasks) | |
| # Canonical 18-method panel (re-derived from the registry every call so | |
| # additions/removals show up without an explicit panel.py edit). | |
| PANEL: list[str] = sorted(_REGISTRY_METHODS.keys()) | |
| # ── Context ablation subset ────────────────────────────────────────────── | |
| # DRAFT.md §5.4.1: a five-step feature-context ablation (A-E) is run on | |
| # the panel's two zero-shot frontier LLMs (GPT-5.1, Gemini-3-Flash) on | |
| # four tasks (T1 at h=252, T2, T4, T5). Running the full A-E factorial | |
| # across all four LLMs would dominate the wall-clock budget; restricting | |
| # to the two frontier LLMs preserves the contrast (does adding context | |
| # channels help the strongest zero-shot models?) while keeping the | |
| # 2 x 5 x 4 = 40-cell budget tractable. | |
| ABLATION_MODEL_IDS: tuple[str, ...] = ("gpt51", "gemini3_flash") | |
| # The submitted ablation reports zero-shot evaluation only. The FT mode is | |
| # retained as a deferred-experiment slot; with no FT cells the table | |
| # generator (gen_tables.gen_tab_ablation) emits a placeholder. | |
| ABLATION_MODES: tuple[str, ...] = ("ZS",) | |
| # Deferred fine-tune cell (DRAFT.md does not report any FT row in the | |
| # Family-6 panel; the submitted paper is zero-shot-only across all | |
| # four LLMs). Kept as an empty tuple so downstream table generators | |
| # emit the deferred-placeholder branch without crashing. | |
| LLM_FT_PANEL_HF_IDS: tuple[str, ...] = () | |
| ABLATION_SETTINGS: dict[str, dict] = { | |
| "A": {"name": "OHLCV only", "n_features": 6}, | |
| "B": {"name": "A + Fundamentals (XBRL + derived)", "n_features": 70}, | |
| "C": {"name": "B + Macro (FRED + EIA)", "n_features": 123}, | |
| "D": {"name": "C + Scenario flags", "n_features": 127}, | |
| "E": {"name": "D + SBERT filing embeddings", "n_features": 511}, | |
| } | |
| ABLATION_TASKS: tuple[Task, ...] = ("T1", "T2", "T4", "T5") | |
| ABLATION_T1_HORIZON: int = 252 | |
| # DRAFT.md §5.4.1 / Fig. 3 caption: T1 ablation uses h=252 (the longest | |
| # horizon, where context-channel sensitivity is highest). The other | |
| # three ablation tasks use their full task-defined targets. T3/T6 are | |
| # excluded because they use per-field MAPE / success_rate (different | |
| # metric family); T7 is excluded because RentCast property features | |
| # don't share the A-E feature space (no XBRL / FRED / scenarios). | |
| # ── Seed policy ─────────────────────────────────────────────────────────── | |
| # v1 (initial submission): SINGLE seed = 42 for every method, every task. | |
| # Bootstrap 95% CI (1000 resamples) on the test set provides per-method | |
| # variance reporting -- the same approach used by 4 of 7 verified peer | |
| # benchmarks (Time-MMD NeurIPS D&B 2024, FinTSB 2025, Fin-RATE 2026, | |
| # SciTS ICLR 2026), all of which were accepted with single-run headline | |
| # tables. Bootstrap CI captures test-set variance; it does NOT capture | |
| # training-stochasticity variance. | |
| # | |
| # v2 (rebuttal-ready, only fired if reviewer asks): MULTI_SEEDS {42, 123, | |
| # 456} on HEADLINE_T1_MULTISEED_METHODS at T1 h=21. Rationale for matching | |
| # the WIT (ICLR 2026) and EDINET-Bench (ICLR 2026) precedent of 3-run mean | |
| # +/- std on stochastic methods. Estimated rebuttal compute: ~24h on | |
| # 4xA100-40GB (well within the 2-week NeurIPS rebuttal window). Deferring | |
| # to rebuttal saves ~410 GPU-h up front and lets us focus initial | |
| # wall-clock on getting the 20-method panel + 2 deferred FT cells + | |
| # 40-cell ablation factorial fully working at single seed first. | |
| from .. import config as _config | |
| # Single source of truth: the seed lives in config.BENCHMARK_SEED. | |
| # panel.PRIMARY_SEED is kept as the import handle that downstream baselines | |
| # already use, but it MUST stay aligned with config.BENCHMARK_SEED -- the | |
| # assertion below catches any silent drift. | |
| PRIMARY_SEED: int = _config.BENCHMARK_SEED | |
| assert PRIMARY_SEED == _config.BENCHMARK_SEED, ( | |
| f"panel.PRIMARY_SEED ({PRIMARY_SEED}) drifted from " | |
| f"config.BENCHMARK_SEED ({_config.BENCHMARK_SEED})" | |
| ) | |
| MULTI_SEEDS: tuple[int, ...] = (42, 123, 456) | |
| # Methods that WILL report mean +/- std across MULTI_SEEDS on the headline | |
| # T1 table IF reviewers request multi-seed during rebuttal. List is locked | |
| # in code so the rebuttal path is documented; in v1 the seeds_for() helper | |
| # returns only PRIMARY_SEED. | |
| # Chosen as the stochastic methods present in the current panel; deterministic | |
| # methods (naive, classical without re-sampling, TSFM zero-shot with fixed | |
| # weights) would report a single seed even if multi-seed were enabled. | |
| HEADLINE_T1_MULTISEED_METHODS: tuple[str, ...] = ( | |
| "dlinear", "itransformer", "moderntcn", | |
| "time_mqa", | |
| ) | |
| # Toggle. v1 = False (single seed everywhere); flip to True during rebuttal | |
| # to activate multi-seed for HEADLINE_T1_MULTISEED_METHODS at T1 h=21. | |
| ENABLE_MULTI_SEED: bool = False | |
| def seeds_for(method_id: str, task: Task, horizon: int | None = None) -> tuple[int, ...]: | |
| """Return the seed list for a method-task pair. | |
| v1 (initial submission, ENABLE_MULTI_SEED=False): always returns | |
| (PRIMARY_SEED,) -- single seed everywhere. | |
| v2 (rebuttal, ENABLE_MULTI_SEED=True): returns MULTI_SEEDS on the | |
| headline T1 subset (method in HEADLINE_T1_MULTISEED_METHODS, | |
| task == 'T1', horizon == 21); single seed otherwise. | |
| """ | |
| if ( | |
| ENABLE_MULTI_SEED | |
| and task == "T1" | |
| and horizon == 21 | |
| and method_id in HEADLINE_T1_MULTISEED_METHODS | |
| ): | |
| return MULTI_SEEDS | |
| return (PRIMARY_SEED,) | |
| # ── GPU assignment ──────────────────────────────────────────────────────── | |
| # MacroLens runs on GPU IDs 4,5,6,7 on the shared host (last 4 of the 8 | |
| # physical A100-SXM4-40GB). All scripts must respect this; | |
| # `CUDA_VISIBLE_DEVICES` is set by the runner wrappers. | |
| # (Memory: project_macrolens_gpus.md) | |
| GPU_IDS: tuple[int, ...] = (4, 5, 6, 7) | |
| CUDA_VISIBLE_DEVICES_STR: str = ",".join(str(i) for i in GPU_IDS) | |
| # ── Summary ─────────────────────────────────────────────────────────────── | |
| def summary() -> dict: | |
| """Return a small dict summarising the panel for logging / CI assertions.""" | |
| return { | |
| "total_methods": len(ALL_METHODS), | |
| "per_family": {f: len(ms) for f, ms in METHODS_BY_FAMILY.items()}, | |
| "per_task": {t: len(methods_for_task_panel(t)) for t in ALL_TASKS}, | |
| "ablation_models": len(ABLATION_MODEL_IDS), | |
| "ablation_settings": len(ABLATION_SETTINGS), | |
| "gpu_ids": list(GPU_IDS), | |
| "primary_seed": PRIMARY_SEED, | |
| "multi_seeds": list(MULTI_SEEDS), | |
| "llm_models": [m.hf_id for m in LLM_MODELS], | |
| } | |
| if __name__ == "__main__": | |
| # Quick sanity check: `python -m baselines.panel`. | |
| # Expected total: 18 methods x 6 families (4 naive + 2 classical | |
| # + 3 sequence + 3 tsfm + 2 llm_ts + 4 llm) -- matches DRAFT.md §5.4 | |
| # and the canon RunRecord JSONs under experiments/results/. | |
| import json | |
| s = summary() | |
| assert s["total_methods"] == 18, f"Expected 18 methods, got {s['total_methods']}" | |
| assert len(s["per_family"]) == 6, ( | |
| f"Expected 6 families, got {len(s['per_family'])}" | |
| ) | |
| print(json.dumps(s, indent=2, default=list)) | |
| print( | |
| f"Context ablation: 2 frontier LLMs x A-E x {{T1 h={ABLATION_T1_HORIZON}," | |
| f" T2, T4, T5}} = 2 x {len(ABLATION_SETTINGS)}" | |
| f" x {len(ABLATION_TASKS)} =" | |
| f" {2 * len(ABLATION_SETTINGS) * len(ABLATION_TASKS)} cells" | |
| " (DRAFT.md §5.4.1)." | |
| ) | |