MacroLens / code /methods /_config.py
itouchz's picture
Upload methods/ (18-method baseline panel implementations)
02412f8 verified
Raw
History Blame Contribute Delete
8.49 kB
"""Per-method typed Pydantic configurations for the MacroLens unified API.
Each method class declares its own ``MethodConfig`` subclass with typed,
validated, default-bearing hyperparameters. The runner records
``config.model_dump()`` into ``RunRecord.hyperparams`` for every result.
"""
from __future__ import annotations
from typing import Literal
import pydantic
class MethodConfig(pydantic.BaseModel):
"""Base for all method configs.
``model_config = ConfigDict(extra="forbid")`` so unknown kwargs raise at
construction; methods can override to allow ``extra="allow"`` if they
intentionally pass through to a wrapped library.
"""
model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
# ── Naive ──────────────────────────────────────────────────────────────────
class PersistenceConfig(MethodConfig):
# Index of the "close" feature on the (N, lookback, F) X array. Since
# X is a numpy ndarray (no column names), the runner must pass this
# in via config; default 0 matches the convention that close is the
# first numeric feature returned by the T1 loader.
close_feature_idx: int = 0
# Optional explicit horizon override; when None, fit() reads horizon
# from y.shape[1] and stores it as self._horizon.
horizon: int | None = None
class SectorMedianConfig(MethodConfig):
fallback_to_global: bool = True
class MetroMedianConfig(MethodConfig):
fallback_to_global: bool = True
metro_key: Literal["city_state", "state", "state_property_type"] = (
"state_property_type"
)
class HistoricalAnalogueConfig(MethodConfig):
fallback_to_global: bool = True
class LogSizeOLSConfig(MethodConfig):
use_log_assets: bool = True
sector_dummies: bool = True
# ── Classical ──────────────────────────────────────────────────────────────
class LightGBMConfig(MethodConfig):
"""LightGBM library defaults; only ``n_jobs`` is a system-level flag."""
n_estimators: int = 100 # LightGBM default
max_depth: int = -1 # LightGBM default (unlimited)
learning_rate: float = 0.1 # LightGBM default
subsample: float = 1.0 # LightGBM default
colsample_bytree: float = 1.0 # LightGBM default
n_jobs: int = 8 # system-level flag (not a hyperparameter)
verbosity: int = -1
t6_text_handling: Literal["sector_industry_only"] = "sector_industry_only"
class RandomForestConfig(MethodConfig):
"""sklearn RandomForestRegressor library defaults; ``n_jobs`` is system-level."""
n_estimators: int = 100 # sklearn default
max_depth: int | None = None # sklearn default (unlimited)
min_samples_leaf: int = 1 # sklearn default
n_jobs: int = 8 # system-level flag (not a hyperparameter)
t6_text_handling: Literal["sector_industry_only"] = "sector_industry_only"
# ── Sequence ───────────────────────────────────────────────────────────────
class SequenceConfig(MethodConfig):
"""Shared training-loop defaults aligned with each upstream paper's
reference script (DLinear / iTransformer / ModernTCN — all 3 papers
use train_epochs=10, batch_size=32, patience=3, no weight_decay)."""
epochs: int = 10 # all three upstream papers use 10
batch_size: int = 32 # all three upstream papers use 32
learning_rate: float = 1e-4 # subclass overrides match each paper
patience: int = 3 # all three upstream papers use 3
weight_decay: float = 0.0 # upstream papers don't use weight_decay
grad_clip: float = 1.0
target_idx: int = 0
class DLinearConfig(SequenceConfig):
"""DLinear (Zeng et al. AAAI 2023; cure-lab/LTSF-Linear, ETTh1 ref)."""
moving_avg: int = 25 # paper default
learning_rate: float = 5e-3 # ETTh1 reference script lr=0.005
class ITransformerConfig(SequenceConfig):
"""iTransformer (Liu et al. ICLR 2024; thuml/iTransformer, ETTh1 ref)."""
d_model: int = 128 # ETTh1 reference d_model=128
n_heads: int = 8 # paper default
e_layers: int = 2 # ETTh1 reference e_layers=2
d_ff: int = 128 # ETTh1 reference d_ff=128
dropout: float = 0.1 # paper default
factor: int = 1 # paper default
activation: str = "gelu" # paper default
learning_rate: float = 1e-4 # ETTh1 reference lr=0.0001
class ModernTCNConfig(SequenceConfig):
"""ModernTCN (Donghao & Xue ICLR 2024; luodhhh/ModernTCN, ETTh1 ref)."""
patch_size: int = 16 # paper default
patch_stride: int = 8 # paper default
d_model: int = 64 # ETTh1 reference d_model=64
kernel_size: int = 25 # paper default
stem_ratio: int = 1 # paper default
downsample_ratio: int = 2 # paper default
ffn_ratio: int = 2 # paper default
num_blocks: tuple[int, ...] = (1,) # paper default
large_size: tuple[int, ...] = (51,) # paper default
small_size: tuple[int, ...] = (5,) # paper default
dropout: float = 0.1 # paper default
head_dropout: float = 0.1 # paper default
revin: bool = True # paper default
affine: bool = True # paper default
learning_rate: float = 1e-3 # ETTh1 reference lr=0.001
# ── TSFM (zero-shot) ───────────────────────────────────────────────────────
class TSFMConfig(MethodConfig):
"""Shared base for Chronos2 / Moirai2 / TimesFM."""
model_id: str = "" # subclass overrides the default
device: Literal["auto", "cpu", "cuda"] = "auto"
batch_size: int = 32
target_idx: int = 0 # close-column index in T1 X (N, L, F)
class Chronos2Config(TSFMConfig):
model_id: str = "amazon/chronos-2"
num_samples: int = 20
class Moirai2Config(TSFMConfig):
model_id: str = "Salesforce/moirai-2.0-R-small"
class TimesFMConfig(TSFMConfig):
model_id: str = "google/timesfm-1.0-200m-pytorch"
per_core_batch_size: int = 32
granularity: Literal["daily", "weekly", "monthly"] = "daily"
# ── LLM (frontier) ─────────────────────────────────────────────────────────
class LLMConfig(MethodConfig):
model_id: str = ""
tensor_parallel_size: int = 1
max_model_len: int = 8192
temperature: float = 0.0
max_tokens: int = 256
enable_thinking: bool = False
# Number of in-context (X_train, y_train) examples to include in the
# prompt at predict time. ``0`` (default) = pure zero-shot.
in_context_k: int = 0
# Smoke-test mode: ``predict`` returns deterministic fake outputs
# without invoking the engine. Used when ``engine=None`` in CI.
dry_run: bool = False
class LlamaScoutConfig(LLMConfig):
model_id: str = "meta-llama/Llama-4-Scout-17B-16E-Instruct"
tensor_parallel_size: int = 4
class Gemma4Config(LLMConfig):
model_id: str = "google/gemma-4-31B-it"
tensor_parallel_size: int = 2
class Qwen35Config(LLMConfig):
model_id: str = "Qwen/Qwen3.5-27B-FP8"
tensor_parallel_size: int = 1
# ── LLM-TS multi-task ──────────────────────────────────────────────────────
class LLMTSConfig(MethodConfig):
model_id: str = ""
device: Literal["auto", "cpu", "cuda"] = "auto"
# Smoke-test mode: ``predict`` returns deterministic fake outputs without
# invoking a real engine. Mirrors :class:`LLMConfig.dry_run`.
dry_run: bool = False
class ChatTimeConfig(LLMTSConfig):
model_id: str = "ChengsenWang/ChatTime-1-7B-Chat"
hist_len: int = 63
pred_len: int = 21
class TimeMQAConfig(LLMTSConfig):
model_id: str = "Time-MQA/Qwen-2.5-7B"
base_model_id: str = "Qwen/Qwen2.5-7B-Instruct"
# ── LLM fine-tune (deferred) ───────────────────────────────────────────────
class LLMFineTunedConfig(LLMConfig):
lora_r: int = 16
lora_alpha: int = 32
epochs: int = 3
learning_rate: float = 2e-4