#!/usr/bin/env python3 """Controlled representation-learning baselines for the LOBench revision.""" from __future__ import annotations import argparse import copy import hashlib import json import math import os import random import socket import sys import time from datetime import datetime, timezone from functools import partial from pathlib import Path import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset ROOT = Path(__file__).resolve().parents[3] SRC = ROOT / "experiments/adma2026_representation/src" if str(SRC) not in sys.path: sys.path.insert(0, str(SRC)) from models import ( # noqa: E402 Classifier, LOBConvGridEncoder, LOBShapeGatedFlowLevelSimLOBEncoder, LOBShapeFlowLevelSimLOBEncoder, LOBShapeFlowSimLOBEncoder, LOBShapeHybridLevelSimLOBEncoder, LOBShapeLevelSimLOBEncoder, LOBShapeStructuredLevelSimLOBEncoder, LOBGridEncoder, LOBShapeGridFusionEncoder, LOBShapeSimLOBEncoder, LOBShapeWideSimLOBEncoder, LOBStructEncoder, PositionalEncoding, SimLOBStyleEncoder, TLOB2025Encoder, ) from train_downstream import ( # noqa: E402 classification_metrics, count_parameters, evaluate, load_npz, sample_label_budget, set_seed, train_epoch, ) def utc_now() -> str: return datetime.now(timezone.utc).isoformat() def sha256_file(path: Path, chunk_size: int = 8 * 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(chunk_size): digest.update(chunk) return digest.hexdigest() def sha256_tensor(tensor: torch.Tensor) -> str: import numpy as np # noqa: PLC0415 value = np.ascontiguousarray( tensor.detach().cpu().numpy(), dtype=np.int64, ) return hashlib.sha256(value.tobytes()).hexdigest() def sha256_state_dict(state_dict: dict[str, torch.Tensor]) -> str: digest = hashlib.sha256() for name in sorted(state_dict): value = state_dict[name].detach().cpu().contiguous() digest.update(name.encode("utf-8")) digest.update(b"\0") digest.update(str(tuple(value.shape)).encode("ascii")) digest.update(b"\0") digest.update(str(value.dtype).encode("ascii")) digest.update(b"\0") digest.update(value.numpy().tobytes()) return digest.hexdigest() def atomic_write_json(path: Path, value: dict) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") temporary.write_text(json.dumps(value, indent=2), encoding="utf-8") os.replace(temporary, path) def atomic_torch_save(state_dict: dict[str, torch.Tensor], path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") torch.save(state_dict, temporary) os.replace(temporary, path) def result_setting_name(config: dict, setting: str) -> str: return str(config.get("result_setting_names", {}).get(setting, setting)) def result_path_for( config: dict, stock: str, method: str, setting: str, seed: int, label_budget: float, ) -> Path: tag = int(round(label_budget * 100)) condition = result_setting_name(config, setting) return Path(config["results_dir"]) / ( f"{stock}_{method}_{condition}_seed{seed}_budget{tag:03d}.json" ) class AdapterClassifier(nn.Module): def __init__(self, encoder: nn.Module, latent_dim: int = 128, num_classes: int = 3, bottleneck: int = 32): super().__init__() self.encoder = encoder self.adapter = nn.Sequential( nn.LayerNorm(latent_dim), nn.Linear(latent_dim, bottleneck), nn.GELU(), nn.Linear(bottleneck, latent_dim), ) self.head = nn.Sequential(nn.LayerNorm(latent_dim), nn.Linear(latent_dim, num_classes)) def forward(self, x): z = self.encoder(x) z = z + self.adapter(z) return self.head(z) class TransformerBackbone(nn.Module): def __init__(self, latent_dim: int = 128, d_model: int = 96, layers: int = 2, nhead: int = 4): super().__init__() self.in_proj = nn.Linear(40, d_model) self.pos = PositionalEncoding(d_model) layer = nn.TransformerEncoderLayer( d_model=d_model, nhead=nhead, dim_feedforward=4 * d_model, batch_first=True, dropout=0.1, activation="gelu", ) self.encoder = nn.TransformerEncoder(layer, num_layers=layers) self.out = nn.Linear(d_model, latent_dim) def sequence(self, x): return self.encoder(self.pos(self.in_proj(x))) def forward(self, x): return self.out(self.sequence(x).mean(dim=1)) class DilatedConvBackbone(nn.Module): def __init__(self, latent_dim: int = 128, d_model: int = 96): super().__init__() self.in_proj = nn.Conv1d(40, d_model, kernel_size=1) self.blocks = nn.ModuleList( [ nn.Sequential( nn.Conv1d(d_model, d_model, kernel_size=3, padding=d, dilation=d), nn.GELU(), nn.Conv1d(d_model, d_model, kernel_size=1), ) for d in (1, 2, 4, 8) ] ) self.norm = nn.LayerNorm(d_model) self.out = nn.Linear(d_model, latent_dim) def sequence(self, x): h = self.in_proj(x.transpose(1, 2)) for block in self.blocks: h = h + block(h) return self.norm(h.transpose(1, 2)) def forward(self, x): return self.out(self.sequence(x).mean(dim=1)) def legalize_lob_prices(raw, gap_scale: float = 0.02): bid_raw = raw[:, :, :10].flip(-1) ask_raw = raw[:, :, 10:20] best_bid = bid_raw[:, :, :1] spread = torch.nn.functional.softplus(ask_raw[:, :, :1] - bid_raw[:, :, :1]) * gap_scale + 1e-5 bid_gaps = torch.nn.functional.softplus(bid_raw[:, :, 1:]) * gap_scale + 1e-5 ask_gaps = torch.nn.functional.softplus(ask_raw[:, :, 1:]) * gap_scale + 1e-5 bid_near = torch.cat([best_bid, best_bid - torch.cumsum(bid_gaps, dim=-1)], dim=-1) best_ask = best_bid + spread ask_near = torch.cat([best_ask, best_ask + torch.cumsum(ask_gaps, dim=-1)], dim=-1) out = raw.clone() out[:, :, :10] = bid_near.flip(-1) out[:, :, 10:20] = ask_near return out class ReconstructionPretrainer(nn.Module): def __init__(self, encoder: nn.Module, d_model: int = 96, legalize_prices: bool = False): super().__init__() self.encoder = encoder self.decode = nn.Sequential(nn.Linear(d_model, d_model), nn.GELU(), nn.Linear(d_model, 40)) self.legalize_prices = legalize_prices def forward(self, x): pred = self.decode(self.encoder.sequence(x)) if self.legalize_prices: pred = legalize_lob_prices(pred) return pred class TrendReconstructionPretrainer(ReconstructionPretrainer): def __init__(self, encoder: nn.Module, d_model: int = 96, legalize_prices: bool = False, latent_dim: int = 128): super().__init__(encoder, d_model=d_model, legalize_prices=legalize_prices) self.trend_head = nn.Sequential(nn.LayerNorm(latent_dim), nn.Linear(latent_dim, 3)) self.auxtrend_weight = 0.25 self.auxtrend_class_weights = None def trend_logits(self, x): return self.trend_head(self.encoder(x)) class TFCPretrainer(nn.Module): def __init__(self, latent_dim: int, d_model: int): super().__init__() self.encoder = TransformerBackbone(latent_dim=latent_dim, d_model=d_model) self.freq_encoder = TransformerBackbone(latent_dim=latent_dim, d_model=d_model) def frequency_view(self, x): freq = torch.fft.rfft(x, dim=1).abs() if freq.size(1) < x.size(1): freq = torch.nn.functional.pad(freq, (0, 0, 0, x.size(1) - freq.size(1))) return freq[:, : x.size(1)] def forward(self, x): return self.encoder(x), self.freq_encoder(self.frequency_view(x)) def make_loader(x, y, idx, batch_size, shuffle, num_workers=0, pin_memory=False): return DataLoader( TensorDataset(x[idx], y[idx]), batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, pin_memory=pin_memory, ) def load_npz_with_train_index( path: Path, index_key: str = "train_idx", relabel_threshold: float | None = None, ): x, y, splits = load_npz(path) if index_key != "train_idx" or relabel_threshold is not None: import numpy as np # noqa: PLC0415 data = np.load(path) if index_key != "train_idx": if index_key not in data.files: raise KeyError(f"{path} does not contain requested index {index_key}") splits["train"] = torch.tensor(data[index_key], dtype=torch.long) if relabel_threshold is not None: if relabel_threshold <= 0: raise ValueError("The relabel threshold must be positive") if "future_returns" not in data.files: raise KeyError(f"{path} does not contain future_returns") future_returns = data["future_returns"] labels = np.where( future_returns > relabel_threshold, 2, np.where(future_returns < -relabel_threshold, 0, 1), ) y = torch.tensor(labels, dtype=torch.long) return x, y, splits def load_test_group_ids(path: Path, test_idx) -> list[str] | None: """Return exchange-date labels aligned with the test-loader order.""" import numpy as np # noqa: PLC0415 data = np.load(path) if "end_times" not in data.files: if "relative_day_id" in data.files: return [str(value) for value in data["relative_day_id"][test_idx.cpu().numpy()]] return None values = data["end_times"][test_idx.cpu().numpy()] return [str(value).split("T", 1)[0].split(" ", 1)[0] for value in values] def data_path_for_stock(config, stock: str) -> Path: template = str(config.get("data_file_template", "{stock}_pilot.npz")) return Path(config["processed_dir"]) / template.format(stock=stock) def make_pooled_loader(config, stocks, split, batch_size, shuffle, num_workers=0, pin_memory=False): xs = [] ys = [] keep_labels = bool(config.get("pooled_keep_labels", False)) pretrain_index_key = str(config.get("pretrain_index_key", "train_idx")) for stock in stocks: x, y, splits = load_npz_with_train_index( data_path_for_stock(config, stock), pretrain_index_key, ) idx = splits[split] xs.append(x[idx]) ys.append(y[idx] if keep_labels else torch.zeros(len(idx), dtype=torch.long)) return DataLoader( TensorDataset(torch.cat(xs, dim=0), torch.cat(ys, dim=0)), batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, pin_memory=pin_memory, ) def _log_epochs_enabled(cfg): return bool(cfg.get("log_epochs", False)) def _log_epoch(cfg, message): if _log_epochs_enabled(cfg): print(message, flush=True) def augment(x, mask_prob: float = 0.12, noise_std: float = 0.02): out = x + noise_std * torch.randn_like(x) mask = torch.rand_like(out) < mask_prob return out.masked_fill(mask, 0.0) def mask_points(x, mask_prob: float): mask = torch.rand(x.size(0), x.size(1), 1, device=x.device) < mask_prob return x.masked_fill(mask, 0.0), mask.expand_as(x) def mask_patches(x, patch_len: int = 10, mask_ratio: float = 0.35): bsz, steps, _ = x.shape n_patches = max(1, steps // patch_len) patch_mask = torch.rand(bsz, n_patches, device=x.device) < mask_ratio mask = torch.zeros(bsz, steps, 1, device=x.device, dtype=torch.bool) for i in range(n_patches): mask[:, i * patch_len : min((i + 1) * patch_len, steps)] = patch_mask[:, i].view(bsz, 1, 1) return x.masked_fill(mask, 0.0), mask.expand_as(x) def nt_xent(z1, z2, temperature: float = 0.2): z1 = torch.nn.functional.normalize(z1, dim=1) z2 = torch.nn.functional.normalize(z2, dim=1) logits = z1 @ z2.t() / temperature labels = torch.arange(z1.size(0), device=z1.device) return 0.5 * ( torch.nn.functional.cross_entropy(logits, labels) + torch.nn.functional.cross_entropy(logits.t(), labels) ) def frequency_loss(pred, target): pred_freq = torch.fft.rfft(pred, dim=1).abs() target_freq = torch.fft.rfft(target, dim=1).abs() return torch.mean((pred_freq - target_freq) ** 2) def lob_sides(x): bid_p = x[:, :, :10].flip(-1) ask_p = x[:, :, 10:20] bid_v = x[:, :, 20:30].flip(-1) ask_v = x[:, :, 30:40] return bid_p, ask_p, bid_v, ask_v def lob_validity_penalty( pred, volume_zero_threshold=None, price_zero_threshold=None, price_gap_margin=0.0, ): """Soft LOB constraints in normalized coordinates. Price ordering and spread are invariant under the benchmark's shared positive affine price transform. Raw volume zero is not invariant under z-scoring, so callers must provide its normalized value ``(0 - volume_mean) / volume_std``. If it is unavailable, the volume term is deliberately omitted instead of using the minimum target value as a surrogate. """ bid_p, ask_p, bid_v, ask_v = lob_sides(pred) gap = torch.as_tensor( price_gap_margin, dtype=pred.dtype, device=pred.device, ).reshape(1, 1, 1) bid_order = torch.relu(gap - (bid_p[:, :, :-1] - bid_p[:, :, 1:])).mean() ask_order = torch.relu(gap - (ask_p[:, :, 1:] - ask_p[:, :, :-1])).mean() spread = torch.relu(gap - (ask_p[:, :, :1] - bid_p[:, :, :1])).mean() volume = pred[:, :, 20:40] if price_zero_threshold is not None: price_floor = torch.as_tensor( price_zero_threshold, dtype=pred.dtype, device=pred.device, ).reshape(1, 1, 1) price_penalty = torch.relu(price_floor - pred[:, :, :20]).mean() else: price_penalty = pred.new_zeros(()) if volume_zero_threshold is not None: volume_floor = torch.as_tensor( volume_zero_threshold, dtype=volume.dtype, device=volume.device, ).reshape(1, 1, 1) volume_penalty = torch.relu(volume_floor - volume).mean() else: volume_penalty = volume.new_zeros(()) return bid_order + ask_order + spread + price_penalty + volume_penalty def lob_aware_reconstruction_loss( pred, target, mask=None, structure_weight: float = 2.0, volume_zero_threshold=None, price_zero_threshold=None, price_gap_margin=0.0, ): if mask is not None and mask.any(): mse = torch.mean((pred[mask] - target[mask]) ** 2) else: mse = torch.mean((pred - target) ** 2) return mse + structure_weight * lob_validity_penalty( pred, volume_zero_threshold=volume_zero_threshold, price_zero_threshold=price_zero_threshold, price_gap_margin=price_gap_margin, ) def inverse_grouped_normalization(x, normalization): raw = x.clone() raw[:, :, :20] = ( raw[:, :, :20] * float(normalization["price_std"]) + float(normalization["price_mean"]) ) raw[:, :, 20:40] = ( raw[:, :, 20:40] * float(normalization["volume_std"]) + float(normalization["volume_mean"]) ) return raw def lob_validity_metrics( pred, target=None, normalization=None, raw_price_tick_size=None, ): """Return strict/weak validity and, when possible, raw-unit errors. Raw volume validity and price/volume MAE are emitted only when the exact training-partition normalization statistics are supplied. """ with torch.no_grad(): evaluated_pred = ( inverse_grouped_normalization(pred, normalization) if normalization is not None else pred ) evaluated_target = ( inverse_grouped_normalization(target, normalization) if target is not None and normalization is not None else target ) bid_p, ask_p, _, _ = lob_sides(evaluated_pred) spread_gap = ask_p[:, :, 0] - bid_p[:, :, 0] bid_gaps = bid_p[:, :, :-1] - bid_p[:, :, 1:] ask_gaps = ask_p[:, :, 1:] - ask_p[:, :, :-1] spread_bad = spread_gap <= 0 bid_strict_bad = (bid_p[:, :, 1:] >= bid_p[:, :, :-1]).any(dim=-1) ask_strict_bad = (ask_p[:, :, 1:] <= ask_p[:, :, :-1]).any(dim=-1) bid_weak_bad = (bid_p[:, :, 1:] > bid_p[:, :, :-1]).any(dim=-1) ask_weak_bad = (ask_p[:, :, 1:] < ask_p[:, :, :-1]).any(dim=-1) metrics = { "spread_cross_rate": float(spread_bad.float().mean().item()), "spread_valid_rate": float((~spread_bad).float().mean().item()), "bid_order_strict_bad_rate": float(bid_strict_bad.float().mean().item()), "bid_order_strict_valid_rate": float((~bid_strict_bad).float().mean().item()), "ask_order_strict_bad_rate": float(ask_strict_bad.float().mean().item()), "ask_order_strict_valid_rate": float((~ask_strict_bad).float().mean().item()), "bid_order_weak_bad_rate": float(bid_weak_bad.float().mean().item()), "bid_order_weak_valid_rate": float((~bid_weak_bad).float().mean().item()), "ask_order_weak_bad_rate": float(ask_weak_bad.float().mean().item()), "ask_order_weak_valid_rate": float((~ask_weak_bad).float().mean().item()), } if normalization is not None: price_bad = (evaluated_pred[:, :, :20] <= 0).any(dim=-1) volume = evaluated_pred[:, :, 20:40] volume_bad = (volume < 0).any(dim=-1) any_bad = ( spread_bad | bid_strict_bad | ask_strict_bad | price_bad | volume_bad ) metrics.update( { "price_nonpositive_rate": float(price_bad.float().mean().item()), "price_positive_valid_rate": float((~price_bad).float().mean().item()), "volume_negative_rate": float(volume_bad.float().mean().item()), "volume_nonnegative_valid_rate": float((~volume_bad).float().mean().item()), "any_lob_illegal_rate": float(any_bad.float().mean().item()), "all_lob_constraints_valid_rate": float((~any_bad).float().mean().item()), } ) if raw_price_tick_size is not None: tick = float(raw_price_tick_size) if tick <= 0: raise ValueError("raw_price_tick_size must be positive") tolerance = max(1e-8, tick * 1e-4) tick_bid_bad = (bid_gaps < tick - tolerance).any(dim=-1) tick_ask_bad = (ask_gaps < tick - tolerance).any(dim=-1) tick_spread_bad = spread_gap < tick - tolerance tick_price_bad = (evaluated_pred[:, :, :20] < tick - tolerance).any(dim=-1) joint_bad = ( tick_bid_bad | tick_ask_bad | tick_spread_bad | tick_price_bad | volume_bad ) bid_violation = torch.relu(tick - bid_gaps) / tick ask_violation = torch.relu(tick - ask_gaps) / tick spread_violation = torch.relu(tick - spread_gap) / tick price_violation = torch.relu(tick - evaluated_pred[:, :, :20]) / tick all_price_violations = torch.cat( [ bid_violation.reshape(-1), ask_violation.reshape(-1), spread_violation.reshape(-1), price_violation.reshape(-1), ] ) metrics.update( { "raw_price_tick_size": tick, "tick_bid_order_valid_rate": float((~tick_bid_bad).float().mean().item()), "tick_ask_order_valid_rate": float((~tick_ask_bad).float().mean().item()), "tick_spread_valid_rate": float((~tick_spread_bad).float().mean().item()), "tick_price_positive_valid_rate": float((~tick_price_bad).float().mean().item()), "joint_five_constraint_snapshot_valid_rate": float((~joint_bad).float().mean().item()), "bid_order_violation_ticks": float(bid_violation.mean().item()), "ask_order_violation_ticks": float(ask_violation.mean().item()), "spread_violation_ticks": float(spread_violation.mean().item()), "price_floor_violation_ticks": float(price_violation.mean().item()), "mean_price_constraint_violation_ticks": float(all_price_violations.mean().item()), } ) if evaluated_target is not None: metrics["raw_price_mae"] = float( torch.mean(torch.abs(evaluated_pred[:, :, :20] - evaluated_target[:, :, :20])).item() ) metrics["raw_volume_mae"] = float( torch.mean(torch.abs(evaluated_pred[:, :, 20:40] - evaluated_target[:, :, 20:40])).item() ) return metrics def build_method( method: str, latent_dim: int, d_model: int, nhead: int = 4, ): if method == "ts2vec": return DilatedConvBackbone(latent_dim=latent_dim, d_model=d_model) if method in {"simmtm", "timae", "timae_lobloss", "timae_softlobloss", "timesurl", "tfc"}: return TransformerBackbone( latent_dim=latent_dim, d_model=d_model, nhead=nhead, ) if method in {"lobconv_timae", "lobconv_timae_lobloss", "lobconv_timae_softlobloss"}: return LOBConvGridEncoder(latent_dim=latent_dim, d_model=d_model) if method in {"lobgrid_timae", "lobgrid_timae_lobloss", "lobgrid_timae_softlobloss"}: return LOBGridEncoder( latent_dim=latent_dim, d_model=d_model, nhead=nhead, ) if method in {"lobstruct_timae", "lobstruct_timae_lobloss"}: return LOBStructEncoder(latent_dim=latent_dim, d_model=d_model) if method in {"tlob2025", "tlob2025_lobloss", "tlob2025_softlobloss"}: return TLOB2025Encoder(latent_dim=latent_dim, d_model=d_model) if method in {"simlob2026", "simlob2026_lobloss", "simlob2026_softlobloss"}: return SimLOBStyleEncoder( latent_dim=latent_dim, d_model=d_model, nhead=nhead, ) if method in { "lobshape_simlob", "lobshape_simlob_lobloss", "lobshape_simlob_lobloss_auxtrend", "lobshape_simlob_twostage_lobloss", }: return LOBShapeSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) if method in {"lobshape_level_simlob", "lobshape_level_simlob_lobloss"}: return LOBShapeLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) if method in {"lobshape_structured_level_simlob", "lobshape_structured_level_simlob_lobloss"}: return LOBShapeStructuredLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) if method in {"lobshape_hybrid_level_simlob", "lobshape_hybrid_level_simlob_lobloss"}: return LOBShapeHybridLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) if method in {"lobshape_flow_simlob", "lobshape_flow_simlob_lobloss", "lobshape_flow_simlob_lobloss_auxtrend"}: return LOBShapeFlowSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) if method in {"lobshape_flow_level_simlob", "lobshape_flow_level_simlob_lobloss"}: return LOBShapeFlowLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) if method in {"lobshape_gated_flow_level_simlob", "lobshape_gated_flow_level_simlob_lobloss"}: return LOBShapeGatedFlowLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) if method in {"lobshape_wide_simlob", "lobshape_wide_simlob_lobloss"}: return LOBShapeWideSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) if method in {"lobshape_gridfusion", "lobshape_gridfusion_lobloss"}: return LOBShapeGridFusionEncoder(latent_dim=latent_dim, d_model=d_model) raise KeyError(f"unknown representation baseline method: {method}") def _run_pretrain_stage( model, save_model, train_step, val_step, train_loader, val_loader, cfg, device, ckpt_path, stage_name, epochs, patience, learning_rate, ): opt = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=cfg["weight_decay"]) best = float("inf") best_epoch = 0 history = [] epochs_without_improvement = 0 started = time.perf_counter() for epoch in range(1, int(epochs) + 1): epoch_started = time.perf_counter() model.train() train_loss = 0.0 train_n = 0 for x, y in train_loader: x = x.to(device) y = y.to(device) opt.zero_grad(set_to_none=True) loss = train_step(model, x, y) loss.backward() opt.step() train_loss += float(loss.item()) * len(x) train_n += len(x) model.eval() val_loss = 0.0 val_n = 0 with torch.no_grad(): for x, y in val_loader: x = x.to(device) y = y.to(device) loss = val_step(model, x, y) val_loss += float(loss.item()) * len(x) val_n += len(x) train_loss /= max(train_n, 1) val_loss /= max(val_n, 1) history.append( { "stage": stage_name, "epoch": epoch, "train_loss": train_loss, "val_loss": val_loss, "epoch_seconds": time.perf_counter() - epoch_started, } ) next_best = min(best, val_loss) _log_epoch( cfg, f"EPOCH pretrain:{stage_name} {epoch}/{int(epochs)} " f"train_loss={train_loss:.6f} val_loss={val_loss:.6f} " f"best={next_best:.6f} epoch_seconds={history[-1]['epoch_seconds']:.2f}", ) if val_loss < best: best = val_loss best_epoch = epoch atomic_torch_save(save_model.state_dict(), ckpt_path) epochs_without_improvement = 0 else: epochs_without_improvement += 1 if patience and epochs_without_improvement >= patience: break return { "stage": stage_name, "best_val_loss": best, "best_epoch": best_epoch, "seconds": time.perf_counter() - started, "history": history, } def pretrain_method( method, latent_dim, d_model, train_loader, val_loader, cfg, device, ckpt_path, *, nhead=4, mask_ratio=0.4, force=False, ): meta_path = ckpt_path.with_suffix(".pretrain.json") if not force and ckpt_path.exists() and meta_path.exists(): return json.loads(meta_path.read_text(encoding="utf-8")) | {"cached": True} if method == "lobshape_simlob_twostage_lobloss": encoder = LOBShapeSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=False).to(device) stage1_epochs = int(cfg.get("twostage_mse_epochs", max(1, int(cfg["pretrain_epochs"]) // 2))) stage2_epochs = int(cfg.get("twostage_lob_epochs", max(1, int(cfg["pretrain_epochs"]) - stage1_epochs))) stage1_patience = int(cfg.get("twostage_mse_patience", cfg.get("pretrain_patience", 0))) stage2_patience = int(cfg.get("twostage_lob_patience", cfg.get("pretrain_patience", 0))) stage1_path = ckpt_path.with_suffix(".mse_stage.pt") stage1 = _run_pretrain_stage( model, model.encoder, timae_step, timae_step, train_loader, val_loader, cfg, device, stage1_path, "mse", stage1_epochs, stage1_patience, float(cfg["learning_rate"]), ) model.encoder.load_state_dict(torch.load(stage1_path, map_location=device)) model.legalize_prices = True stage2 = _run_pretrain_stage( model, model.encoder, lob_aware_timae_step, lob_aware_timae_step, train_loader, val_loader, cfg, device, ckpt_path, "lob_aware", stage2_epochs, stage2_patience, float(cfg.get("twostage_lob_learning_rate", float(cfg["learning_rate"]) * 0.5)), ) history = stage1["history"] + stage2["history"] meta = { "method": method, "best_val_loss": stage2["best_val_loss"], "best_epoch": stage1_epochs + stage2["best_epoch"], "seconds": stage1["seconds"] + stage2["seconds"], "stages": [ {key: value for key, value in stage1.items() if key != "history"}, {key: value for key, value in stage2.items() if key != "history"}, ], "history": history, "cached": False, "implementation": "local_lite_twostage", } atomic_write_json(meta_path, meta) return meta if method == "ts2vec": model = DilatedConvBackbone(latent_dim=latent_dim, d_model=d_model).to(device) train_step = ts2vec_step val_step = ts2vec_step save_model = model elif method == "tfc": model = TFCPretrainer(latent_dim=latent_dim, d_model=d_model).to(device) train_step = tfc_step val_step = tfc_step save_model = model.encoder elif method == "simmtm": encoder = TransformerBackbone( latent_dim=latent_dim, d_model=d_model, nhead=nhead, ) model = ReconstructionPretrainer(encoder, d_model=d_model).to(device) train_step = simmtm_step val_step = simmtm_step save_model = model.encoder elif method in {"timae", "timae_lobloss", "timae_softlobloss"}: encoder = TransformerBackbone( latent_dim=latent_dim, d_model=d_model, nhead=nhead, ) use_lob_loss = method.endswith("_lobloss") or method.endswith("_softlobloss") model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) step = lob_aware_timae_step if use_lob_loss else timae_step train_step = partial(step, mask_ratio=mask_ratio) val_step = partial(step, mask_ratio=mask_ratio) save_model = model.encoder elif method in {"lobconv_timae", "lobconv_timae_lobloss", "lobconv_timae_softlobloss"}: encoder = LOBConvGridEncoder(latent_dim=latent_dim, d_model=d_model) use_lob_loss = method.endswith("_lobloss") or method.endswith("_softlobloss") model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if use_lob_loss else timae_step val_step = lob_aware_timae_step if use_lob_loss else timae_step save_model = model.encoder elif method in {"lobgrid_timae", "lobgrid_timae_lobloss", "lobgrid_timae_softlobloss"}: encoder = LOBGridEncoder( latent_dim=latent_dim, d_model=d_model, nhead=nhead, ) use_lob_loss = method.endswith("_lobloss") or method.endswith("_softlobloss") model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) step = lob_aware_timae_step if use_lob_loss else timae_step train_step = partial(step, mask_ratio=mask_ratio) val_step = partial(step, mask_ratio=mask_ratio) save_model = model.encoder elif method in {"lobstruct_timae", "lobstruct_timae_lobloss"}: encoder = LOBStructEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step save_model = model.encoder elif method in {"tlob2025", "tlob2025_lobloss", "tlob2025_softlobloss"}: encoder = TLOB2025Encoder(latent_dim=latent_dim, d_model=d_model) use_lob_loss = method.endswith("_lobloss") or method.endswith("_softlobloss") model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if use_lob_loss else timae_step val_step = lob_aware_timae_step if use_lob_loss else timae_step save_model = model.encoder elif method in {"simlob2026", "simlob2026_lobloss", "simlob2026_softlobloss"}: encoder = SimLOBStyleEncoder( latent_dim=latent_dim, d_model=d_model, nhead=nhead, ) use_lob_loss = method.endswith("_lobloss") or method.endswith("_softlobloss") model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) step = lob_aware_timae_step if use_lob_loss else timae_step train_step = partial(step, mask_ratio=mask_ratio) val_step = partial(step, mask_ratio=mask_ratio) save_model = model.encoder elif method in {"lobshape_simlob", "lobshape_simlob_lobloss"}: encoder = LOBShapeSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step save_model = model.encoder elif method in {"lobshape_level_simlob", "lobshape_level_simlob_lobloss"}: encoder = LOBShapeLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step save_model = model.encoder elif method in {"lobshape_structured_level_simlob", "lobshape_structured_level_simlob_lobloss"}: encoder = LOBShapeStructuredLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step save_model = model.encoder elif method in {"lobshape_hybrid_level_simlob", "lobshape_hybrid_level_simlob_lobloss"}: encoder = LOBShapeHybridLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step save_model = model.encoder elif method == "lobshape_simlob_lobloss_auxtrend": encoder = LOBShapeSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = TrendReconstructionPretrainer( encoder, d_model=d_model, legalize_prices=True, latent_dim=latent_dim, ).to(device) model.auxtrend_weight = float(cfg.get("auxtrend_weight", 0.25)) if cfg.get("auxtrend_class_weights") is not None: model.auxtrend_class_weights = torch.tensor( cfg["auxtrend_class_weights"], dtype=torch.float32, device=device, ) train_step = auxtrend_lob_aware_timae_step val_step = auxtrend_lob_aware_timae_step save_model = model.encoder elif method in {"lobshape_flow_simlob", "lobshape_flow_simlob_lobloss"}: encoder = LOBShapeFlowSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step save_model = model.encoder elif method in {"lobshape_flow_level_simlob", "lobshape_flow_level_simlob_lobloss"}: encoder = LOBShapeFlowLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step save_model = model.encoder elif method in {"lobshape_gated_flow_level_simlob", "lobshape_gated_flow_level_simlob_lobloss"}: encoder = LOBShapeGatedFlowLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step save_model = model.encoder elif method == "lobshape_flow_simlob_lobloss_auxtrend": encoder = LOBShapeFlowSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = TrendReconstructionPretrainer( encoder, d_model=d_model, legalize_prices=True, latent_dim=latent_dim, ).to(device) model.auxtrend_weight = float(cfg.get("auxtrend_weight", 0.25)) if cfg.get("auxtrend_class_weights") is not None: model.auxtrend_class_weights = torch.tensor( cfg["auxtrend_class_weights"], dtype=torch.float32, device=device, ) train_step = auxtrend_lob_aware_timae_step val_step = auxtrend_lob_aware_timae_step save_model = model.encoder elif method in {"lobshape_wide_simlob", "lobshape_wide_simlob_lobloss"}: encoder = LOBShapeWideSimLOBEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step save_model = model.encoder elif method in {"lobshape_gridfusion", "lobshape_gridfusion_lobloss"}: encoder = LOBShapeGridFusionEncoder(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device) train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step save_model = model.encoder elif method == "timesurl": encoder = TransformerBackbone(latent_dim=latent_dim, d_model=d_model) model = ReconstructionPretrainer(encoder, d_model=d_model).to(device) train_step = timesurl_step val_step = timesurl_step save_model = model.encoder else: raise KeyError(method) opt = torch.optim.AdamW(model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"]) best = float("inf") best_epoch = 0 history = [] epochs_without_improvement = 0 patience = int(cfg.get("pretrain_patience", 0)) started = time.perf_counter() for epoch in range(1, int(cfg["pretrain_epochs"]) + 1): epoch_started = time.perf_counter() model.train() train_loss = 0.0 train_n = 0 for x, y in train_loader: x = x.to(device) y = y.to(device) opt.zero_grad(set_to_none=True) loss = train_step(model, x, y) loss.backward() opt.step() train_loss += float(loss.item()) * len(x) train_n += len(x) model.eval() val_loss = 0.0 val_n = 0 with torch.no_grad(): for x, y in val_loader: x = x.to(device) y = y.to(device) loss = val_step(model, x, y) val_loss += float(loss.item()) * len(x) val_n += len(x) train_loss /= max(train_n, 1) val_loss /= max(val_n, 1) history.append( { "epoch": epoch, "train_loss": train_loss, "val_loss": val_loss, "epoch_seconds": time.perf_counter() - epoch_started, } ) next_best = min(best, val_loss) _log_epoch( cfg, f"EPOCH pretrain:{method} {epoch}/{int(cfg['pretrain_epochs'])} " f"train_loss={train_loss:.6f} val_loss={val_loss:.6f} " f"best={next_best:.6f} epoch_seconds={history[-1]['epoch_seconds']:.2f}", ) if val_loss < best: best = val_loss best_epoch = epoch atomic_torch_save(save_model.state_dict(), ckpt_path) epochs_without_improvement = 0 else: epochs_without_improvement += 1 if patience and epochs_without_improvement >= patience: break meta = { "method": method, "best_val_loss": best, "best_epoch": best_epoch, "seconds": time.perf_counter() - started, "history": history, "stopped_epoch": len(history), "batches_per_epoch": len(train_loader), "optimizer_steps": len(history) * len(train_loader), "cached": False, "epoch_cap": int(cfg["pretrain_epochs"]), "patience": int(cfg.get("pretrain_patience", 0)), "max_epoch_hit": len(history) >= int(cfg["pretrain_epochs"]), "implementation": "controlled_benchmark_v1", "hyperparameters": { "latent_dim": int(latent_dim), "d_model": int(d_model), "nhead": int(nhead), "mask_ratio": float(mask_ratio), "learning_rate": float(cfg["learning_rate"]), "batch_size": int(cfg["batch_size"]), "epoch_cap": int(cfg["pretrain_epochs"]), "patience": int(cfg.get("pretrain_patience", 0)), }, } atomic_write_json(meta_path, meta) return meta def ts2vec_step(model, x, y=None): z1 = model(augment(x)) z2 = model(augment(x)) return nt_xent(z1, z2) def tfc_step(model, x, y=None): time_z, freq_z = model(augment(x)) return nt_xent(time_z, freq_z) def simmtm_step(model, x, y=None): masked, mask = mask_points(x, mask_prob=0.25) pred = model(masked) recon = torch.mean((pred[mask] - x[mask]) ** 2) if mask.any() else torch.mean((pred - x) ** 2) align = nt_xent(model.encoder(x), model.encoder(masked)) return recon + 0.2 * align def timae_step(model, x, y=None, mask_ratio=0.4): masked, mask = mask_patches(x, patch_len=10, mask_ratio=mask_ratio) pred = model(masked) return torch.mean((pred[mask] - x[mask]) ** 2) if mask.any() else torch.mean((pred - x) ** 2) def lob_aware_timae_step(model, x, y=None, mask_ratio=0.4): masked, mask = mask_patches(x, patch_len=10, mask_ratio=mask_ratio) pred = model(masked) return lob_aware_reconstruction_loss(pred, x, mask=mask, structure_weight=2.0) def auxtrend_lob_aware_timae_step(model, x, y=None): masked, mask = mask_patches(x, patch_len=10, mask_ratio=0.4) pred = model(masked) recon = lob_aware_reconstruction_loss(pred, x, mask=mask, structure_weight=2.0) if y is None: return recon logits = model.trend_logits(x) trend = torch.nn.functional.cross_entropy(logits, y, weight=model.auxtrend_class_weights) return recon + float(model.auxtrend_weight) * trend def timesurl_step(model, x, y=None): point_masked, point_mask = mask_points(x, mask_prob=0.2) pred = model(point_masked) recon = torch.mean((pred[point_mask] - x[point_mask]) ** 2) if point_mask.any() else torch.mean((pred - x) ** 2) contrast = nt_xent(model.encoder(augment(x)), model.encoder(augment(x, mask_prob=0.18, noise_std=0.015))) return recon + 0.2 * contrast + 0.05 * frequency_loss(pred, x) def collect_logits(model, loader, device): model.eval() logits_all = [] y_all = [] with torch.no_grad(): for x, y in loader: logits_all.append(model(x.to(device)).cpu()) y_all.append(y) return torch.cat(logits_all), torch.cat(y_all) def confusion_summary(logits, y_true): pred = logits.argmax(dim=1) matrix = torch.zeros(3, 3, dtype=torch.long) for true_cls in range(3): for pred_cls in range(3): matrix[true_cls, pred_cls] = ((y_true == true_cls) & (pred == pred_cls)).sum() pred_counts = torch.bincount(pred, minlength=3) true_counts = torch.bincount(y_true, minlength=3) return { "matrix_rows_true_cols_pred": matrix.tolist(), "pred_counts": pred_counts.tolist(), "true_counts": true_counts.tolist(), } def classification_metrics_by_group(logits, y_true, group_ids): if group_ids is None: return None if len(group_ids) != len(y_true): raise ValueError( f"group label count {len(group_ids)} does not match predictions {len(y_true)}" ) rows = {} for group in sorted(set(group_ids)): keep = torch.tensor( [value == group for value in group_ids], dtype=torch.bool, ) rows[group] = { "n": int(keep.sum().item()), "metrics": classification_metrics(logits[keep], y_true[keep]), "confusion": confusion_summary(logits[keep], y_true[keep]), } return rows def evaluate_with_logit_bias(model, loader, device, bias): logits, y_true = collect_logits(model, loader, device) bias_tensor = torch.tensor(bias, dtype=logits.dtype).view(1, -1) return classification_metrics(logits + bias_tensor, y_true) def tune_logit_bias(model, val_loader, device): logits, y_true = collect_logits(model, val_loader, device) best_bias = torch.zeros(3) best_metrics = classification_metrics(logits, y_true) best_score = best_metrics["macro_f1"] grid = torch.linspace(-1.5, 1.5, steps=13) for b0 in grid: for b1 in grid: for b2 in grid: bias = torch.tensor([b0, b1, b2], dtype=logits.dtype) bias = bias - bias.mean() metrics = classification_metrics(logits + bias.view(1, -1), y_true) if metrics["macro_f1"] > best_score: best_score = metrics["macro_f1"] best_metrics = metrics best_bias = bias return {"bias": [float(v) for v in best_bias.tolist()], "val": best_metrics} def train_downstream_model( encoder, x, y, splits, train_idx, train_cfg, setting, device, return_artifacts=False, test_group_ids=None, ): if setting == "multiinit_fine_tune": trials = [] best_result = None best_score = -1.0 start_seed = int(train_cfg.get("multiinit_seed_start", 31000)) for init_id in range(int(train_cfg.get("multiinit_count", 5))): set_seed(start_seed + init_id) trial = train_downstream_model( copy.deepcopy(encoder), x, y, splits, train_idx, train_cfg, "fine_tune", device, return_artifacts=False, test_group_ids=test_group_ids, ) trials.append( { "init_id": init_id, "seed": start_seed + init_id, "best_val_macro_f1": trial["best_val_macro_f1"], "best_epoch": trial["best_epoch"], "test": trial["test"], "test_confusion": trial["test_confusion"], "downstream_seconds": trial["downstream_seconds"], } ) if trial["best_val_macro_f1"] > best_score: best_score = trial["best_val_macro_f1"] best_result = trial best_result = copy.deepcopy(best_result) best_result["multiinit"] = { "selected_by": "validation_macro_f1", "count": len(trials), "trials": trials, } best_result["downstream_seconds"] = sum(trial["downstream_seconds"] for trial in trials) return best_result ensemble_pairs = { "probe_finetune_ensemble": ("frozen_probe", "fine_tune"), "probe_adapter_ensemble": ("frozen_probe", "adapter_tune"), "adapter_finetune_ensemble": ("adapter_tune", "fine_tune"), } if setting in ensemble_pairs: left_name, right_name = ensemble_pairs[setting] left = train_downstream_model( copy.deepcopy(encoder), x, y, splits, train_idx, train_cfg, left_name, device, return_artifacts=True, test_group_ids=test_group_ids, ) right = train_downstream_model( copy.deepcopy(encoder), x, y, splits, train_idx, train_cfg, right_name, device, return_artifacts=True, test_group_ids=test_group_ids, ) best_alpha = 0.0 best_val = None best_score = -1.0 for alpha in torch.linspace(0.0, 1.0, steps=int(train_cfg.get("ensemble_alpha_steps", 21))): alpha_value = float(alpha.item()) val_logits = (1.0 - alpha_value) * left["_val_logits"] + alpha_value * right["_val_logits"] metrics = classification_metrics(val_logits, left["_val_true"]) if metrics["macro_f1"] > best_score: best_score = metrics["macro_f1"] best_alpha = alpha_value best_val = metrics test_logits = (1.0 - best_alpha) * left["_test_logits"] + best_alpha * right["_test_logits"] test_metrics = classification_metrics(test_logits, left["_test_true"]) result = { "parameters": { "total": left["parameters"]["total"] + right["parameters"]["total"], "trainable": left["parameters"]["trainable"] + right["parameters"]["trainable"], }, "best_val_macro_f1": best_score, "best_epoch": { left_name: left["best_epoch"], right_name: right["best_epoch"], }, "downstream_seconds": left["downstream_seconds"] + right["downstream_seconds"], "val": best_val, "test": test_metrics, "val_confusion": confusion_summary( (1.0 - best_alpha) * left["_val_logits"] + best_alpha * right["_val_logits"], left["_val_true"], ), "test_confusion": confusion_summary(test_logits, left["_test_true"]), "test_by_group": classification_metrics_by_group( test_logits, left["_test_true"], test_group_ids, ), "calibration": None, "history": { left_name: left["history"], right_name: right["history"], }, "ensemble": { f"alpha_{right_name}": best_alpha, f"alpha_{left_name}": 1.0 - best_alpha, f"{left_name}_test": left["test"], f"{right_name}_test": right["test"], f"{left_name}_best_val_macro_f1": left["best_val_macro_f1"], f"{right_name}_best_val_macro_f1": right["best_val_macro_f1"], }, } return result if setting in {"frozen_probe", "adapter_tune", "calibrated_probe", "adapter_calibrated"}: for param in encoder.parameters(): param.requires_grad = False if setting == "fusion_tune": for param in encoder.parameters(): param.requires_grad = False for module_name in ("fuse", "time_score", "out"): module = getattr(encoder, module_name, None) if module is not None: for param in module.parameters(): param.requires_grad = True if setting in {"adapter_tune", "adapter_calibrated"}: model = AdapterClassifier( encoder, latent_dim=int(train_cfg["latent_dim"]), bottleneck=int(train_cfg.get("adapter_bottleneck", 32)), ).to(device) else: model = Classifier(encoder, latent_dim=int(train_cfg["latent_dim"])).to(device) parameters = count_parameters(model) if setting == "slow_fine_tune" and hasattr(model, "encoder") and hasattr(model, "head"): encoder_lr = float(train_cfg["learning_rate"]) * float(train_cfg.get("encoder_lr_mult", 0.25)) opt = torch.optim.AdamW( [ {"params": [p for p in model.encoder.parameters() if p.requires_grad], "lr": encoder_lr}, {"params": [p for p in model.head.parameters() if p.requires_grad], "lr": train_cfg["learning_rate"]}, ], weight_decay=train_cfg["weight_decay"], ) else: opt = torch.optim.AdamW( [p for p in model.parameters() if p.requires_grad], lr=train_cfg["learning_rate"], weight_decay=train_cfg["weight_decay"], ) class_weights = train_cfg.get("class_weights") if class_weights == "balanced": counts = torch.bincount(y[train_idx], minlength=3).to(dtype=torch.float32) weights = counts.sum() / (3.0 * counts.clamp_min(1.0)) criterion = nn.CrossEntropyLoss(weight=weights.to(device)) elif class_weights is not None: criterion = nn.CrossEntropyLoss(weight=torch.tensor(class_weights, dtype=torch.float32, device=device)) else: criterion = nn.CrossEntropyLoss() batch_size = int(train_cfg["batch_size"]) num_workers = int(train_cfg.get("num_workers", 0)) pin_memory = device.type == "cuda" train_loader = make_loader(x, y, train_idx, batch_size, True, num_workers, pin_memory) val_loader = make_loader(x, y, splits["val"], batch_size, False, num_workers, pin_memory) test_loader = make_loader(x, y, splits["test"], batch_size, False, num_workers, pin_memory) best_val_macro_f1 = -1.0 best_epoch = 0 best_state = copy.deepcopy(model.state_dict()) history = [] patience = int(train_cfg.get("downstream_patience", 0)) epochs_without_improvement = 0 started = time.perf_counter() for epoch in range(1, int(train_cfg["downstream_epochs"]) + 1): epoch_started = time.perf_counter() loss = train_epoch(model, train_loader, opt, device, criterion) metrics = evaluate(model, val_loader, device) if metrics["macro_f1"] > best_val_macro_f1: best_val_macro_f1 = metrics["macro_f1"] best_epoch = epoch best_state = copy.deepcopy(model.state_dict()) epochs_without_improvement = 0 else: epochs_without_improvement += 1 history.append( { "epoch": epoch, "loss": loss, "epoch_seconds": time.perf_counter() - epoch_started, **{f"val_{k}": v for k, v in metrics.items()}, } ) _log_epoch( train_cfg, f"EPOCH downstream:{setting} {epoch}/{int(train_cfg['downstream_epochs'])} " f"loss={loss:.6f} val_macro_f1={metrics['macro_f1']:.6f} " f"best={best_val_macro_f1:.6f} epoch_seconds={history[-1]['epoch_seconds']:.2f}", ) if patience and epochs_without_improvement >= patience: break model.load_state_dict(best_state) calibration = None val_logits, val_true = collect_logits(model, val_loader, device) test_logits, test_true = collect_logits(model, test_loader, device) val_metrics = classification_metrics(val_logits, val_true) test_metrics = classification_metrics(test_logits, test_true) val_confusion = confusion_summary(val_logits, val_true) test_confusion = confusion_summary(test_logits, test_true) if setting in {"calibrated_probe", "adapter_calibrated", "fine_tune_calibrated"}: calibration = tune_logit_bias(model, val_loader, device) bias_tensor = torch.tensor(calibration["bias"], dtype=val_logits.dtype).view(1, -1) val_metrics = classification_metrics(val_logits + bias_tensor, val_true) test_metrics = classification_metrics(test_logits + bias_tensor, test_true) val_confusion = confusion_summary(val_logits + bias_tensor, val_true) test_confusion = confusion_summary(test_logits + bias_tensor, test_true) result = { "parameters": parameters, "best_val_macro_f1": best_val_macro_f1, "best_epoch": best_epoch, "downstream_seconds": time.perf_counter() - started, "val": val_metrics, "test": test_metrics, "val_confusion": val_confusion, "test_confusion": test_confusion, "test_by_group": classification_metrics_by_group( test_logits, test_true, test_group_ids, ), "calibration": calibration, "history": history, "stopped_epoch": len(history), "epoch_cap": int(train_cfg["downstream_epochs"]), "patience": patience, "max_epoch_hit": len(history) >= int(train_cfg["downstream_epochs"]), "optimizer_steps": len(history) * len(train_loader), "batches_per_epoch": len(train_loader), } if return_artifacts: result["_val_logits"] = val_logits result["_val_true"] = val_true result["_test_logits"] = test_logits result["_test_true"] = test_true return result def completed_result(path: Path) -> bool: if not path.exists(): return False try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return False return value.get("status") == "complete" and isinstance(value.get("test"), dict) def checkpoint_pair_valid(ckpt: Path, meta_path: Path) -> bool: if not ckpt.exists() or not meta_path.exists(): return False try: meta = json.loads(meta_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return False expected = meta.get("checkpoint_sha256") return bool(expected) and expected == sha256_file(ckpt) def index_provenance(path: Path, index_key: str) -> dict: import numpy as np # noqa: PLC0415 with np.load(path) as data: if index_key not in data.files: raise KeyError(f"{path} does not contain requested index {index_key}") indices = np.asarray(data[index_key], dtype=np.int64) contiguous = np.ascontiguousarray(indices, dtype=np.int64) return { "samples": int(len(indices)), "index_sha256": hashlib.sha256(contiguous.tobytes()).hexdigest(), } def dataset_provenance(config: dict, stock: str, data_path: Path) -> dict: manifest_path = Path( config.get( "dataset_manifest", Path(config["processed_dir"]).parent / "manifest.json", ) ) value = { "dataset_path": str(data_path.resolve()), "manifest_path": str(manifest_path.resolve()), } if not manifest_path.exists(): value["manifest_available"] = False return value manifest = json.loads(manifest_path.read_text(encoding="utf-8")) duration = str(config.get("duration", Path(config["processed_dir"]).name)) condition = manifest.get("stocks", {}).get(stock, {}).get("conditions", {}).get(duration, {}) value.update( { "manifest_available": True, "manifest_schema": manifest.get("manifest_schema"), "manifest_sha256": sha256_file(manifest_path), "dataset_sha256": condition.get("npz_sha256"), "train_dates": condition.get("train_dates"), "validation_dates": condition.get("validation_dates"), "test_dates": condition.get("test_dates"), "normalization": condition.get("normalization"), "holdout_fingerprints": condition.get("holdout_fingerprints"), } ) return value def run_one( config, stock, method, seed, label_budget, settings, force=False, force_pretrain=False, ): train_cfg = config["training"] out_dir = Path(config["results_dir"]) out_dir.mkdir(parents=True, exist_ok=True) result_paths = [ result_path_for(config, stock, method, setting, seed, label_budget) for setting in settings ] if not force and all(completed_result(path) for path in result_paths): print(f"SKIP {stock} {method}: downstream results already exist", flush=True) return set_seed(seed) device = torch.device(train_cfg["device"] if torch.cuda.is_available() else "cpu") data_path = data_path_for_stock(config, stock) downstream_index_key = str(config.get("downstream_index_key", "train_idx")) pretrain_index_key = str(config.get("pretrain_index_key", "train_idx")) data_cfg = config.get("data", {}) relabel_threshold = ( float(data_cfg["label_threshold"]) if data_cfg.get("relabel_from_future_returns", False) else None ) x, y, splits = load_npz_with_train_index( data_path, downstream_index_key, relabel_threshold=relabel_threshold, ) test_group_ids = load_test_group_ids(data_path, splits["test"]) _log_epoch( train_cfg, f"START {stock} {method} seed={seed} budget={label_budget} " f"device={device} train={len(splits['train'])} val={len(splits['val'])} test={len(splits['test'])}", ) batch_size = int(train_cfg["batch_size"]) num_workers = int(train_cfg.get("num_workers", 0)) pin_memory = device.type == "cuda" pretrain_scope = config.get("pretrain_scope", "local") pretrain_stocks = config.get("pretrain_stocks", config.get("stocks", [stock])) pretrain_id = config.get("pretrain_id", f"pooled{len(pretrain_stocks)}") latent_dim = int(train_cfg["latent_dim"]) d_model = int(train_cfg.get("d_model", 96)) nhead = int(train_cfg.get("nhead", 4)) mask_ratio = float(train_cfg.get("mask_ratio", 0.4)) if d_model % nhead: raise ValueError( f"d_model={d_model} must be divisible by nhead={nhead}" ) if not 0.0 < mask_ratio < 1.0: raise ValueError(f"mask_ratio must lie in (0, 1), got {mask_ratio}") pretrain_dir = Path(config.get("pretrain_dir", out_dir)) pretrain_dir.mkdir(parents=True, exist_ok=True) if pretrain_scope == "pooled": ckpt = pretrain_dir / f"{pretrain_id}_{method}_seed{seed}_encoder.pt" pretrain_run_id = f"{config.get('duration', 'duration')}:{pretrain_id}:{method}:seed{seed}" else: ckpt = pretrain_dir / f"{stock}_{method}_seed{seed}_encoder.pt" pretrain_run_id = ( f"{config.get('duration', 'duration')}:target-local:{stock}:{method}:seed{seed}" ) meta_path = ckpt.with_suffix(".pretrain.json") needs_pretraining = any(setting != "from_scratch" for setting in settings) if not needs_pretraining: pretrain = { "method": method, "skipped": True, "seconds": 0.0, "history": [], "best_epoch": None, "stopped_epoch": 0, "batches_per_epoch": 0, "optimizer_steps": 0, "cached": False, "epoch_cap": int(train_cfg.get("pretrain_epochs", 0)), "patience": int(train_cfg.get("pretrain_patience", 0)), "max_epoch_hit": False, } elif not force_pretrain and checkpoint_pair_valid(ckpt, meta_path): pretrain = json.loads(meta_path.read_text(encoding="utf-8")) | {"cached": True} _log_epoch(train_cfg, f"PRETRAIN cache hit {ckpt}") else: producer_started = utc_now() if pretrain_scope == "pooled": train_loader = make_pooled_loader(config, pretrain_stocks, "train", batch_size, True, num_workers, pin_memory) val_loader = make_pooled_loader(config, pretrain_stocks, "val", batch_size, False, num_workers, pin_memory) else: _, _, pretrain_splits = load_npz_with_train_index(data_path, pretrain_index_key) train_loader = make_loader(x, y, pretrain_splits["train"], batch_size, True, num_workers, pin_memory) val_loader = make_loader(x, y, splits["val"], batch_size, False, num_workers, pin_memory) pretrain = pretrain_method( method, latent_dim, d_model, train_loader, val_loader, train_cfg, device, ckpt, nhead=nhead, mask_ratio=mask_ratio, # The outer checksum-aware cache check already decided that this # pair must be produced (or reproduced). force=True, ) producer_finished = utc_now() partition_stocks = pretrain_stocks if pretrain_scope == "pooled" else [stock] partition_provenance = { value: index_provenance( data_path_for_stock(config, value), pretrain_index_key, ) for value in partition_stocks } pretrain.update( { "cached": False, "run_id": pretrain_run_id, "scope": pretrain_scope, "duration": config.get("duration"), "checkpoint_path": str(ckpt.resolve()), "checkpoint_sha256": sha256_file(ckpt), "meta_path": str(meta_path.resolve()), "train_partitions": partition_provenance, "natural_partition_concatenation": pretrain_scope == "pooled", "producer_started_at_utc": producer_started, "producer_finished_at_utc": producer_finished, "cache_producer": { "hostname": socket.gethostname(), "pid": os.getpid(), "stock_invocation": stock, "task_id": os.environ.get("LOBENCH_TASK_ID"), "attempt": int(os.environ.get("LOBENCH_RUN_ATTEMPT", "1")), }, "epoch_cap": int(train_cfg["pretrain_epochs"]), "patience": int(train_cfg.get("pretrain_patience", 0)), } ) pretrain["max_epoch_hit"] = int(pretrain.get("stopped_epoch", 0)) >= int( train_cfg["pretrain_epochs"] ) atomic_write_json(meta_path, pretrain) if needs_pretraining and not checkpoint_pair_valid(ckpt, meta_path): raise RuntimeError(f"Incomplete or checksum-mismatched pretrain cache: {ckpt}") downstream_train_idx = sample_label_budget(y, splits["train"], label_budget, seed) train_class_counts = torch.bincount(y[downstream_train_idx], minlength=3) downstream_index_sha256 = sha256_tensor(downstream_train_idx) data_lineage = dataset_provenance(config, stock, data_path) for setting, result_path in zip(settings, result_paths): if completed_result(result_path) and not force: print(f"SKIP {stock} {method} {setting}: {result_path}", flush=True) continue # Reset before every downstream arm so that the random encoder/head # initialization is paired across from-scratch and pretrained controls. set_seed(seed) encoder = build_method(method, latent_dim, d_model, nhead=nhead) uses_pretraining = setting != "from_scratch" if uses_pretraining: encoder.load_state_dict(torch.load(ckpt, map_location="cpu")) initial_encoder_state_sha256 = sha256_state_dict(encoder.state_dict()) downstream_setting = "fine_tune" if setting == "from_scratch" else setting downstream = train_downstream_model( encoder, x, y, splits, downstream_train_idx, train_cfg, downstream_setting, device, test_group_ids=test_group_ids, ) condition_name = result_setting_name(config, setting) training_condition = ( "direct" if setting == "from_scratch" else ("pooled" if pretrain_scope == "pooled" else "target_local") ) task_id = os.environ.get("LOBENCH_TASK_ID") or ( f"{config.get('duration')}__{training_condition}__{stock}__" f"{method}__seed{seed}" ) result = { "schema": "training_duration_core_result_v1", "status": "complete", "experiment_id": config.get("experiment_id"), "config_path": config.get("_config_path"), "config_sha256": config.get("_config_sha256"), "duration": config.get("duration"), "stock": stock, "method": method, "setting": setting, "condition": condition_name, "training_condition": training_condition, "downstream_setting": downstream_setting, "initialization": "pretrained" if uses_pretraining else "random", "pretrain_used": uses_pretraining, "seed": seed, "label_budget": label_budget, "label_horizon": config.get("data", {}).get("label_horizon"), "label_threshold": config.get("data", {}).get("label_threshold"), "hyperparameters": { "latent_dim": latent_dim, "d_model": d_model, "nhead": nhead, "mask_ratio": mask_ratio, "learning_rate": float(train_cfg["learning_rate"]), "batch_size": int(train_cfg["batch_size"]), "weight_decay": float(train_cfg["weight_decay"]), "pretrain_epoch_cap": int(train_cfg.get("pretrain_epochs", 0)), "pretrain_patience": int(train_cfg.get("pretrain_patience", 0)), "downstream_epoch_cap": int(train_cfg["downstream_epochs"]), "downstream_patience": int(train_cfg.get("downstream_patience", 0)), }, "train_samples": int(len(downstream_train_idx)), "full_train_samples": int(len(splits["train"])), "downstream_train_index_sha256": downstream_index_sha256, "downstream_train_index_count": int(len(downstream_train_idx)), "downstream_train_index_class_counts": { "down": int(train_class_counts[0]), "stationary": int(train_class_counts[1]), "up": int(train_class_counts[2]), }, "downstream_train_class_counts": { "down": int(train_class_counts[0]), "stationary": int(train_class_counts[1]), "up": int(train_class_counts[2]), }, "classification_head": { "architecture": "LayerNorm(latent_dim)+Linear(latent_dim,3)", "latent_dim": latent_dim, "classes": ["down", "stationary", "up"], "paired_initialization_seed": seed, }, "pretrain": pretrain, "pretrain_scope": pretrain_scope if uses_pretraining else "none", "configured_pretrain_scope": pretrain_scope, "pretrain_id": ( pretrain_id if pretrain_scope == "pooled" else stock ) if uses_pretraining else None, "pretrain_run_id": pretrain_run_id if uses_pretraining else None, "pretrain_index_key": pretrain_index_key, "downstream_index_key": downstream_index_key, "pretrain_cached": bool(pretrain.get("cached")), "pretrain_cache_dir": str(pretrain_dir), "encoder_checkpoint_path": str(ckpt.resolve()) if uses_pretraining else None, "encoder_checkpoint_sha256": sha256_file(ckpt) if uses_pretraining else None, "initial_encoder_state_sha256": initial_encoder_state_sha256, "random_initialization_sha256": ( initial_encoder_state_sha256 if not uses_pretraining else None ), "data_lineage": data_lineage, "reproducibility": { "paired_seed_reset": True, "deterministic_algorithms": bool( torch.are_deterministic_algorithms_enabled() ), "cudnn_deterministic": bool(torch.backends.cudnn.deterministic), "cudnn_benchmark": bool(torch.backends.cudnn.benchmark), "task_id": task_id, "attempt": int(os.environ.get("LOBENCH_RUN_ATTEMPT", "1")), }, "data_protocol": { "sessions": config.get("data", {}).get("sessions"), "session_end_inclusive": config.get("data", {}).get( "session_end_inclusive" ), "sampling": config.get("data", {}).get("sampling"), "label_budget_sampling": "per-class-stratified-within-natural-train", }, **downstream, } result["total_seconds"] = result["downstream_seconds"] + ( float(pretrain.get("seconds", 0.0)) if uses_pretraining else 0.0 ) result["completed_at_utc"] = utc_now() atomic_write_json(result_path, result) print( f"DONE {stock} {method} {setting}: " f"macro_f1={result['test']['macro_f1']:.4f} acc={result['test']['accuracy']:.4f}", flush=True, ) def summarize(config, name: str): out_dir = Path(config["results_dir"]) rows = [] for path in sorted(out_dir.glob("*.json")): if path.name.endswith(".pretrain.json"): continue data = json.loads(path.read_text(encoding="utf-8")) if "test" not in data: continue rows.append( { "stock": data["stock"], "method": data["method"], "setting": data["setting"], "seed": data["seed"], "label_budget": data["label_budget"], "macro_f1": data["test"]["macro_f1"], "balanced_accuracy": data["test"]["balanced_accuracy"], "accuracy": data["test"]["accuracy"], "best_epoch": data["best_epoch"], "pretrain_best_epoch": data["pretrain"].get("best_epoch"), "total_seconds": data["total_seconds"], } ) summary_dir = out_dir.parent / "summary" summary_dir.mkdir(parents=True, exist_ok=True) csv_path = summary_dir / f"{name}_per_stock.csv" md_path = summary_dir / f"{name}_summary.md" if rows: import csv with csv_path.open("w", newline="", encoding="utf-8") as fh: writer = csv.DictWriter(fh, fieldnames=list(rows[0].keys())) writer.writeheader() writer.writerows(rows) grouped = {} for row in rows: grouped.setdefault((row["method"], row["setting"]), []).append(row["macro_f1"]) lines = [f"# {name} Summary", "", "| method | setting | n | mean_macro_f1 |", "|---|---|---:|---:|"] for (method, setting), values in sorted(grouped.items()): lines.append(f"| {method} | {setting} | {len(values)} | {sum(values) / len(values):.4f} |") md_path.write_text("\n".join(lines) + "\n", encoding="utf-8") print(f"wrote {csv_path}", flush=True) print(f"wrote {md_path}", flush=True) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--config", required=True) parser.add_argument("--stocks", nargs="+") parser.add_argument("--methods", nargs="+") parser.add_argument("--settings", nargs="+") parser.add_argument("--seeds", nargs="+", type=int) parser.add_argument("--label-budgets", nargs="+", type=float) parser.add_argument("--force", action="store_true") parser.add_argument("--force-pretrain", action="store_true") parser.add_argument("--pretrain-epochs", type=int, default=None) parser.add_argument("--downstream-epochs", type=int, default=None) parser.add_argument("--summarize-only", action="store_true") parser.add_argument("--no-summarize", action="store_true") parser.add_argument("--name", default=None) return parser.parse_args() def main(): args = parse_args() config_path = Path(args.config) config = json.loads(config_path.read_text(encoding="utf-8")) config["_config_path"] = str(config_path.resolve()) config["_config_sha256"] = sha256_file(config_path) if args.pretrain_epochs is not None: config["training"]["pretrain_epochs"] = int(args.pretrain_epochs) if args.downstream_epochs is not None: config["training"]["downstream_epochs"] = int(args.downstream_epochs) name = args.name or Path(args.config).stem if args.summarize_only: summarize(config, name) return stocks = args.stocks or config["stocks"] methods = args.methods or config["methods"] settings = args.settings or config["settings"] seeds = args.seeds or config["seeds"] label_budgets = args.label_budgets or config["label_budgets"] total = len(stocks) * len(methods) * len(seeds) * len(label_budgets) i = 0 for stock in stocks: for method in methods: for seed in seeds: for label_budget in label_budgets: i += 1 print(f"RUN {i}/{total} {stock} {method} seed={seed} budget={label_budget}", flush=True) run_one( config, stock, method, seed, label_budget, settings, force=args.force, force_pretrain=args.force_pretrain, ) if not args.no_summarize: summarize(config, name) if __name__ == "__main__": main()