LOBench-A-share-processed / code /experiments /tbd_revision /scripts /run_representation_task_suite.py
Download code/experiments/tbd_revision/scripts/run_representation_task_suite.py from mythezone/LOBench-A-share-processed: direct link, hf CLI and curl.
- Browser
- Download file 30.8 kB
-
https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/tbd_revision/scripts/run_representation_task_suite.py
- Command line
-
hf download hf://datasets/mythezone/LOBench-A-share-processed/code/experiments/tbd_revision/scripts/run_representation_task_suite.py
-
curl -L -o run_representation_task_suite.py https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/tbd_revision/scripts/run_representation_task_suite.py
30.8 kB
| #!/usr/bin/env python3 | |
| """Run reconstruction, imputation, interpolation, and trend tasks.""" | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import csv | |
| import json | |
| import math | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import torch | |
| from torch import nn | |
| ROOT = Path(__file__).resolve().parents[3] | |
| SRC = ROOT / "experiments/adma2026_representation/src" | |
| SCRIPT_DIR = ROOT / "experiments/tbd_revision/scripts" | |
| for path in (SRC, SCRIPT_DIR): | |
| if str(path) not in sys.path: | |
| sys.path.insert(0, str(path)) | |
| from models import Classifier # noqa: E402 | |
| from train_downstream import classification_metrics, evaluate, load_npz, sample_label_budget, set_seed, train_epoch # noqa: E402 | |
| from train_representation_baselines import ( # noqa: E402 | |
| ReconstructionPretrainer, | |
| build_method, | |
| collect_logits, | |
| confusion_summary, | |
| data_path_for_stock, | |
| lob_aware_reconstruction_loss, | |
| lob_validity_metrics, | |
| inverse_grouped_normalization, | |
| make_loader, | |
| mask_patches, | |
| train_downstream_model, | |
| tune_logit_bias, | |
| ) | |
| def uses_lob_aware_loss(method: str) -> bool: | |
| return method.endswith("_lobloss") or method.endswith("_softlobloss") | |
| def structural_loss_enabled(method: str, structure_weight) -> bool: | |
| if structure_weight is None: | |
| return uses_lob_aware_loss(method) | |
| return float(structure_weight) > 0 | |
| def effective_structure_weight(method: str, structure_weight) -> float: | |
| if structure_weight is None: | |
| return 2.0 if uses_lob_aware_loss(method) else 0.0 | |
| return float(structure_weight) | |
| def lambda_tag(value: float) -> str: | |
| return str(float(value)).replace("-", "m").replace(".", "p") | |
| def uses_legalized_decoder(method: str) -> bool: | |
| return method.endswith("_lobloss") | |
| def make_plateau_scheduler(optimizer, train_cfg, mode): | |
| if not bool(train_cfg.get("reduce_lr_on_plateau", False)): | |
| return None | |
| return torch.optim.lr_scheduler.ReduceLROnPlateau( | |
| optimizer, | |
| mode=mode, | |
| factor=float(train_cfg.get("lr_plateau_factor", 0.5)), | |
| patience=int(train_cfg.get("lr_plateau_patience", 5)), | |
| threshold=float(train_cfg.get("lr_plateau_threshold", 1e-3)), | |
| threshold_mode=str(train_cfg.get("lr_plateau_threshold_mode", "rel")), | |
| min_lr=float(train_cfg.get("min_learning_rate", 1e-6)), | |
| ) | |
| def materially_improved(value, reference, mode, min_delta_abs=0.0, min_delta_rel=0.0): | |
| if not math.isfinite(reference): | |
| return True | |
| margin = max(float(min_delta_abs), abs(float(reference)) * float(min_delta_rel)) | |
| if mode == "min": | |
| return value < reference - margin | |
| if mode == "max": | |
| return value > reference + margin | |
| raise KeyError(mode) | |
| def ae_loss(model, x, task): | |
| if task == "reconstruction": | |
| pred = model(x) | |
| return torch.mean((pred - x) ** 2) | |
| if task == "interpolation": | |
| masked, mask = mask_patches(x, patch_len=10, mask_ratio=0.4) | |
| pred = model(masked) | |
| return torch.mean((pred[mask] - x[mask]) ** 2) if mask.any() else torch.mean((pred - x) ** 2) | |
| raise KeyError(task) | |
| def mask_entries(x, mask_ratio=0.2): | |
| """Hide individual LOB values for the benchmark imputation task.""" | |
| mask = torch.rand_like(x) < float(mask_ratio) | |
| return x.masked_fill(mask, 0.0), mask | |
| def task_loss( | |
| model, | |
| x, | |
| task, | |
| method, | |
| volume_zero_threshold=None, | |
| price_zero_threshold=None, | |
| price_gap_margin=0.0, | |
| structure_weight=None, | |
| imputation_mask_ratio=0.2, | |
| ): | |
| if task == "reconstruction": | |
| pred = model(x) | |
| if structural_loss_enabled(method, structure_weight): | |
| return lob_aware_reconstruction_loss( | |
| pred, | |
| x, | |
| structure_weight=effective_structure_weight(method, structure_weight), | |
| volume_zero_threshold=volume_zero_threshold, | |
| price_zero_threshold=price_zero_threshold, | |
| price_gap_margin=price_gap_margin, | |
| ) | |
| return torch.mean((pred - x) ** 2) | |
| if task == "interpolation": | |
| masked, mask = mask_patches(x, patch_len=10, mask_ratio=0.4) | |
| pred = model(masked) | |
| if structural_loss_enabled(method, structure_weight): | |
| return lob_aware_reconstruction_loss( | |
| pred, | |
| x, | |
| mask=mask, | |
| structure_weight=effective_structure_weight(method, structure_weight), | |
| volume_zero_threshold=volume_zero_threshold, | |
| price_zero_threshold=price_zero_threshold, | |
| price_gap_margin=price_gap_margin, | |
| ) | |
| return torch.mean((pred[mask] - x[mask]) ** 2) if mask.any() else torch.mean((pred - x) ** 2) | |
| if task == "imputation": | |
| masked, mask = mask_entries(x, mask_ratio=imputation_mask_ratio) | |
| pred = model(masked) | |
| completed = torch.where(mask, pred, x) | |
| if structural_loss_enabled(method, structure_weight): | |
| return lob_aware_reconstruction_loss( | |
| completed, | |
| x, | |
| mask=mask, | |
| structure_weight=effective_structure_weight(method, structure_weight), | |
| volume_zero_threshold=volume_zero_threshold, | |
| price_zero_threshold=price_zero_threshold, | |
| price_gap_margin=price_gap_margin, | |
| ) | |
| return torch.mean((pred[mask] - x[mask]) ** 2) | |
| raise KeyError(task) | |
| def eval_autoencoding( | |
| model, | |
| loader, | |
| task, | |
| method, | |
| device, | |
| normalization, | |
| volume_zero_threshold, | |
| price_zero_threshold, | |
| price_gap_margin, | |
| raw_price_tick_size, | |
| structure_weight=None, | |
| mask_seed=None, | |
| imputation_mask_ratio=0.2, | |
| ): | |
| devices = [device.index if device.index is not None else torch.cuda.current_device()] if device.type == "cuda" else [] | |
| with torch.random.fork_rng(devices=devices, enabled=mask_seed is not None): | |
| if mask_seed is not None: | |
| torch.manual_seed(int(mask_seed)) | |
| model.eval() | |
| total_loss = 0.0 | |
| region_squared_error = 0.0 | |
| region_entries = 0 | |
| endpoint_squared_error = 0.0 | |
| endpoint_entries = 0 | |
| all_position_squared_error = 0.0 | |
| all_position_entries = 0 | |
| raw_price_absolute_error = 0.0 | |
| raw_price_entries = 0 | |
| raw_volume_absolute_error = 0.0 | |
| raw_volume_entries = 0 | |
| total_n = 0 | |
| metric_sums = {} | |
| with torch.no_grad(): | |
| for bx, _ in loader: | |
| bx = bx.to(device) | |
| if task == "reconstruction": | |
| pred = model(bx) | |
| completed = pred | |
| mask = torch.ones_like(bx, dtype=torch.bool) | |
| loss = ( | |
| lob_aware_reconstruction_loss( | |
| pred, | |
| bx, | |
| structure_weight=effective_structure_weight(method, structure_weight), | |
| volume_zero_threshold=volume_zero_threshold, | |
| price_zero_threshold=price_zero_threshold, | |
| price_gap_margin=price_gap_margin, | |
| ) | |
| if structural_loss_enabled(method, structure_weight) | |
| else torch.mean((pred - bx) ** 2) | |
| ) | |
| elif task == "interpolation": | |
| masked, mask = mask_patches(bx, patch_len=10, mask_ratio=0.4) | |
| pred = model(masked) | |
| completed = pred | |
| loss = ( | |
| lob_aware_reconstruction_loss( | |
| pred, | |
| bx, | |
| mask=mask, | |
| structure_weight=effective_structure_weight(method, structure_weight), | |
| volume_zero_threshold=volume_zero_threshold, | |
| price_zero_threshold=price_zero_threshold, | |
| price_gap_margin=price_gap_margin, | |
| ) | |
| if structural_loss_enabled(method, structure_weight) | |
| else (torch.mean((pred[mask] - bx[mask]) ** 2) if mask.any() else torch.mean((pred - bx) ** 2)) | |
| ) | |
| elif task == "imputation": | |
| masked, mask = mask_entries(bx, mask_ratio=imputation_mask_ratio) | |
| pred = model(masked) | |
| completed = torch.where(mask, pred, bx) | |
| loss = ( | |
| lob_aware_reconstruction_loss( | |
| completed, | |
| bx, | |
| mask=mask, | |
| structure_weight=effective_structure_weight(method, structure_weight), | |
| volume_zero_threshold=volume_zero_threshold, | |
| price_zero_threshold=price_zero_threshold, | |
| price_gap_margin=price_gap_margin, | |
| ) | |
| if structural_loss_enabled(method, structure_weight) | |
| else torch.mean((pred[mask] - bx[mask]) ** 2) | |
| ) | |
| else: | |
| raise KeyError(task) | |
| region_difference = pred[mask] - bx[mask] | |
| endpoint_pred = completed[:, -1:, :] | |
| endpoint_target = bx[:, -1:, :] | |
| endpoint_difference = endpoint_pred - endpoint_target | |
| all_position_difference = completed - bx | |
| metrics = lob_validity_metrics( | |
| endpoint_pred, | |
| endpoint_target, | |
| normalization=normalization, | |
| raw_price_tick_size=raw_price_tick_size, | |
| ) | |
| all_position_metrics = lob_validity_metrics( | |
| completed, | |
| bx, | |
| normalization=normalization, | |
| raw_price_tick_size=raw_price_tick_size, | |
| ) | |
| total_loss += float(loss.item()) * len(bx) | |
| region_squared_error += float((region_difference * region_difference).sum().item()) | |
| region_entries += int(region_difference.numel()) | |
| endpoint_squared_error += float((endpoint_difference * endpoint_difference).sum().item()) | |
| endpoint_entries += int(endpoint_difference.numel()) | |
| all_position_squared_error += float((all_position_difference * all_position_difference).sum().item()) | |
| all_position_entries += int(all_position_difference.numel()) | |
| raw_pred = inverse_grouped_normalization(pred, normalization) | |
| raw_target = inverse_grouped_normalization(bx, normalization) | |
| raw_difference = torch.abs(raw_pred - raw_target) | |
| price_mask = mask[:, :, :20] | |
| volume_mask = mask[:, :, 20:40] | |
| raw_price_absolute_error += float(raw_difference[:, :, :20][price_mask].sum().item()) | |
| raw_price_entries += int(price_mask.sum().item()) | |
| raw_volume_absolute_error += float(raw_difference[:, :, 20:40][volume_mask].sum().item()) | |
| raw_volume_entries += int(volume_mask.sum().item()) | |
| total_n += len(bx) | |
| for key, value in metrics.items(): | |
| metric_sums[key] = metric_sums.get(key, 0.0) + value * len(bx) | |
| for key, value in all_position_metrics.items(): | |
| prefixed = f"all_positions_{key}" | |
| metric_sums[prefixed] = metric_sums.get(prefixed, 0.0) + value * len(bx) | |
| return { | |
| "loss": total_loss / max(total_n, 1), | |
| "mse": endpoint_squared_error / max(endpoint_entries, 1), | |
| "region_mse": region_squared_error / max(region_entries, 1), | |
| "endpoint_mse": endpoint_squared_error / max(endpoint_entries, 1), | |
| "all_positions_mse": all_position_squared_error / max(all_position_entries, 1), | |
| "region_raw_price_mae": raw_price_absolute_error / max(raw_price_entries, 1), | |
| "region_raw_volume_mae": raw_volume_absolute_error / max(raw_volume_entries, 1), | |
| **{key: value / max(total_n, 1) for key, value in metric_sums.items()}, | |
| } | |
| def load_normalization(processed_dir: Path, stock: str) -> dict[str, float]: | |
| manifest_path = processed_dir / "manifest.json" | |
| if not manifest_path.exists(): | |
| raise FileNotFoundError( | |
| f"Raw-unit evaluation requires the processed-data manifest: {manifest_path}" | |
| ) | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| if stock in manifest and "normalization" in manifest[stock]: | |
| normalization = manifest[stock]["normalization"] | |
| else: | |
| public_asset = next( | |
| ( | |
| asset | |
| for asset in manifest.get("assets", []) | |
| if asset.get("alias") == stock | |
| ), | |
| None, | |
| ) | |
| if public_asset is None or "normalization_training_only" not in public_asset: | |
| raise KeyError( | |
| f"Missing normalization statistics for {stock} in {manifest_path}" | |
| ) | |
| normalization = public_asset["normalization_training_only"] | |
| required = {"price_mean", "price_std", "volume_mean", "volume_std"} | |
| missing = required.difference(normalization) | |
| if missing: | |
| raise KeyError(f"Missing normalization fields for {stock}: {sorted(missing)}") | |
| if float(normalization["price_std"]) <= 0 or float(normalization["volume_std"]) <= 0: | |
| raise ValueError(f"Non-positive normalization scale for {stock}") | |
| return {key: float(normalization[key]) for key in sorted(required)} | |
| def train_autoencoding_task( | |
| cfg, | |
| stock, | |
| method, | |
| task, | |
| seed, | |
| force=False, | |
| structure_weight=None, | |
| ): | |
| out_dir = Path(cfg["results_dir"]) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| suffix = ( | |
| f"_lambda{lambda_tag(structure_weight)}" | |
| if structure_weight is not None | |
| else "" | |
| ) | |
| out_file = out_dir / f"{stock}_{method}_{task}_seed{seed}{suffix}.json" | |
| if out_file.exists() and not force: | |
| print(f"SKIP {stock} {method} {task} seed={seed}", flush=True) | |
| return | |
| set_seed(seed) | |
| train_cfg = cfg["training"] | |
| device = torch.device(train_cfg["device"] if torch.cuda.is_available() else "cpu") | |
| processed_dir = Path(cfg["processed_dir"]) | |
| x, y, splits = load_npz(data_path_for_stock(cfg, stock)) | |
| normalization = load_normalization(processed_dir, stock) | |
| volume_zero_threshold = ( | |
| -normalization["volume_mean"] / normalization["volume_std"] | |
| ) | |
| raw_price_tick_size = float(cfg.get("raw_price_tick_size", 0.01)) | |
| price_zero_threshold = ( | |
| (raw_price_tick_size - normalization["price_mean"]) | |
| / normalization["price_std"] | |
| ) | |
| price_gap_margin = raw_price_tick_size / normalization["price_std"] | |
| imputation_mask_ratio = float(cfg.get("imputation_mask_ratio", 0.2)) | |
| 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, splits["train"], 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) | |
| encoder = build_method(method, int(train_cfg["latent_dim"]), int(train_cfg.get("d_model", 96))) | |
| model = ReconstructionPretrainer( | |
| encoder, | |
| d_model=int(train_cfg.get("d_model", 96)), | |
| legalize_prices=uses_legalized_decoder(method), | |
| ).to(device) | |
| opt = torch.optim.AdamW(model.parameters(), lr=train_cfg["learning_rate"], weight_decay=train_cfg["weight_decay"]) | |
| scheduler = make_plateau_scheduler(opt, train_cfg, "min") | |
| best = float("inf") | |
| patience_best = float("inf") | |
| best_state = copy.deepcopy(model.state_dict()) | |
| best_epoch = 0 | |
| history = [] | |
| patience = int(train_cfg.get("pretrain_patience", 0)) | |
| min_delta_abs = float(train_cfg.get("pretrain_early_stopping_min_delta_abs", 0.0)) | |
| min_delta_rel = float(train_cfg.get("pretrain_early_stopping_min_delta_rel", 0.0)) | |
| eval_mask_seed = seed if bool(train_cfg.get("fixed_eval_mask", False)) else None | |
| stale = 0 | |
| started = time.perf_counter() | |
| for epoch in range(1, int(train_cfg["pretrain_epochs"]) + 1): | |
| epoch_started = time.perf_counter() | |
| model.train() | |
| train_loss = 0.0 | |
| train_n = 0 | |
| for bx, _ in train_loader: | |
| bx = bx.to(device) | |
| opt.zero_grad(set_to_none=True) | |
| loss = task_loss( | |
| model, | |
| bx, | |
| task, | |
| method, | |
| volume_zero_threshold=volume_zero_threshold, | |
| price_zero_threshold=price_zero_threshold, | |
| price_gap_margin=price_gap_margin, | |
| structure_weight=structure_weight, | |
| imputation_mask_ratio=imputation_mask_ratio, | |
| ) | |
| loss.backward() | |
| opt.step() | |
| train_loss += float(loss.item()) * len(bx) | |
| train_n += len(bx) | |
| train_loss /= max(train_n, 1) | |
| val_eval = eval_autoencoding( | |
| model, | |
| val_loader, | |
| task, | |
| method, | |
| device, | |
| normalization, | |
| volume_zero_threshold, | |
| price_zero_threshold, | |
| price_gap_margin, | |
| raw_price_tick_size, | |
| structure_weight, | |
| eval_mask_seed, | |
| imputation_mask_ratio, | |
| ) | |
| val_loss = val_eval["loss"] | |
| learning_rate = float(opt.param_groups[0]["lr"]) | |
| history.append( | |
| { | |
| "epoch": epoch, | |
| "train_loss": train_loss, | |
| "val_loss": val_loss, | |
| "val_mse": val_eval["mse"], | |
| "learning_rate": learning_rate, | |
| **{f"val_{key}": value for key, value in val_eval.items() if key not in {"loss", "mse"}}, | |
| "epoch_seconds": time.perf_counter() - epoch_started, | |
| } | |
| ) | |
| if scheduler is not None: | |
| scheduler.step(val_loss) | |
| if bool(train_cfg.get("log_epochs", False)): | |
| print( | |
| f"EPOCH {stock} {method} {task} seed={seed} " | |
| f"{epoch}/{train_cfg['pretrain_epochs']}: " | |
| f"train_loss={train_loss:.6f} val_loss={val_loss:.6f} " | |
| f"val_mse={val_eval['mse']:.6f} lr={learning_rate:.2e}", | |
| flush=True, | |
| ) | |
| if val_loss < best: | |
| best = val_loss | |
| best_epoch = epoch | |
| best_state = copy.deepcopy(model.state_dict()) | |
| if materially_improved(val_loss, patience_best, "min", min_delta_abs, min_delta_rel): | |
| patience_best = val_loss | |
| stale = 0 | |
| else: | |
| stale += 1 | |
| if patience and stale >= patience: | |
| break | |
| model.load_state_dict(best_state) | |
| test_mask_seed = eval_mask_seed + 100_000 if eval_mask_seed is not None else None | |
| test_eval = eval_autoencoding( | |
| model, | |
| test_loader, | |
| task, | |
| method, | |
| device, | |
| normalization, | |
| volume_zero_threshold, | |
| price_zero_threshold, | |
| price_gap_margin, | |
| raw_price_tick_size, | |
| structure_weight, | |
| test_mask_seed, | |
| imputation_mask_ratio, | |
| ) | |
| reconstruction_seconds = time.perf_counter() - started | |
| downstream = None | |
| if task == "reconstruction" and bool( | |
| cfg.get("downstream_after_reconstruction", False) | |
| ): | |
| label_budget = float(cfg.get("label_budget", 0.5)) | |
| downstream_train_idx = sample_label_budget( | |
| y, | |
| splits["train"], | |
| label_budget, | |
| seed, | |
| ) | |
| # Reset all RNGs so MSE and soft-penalty arms receive the same head, | |
| # minibatch ordering, and downstream stochastic state. | |
| set_seed(seed) | |
| downstream = train_downstream_model( | |
| copy.deepcopy(model.encoder), | |
| x, | |
| y, | |
| splits, | |
| downstream_train_idx, | |
| train_cfg, | |
| "fine_tune", | |
| device, | |
| ) | |
| result = { | |
| "stock": stock, | |
| "method": method, | |
| "task": task, | |
| "seed": seed, | |
| "structure_weight": effective_structure_weight(method, structure_weight), | |
| "raw_price_tick_size": raw_price_tick_size, | |
| "normalization": normalization, | |
| "normalized_raw_volume_zero": volume_zero_threshold, | |
| "normalized_raw_price_floor": price_zero_threshold, | |
| "normalized_one_tick_gap": price_gap_margin, | |
| "imputation_mask_ratio": imputation_mask_ratio if task == "imputation" else None, | |
| "best_epoch": best_epoch, | |
| "best_val_loss": best, | |
| "stopped_epoch": len(history), | |
| "stopped_early": len(history) < int(train_cfg["pretrain_epochs"]), | |
| "test_loss": test_eval["loss"], | |
| "test_mse": test_eval["mse"], | |
| "test_lob_metrics": {key: value for key, value in test_eval.items() if key not in {"loss", "mse"}}, | |
| "seconds": reconstruction_seconds, | |
| "total_seconds": time.perf_counter() - started, | |
| "downstream_after_reconstruction": downstream, | |
| "downstream_protocol": { | |
| "enabled": downstream is not None, | |
| "setting": "fine_tune" if downstream is not None else None, | |
| "label_budget": float(cfg.get("label_budget", 0.5)) | |
| if downstream is not None | |
| else None, | |
| "paired_seed_reset": downstream is not None, | |
| "logits": "raw" if downstream is not None else None, | |
| }, | |
| "history": history, | |
| } | |
| out_file.write_text(json.dumps(result, indent=2), encoding="utf-8") | |
| print(f"DONE {stock} {method} {task}: test_loss={result['test_loss']:.6f}", flush=True) | |
| def train_trend_task(cfg, stock, method, seed, label_budget, force=False): | |
| out_dir = Path(cfg["results_dir"]) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| out_file = out_dir / f"{stock}_{method}_trend_seed{seed}_budget{int(round(label_budget * 100)):03d}.json" | |
| if out_file.exists() and not force: | |
| print(f"SKIP {stock} {method} trend seed={seed}", flush=True) | |
| return | |
| set_seed(seed) | |
| train_cfg = cfg["training"] | |
| device = torch.device(train_cfg["device"] if torch.cuda.is_available() else "cpu") | |
| x, y, splits = load_npz(data_path_for_stock(cfg, stock)) | |
| train_idx = sample_label_budget(y, splits["train"], label_budget, seed) | |
| 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) | |
| encoder = build_method(method, int(train_cfg["latent_dim"]), int(train_cfg.get("d_model", 96))) | |
| model = Classifier(encoder, latent_dim=int(train_cfg["latent_dim"])).to(device) | |
| opt = torch.optim.AdamW(model.parameters(), lr=train_cfg["learning_rate"], weight_decay=train_cfg["weight_decay"]) | |
| scheduler = make_plateau_scheduler(opt, train_cfg, "max") | |
| criterion = nn.CrossEntropyLoss() | |
| best_f1 = -1.0 | |
| patience_best_f1 = float("-inf") | |
| best_epoch = 0 | |
| best_state = copy.deepcopy(model.state_dict()) | |
| stale = 0 | |
| patience = int(train_cfg.get("downstream_patience", 0)) | |
| min_delta_abs = float(train_cfg.get("downstream_early_stopping_min_delta_abs", 0.0)) | |
| min_delta_rel = float(train_cfg.get("downstream_early_stopping_min_delta_rel", 0.0)) | |
| history = [] | |
| 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) | |
| val = evaluate(model, val_loader, device) | |
| learning_rate = float(opt.param_groups[0]["lr"]) | |
| history.append( | |
| { | |
| "epoch": epoch, | |
| "loss": loss, | |
| "learning_rate": learning_rate, | |
| "epoch_seconds": time.perf_counter() - epoch_started, | |
| **{f"val_{k}": v for k, v in val.items()}, | |
| } | |
| ) | |
| if scheduler is not None: | |
| scheduler.step(val["macro_f1"]) | |
| if bool(train_cfg.get("log_epochs", False)): | |
| print( | |
| f"EPOCH {stock} {method} trend seed={seed} " | |
| f"{epoch}/{train_cfg['downstream_epochs']}: " | |
| f"train_loss={loss:.6f} val_macro_f1={val['macro_f1']:.6f} " | |
| f"lr={learning_rate:.2e}", | |
| flush=True, | |
| ) | |
| if val["macro_f1"] > best_f1: | |
| best_f1 = val["macro_f1"] | |
| best_epoch = epoch | |
| best_state = copy.deepcopy(model.state_dict()) | |
| if materially_improved( | |
| val["macro_f1"], | |
| patience_best_f1, | |
| "max", | |
| min_delta_abs, | |
| min_delta_rel, | |
| ): | |
| patience_best_f1 = val["macro_f1"] | |
| stale = 0 | |
| else: | |
| stale += 1 | |
| if patience and stale >= patience: | |
| break | |
| model.load_state_dict(best_state) | |
| val_logits, val_true = collect_logits(model, val_loader, device) | |
| test_logits, test_true = collect_logits(model, test_loader, device) | |
| raw_val = classification_metrics(val_logits, val_true) | |
| raw_test = classification_metrics(test_logits, test_true) | |
| val_metrics = raw_val | |
| test_metrics = raw_test | |
| val_confusion = confusion_summary(val_logits, val_true) | |
| test_confusion = confusion_summary(test_logits, test_true) | |
| calibration = None | |
| if bool(train_cfg.get("trend_calibration", False)): | |
| 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 = { | |
| "stock": stock, | |
| "method": method, | |
| "task": "trend", | |
| "seed": seed, | |
| "label_budget": label_budget, | |
| "best_epoch": best_epoch, | |
| "best_val_macro_f1": best_f1, | |
| "stopped_epoch": len(history), | |
| "stopped_early": len(history) < int(train_cfg["downstream_epochs"]), | |
| "raw_val": raw_val, | |
| "raw_test": raw_test, | |
| "val": val_metrics, | |
| "test": test_metrics, | |
| "val_confusion": val_confusion, | |
| "test_confusion": test_confusion, | |
| "calibration": calibration, | |
| "seconds": time.perf_counter() - started, | |
| "history": history, | |
| } | |
| out_file.write_text(json.dumps(result, indent=2), encoding="utf-8") | |
| print(f"DONE {stock} {method} trend: macro_f1={result['test']['macro_f1']:.4f}", flush=True) | |
| def summarize(cfg, name): | |
| out_dir = Path(cfg["results_dir"]) | |
| rows = [] | |
| for path in sorted(out_dir.glob("*.json")): | |
| data = json.loads(path.read_text(encoding="utf-8")) | |
| row = {"stock": data["stock"], "method": data["method"], "task": data["task"], "seed": data["seed"]} | |
| if data["task"] == "trend": | |
| row["metric"] = data["test"]["macro_f1"] | |
| row["metric_name"] = "macro_f1" | |
| else: | |
| row["metric"] = data["test_loss"] | |
| row["metric_name"] = "test_loss" | |
| row["test_mse"] = data.get("test_mse", data["test_loss"]) | |
| for key, value in data.get("test_lob_metrics", {}).items(): | |
| row[key] = value | |
| rows.append(row) | |
| summary_dir = out_dir.parent / "summary" | |
| summary_dir.mkdir(parents=True, exist_ok=True) | |
| csv_path = summary_dir / f"{name}_task_suite.csv" | |
| if rows: | |
| with csv_path.open("w", newline="", encoding="utf-8") as fh: | |
| fieldnames = [] | |
| for row in rows: | |
| for key in row: | |
| if key not in fieldnames: | |
| fieldnames.append(key) | |
| writer = csv.DictWriter(fh, fieldnames=fieldnames, extrasaction="ignore") | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| print(f"wrote {csv_path}", flush=True) | |
| def parse_args(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--config", required=True) | |
| parser.add_argument("--name", default=None) | |
| parser.add_argument("--stocks", nargs="+") | |
| parser.add_argument("--methods", nargs="+") | |
| parser.add_argument("--tasks", nargs="+") | |
| parser.add_argument("--seeds", nargs="+", type=int) | |
| parser.add_argument("--label-budget", type=float, default=None) | |
| parser.add_argument("--force", action="store_true") | |
| parser.add_argument("--summarize-only", action="store_true") | |
| return parser.parse_args() | |
| def main(): | |
| args = parse_args() | |
| cfg = json.loads(Path(args.config).read_text(encoding="utf-8")) | |
| name = args.name or Path(args.config).stem | |
| if args.summarize_only: | |
| summarize(cfg, name) | |
| return | |
| stocks = args.stocks or cfg["stocks"] | |
| methods = args.methods or cfg["methods"] | |
| tasks = args.tasks or cfg["tasks"] | |
| seeds = args.seeds or cfg["seeds"] | |
| label_budget = args.label_budget if args.label_budget is not None else cfg.get("label_budget", 0.5) | |
| for stock in stocks: | |
| for method in methods: | |
| for seed in seeds: | |
| for task in tasks: | |
| if task in {"reconstruction", "interpolation", "imputation"}: | |
| weights = cfg.get("structure_weights", [None]) | |
| for structure_weight in weights: | |
| train_autoencoding_task( | |
| cfg, | |
| stock, | |
| method, | |
| task, | |
| seed, | |
| args.force, | |
| structure_weight, | |
| ) | |
| elif task == "trend": | |
| train_trend_task(cfg, stock, method, seed, label_budget, args.force) | |
| else: | |
| raise KeyError(task) | |
| summarize(cfg, name) | |
| if __name__ == "__main__": | |
| main() | |