simons-forecasting 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. simons/__init__.py +10 -0
  2. simons/config.py +82 -0
  3. simons/covariates.py +338 -0
  4. simons/forecast.py +578 -0
  5. simons/model.py +696 -0
  6. simons/periodicity.py +188 -0
  7. simons/predictor.py +56 -0
  8. simons/synth/__init__.py +5 -0
  9. simons/synth/augment.py +143 -0
  10. simons/synth/base.py +448 -0
  11. simons/synth/calendar.py +157 -0
  12. simons/synth/causal.py +193 -0
  13. simons/synth/covariates/__init__.py +1 -0
  14. simons/synth/covariates/classical.py +637 -0
  15. simons/synth/covariates/effects.py +155 -0
  16. simons/synth/covariates/energy.py +528 -0
  17. simons/synth/covariates/families.py +296 -0
  18. simons/synth/covariates/generic.py +342 -0
  19. simons/synth/heavy.py +234 -0
  20. simons/synth/mech.py +636 -0
  21. simons/synth/multi.py +274 -0
  22. simons/synth/nonstat.py +204 -0
  23. simons/synth/observe.py +117 -0
  24. simons/training/__init__.py +1 -0
  25. simons/training/__main__.py +77 -0
  26. simons/training/augment.py +125 -0
  27. simons/training/clusters.py +215 -0
  28. simons/training/config.py +321 -0
  29. simons/training/covariates/__init__.py +1 -0
  30. simons/training/covariates/roles.py +370 -0
  31. simons/training/covariates/stream.py +243 -0
  32. simons/training/covariates/windows.py +239 -0
  33. simons/training/data.py +319 -0
  34. simons/training/distributed.py +124 -0
  35. simons/training/mixture.py +140 -0
  36. simons/training/network.py +115 -0
  37. simons/training/objective.py +193 -0
  38. simons/training/optim.py +164 -0
  39. simons/training/packing.py +94 -0
  40. simons/training/schedule.py +117 -0
  41. simons/training/soup.py +93 -0
  42. simons/training/stitching.py +50 -0
  43. simons/training/trainer.py +571 -0
  44. simons/training/warp.py +144 -0
  45. simons_forecasting-0.1.3.dist-info/METADATA +156 -0
  46. simons_forecasting-0.1.3.dist-info/RECORD +49 -0
  47. simons_forecasting-0.1.3.dist-info/WHEEL +4 -0
  48. simons_forecasting-0.1.3.dist-info/licenses/LICENSE +202 -0
  49. simons_forecasting-0.1.3.dist-info/licenses/NOTICE +57 -0
@@ -0,0 +1,239 @@
1
+ """Sample synthetic effects, sibling pairs and real known-future covariate windows.
2
+ Corpora use train-*.parquet rows with item_id, source, freq, target [T], covariates [C,T].
3
+ Covariates must be known at forecast time; NaN marks unknown values."""
4
+
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import pyarrow.parquet as pq
9
+
10
+ from simons.synth.covariates.effects import MAX_COV
11
+ from simons.training.data import corpus_files, resolve
12
+
13
+ PATCH = 32
14
+
15
+
16
+ def horizon_for(freq: str, rng) -> int:
17
+ """A frequency-typical horizon (multiple of PATCH): long for sub-hourly, short for low."""
18
+ f = (freq or "").upper()
19
+ if f.endswith(("MIN", "T", "S")):
20
+ patches = [1, 2, 3, 4, 6, 8]
21
+ elif f.endswith("H"):
22
+ patches = [1, 2, 3, 4, 6]
23
+ else:
24
+ patches = [1, 1, 2]
25
+ return int(rng.choice(patches) * PATCH)
26
+
27
+
28
+ BASE_VALUES = 32_000_000
29
+
30
+
31
+ class BaseSeries:
32
+ """Load univariate channels and equal-length multivariate rows for sibling sampling."""
33
+
34
+ def __init__(self, paths, min_len: int = 384, values: int = BASE_VALUES):
35
+ paths = [paths] if isinstance(paths, (str, Path)) else list(paths)
36
+ self.uni, self.multi = [], []
37
+ if len(paths) == 1:
38
+ table = pq.read_table(paths[0], columns=["target", "freq"]).to_pydict()
39
+ for chans, freq in zip(table["target"], table["freq"]):
40
+ self._add(chans, freq, min_len)
41
+ return
42
+ share = values // len(paths)
43
+ for path in paths:
44
+ read = 0
45
+ with pq.ParquetFile(path) as file:
46
+ for batch in file.iter_batches(batch_size=16, columns=["target", "freq"]):
47
+ rows = batch.to_pydict()
48
+ for chans, freq in zip(rows["target"], rows["freq"]):
49
+ self._add(chans, freq, min_len)
50
+ read += sum(len(c) for c in chans)
51
+ if read >= share:
52
+ break
53
+ if read >= share:
54
+ break
55
+
56
+ def _add(self, chans, freq, min_len: int):
57
+ arrs = [np.asarray(c, dtype="float32") for c in chans]
58
+ arrs = [a for a in arrs if np.isfinite(a).sum() >= min_len]
59
+ for a in arrs:
60
+ self.uni.append((a, freq))
61
+ if len(arrs) >= 2 and len({len(a) for a in arrs}) == 1:
62
+ self.multi.append((np.stack(arrs), freq))
63
+
64
+
65
+ def sibling(base: BaseSeries, rng, hist: int, horizon: int):
66
+ L = hist + horizon
67
+ arr, _ = base.multi[rng.integers(len(base.multi))]
68
+ j = int(rng.integers(len(arr)))
69
+ if arr.shape[1] >= L:
70
+ s = rng.integers(0, arr.shape[1] - L + 1)
71
+ w = arr[:, s:s + L]
72
+ else:
73
+ w = np.concatenate([np.full((len(arr), L - arr.shape[1]), np.nan, "float32"), arr], 1)
74
+ others = [i for i in range(len(arr)) if i != j]
75
+ rng.shuffle(others)
76
+ return w[j].copy(), w[others[:MAX_COV]].copy()
77
+
78
+
79
+ def base_files(folder) -> list[str]:
80
+ """Find the first training file in a corpus, or one per dataset subfolder."""
81
+ folder = Path(resolve(folder, "univariate"))
82
+ files = corpus_files(folder)
83
+ if not files:
84
+ raise FileNotFoundError(f"no train-*.parquet files in {folder}")
85
+ flat = [f for f in files if Path(f).parent == folder]
86
+ if flat:
87
+ return flat[:1]
88
+ first = {}
89
+ for f in files:
90
+ first.setdefault(Path(f).parent, f)
91
+ return list(first.values())
92
+
93
+
94
+ def load_items(path) -> dict:
95
+ """{source: set of item ids} from a JSON file {"items": {source: [item ids]}} (or the
96
+ mapping itself)."""
97
+ import json
98
+
99
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
100
+ data = data.get("items", data)
101
+ return {str(s): set(map(str, v)) for s, v in data.items()}
102
+
103
+
104
+ def source_weights(spec, sources):
105
+ """Sampling probabilities over `sources` (in that order) from {source: weight} (sources not
106
+ named: 1), or None when `spec` is None. Unknown names are an error."""
107
+ if spec is None:
108
+ return None
109
+ if isinstance(spec, (str, Path)):
110
+ import json
111
+
112
+ spec = json.loads(Path(spec).read_text(encoding="utf-8"))
113
+ weights = {str(k): float(v) for k, v in dict(spec).items()}
114
+ unknown = sorted(set(weights) - set(sources))
115
+ if unknown:
116
+ raise ValueError(f"covariate_source_weights: sources not in the covariate corpus: "
117
+ f"{unknown}")
118
+ w = np.array([weights.get(s, 1.0) for s in sources], float)
119
+ if (w < 0).any() or w.sum() <= 0:
120
+ raise ValueError("covariate_source_weights: weights must be non-negative with a positive "
121
+ "sum")
122
+ return w / w.sum()
123
+
124
+
125
+ def _list_arrays(column):
126
+ import pyarrow as pa
127
+
128
+ if not len(column):
129
+ return []
130
+ values = pa.concat_arrays(column.chunks)
131
+ offsets = values.offsets.to_numpy()
132
+ flat = values.values.to_numpy(zero_copy_only=False).astype("float32")
133
+ nulls = values.is_null().to_numpy(zero_copy_only=False)
134
+ return [None if nulls[i] else flat[offsets[i]:offsets[i + 1]] for i in range(len(values))]
135
+
136
+
137
+ RAGGED = "ragged"
138
+
139
+
140
+ def _matrix_arrays(column):
141
+ """Decode Arrow rows to float32 [C,L], None for empty/null, or RAGGED for unequal lengths."""
142
+ import pyarrow as pa
143
+
144
+ if not len(column):
145
+ return []
146
+ rows = pa.concat_arrays(column.chunks)
147
+ row_offsets = rows.offsets.to_numpy()
148
+ inner = rows.values
149
+ offsets = inner.offsets.to_numpy()
150
+ flat = inner.values.to_numpy(zero_copy_only=False)
151
+ nulls = rows.is_null().to_numpy(zero_copy_only=False)
152
+ out = []
153
+ for i in range(len(rows)):
154
+ a, b = row_offsets[i], row_offsets[i + 1]
155
+ if nulls[i] or b <= a:
156
+ out.append(None)
157
+ continue
158
+ lengths = offsets[a + 1:b + 1] - offsets[a:b]
159
+ if len(set(lengths.tolist())) != 1:
160
+ out.append(RAGGED)
161
+ continue
162
+ out.append(flat[offsets[a]:offsets[b]].astype("float32").reshape(b - a, int(lengths[0])))
163
+ return out
164
+
165
+
166
+ class CovariateCorpus:
167
+ """Load aligned targets and known-future covariates from train-*.parquet rows."""
168
+
169
+ def __init__(self, folder: str, exclude=None, min_length: int = 0, weights=None):
170
+ self.recs = []
171
+ self.excluded = 0
172
+ for path in corpus_files(resolve(folder, "covariates")):
173
+ table = pq.read_table(path, columns=["item_id", "source", "freq", "target",
174
+ "covariates"])
175
+ names = table.column("source").to_pylist()
176
+ items = table.column("item_id").to_pylist()
177
+ freqs = table.column("freq").to_pylist()
178
+ targets = _list_arrays(table.column("target"))
179
+ covariates = _matrix_arrays(table.column("covariates"))
180
+ for i in range(len(names)):
181
+ if exclude and str(items[i]) in exclude.get(names[i], ()):
182
+ self.excluded += 1
183
+ continue
184
+ if targets[i] is None or (min_length and len(targets[i]) < min_length):
185
+ continue
186
+ if covariates[i] is None:
187
+ continue
188
+ if covariates[i] is RAGGED or covariates[i].shape[1] != len(targets[i]):
189
+ steps = ("unequal lengths" if covariates[i] is RAGGED
190
+ else f"{covariates[i].shape[1]} steps")
191
+ raise ValueError(
192
+ f"{path}: series {items[i]!r} of {names[i]!r} has covariates of {steps} "
193
+ f"for a target of {len(targets[i])}: every covariate must be aligned "
194
+ "with the target step by step")
195
+ self.recs.append({"source": names[i], "freq": freqs[i], "target": targets[i],
196
+ "covs": covariates[i]})
197
+ self.by_source = {}
198
+ for i, r in enumerate(self.recs):
199
+ self.by_source.setdefault(r["source"], []).append(i)
200
+ self.sources = sorted(self.by_source)
201
+ self.p = source_weights(weights, self.sources)
202
+ if self.p is not None and (self.p == 0).any():
203
+ keep = self.p > 0
204
+ self.sources = [s for s, k in zip(self.sources, keep) if k]
205
+ self.p = self.p[keep] / self.p[keep].sum()
206
+
207
+ def train_sample(self, rng, hist: int, min_observed: float = 0.0):
208
+ """Return (target [hist+H], covariates [C,hist+H], H), or None after 20 failed draws.
209
+ `min_observed` requires that fraction of history steps to be observed."""
210
+ for _ in range(20):
211
+ if self.p is None:
212
+ src = self.sources[rng.integers(len(self.sources))]
213
+ else:
214
+ src = self.sources[rng.choice(len(self.sources), p=self.p)]
215
+ r = self.recs[self.by_source[src][rng.integers(len(self.by_source[src]))]]
216
+ horizon = horizon_for(r["freq"], rng)
217
+ n = len(r["target"])
218
+ if n < horizon + 64:
219
+ continue
220
+ low = horizon + 64
221
+ if min_observed > 0:
222
+ low = max(low, horizon + int(np.ceil(min_observed * hist)))
223
+ if low > n:
224
+ continue
225
+ end = int(rng.integers(low, n + 1))
226
+ start = end - horizon - hist
227
+ y = r["target"][max(start, 0):end]
228
+ c = r["covs"][:MAX_COV, max(start, 0):end]
229
+ pad = (hist + horizon) - y.shape[-1]
230
+ if pad:
231
+ y = np.concatenate([np.full(pad, np.nan, "float32"), y])
232
+ c = np.concatenate([np.full((len(c), pad), np.nan, "float32"), c], 1)
233
+ if (np.isfinite(y[-horizon:]).sum() < horizon // 4
234
+ or np.isfinite(y[:-horizon]).sum() < 32):
235
+ continue
236
+ if min_observed > 0 and np.isfinite(y[:-horizon]).sum() < min_observed * hist:
237
+ continue
238
+ return y, c, horizon
239
+ return None
@@ -0,0 +1,319 @@
1
+ """Load training corpora and sample packed time-series windows.
2
+ Parquet rows hold item_id, source, freq, target [variate,time] and optional domain/subdomain.
3
+ NaN marks missing values; `<base>@<offset>` IDs identify contiguous segments."""
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import torch
11
+ from torch.utils.data import Dataset
12
+
13
+ from simons.model import MAX_VARIATES
14
+
15
+ TOY = "toy"
16
+
17
+
18
+ def write_json(path: Path, value):
19
+ path.parent.mkdir(parents=True, exist_ok=True)
20
+ temporary = path.with_suffix(path.suffix + ".tmp")
21
+ temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
22
+ temporary.replace(path)
23
+
24
+
25
+ def resolve(name, part: str) -> str:
26
+ """Resolve a local corpus folder or download a Hub dataset's `part` folder to its cache.
27
+ `part` is "univariate" or "covariates"; local paths expand ~."""
28
+ name = os.path.expanduser(str(name))
29
+ if name == TOY or Path(name).exists() or name.count("/") != 1 or name.startswith((".", "/")):
30
+ return name
31
+ from huggingface_hub import snapshot_download
32
+
33
+ try:
34
+ root = snapshot_download(name, repo_type="dataset", allow_patterns=[f"{part}/**"])
35
+ except (OSError, ValueError) as error:
36
+ reason = (str(error).splitlines() or [""])[0]
37
+ raise FileNotFoundError(
38
+ f"{name!r} is not a local folder, and no Hugging Face dataset of that name could be "
39
+ f"read ({type(error).__name__}: {reason})") from error
40
+ return str(Path(root) / part)
41
+
42
+
43
+ def corpus_files(folder, split: str = "train") -> list[str]:
44
+ """Find `<split>-*.parquet` files in a folder or its dataset subfolders."""
45
+ folder, pattern = Path(folder), f"{split}-*.parquet"
46
+ deeper = next(folder.glob(f"*/*/**/{pattern}"), None)
47
+ if deeper is not None:
48
+ raise ValueError(f"{deeper} is more than one folder below the corpus folder {folder}: "
49
+ "put each dataset's files in <corpus>/<dataset>/")
50
+ return sorted(str(p) for p in [*folder.glob(pattern), *folder.glob(f"*/{pattern}")])
51
+
52
+
53
+ def load(name: str, split: str = "train"):
54
+ """The toy corpus, or a corpus of train-*.parquet / validation-*.parquet files: a local
55
+ folder (files in it or in its subfolders) or a Hugging Face dataset repo (`resolve`)."""
56
+ from datasets import load_dataset
57
+
58
+ if name == TOY:
59
+ return toy(split)
60
+ folder = resolve(name, "univariate")
61
+ if not Path(folder).is_dir():
62
+ raise FileNotFoundError(f"no folder {folder!r} (data must be {TOY!r}, a local parquet "
63
+ "folder or a Hugging Face dataset repo id)")
64
+ files = corpus_files(folder, split)
65
+ if not files:
66
+ raise FileNotFoundError(f"no {split}-*.parquet files in {folder}")
67
+ return load_dataset("parquet", data_files=files, split="train")
68
+
69
+
70
+ def column(dataset, name: str) -> list:
71
+ """A dataset column as a Python list, read through Arrow (much faster than dataset[name])."""
72
+ return dataset.with_format("arrow")[:].column(name).to_pylist()
73
+
74
+
75
+ def arrays(dataset) -> list[np.ndarray]:
76
+ """Float32 [variate, time] arrays of the `target` column (memory-mapped views may be
77
+ read-only)."""
78
+ import pyarrow as pa
79
+
80
+ out = []
81
+ for chunk in dataset.with_format("arrow")[:].column("target").chunks:
82
+ variates, points = chunk.offsets.to_numpy(), chunk.values.offsets.to_numpy()
83
+ values = chunk.values.values
84
+ if values.type != pa.float32():
85
+ values = values.cast(pa.float32())
86
+ values = values.to_numpy(zero_copy_only=False)
87
+ lengths = np.diff(points)
88
+ counts = np.diff(variates)
89
+ if len(counts) and (np.any(counts == 0) or np.any(
90
+ lengths[variates[0]:variates[-1]] != np.repeat(lengths[variates[:-1]], counts))):
91
+ raise ValueError("Each target must be a nonempty [variate][time] list")
92
+ for row in range(len(chunk)):
93
+ first, last = variates[row], variates[row + 1]
94
+ out.append(values[points[first] : points[last]].reshape(last - first, -1))
95
+ return out
96
+
97
+
98
+ def toy(split: str, seed: int = 7, series: int = 24, length: int = 512):
99
+ from datasets import Dataset as HFDataset
100
+
101
+ rng = np.random.default_rng(seed)
102
+ time = np.arange(length)
103
+ rows = {"item_id": [], "source": [], "freq": [], "target": []}
104
+ for index in range(series):
105
+ period = rng.choice([12, 24, 48])
106
+ values = (
107
+ rng.uniform(0.5, 3) * np.sin(2 * np.pi * time / period + rng.random())
108
+ + rng.normal(0, 0.1, length)
109
+ + 0.002 * time
110
+ ).astype("float32")
111
+ values[rng.random(length) < 0.02] = np.nan
112
+ if ("validation" if index % 5 == 0 else "train") == split:
113
+ rows["item_id"].append(f"{TOY}/{index}")
114
+ rows["source"].append(f"{TOY}-{index % 3}")
115
+ rows["freq"].append("H")
116
+ rows["target"].append([values.tolist()])
117
+ if not rows["item_id"]:
118
+ raise ValueError(f"The toy data has no {split} split")
119
+ return HFDataset.from_dict(rows)
120
+
121
+
122
+ class Windows(Dataset):
123
+ """Draw deterministic source, series, variate and window samples by index.
124
+ Return NaN-padded, right-aligned `context` history steps and `horizon` target steps."""
125
+
126
+ def __init__(
127
+ self, dataset, context: int, horizon: int, count: int, seed: int,
128
+ downsample=0.0, downsample_max=8, downsample_min_points=512,
129
+ stretch=0.0, stretch_up=0.5, stitch_index=False,
130
+ ):
131
+ self.context, self.horizon, self.count, self.seed = context, horizon, count, seed
132
+ self.downsample, self.downsample_max = downsample, downsample_max
133
+ self.downsample_min_points = downsample_min_points
134
+ self.end_min = 0
135
+ self.stretch, self.stretch_up = stretch, stretch_up
136
+ self.stitch, self.prev = False, None
137
+ self.weights = None
138
+ self.shape = None
139
+ sources, rows = {}, {}
140
+ for row, (source, values) in enumerate(zip(column(dataset, "source"), arrays(dataset),
141
+ strict=True)):
142
+ if values.shape[1] > horizon:
143
+ sources.setdefault(source, []).append(values)
144
+ rows.setdefault(source, []).append(row)
145
+ self.sources = list(sources.values())
146
+ if stitch_index:
147
+ from simons.training.stitching import positions
148
+
149
+ ids = column(dataset, "item_id")
150
+ self.prev = [positions([ids[r] for r in rows[name]], [a.shape for a in members])
151
+ for name, members in sources.items()]
152
+ self.names = list(sources.keys())
153
+ self.shapes = [np.array([a.shape for a in s], dtype=np.int64) for s in self.sources]
154
+ if not self.sources or min(context, horizon, count) <= 0:
155
+ raise ValueError("No series longer than the horizon, or an invalid window/count")
156
+
157
+ def __len__(self):
158
+ return self.count
159
+
160
+ def __getitem__(self, index):
161
+ rng = np.random.default_rng(np.random.SeedSequence([self.seed, int(index)]))
162
+ srng = (np.random.default_rng(np.random.SeedSequence([self.seed, int(index), 7907]))
163
+ if self.stretch > 0 else None)
164
+ crng = (np.random.default_rng(np.random.SeedSequence([self.seed, int(index), 4441]))
165
+ if self.shape is not None else None)
166
+ for _ in range(100):
167
+ if self.weights is None:
168
+ source_index = rng.integers(len(self.sources))
169
+ else:
170
+ source_index = rng.choice(len(self.sources), p=self.weights)
171
+ source = self.sources[source_index]
172
+ position = rng.integers(len(source))
173
+ if crng is not None and crng.random() < self.shape.mix:
174
+ # Preserve the main stream's draws when substituting a cluster-stream row.
175
+ source_index, position = self.shape.draw(crng)
176
+ source = self.sources[source_index]
177
+ group = source[position]
178
+ prev = self.prev[source_index] if self.stitch else None
179
+ channels = np.sort(
180
+ rng.choice(group.shape[0], min(group.shape[0], MAX_VARIATES), replace=False)
181
+ )
182
+ if self.downsample > 0 and rng.random() < self.downsample:
183
+ window = downsampled_window(
184
+ group, channels, self.context + self.horizon, rng, self.downsample_max,
185
+ self.downsample_min_points,
186
+ )
187
+ length = window.shape[1]
188
+ elif self.stretch > 0 and srng.random() < self.stretch:
189
+ from simons.training.warp import stretch_window
190
+
191
+ window = stretch_window(
192
+ group, channels, self.context + self.horizon, srng, self.stretch_up,
193
+ self.downsample_min_points,
194
+ )
195
+ length = window.shape[1]
196
+ elif self.end_min and group.shape[1] > self.end_min:
197
+ end = self.end_min + rng.integers(group.shape[1] - self.end_min + 1)
198
+ start = max(0, end - (self.context + self.horizon))
199
+ if prev is not None and start == 0 and prev[position] >= 0:
200
+ from simons.training.stitching import extend
201
+
202
+ window = extend(source, prev, position, channels, end,
203
+ self.context + self.horizon)
204
+ else:
205
+ window = np.array(group[channels, start:end], copy=True)
206
+ length = window.shape[1]
207
+ else:
208
+ length = min(group.shape[1], self.context + self.horizon)
209
+ start = rng.integers(group.shape[1] - length + 1)
210
+ if prev is not None and start == 0 and prev[position] >= 0:
211
+ from simons.training.stitching import extend
212
+
213
+ window = extend(source, prev, position, channels, length,
214
+ self.context + self.horizon)
215
+ length = window.shape[1]
216
+ else:
217
+ window = np.array(group[channels, start : start + length], copy=True)
218
+ if length <= self.horizon:
219
+ continue
220
+ cut = length - self.horizon
221
+ if np.isfinite(window[:, :cut]).any() and np.isfinite(window[:, cut:]).any():
222
+ history = np.full((len(channels), self.context), np.nan, dtype="float32")
223
+ history[:, -cut:] = window[:, :cut]
224
+ return torch.from_numpy(history), torch.from_numpy(window[:, cut:])
225
+ raise ValueError("Could not find an observed window after 100 attempts")
226
+
227
+
228
+ def downsampled_window(group, channels, want, rng, k_max, min_points):
229
+ """Return up to `want` steps after NaN-aware mean pooling by k ~ LogU[2,k_max].
230
+ Retain at least `min_points` steps when available; empty blocks remain NaN."""
231
+ cap = min(k_max, group.shape[1] // max(1, min_points))
232
+ k = 1
233
+ if cap >= 2:
234
+ k = int(np.floor(np.exp(rng.uniform(np.log(2), np.log(cap + 1)))))
235
+ k = min(max(k, 2), cap)
236
+ raw = min(group.shape[1] // k * k, want * k)
237
+ start = rng.integers(group.shape[1] - raw + 1)
238
+ block = np.asarray(group[channels, start : start + raw], dtype="float32")
239
+ block = block.reshape(len(channels), raw // k, k)
240
+ finite = np.isfinite(block)
241
+ counts = finite.sum(-1)
242
+ sums = np.where(finite, block, 0.0).sum(-1, dtype="float64")
243
+ with np.errstate(invalid="ignore", divide="ignore"):
244
+ pooled = np.where(counts > 0, sums / np.maximum(counts, 1), np.nan)
245
+ return pooled.astype("float32")
246
+
247
+
248
+ def pack_windows(samples):
249
+ """Pack aligned (history, target) samples into rows of up to 32 variate slots; returns
250
+ history [R,W,C], target [R,W,H] and series ids [R,W] (the sample index, -1 = empty)."""
251
+ if not samples:
252
+ raise ValueError("Cannot pack an empty batch")
253
+ rows, row, used = [], [], 0
254
+ context, horizon = samples[0][0].shape[-1], samples[0][1].shape[-1]
255
+ for index, (history, target) in enumerate(samples):
256
+ variates = history.shape[0]
257
+ if (
258
+ history.shape != (variates, context)
259
+ or target.shape != (variates, horizon)
260
+ or not 0 < variates <= MAX_VARIATES
261
+ ):
262
+ raise ValueError("Samples must be aligned [V,C]/[V,H] with 1 <= V <= 32")
263
+ if used + variates > MAX_VARIATES:
264
+ rows.append(row)
265
+ row, used = [], 0
266
+ row.append((index, history, target))
267
+ used += variates
268
+ rows.append(row)
269
+ width = max(sum(h.shape[0] for _, h, _ in row) for row in rows)
270
+ history = torch.full((len(rows), width, context), float("nan"))
271
+ target = torch.full((len(rows), width, horizon), float("nan"))
272
+ ids = torch.full((len(rows), width), -1, dtype=torch.long)
273
+ for batch, row in enumerate(rows):
274
+ offset = 0
275
+ for index, h, t in row:
276
+ stop = offset + h.shape[0]
277
+ history[batch, offset:stop] = h
278
+ target[batch, offset:stop] = t
279
+ ids[batch, offset:stop] = index
280
+ offset = stop
281
+ return history, target, ids
282
+
283
+
284
+ def first_patches(sequence: torch.Tensor, patch: int) -> torch.Tensor:
285
+ """First patch with an observed value per slot of [..., T] (T // patch when none)."""
286
+ seen = torch.isfinite(sequence).unflatten(-1, (-1, patch)).any(-1)
287
+ patches = seen.shape[-1]
288
+ position = torch.arange(patches, device=sequence.device)
289
+ return torch.where(seen, position, patches).amin(-1)
290
+
291
+
292
+ def collate(patch: int):
293
+ """`pack_windows` returning (sequence [R,W,T], ids [R,W], first observed patch [R,W])."""
294
+
295
+ def collate_fn(samples):
296
+ history, target, ids = pack_windows(samples)
297
+ sequence = torch.cat([history, target], dim=-1)
298
+ return sequence, ids, first_patches(sequence, patch)
299
+
300
+ return collate_fn
301
+
302
+
303
+ class StepIndices:
304
+ """Window indices of one rank's loader: for step s in [start, end), `size` indices from
305
+ s * stride + offset (stride = global batch; one device: offset 0, size = stride)."""
306
+
307
+ def __init__(self, start: int, end: int, stride: int, offset: int, size: int):
308
+ self.start, self.end, self.stride, self.offset, self.size = start, end, stride, offset, size
309
+
310
+ def __len__(self):
311
+ return max(0, self.end - self.start) * self.size
312
+
313
+ def __getitem__(self, i):
314
+ if i < 0:
315
+ i += len(self)
316
+ if not 0 <= i < len(self):
317
+ raise IndexError(i)
318
+ step, j = divmod(i, self.size)
319
+ return (self.start + step) * self.stride + self.offset + j
@@ -0,0 +1,124 @@
1
+ """Data-parallel training with token-weighted losses and one flat gradient all-reduce."""
2
+
3
+ import os
4
+ from dataclasses import dataclass
5
+
6
+ import torch
7
+
8
+ STREAM_OFFSET = 1_000_003
9
+
10
+
11
+ @dataclass
12
+ class Rank:
13
+ rank: int = 0
14
+ world: int = 1
15
+ local: int = 0
16
+
17
+ @classmethod
18
+ def from_env(cls, device_type: str) -> "Rank":
19
+ world = int(os.environ.get("WORLD_SIZE", "1"))
20
+ if world <= 1:
21
+ return cls()
22
+ import torch.distributed as dist
23
+
24
+ rank, local = int(os.environ["RANK"]), int(os.environ.get("LOCAL_RANK", "0"))
25
+ if device_type == "cuda":
26
+ torch.cuda.set_device(local)
27
+ dist.init_process_group("nccl" if device_type == "cuda" else "gloo")
28
+ return cls(rank, world, local)
29
+
30
+ @property
31
+ def active(self) -> bool:
32
+ return self.world > 1
33
+
34
+ @property
35
+ def main(self) -> bool:
36
+ return self.rank == 0
37
+
38
+ def split(self, total: int) -> tuple[int, int]:
39
+ """(offset, size) of this rank's share of `total` items per step."""
40
+ base, extra = divmod(total, self.world)
41
+ size = base + (1 if self.rank < extra else 0)
42
+ if size <= 0:
43
+ raise ValueError(f"{total} items per step cannot be split over {self.world} ranks")
44
+ return self.rank * base + min(self.rank, extra), size
45
+
46
+ def stream_seed(self, seed: int) -> int:
47
+ """Return the initialization value for this rank's private random streams."""
48
+ return seed + STREAM_OFFSET * self.rank
49
+
50
+ def loader_workers(self, workers: int) -> int:
51
+ cpus = os.cpu_count() or 1
52
+ if not self.active:
53
+ return min(workers, cpus)
54
+ return max(2, min(workers, cpus // (2 * self.world)))
55
+
56
+ def scale_loss(self, loss: torch.Tensor, count: torch.Tensor):
57
+ """(objective to back-propagate, global mean loss for logging)."""
58
+ if not self.active:
59
+ return loss, loss.detach()
60
+ import torch.distributed as dist
61
+
62
+ count = count.detach().to(torch.float64)
63
+ parts = torch.stack([loss.detach().to(torch.float64) * count, count])
64
+ dist.all_reduce(parts)
65
+ total = parts[1].clamp_min(1.0)
66
+ return loss * (self.world * count / total).to(loss.dtype), (parts[0] / total).float()
67
+
68
+ def mean_value(self, value: torch.Tensor) -> torch.Tensor:
69
+ """The mean of a scalar over ranks (for logging; every rank must call it)."""
70
+ if not self.active:
71
+ return value
72
+ import torch.distributed as dist
73
+
74
+ total = value.detach().to(torch.float64).reshape(1).clone()
75
+ dist.all_reduce(total)
76
+ return (total[0] / self.world).float()
77
+
78
+ def average_gradients(self, model):
79
+ """Average gradients across ranks; missing local gradients count as zero.
80
+ Leave a gradient unset if it is missing on every rank."""
81
+ if not self.active:
82
+ return
83
+ import torch.distributed as dist
84
+ from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
85
+
86
+ params = [p for p in model.parameters() if p.requires_grad]
87
+ device = params[0].device
88
+ present = torch.tensor([int(p.grad is not None) for p in params], device=device)
89
+ dist.all_reduce(present)
90
+ keep = []
91
+ for p, n in zip(params, present.tolist()):
92
+ if n > 0:
93
+ if p.grad is None:
94
+ p.grad = torch.zeros_like(p)
95
+ keep.append(p)
96
+ else:
97
+ p.grad = None
98
+ if not keep:
99
+ return
100
+ grads = [p.grad for p in keep]
101
+ flat = _flatten_dense_tensors(grads)
102
+ dist.all_reduce(flat)
103
+ flat.div_(self.world)
104
+ for p, g in zip(keep, _unflatten_dense_tensors(flat, grads)):
105
+ p.grad = g
106
+
107
+ def broadcast_model(self, model):
108
+ if self.active:
109
+ import torch.distributed as dist
110
+
111
+ for t in [*model.parameters(), *model.buffers()]:
112
+ dist.broadcast(t.data, 0)
113
+
114
+ def barrier(self):
115
+ if self.active:
116
+ import torch.distributed as dist
117
+
118
+ dist.barrier()
119
+
120
+ def close(self):
121
+ if self.active:
122
+ import torch.distributed as dist
123
+
124
+ dist.destroy_process_group()