Coverage for retraining/slicing.py: 100%
91 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Training on a small machine (V6.6.10): memory profiles, lazy sequence windows and the process's memory, numpy and stdlib only.
3The sequence trainer used to build a dense (rows, window, features) float32 array per split, about 2 GB for the 2014-2021 train
4window. Under the `low` profile it keeps one (rows, features) matrix and an index of each row's window instead, and gathers a
5batch's windows when the batch is drawn: `gather_windows(matrix, sequence_window_index(...))` is exactly
6`train.build_sequence_tensor_dataset(...)`, so training on either is the same computation.
7"""
9from __future__ import annotations
11import ctypes
12import json
13import sys
14from collections.abc import Sequence
15from dataclasses import asdict, dataclass
16from pathlib import Path
17from typing import TYPE_CHECKING, Any
19import numpy as np
21if TYPE_CHECKING:
22 import pandas as pd
24GIB = 1024.0 ** 3
27@dataclass(frozen=True)
28class MemoryProfile:
29 """How a trainer holds its data. `min_total_gb` is the RAM `ram_preflight` asks of a local host under this profile; `timeout_factor`
30 scales the walk-forward's per-trainer timeouts (a low-profile trainer is slower: at 1x the later windows' trainers were killed, #408)."""
31 name: str
32 lazy_windows: bool
33 read_chunk_rows: int
34 checkpoint_every: int
35 min_total_gb: float
36 timeout_factor: float = 1.0
39PROFILES = {
40 "standard": MemoryProfile("standard", lazy_windows=False, read_chunk_rows=40_000, checkpoint_every=0, min_total_gb=14.0),
41 "low": MemoryProfile("low", lazy_windows=True, read_chunk_rows=10_000, checkpoint_every=1, min_total_gb=3.5, timeout_factor=4.0),
42}
45def memory_profile(name: str) -> MemoryProfile:
46 """The named profile; an unknown name is an error, never a silent default."""
47 if name not in PROFILES:
48 raise ValueError(f"unknown memory profile {name!r}; expected one of {sorted(PROFILES)}")
49 return PROFILES[name]
52def estimate_peak_gb(rows: int, columns: int, features: int, *, window: int, profile: str, train_fraction: float = 0.62) -> float:
53 """A conservative estimate of the sequence trainer's peak resident memory, in GB.
55 The frame (float32, plus pandas' parse buffers of one chunk in float64), the sequence windows (dense per split, or the row matrix
56 and an int32 index), and a fixed 0.6 GB for the interpreter, torch and the model. The sequence stage is the largest of the stack's
57 stages; the others hold the frame and a flat copy of it."""
58 chosen = memory_profile(profile)
59 frame = rows * columns * 4 + chosen.read_chunk_rows * columns * 8
60 if chosen.lazy_windows:
61 windows = rows * features * 4 + rows * window * 4
62 else:
63 windows = rows * window * features * 4 * max(train_fraction, 1.0 - train_fraction)
64 return round((frame + windows) / GIB + 0.6, 2)
67def sequence_window_index(tickers: Sequence[Any] | np.ndarray, window_size: int, row_mask: np.ndarray | None = None) -> np.ndarray:
68 """(rows, window_size) int32 positions into the frame: row i's window is its ticker's last `window_size` rows up to and including i,
69 in frame order, left-padded with -1 where the ticker has fewer rows. With `row_mask`, only the masked rows, in frame order (a window
70 still reaches back into rows the mask leaves out, exactly as `build_sequence_tensor_dataset` does)."""
71 if window_size < 1:
72 raise ValueError("window_size must be at least 1")
73 tickers = np.asarray(tickers)
74 rows = len(tickers)
75 if rows >= np.iinfo(np.int32).max:
76 raise ValueError("too many rows for an int32 index")
77 index = np.full((rows, window_size), -1, dtype=np.int32)
78 if rows:
79 _, codes = np.unique(tickers, return_inverse=True)
80 order = np.argsort(codes, kind="stable")
81 bounds = np.flatnonzero(np.diff(codes[order])) + 1
82 for positions in np.split(order.astype(np.int32), bounds):
83 padded = np.concatenate([np.full(window_size - 1, -1, dtype=np.int32), positions])
84 index[positions] = np.lib.stride_tricks.sliding_window_view(padded, window_size)
85 if row_mask is not None:
86 index = index[np.asarray(row_mask, dtype=bool)]
87 return index
90def gather_windows(matrix: np.ndarray, index: np.ndarray) -> np.ndarray:
91 """The (len(index), window, features) float32 windows: `matrix[index]` with every -1 position as a row of zeros."""
92 out = np.asarray(matrix, dtype=np.float32)[np.maximum(index, 0)]
93 out[index < 0] = 0.0
94 return out
97def read_csv_float32(path: Path | str, chunk_rows: int = 40_000) -> pd.DataFrame:
98 """`pd.read_csv(path)` with every float64 column as float32, parsed in chunks: the whole file is never held in float64. Dates,
99 tickers and boolean flags keep their types."""
100 import pandas as pd
102 parts = []
103 for chunk in pd.read_csv(path, chunksize=max(1, int(chunk_rows))):
104 parts.append(chunk.astype(dict.fromkeys(chunk.columns[chunk.dtypes == np.float64], np.float32)))
105 return pd.concat(parts, ignore_index=True) # a header-only file still yields one (empty) chunk
108def process_memory_mb() -> tuple[float, float] | None:
109 """(current, peak) resident memory of this process in MB: /proc on Linux, GetProcessMemoryInfo on Windows; None elsewhere."""
110 if sys.platform == "win32":
111 return _windows_memory_mb()
112 try:
113 values = {}
114 with open("/proc/self/status", encoding="ascii") as handle:
115 for line in handle:
116 if line.startswith(("VmRSS:", "VmHWM:")):
117 values[line.split(":")[0]] = float(line.split()[1]) / 1024.0
118 return values["VmRSS"], values["VmHWM"]
119 except (OSError, KeyError, ValueError):
120 return None
123def _windows_memory_mb() -> tuple[float, float] | None:
124 class _Counters(ctypes.Structure):
125 _fields_ = [
126 ("cb", ctypes.c_ulong), ("page_fault_count", ctypes.c_ulong), ("peak_working_set", ctypes.c_size_t), ("working_set", ctypes.c_size_t),
127 ("quota_peak_paged_pool", ctypes.c_size_t), ("quota_paged_pool", ctypes.c_size_t), ("quota_peak_non_paged_pool", ctypes.c_size_t),
128 ("quota_non_paged_pool", ctypes.c_size_t), ("pagefile_usage", ctypes.c_size_t), ("peak_pagefile_usage", ctypes.c_size_t),
129 ]
131 try:
132 counters = _Counters()
133 counters.cb = ctypes.sizeof(_Counters)
134 # the pseudo-handle is -1: as a default c_int argument it would reach a 64-bit API truncated to 0xFFFFFFFF, an invalid handle
135 process = ctypes.c_void_p(ctypes.windll.kernel32.GetCurrentProcess())
136 if not ctypes.windll.psapi.GetProcessMemoryInfo(process, ctypes.byref(counters), counters.cb):
137 return None
138 return counters.working_set / 1024.0 ** 2, counters.peak_working_set / 1024.0 ** 2
139 except (AttributeError, OSError):
140 return None
143def log_peak(path: Path, stage: str, *, profile: str, memory: tuple[float, float] | None = None) -> dict[str, Any]:
144 """Appends this process's peak memory for `stage` to the JSONL at `path` and returns the row (peak None where it can't be read)."""
145 memory = process_memory_mb() if memory is None else memory
146 row = {"stage": stage, "profile": profile, "peak_gb": None if memory is None else round(memory[1] / 1024.0, 3)}
147 path.parent.mkdir(parents=True, exist_ok=True)
148 with path.open("a", encoding="utf-8", newline="\n") as handle:
149 handle.write(json.dumps(row) + "\n")
150 return row
153def profile_summary(name: str) -> dict[str, Any]:
154 """The profile as a plain dict, for `aq cycle retrain --estimate` and the metrics a trainer writes."""
155 return asdict(memory_profile(name))