Download code/experiments/adma2026_representation/src/train_downstream.py from mythezone/LOBench-A-share-processed: direct link, hf CLI and curl.
- Browser
- Download file 16.4 kB
-
https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/adma2026_representation/src/train_downstream.py
- Command line
-
hf download hf://datasets/mythezone/LOBench-A-share-processed/code/experiments/adma2026_representation/src/train_downstream.py
-
curl -L -o train_downstream.py https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/adma2026_representation/src/train_downstream.py
16.4 kB
| #!/usr/bin/env python3 | |
| """Train end-to-end, frozen-probe, and fine-tuned downstream classifiers.""" | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import json | |
| import random | |
| import time | |
| from pathlib import Path | |
| import torch | |
| from torch import nn | |
| from torch.utils.data import DataLoader, TensorDataset | |
| from models import AutoEncoder, Classifier, build_encoder | |
| def load_npz(path: Path): | |
| import numpy as np # noqa: PLC0415 | |
| with np.load(path, allow_pickle=False) as data: | |
| x = torch.tensor(data["x"], dtype=torch.float32) | |
| y = torch.tensor(data["y"] + 1, dtype=torch.long) | |
| train_key = "train_idx" if "train_idx" in data else "natural_train_idx" | |
| keys = {"train": train_key, "val": "val_idx", "test": "test_idx"} | |
| splits = {name: torch.tensor(data[key], dtype=torch.long) for name, key in keys.items()} | |
| return x, y, splits | |
| 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 sample_label_budget(y, train_idx, budget: float, seed: int): | |
| if budget >= 0.999: | |
| return train_idx | |
| if budget <= 0: | |
| raise ValueError("label budget must be positive.") | |
| import numpy as np # noqa: PLC0415 | |
| rng = np.random.default_rng(seed) | |
| train_np = train_idx.cpu().numpy() | |
| y_np = y.cpu().numpy() | |
| chosen = [] | |
| for cls in sorted(set(y_np[train_np].tolist())): | |
| cls_idx = train_np[y_np[train_np] == cls] | |
| if len(cls_idx) == 0: | |
| continue | |
| n = max(1, int(round(len(cls_idx) * budget))) | |
| chosen.append(rng.choice(cls_idx, size=min(n, len(cls_idx)), replace=False)) | |
| if not chosen: | |
| raise ValueError("label budget produced an empty training split.") | |
| return torch.tensor(np.sort(np.concatenate(chosen)), dtype=torch.long) | |
| def count_parameters(model): | |
| total = sum(p.numel() for p in model.parameters()) | |
| trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) | |
| return {"total": total, "trainable": trainable} | |
| def classification_metrics(logits, y): | |
| pred = logits.argmax(dim=1) | |
| acc = (pred == y).float().mean().item() | |
| precisions = [] | |
| recalls = [] | |
| f1s = [] | |
| for cls in range(3): | |
| tp = ((pred == cls) & (y == cls)).sum().item() | |
| fp = ((pred == cls) & (y != cls)).sum().item() | |
| fn = ((pred != cls) & (y == cls)).sum().item() | |
| recall = tp / max(tp + fn, 1) | |
| precision = tp / max(tp + fp, 1) | |
| precisions.append(precision) | |
| recalls.append(recall) | |
| f1s.append(2 * precision * recall / max(precision + recall, 1e-12)) | |
| class_names = ("down", "stationary", "up") | |
| details = { | |
| f"precision_{name}": float(precisions[index]) | |
| for index, name in enumerate(class_names) | |
| } | |
| details.update( | |
| { | |
| f"recall_{name}": float(recalls[index]) | |
| for index, name in enumerate(class_names) | |
| } | |
| ) | |
| details.update( | |
| { | |
| f"f1_{name}": float(f1s[index]) | |
| for index, name in enumerate(class_names) | |
| } | |
| ) | |
| return { | |
| "accuracy": acc, | |
| "balanced_accuracy": sum(recalls) / 3, | |
| "macro_f1": sum(f1s) / 3, | |
| **details, | |
| } | |
| def evaluate(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 classification_metrics(torch.cat(logits_all), torch.cat(y_all)) | |
| def train_epoch(model, loader, optimizer, device, criterion): | |
| model.train() | |
| total = 0.0 | |
| n = 0 | |
| for x, y in loader: | |
| x, y = x.to(device), y.to(device) | |
| optimizer.zero_grad(set_to_none=True) | |
| loss = criterion(model(x), y) | |
| loss.backward() | |
| optimizer.step() | |
| total += float(loss.item()) * len(y) | |
| n += len(y) | |
| return total / max(n, 1) | |
| def level_weights(device: torch.device, dtype: torch.dtype, decay: float = 0.85) -> torch.Tensor: | |
| near_to_far = torch.pow( | |
| torch.full((10,), decay, device=device, dtype=dtype), | |
| torch.arange(10, device=device, dtype=dtype), | |
| ) | |
| weights = torch.cat([near_to_far.flip(0), near_to_far, near_to_far.flip(0), near_to_far]) | |
| return weights / weights.mean() | |
| def structure_regularizer(recon: torch.Tensor) -> torch.Tensor: | |
| prices = recon[:, :, :20] | |
| bid = prices[:, :, :10] | |
| ask = prices[:, :, 10:20] | |
| bid_order = torch.relu(bid[:, :, :-1] - bid[:, :, 1:]).mean() | |
| ask_order = torch.relu(ask[:, :, :-1] - ask[:, :, 1:]).mean() | |
| spread = torch.relu(bid[:, :, -1] - ask[:, :, 0]).mean() | |
| return bid_order + ask_order + spread | |
| def reconstruction_loss(pred: torch.Tensor, target: torch.Tensor, loss_name: str, structure_weight: float) -> torch.Tensor: | |
| mse = torch.mean((pred - target) ** 2) | |
| if loss_name == "mse": | |
| return mse | |
| if loss_name == "wmse": | |
| weights = level_weights(pred.device, pred.dtype) | |
| return torch.mean((pred - target) ** 2 * weights) | |
| if loss_name == "mse_structure": | |
| return mse + structure_weight * structure_regularizer(pred) | |
| if loss_name in {"lobench", "wmse_structure"}: | |
| weights = level_weights(pred.device, pred.dtype) | |
| wmse = torch.mean((pred - target) ** 2 * weights) | |
| return wmse + structure_weight * structure_regularizer(pred) | |
| raise ValueError(f"unknown pretrain_loss: {loss_name}") | |
| def pretrain_encoder(model_name, latent_dim, train_loader, val_loader, cfg, device, ckpt_path): | |
| meta_path = ckpt_path.with_suffix(".pretrain.json") | |
| if ckpt_path.exists() and meta_path.exists(): | |
| return json.loads(meta_path.read_text(encoding="utf-8")) | {"cached": True} | |
| encoder = build_encoder(model_name, latent_dim) | |
| decoder_name = cfg.get("pretrain_decoder", "mlp") | |
| ae = AutoEncoder( | |
| encoder, | |
| latent_dim=latent_dim, | |
| decoder_name=decoder_name, | |
| decoder_layers=int(cfg.get("pretrain_decoder_layers", 2)), | |
| decoder_heads=int(cfg.get("pretrain_decoder_heads", 8)), | |
| decoder_d_model=int(cfg.get("pretrain_decoder_d_model", latent_dim)), | |
| ).to(device) | |
| opt = torch.optim.AdamW(ae.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"]) | |
| loss_name = cfg.get("pretrain_loss", "mse") | |
| structure_weight = float(cfg.get("pretrain_structure_weight", 0.1)) | |
| 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() | |
| ae.train() | |
| train_loss = 0.0 | |
| train_mse = 0.0 | |
| train_n = 0 | |
| for x, _ in train_loader: | |
| x = x.to(device) | |
| opt.zero_grad(set_to_none=True) | |
| pred = ae(x) | |
| loss = reconstruction_loss(pred, x, loss_name, structure_weight) | |
| loss.backward() | |
| opt.step() | |
| train_loss += float(loss.item()) * len(x) | |
| train_mse += float(torch.mean((pred.detach() - x) ** 2).item()) * len(x) | |
| train_n += len(x) | |
| val = 0.0 | |
| val_mse = 0.0 | |
| n = 0 | |
| ae.eval() | |
| with torch.no_grad(): | |
| for x, _ in val_loader: | |
| x = x.to(device) | |
| pred = ae(x) | |
| batch_loss = reconstruction_loss(pred, x, loss_name, structure_weight).item() | |
| batch_mse = torch.mean((pred - x) ** 2).item() | |
| val += batch_loss * len(x) | |
| val_mse += batch_mse * len(x) | |
| n += len(x) | |
| val /= max(n, 1) | |
| val_mse /= max(n, 1) | |
| history.append( | |
| { | |
| "epoch": epoch, | |
| "train_loss": train_loss / max(train_n, 1), | |
| "val_loss": val, | |
| "train_mse": train_mse / max(train_n, 1), | |
| "val_mse": val_mse, | |
| f"train_{loss_name}": train_loss / max(train_n, 1), | |
| f"val_{loss_name}": val, | |
| "epoch_seconds": time.perf_counter() - epoch_started, | |
| } | |
| ) | |
| if val < best: | |
| best = val | |
| best_epoch = epoch | |
| torch.save(ae.encoder.state_dict(), ckpt_path) | |
| epochs_without_improvement = 0 | |
| else: | |
| epochs_without_improvement += 1 | |
| if patience and epochs_without_improvement >= patience: | |
| break | |
| meta = { | |
| "decoder": decoder_name, | |
| "pretrain_loss": loss_name, | |
| "pretrain_structure_weight": structure_weight, | |
| "best_val_loss": best, | |
| f"best_val_{loss_name}": best, | |
| "best_val_mse": history[best_epoch - 1]["val_mse"] if best_epoch else None, | |
| "best_epoch": best_epoch, | |
| "seconds": time.perf_counter() - started, | |
| "history": history, | |
| "cached": False, | |
| } | |
| meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8") | |
| return meta | |
| def set_seed(seed: int) -> None: | |
| import os # noqa: PLC0415 | |
| os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") | |
| random.seed(seed) | |
| torch.manual_seed(seed) | |
| if torch.cuda.is_available(): | |
| torch.cuda.manual_seed_all(seed) | |
| torch.backends.cudnn.benchmark = False | |
| torch.backends.cudnn.deterministic = True | |
| # Fail loudly if a final evidence run reaches a nondeterministic CUDA | |
| # kernel. Repeated seeds are meaningful only when the execution policy is | |
| # itself recorded and enforced. | |
| torch.use_deterministic_algorithms(True, warn_only=False) | |
| try: | |
| import numpy as np # noqa: PLC0415 | |
| np.random.seed(seed) | |
| except Exception: | |
| pass | |
| def run(args): | |
| cfg = json.loads(Path(args.config).read_text(encoding="utf-8")) | |
| train_cfg = cfg["training"] | |
| out_dir = Path(cfg["results_dir"]) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| pretrain_stock = args.pretrain_stock or args.stock | |
| windows = Path(cfg["processed_dir"]) / f"{args.stock}_pilot.npz" | |
| x, y, splits = load_npz(windows) | |
| set_seed(args.seed) | |
| device = torch.device(train_cfg["device"] if torch.cuda.is_available() else "cpu") | |
| batch_size = int(train_cfg["batch_size"]) | |
| num_workers = int(train_cfg.get("num_workers", 0)) | |
| pin_memory = device.type == "cuda" | |
| label_budget = float(args.label_budget) | |
| downstream_train_idx = sample_label_budget(y, splits["train"], label_budget, args.seed) | |
| pretrain_train_loader = make_loader(x, y, splits["train"], batch_size, shuffle=True, num_workers=num_workers, pin_memory=pin_memory) | |
| train_loader = make_loader(x, y, downstream_train_idx, batch_size, shuffle=True, num_workers=num_workers, pin_memory=pin_memory) | |
| val_loader = make_loader(x, y, splits["val"], batch_size, shuffle=False, num_workers=num_workers, pin_memory=pin_memory) | |
| test_loader = make_loader(x, y, splits["test"], batch_size, shuffle=False, num_workers=num_workers, pin_memory=pin_memory) | |
| latent_dim = int(train_cfg["latent_dim"]) | |
| decoder_name = train_cfg.get("pretrain_decoder", "mlp") | |
| pretrain_loss_name = train_cfg.get("pretrain_loss", "mse") | |
| encoder = build_encoder(args.model, latent_dim) | |
| loss_tag = "" if pretrain_loss_name == "mse" else f"_loss{pretrain_loss_name}" | |
| ckpt = out_dir / f"{pretrain_stock}_{args.model}_{decoder_name}{loss_tag}_seed{args.seed}_encoder.pt" | |
| pretrain = None | |
| if args.setting in {"frozen_probe", "fine_tune"}: | |
| source_train_loader = pretrain_train_loader | |
| source_val_loader = val_loader | |
| if pretrain_stock != args.stock: | |
| source_windows = Path(cfg["processed_dir"]) / f"{pretrain_stock}_pilot.npz" | |
| sx, sy, source_splits = load_npz(source_windows) | |
| source_train_loader = make_loader( | |
| sx, | |
| sy, | |
| source_splits["train"], | |
| batch_size, | |
| shuffle=True, | |
| num_workers=num_workers, | |
| pin_memory=pin_memory, | |
| ) | |
| source_val_loader = make_loader( | |
| sx, | |
| sy, | |
| source_splits["val"], | |
| batch_size, | |
| shuffle=False, | |
| num_workers=num_workers, | |
| pin_memory=pin_memory, | |
| ) | |
| pretrain = pretrain_encoder(args.model, latent_dim, source_train_loader, source_val_loader, train_cfg, device, ckpt) | |
| encoder.load_state_dict(torch.load(ckpt, map_location="cpu")) | |
| if args.setting in {"frozen_probe", "random_frozen"}: | |
| for p in encoder.parameters(): | |
| p.requires_grad = False | |
| model = Classifier(encoder, latent_dim=latent_dim).to(device) | |
| parameters = count_parameters(model) | |
| 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"], | |
| ) | |
| criterion = nn.CrossEntropyLoss() | |
| history = [] | |
| train_started = time.perf_counter() | |
| best_val_macro_f1 = -1.0 | |
| best_epoch = 0 | |
| best_state = copy.deepcopy(model.state_dict()) | |
| epochs_without_improvement = 0 | |
| patience = int(train_cfg.get("downstream_patience", 0)) | |
| 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()}, | |
| } | |
| ) | |
| if patience and epochs_without_improvement >= patience: | |
| break | |
| downstream_seconds = time.perf_counter() - train_started | |
| model.load_state_dict(best_state) | |
| result = { | |
| "stock": args.stock, | |
| "pretrain_stock": pretrain_stock, | |
| "model": args.model, | |
| "setting": args.setting, | |
| "seed": args.seed, | |
| "label_budget": label_budget, | |
| "label_horizon": cfg.get("data", {}).get("label_horizon"), | |
| "label_threshold": cfg.get("data", {}).get("label_threshold"), | |
| "train_samples": int(len(downstream_train_idx)), | |
| "full_train_samples": int(len(splits["train"])), | |
| "pretrain_decoder": decoder_name, | |
| "pretrain": pretrain, | |
| "pretrain_cached": bool(pretrain.get("cached")) if pretrain else False, | |
| "parameters": parameters, | |
| "best_val_macro_f1": best_val_macro_f1, | |
| "best_epoch": best_epoch, | |
| "downstream_seconds": downstream_seconds, | |
| "total_seconds": downstream_seconds + (pretrain["seconds"] if pretrain else 0.0), | |
| "val": evaluate(model, val_loader, device), | |
| "test": evaluate(model, test_loader, device), | |
| "history": history, | |
| } | |
| budget_tag = f"_budget{int(round(label_budget * 100)):03d}" if label_budget < 0.999 else "" | |
| source_tag = f"_from{pretrain_stock}" if pretrain_stock != args.stock else "" | |
| out_file = out_dir / f"{args.stock}_{args.model}_{args.setting}{source_tag}_seed{args.seed}{budget_tag}.json" | |
| out_file.write_text(json.dumps(result, indent=2), encoding="utf-8") | |
| print(json.dumps(result["test"], indent=2)) | |
| print(f"wrote {out_file}") | |
| def parse_args(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--config", required=True) | |
| parser.add_argument("--stock", required=True) | |
| parser.add_argument("--model", required=True) | |
| parser.add_argument("--setting", choices=["end_to_end", "random_frozen", "frozen_probe", "fine_tune"], required=True) | |
| parser.add_argument("--seed", type=int, required=True) | |
| parser.add_argument("--label-budget", type=float, default=1.0) | |
| parser.add_argument("--pretrain-stock", default=None) | |
| return parser.parse_args() | |
| if __name__ == "__main__": | |
| run(parse_args()) | |