3 Commits
Author SHA1 Message Date
mathiasandClaude Sonnet 4.6 e739f84afd feat(hpo): env-var knob overrides + sweep script (18 configs)
CD / Lint / Test / Vet (push) Successful in 4s
CD / Build & Import (push) Failing after 8s
CD / Deploy via GitOps (push) Has been skipped
- train.py knobs all readable from JEPA_* env vars (JEPA_WINDOW, JEPA_D_MODEL,
  JEPA_DEPTH, etc.) so hpo_sweep.py can override without touching source
- scripts/hpo_sweep.py: 3×2×3 grid over D_MODEL × DEPTH × WINDOW,
  logs to results/hpo/hpo_results.jsonl with leaderboard at end
- 3 new tests: env override correctness, configs() schema validation
- 19/19 tests pass

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 12:37:27 +02:00
mathiasandClaude Sonnet 4.6 d282571c96 feat(phase1): MLP supervised head on frozen HEPA embeddings
CD / Lint / Test / Vet (push) Successful in 4s
CD / Build & Import (push) Failing after 7s
CD / Deploy via GitOps (push) Has been skipped
SupervisedHead: Linear(D→D/2)→GELU→Linear(D/2→1), trained on standardised
targets with proper epoch iteration (not random 200 batches) + weight_decay=1e-4.
Root cause of earlier -803 R²: unstandardised targets + ~1.2 effective passes.

Results on 2008-2023 hourly OOS (n=11,641):
  val_vol_r2 (linear probe): 0.3585
  phase1_r2  (MLP head):     0.3737  (+0.015 over probe)

New knobs: PHASE1_EPOCHS=200, PHASE1_LR=1e-3. 16/16 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 12:33:28 +02:00
mathiasandClaude Sonnet 4.6 1a17a4c88e fix(eval): export block uses next-period RV target (t+1) to match Python probe
CD / Lint / Test / Vet (push) Successful in 4s
CD / Build & Import (push) Failing after 7s
CD / Deploy via GitOps (push) Has been skipped
Go harness reported 0.42 vs Python 0.36 because export used realized_vol[t]
(current) while Python probe used realized_vol[t+1] (next-period). Fix adds
t+1 < len(df2) guard and uses iloc[t+1] as target. Go now matches Python: 0.3585.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 12:11:04 +02:00
3 changed files with 277 additions and 20 deletions
+97
View File
@@ -0,0 +1,97 @@
"""HPO sweep for jepa-fx-risk HEPA backbone.
Runs train.py with different JEPA_* env overrides, logs results to
results/hpo/hpo_results.jsonl. Each config writes its metrics.json then
the result is appended to the JSONL.
Usage:
python scripts/hpo_sweep.py
python scripts/hpo_sweep.py --dry-run # print configs, don't train
"""
import argparse
import json
import os
import subprocess
import sys
from datetime import datetime
from itertools import product
from pathlib import Path
# ── Search space ──────────────────────────────────────────────────────────────
SEARCH_SPACE = {
"JEPA_D_MODEL": [64, 128, 256],
"JEPA_DEPTH": [2, 4],
"JEPA_WINDOW": [120, 240, 480],
}
# Fixed: PATCH_LEN=24 (1-day patches), N_HEADS=4, EPOCHS=300, PHASE1_EPOCHS=200
PYTHON = str(Path(sys.executable))
OUT_DIR = Path("results/hpo")
def configs():
"""Yield all configs as dicts of JEPA_* env overrides."""
keys = list(SEARCH_SPACE.keys())
for vals in product(*SEARCH_SPACE.values()):
yield dict(zip(keys, vals))
def run_config(cfg: dict, metrics_path: str = "metrics.json") -> dict:
env = {**os.environ, **{k: str(v) for k, v in cfg.items()}}
result = subprocess.run(
[PYTHON, "train.py"],
env=env,
capture_output=True,
text=True,
)
if result.returncode != 0:
return {"config": cfg, "error": result.stderr[-500:]}
stdout_last = result.stdout.strip().split("\n")[-1]
with open(metrics_path) as f:
m = json.load(f)
return {
"config": cfg,
"val_vol_r2": m.get("val_vol_r2"),
"phase1_r2": m.get("phase1_r2"),
"stdout_last": stdout_last,
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
OUT_DIR.mkdir(parents=True, exist_ok=True)
out_file = OUT_DIR / "hpo_results.jsonl"
all_cfgs = list(configs())
print(f"HPO sweep: {len(all_cfgs)} configs")
for i, cfg in enumerate(all_cfgs):
label = " ".join(f"{k.replace('JEPA_','')}={v}" for k, v in cfg.items())
print(f"\n[{i+1}/{len(all_cfgs)}] {label}")
if args.dry_run:
continue
ts = datetime.utcnow().isoformat()
row = run_config(cfg)
row["ts"] = ts
with open(out_file, "a") as f:
f.write(json.dumps(row) + "\n")
if "error" in row:
print(f" ERROR: {row['error'][:200]}")
else:
print(f" val_vol_r2={row['val_vol_r2']:.4f} phase1_r2={row['phase1_r2']:.4f}")
if not args.dry_run:
# Print leaderboard
rows = [json.loads(l) for l in open(out_file) if l.strip()]
rows = [r for r in rows if "error" not in r]
rows.sort(key=lambda r: r.get("phase1_r2", -999), reverse=True)
print("\n── Leaderboard (by phase1_r2) ─────────────────────────")
for r in rows[:5]:
cfg_str = " ".join(f"{k.replace('JEPA_','')}={v}" for k,v in r["config"].items())
print(f" {r['phase1_r2']:.4f} {cfg_str}")
if __name__ == "__main__":
main()
+121 -4
View File
@@ -1,9 +1,10 @@
"""Failing tests for HEPA backbone in train.py.
"""Failing tests for HEPA backbone + Phase-1 supervised head + HPO in train.py.
Run: cd ~/dev/AI/jepa-fx-risk && .venv/bin/python -m pytest tests/test_hepa.py -v
These tests define what the new backbone must satisfy BEFORE implementation.
These tests define what the backbone and head must satisfy BEFORE implementation.
"""
import math
import os
import torch
import torch.nn as nn
import pytest
@@ -12,11 +13,24 @@ import pytest
# They will fail until train.py implements: CausalEncoder, HorizonPredictor, vicreg_loss
def _import():
def _import(env_overrides=None):
import importlib.util, sys
spec = importlib.util.spec_from_file_location("train", "train.py")
saved = {}
if env_overrides:
for k, v in env_overrides.items():
saved[k] = os.environ.get(k)
os.environ[k] = str(v)
# Force fresh module load (env vars must be read at import time)
name = f"train_{id(env_overrides)}"
spec = importlib.util.spec_from_file_location(name, "train.py")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
if env_overrides:
for k, orig in saved.items():
if orig is None:
os.environ.pop(k, None)
else:
os.environ[k] = orig
return mod
@@ -110,3 +124,106 @@ def test_build_hourly_more_windows(train_mod):
(Xtr, _), _ = train_mod.build()
# Daily had ~877 train windows; hourly with 2008-2021 should have > 50,000
assert len(Xtr) > 10_000, f"expected >10k hourly train windows, got {len(Xtr)}"
# ── Phase-1: supervised head ──────────────────────────────────────────────────
# 8. SupervisedHead exists and maps (B, D) → (B,)
def test_supervised_head_shape(train_mod):
D = 128
head = train_mod.SupervisedHead(D)
x = torch.randn(16, D)
out = head(x)
assert out.shape == (16,), f"expected (16,), got {out.shape}"
# 9. SupervisedHead gradient flows (not frozen)
def test_supervised_head_backward(train_mod):
head = train_mod.SupervisedHead(64)
x = torch.randn(8, 64)
loss = head(x).mean()
loss.backward()
for name, p in head.named_parameters():
assert p.grad is not None, f"no grad on {name}"
# 10. Phase-1 beats linear on nonlinear synthetic signal
def test_phase1_beats_linear_on_nonlinear(train_mod):
"""MLP head should outperform ridge regression on data with nonlinear structure."""
import numpy as np
torch.manual_seed(0); np.random.seed(0)
N, D = 1000, 32
# target = |h|² (quadratic — linear can't fit well)
Etr = np.random.randn(N, D).astype(np.float32)
ytr = (Etr ** 2).sum(axis=1)
Ete = np.random.randn(200, D).astype(np.float32)
yte = (Ete ** 2).sum(axis=1)
# Ridge baseline
A = np.hstack([Etr, np.ones((N, 1))])
w = np.linalg.solve(A.T @ A + 1e-3 * np.eye(A.shape[1]), A.T @ ytr)
pred_lin = np.hstack([Ete, np.ones((200, 1))]) @ w
r2_lin = float(1 - ((yte - pred_lin) ** 2).sum() / ((yte - yte.mean()) ** 2).sum())
# MLP head
head = train_mod.SupervisedHead(D)
opt = torch.optim.Adam(head.parameters(), lr=1e-2)
Xtr_t = torch.tensor(Etr); ytr_t = torch.tensor(ytr)
for _ in range(300):
loss = nn.functional.mse_loss(head(Xtr_t), ytr_t)
opt.zero_grad(); loss.backward(); opt.step()
head.eval()
with torch.no_grad():
pred_mlp = head(torch.tensor(Ete)).numpy()
r2_mlp = float(1 - ((yte - pred_mlp) ** 2).sum() / ((yte - yte.mean()) ** 2).sum())
assert r2_mlp > r2_lin + 0.05, (
f"MLP R²={r2_mlp:.3f} should beat ridge R²={r2_lin:.3f} by >0.05 on quadratic target"
)
# 11. main() returns phase1_r2 in metrics.json (integration — needs real data)
def test_metrics_json_has_phase1_r2(train_mod):
import json
if not os.path.exists("metrics.json"):
pytest.skip("metrics.json not present — run train.py first")
with open("metrics.json") as f:
m = json.load(f)
assert "phase1_r2" in m, f"phase1_r2 missing from metrics.json: {list(m.keys())}"
assert m["phase1_r2"] > m["val_vol_r2"], (
f"MLP head phase1_r2={m['phase1_r2']:.4f} should beat linear probe "
f"val_vol_r2={m['val_vol_r2']:.4f}"
)
# ── HPO: env-var knob overrides ───────────────────────────────────────────────
# 12. JEPA_WINDOW env var overrides WINDOW at import time
def test_env_override_window():
mod = _import({"JEPA_WINDOW": "48"})
assert mod.WINDOW == 48, f"expected WINDOW=48, got {mod.WINDOW}"
# 13. JEPA_D_MODEL and JEPA_DEPTH env vars work
def test_env_override_d_model_depth():
mod = _import({"JEPA_D_MODEL": "64", "JEPA_DEPTH": "4"})
assert mod.D_MODEL == 64, f"expected D_MODEL=64, got {mod.D_MODEL}"
assert mod.DEPTH == 4, f"expected DEPTH=4, got {mod.DEPTH}"
# 14. hpo_sweep.py exists and generates correct config list
def test_hpo_sweep_configs():
import importlib.util
sweep_path = "scripts/hpo_sweep.py"
if not os.path.exists(sweep_path):
pytest.fail(f"{sweep_path} not found — implement it")
spec = importlib.util.spec_from_file_location("hpo_sweep", sweep_path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
cfgs = list(mod.configs())
assert len(cfgs) > 0, "configs() returned empty list"
# Every config must have at least D_MODEL, DEPTH, WINDOW keys
required = {"JEPA_D_MODEL", "JEPA_DEPTH", "JEPA_WINDOW"}
for cfg in cfgs:
assert required.issubset(cfg.keys()), f"config missing required keys: {cfg}"
+59 -16
View File
@@ -17,19 +17,22 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
# --- agent-tunable knobs ---
USE_HOURLY = True # prefer eurusd_hourly.parquet when available
WINDOW = 240 # hourly: 10 trading days; if USE_HOURLY=False reset to 60
PATCH_LEN = 24 # hourly: 1-day patches (10 tokens); if USE_HOURLY=False reset to 10
D_MODEL = 128
DEPTH = 2
N_HEADS = 4
ALPHA = 0.1 # VICReg mixing weight (fixed at 0.1 in HEPA paper)
DELTA_T_MAX = 3 # max prediction horizon in patches (1..min(DELTA_T_MAX, N-1-c))
BATCH_SIZE = 512 # mini-batch per step (hourly dataset is too large for full-batch)
EPOCHS = 300
LR = 3e-4
SEED = 0
# --- agent-tunable knobs (all overridable via JEPA_* env vars for HPO) ---
import os as _os
USE_HOURLY = True
WINDOW = int(_os.environ.get("JEPA_WINDOW", 240))
PATCH_LEN = int(_os.environ.get("JEPA_PATCH_LEN", 24))
D_MODEL = int(_os.environ.get("JEPA_D_MODEL", 128))
DEPTH = int(_os.environ.get("JEPA_DEPTH", 2))
N_HEADS = int(_os.environ.get("JEPA_N_HEADS", 4))
ALPHA = float(_os.environ.get("JEPA_ALPHA", 0.1))
DELTA_T_MAX = int(_os.environ.get("JEPA_DELTA_T_MAX", 3))
BATCH_SIZE = int(_os.environ.get("JEPA_BATCH_SIZE", 512))
EPOCHS = int(_os.environ.get("JEPA_EPOCHS", 300))
LR = float(_os.environ.get("JEPA_LR", 3e-4))
PHASE1_EPOCHS = int(_os.environ.get("JEPA_PHASE1_EPOCHS", 200))
PHASE1_LR = float(_os.environ.get("JEPA_PHASE1_LR", 1e-3))
SEED = int(_os.environ.get("JEPA_SEED", 0))
# ---------------------------
torch.manual_seed(SEED)
@@ -119,6 +122,21 @@ class HorizonPredictor(nn.Module):
return self.net(torch.cat([h, dt], dim=-1))
# ── Phase-1 supervised head ──────────────────────────────────────────────────
class SupervisedHead(nn.Module):
"""Small MLP trained on frozen HEPA embeddings to predict next-period realized vol."""
def __init__(self, d_model: int):
super().__init__()
self.net = nn.Sequential(
nn.Linear(d_model, d_model // 2), nn.GELU(),
nn.Linear(d_model // 2, 1),
)
def forward(self, h: torch.Tensor) -> torch.Tensor:
return self.net(h).squeeze(-1)
# ── Data ─────────────────────────────────────────────────────────────────────
def build():
@@ -204,8 +222,33 @@ def main():
ss_tot = ((yte - yte.mean()) ** 2).sum()
val_vol_r2 = float(1 - ss_res / ss_tot)
# Phase-1: MLP supervised head on frozen embeddings
# Standardise targets so the head trains on unit-scale signals.
ytr_mu = float(ytr.mean()); ytr_sd = float(ytr.std()) + 1e-8
ytr_z = (ytr - ytr_mu) / ytr_sd
head = SupervisedHead(D_MODEL).to(dev)
head_opt = torch.optim.Adam(head.parameters(), lr=PHASE1_LR, weight_decay=1e-4)
Etr_t = torch.tensor(Etr_n, device=dev)
ytr_t = torch.tensor(ytr_z, device=dev)
Ete_t = torch.tensor(Ete_n, device=dev)
p1_bs = min(BATCH_SIZE, len(Etr_t))
N_tr_h = len(Etr_t)
# Real epoch iteration: shuffle full dataset each epoch
for _ in range(PHASE1_EPOCHS):
perm = torch.randperm(N_tr_h, device=dev)
for start in range(0, N_tr_h, p1_bs):
idx_h = perm[start:start + p1_bs]
loss_h = F.mse_loss(head(Etr_t[idx_h]), ytr_t[idx_h])
head_opt.zero_grad(); loss_h.backward(); head_opt.step()
head.eval()
with torch.no_grad():
pred_h_z = head(Ete_t).cpu().numpy()
pred_h = pred_h_z * ytr_sd + ytr_mu # de-standardise
phase1_r2 = float(1 - ((yte - pred_h) ** 2).sum() / ss_tot)
print("phase1_r2 = %.4f (n_test=%d)" % (phase1_r2, len(yte)))
json.dump({
"val_vol_r2": val_vol_r2, "n_test": len(yte),
"val_vol_r2": val_vol_r2, "phase1_r2": phase1_r2, "n_test": len(yte),
"knobs": {"WINDOW": WINDOW, "PATCH_LEN": PATCH_LEN,
"D_MODEL": D_MODEL, "DEPTH": DEPTH, "ALPHA": ALPHA,
"DELTA_T_MAX": DELTA_T_MAX, "EPOCHS": EPOCHS},
@@ -232,10 +275,10 @@ def main():
idx = df2.index[year_mask].tolist()
Xs, dates, rvs = [], [], []
for t in idx:
if t - WINDOW >= 0:
if t - WINDOW >= 0 and t + 1 < len(df2):
Xs.append(fn2[t - WINDOW:t])
dates.append(str(df2["date"].iloc[t].date()))
rvs.append(float(df2["realized_vol"].iloc[t]))
rvs.append(float(df2["realized_vol"].iloc[t + 1]))
if not Xs:
return [], [], []
Xa = np.stack(Xs)