-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtrain.py
More file actions
134 lines (110 loc) · 5.18 KB
/
train.py
File metadata and controls
134 lines (110 loc) · 5.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# train.py
"""
DiffQuant — training entry point.
Usage:
python train.py --config configs/experiments/itransformer_hybrid.py
python train.py --config configs/experiments/lstm_hybrid.py --device cuda
python train.py --config configs/experiments/itransformer_hybrid.py --skip-sanity
"""
import argparse
import logging
import pathlib
import sys
import torch
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(logging.Formatter(
"%(asctime)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
))
logging.basicConfig(
level = logging.INFO, # root logger
handlers = [console_handler],
)
logging.getLogger("matplotlib").setLevel(logging.WARNING)
logging.getLogger("PIL").setLevel(logging.WARNING)
log = logging.getLogger(__name__)
def main() -> None:
parser = argparse.ArgumentParser(description="DiffQuant training pipeline")
parser.add_argument("--config", "-c", required=True,
help="Path to experiment config")
parser.add_argument("--device", "-d", default=None,
help="Override device: cpu | cuda | mps")
parser.add_argument("--skip-sanity", action="store_true",
help="Skip sanity checks (not recommended)")
args = parser.parse_args()
# ── Load config ───────────────────────────────────────────────────────────
from configs.experiments import load_config
cfg = load_config(args.config)
if args.device:
cfg.device = args.device
if cfg.device == "cuda" and not torch.cuda.is_available():
log.warning("CUDA not available — falling back to CPU")
cfg.device = "cpu"
if cfg.device == "mps" and not torch.backends.mps.is_available():
log.warning("MPS not available — falling back to CPU")
cfg.device = "cpu"
torch.manual_seed(cfg.seed)
# ── Attach file handler immediately — before any other logging ────────────
# This ensures ALL log messages (sanity checks, data pipeline, model init)
# are written to training.log, not just those after DiffTrainer.__init__.
out_dir = pathlib.Path(cfg.paths.output_dir)
out_dir.mkdir(parents=True, exist_ok=True)
log_path = out_dir / "training.log"
root_logger = logging.getLogger()
already_added = any(
isinstance(h, logging.FileHandler) and
getattr(h, "baseFilename", None) == str(log_path.resolve())
for h in root_logger.handlers
)
if not already_added:
fh = logging.FileHandler(log_path)
fh.setLevel(logging.INFO)
fh.setFormatter(logging.Formatter(
"%(asctime)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
))
root_logger.addHandler(fh)
# ── Log run parameters ────────────────────────────────────────────────────
log.info("Experiment : %s", cfg.experiment_name)
log.info("Device : %s", cfg.device)
log.info("Backbone : %s", cfg.backbone.type)
log.info("Loss : %s", cfg.loss.type)
log.info("Output : %s", cfg.paths.output_dir)
# ── Sanity checks ─────────────────────────────────────────────────────────
if not args.skip_sanity:
from model.policy_network import PolicyNetwork
from simulator.diff_simulator import DiffSimulator, SimConfig
from sanity.checks import run_all_checks
_model = PolicyNetwork(cfg)
_sim = DiffSimulator(SimConfig(
commission_rate = cfg.simulator.commission_rate,
slippage_rate = cfg.simulator.slippage_rate,
))
if not run_all_checks(_model, _sim, cfg):
log.error("Sanity checks failed. Aborting training.")
sys.exit(1)
del _model, _sim
else:
log.warning("Sanity checks skipped.")
# ── Data ──────────────────────────────────────────────────────────────────
from data.pipeline import load_or_build
from data.dataset import TradingDataset
splits = load_or_build(
source_path = cfg.paths.source_data,
cfg = cfg,
cache_dir = cfg.paths.cache_dir,
)
train_ds = TradingDataset(splits["train"])
log.info(
"Dataset — train: %s samples | val raw: %s bars",
f"{len(train_ds):,}",
f"{len(splits['val']['raw_features']):,}",
)
# ── Train ─────────────────────────────────────────────────────────────────
from training.trainer import DiffTrainer
trainer = DiffTrainer(cfg)
trainer.train(
train_dataset = train_ds,
raw_val = splits["val"],
)
if __name__ == "__main__":
main()