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,370 @@
1
+ """Add known-future covariate roles to coupled synthetic groups and effect rows."""
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch.utils.data import DataLoader, IterableDataset, get_worker_info
8
+
9
+ from simons.covariates import ROLE_BINARY, ROLE_KNOWN, known_rows
10
+ from simons.synth.multi import MECHANISMS
11
+
12
+ WIDTH = 32
13
+ PATCH = 32
14
+ EFFECT_ID = 50_000_000
15
+ MECH = {name: i for i, name in enumerate(MECHANISMS)}
16
+
17
+ DEFAULTS = {
18
+ "boundaries": [0.27, 0.53],
19
+ "p_role": [0.10, 0.20, 0.40],
20
+ "p_eff": [0.0, 0.0, 0.0],
21
+ "root_p": 0.8,
22
+ "sibling_p": [0.2, 0.5],
23
+ "max_cov": 8,
24
+ "partial_future": 0.15,
25
+ "end_block": 0.5,
26
+ "end_block_max": 16,
27
+ "effect_workers": 3,
28
+ "effect_horizons": [1, 2, 3, 4, 6, 8, 12, 16],
29
+ "effect_pad": 0.4,
30
+ "effect_min_observed": 1024,
31
+ "effect_flip": 0.3,
32
+ "base_families": "kernel,sarima,sde,step,spike,cauker,rhythm,wave,fpfn,ets,levy,pulse",
33
+ "base_weights": "0.21056,0.21056,0.12024,0.05512,0.05512,0.08016,0.04008,0.03008,0.03008,"
34
+ "0.068,0.015,0.015",
35
+ "synth_calendar": 0.3,
36
+ "effect_mix": None,
37
+ }
38
+
39
+
40
+ def settings(spec):
41
+ """The role settings: DEFAULTS updated by `spec` (validated)."""
42
+ s = {**DEFAULTS, **(spec or {})}
43
+ unknown = set(spec or {}) - set(DEFAULTS)
44
+ if unknown:
45
+ raise ValueError(f"covariate roles: unknown fields {sorted(unknown)}")
46
+ if len(s["p_role"]) != len(s["boundaries"]) + 1 or len(s["p_eff"]) != len(s["p_role"]):
47
+ raise ValueError("role_share and effect_share need one value per role phase")
48
+ if max(s["p_eff"]) > 0 and s["effect_mix"] is None:
49
+ raise ValueError("effect rows (effect_share > 0) need effect_mix")
50
+ if s["effect_mix"] is not None:
51
+ from simons.synth.covariates import families
52
+
53
+ families.parse_mix(s["effect_mix"])
54
+ return s
55
+
56
+
57
+ def phase_value(values, boundaries, fraction):
58
+ return values[int(np.searchsorted(np.asarray(boundaries, float), fraction, side="right"))]
59
+
60
+
61
+ class RolePlanner:
62
+ """Assign covariate roles and future visibility to coupled synthetic groups."""
63
+
64
+ def __init__(self, s, seed: int, stage_steps: int):
65
+ self.s = s
66
+ self.rng = np.random.default_rng([int(seed), 4417])
67
+ self.stage_steps = max(1, int(stage_steps))
68
+ self.step = 0
69
+ self.stats = {"pools": 0, "groups": 0, "role_groups": 0, "cov_slots": 0,
70
+ "target_slots": 0, "end_blocks": 0, "cuts": 0, "by_mech": {}}
71
+
72
+ def fraction(self):
73
+ return self.step / self.stage_steps
74
+
75
+ def p_role(self):
76
+ return float(phase_value(self.s["p_role"], self.s["boundaries"], self.fraction()))
77
+
78
+ def plan_pool(self, structure, kinds, length, n_pool):
79
+ """Return [n_pool,3]: role, target end-block patches, future cut step (0: none).
80
+ `kinds` follows pool row order; True marks coupled rows."""
81
+ s, rng = self.s, self.rng
82
+ group, mech, root = structure["group"], structure["mech"], structure["root"]
83
+ n_c = len(group)
84
+ meta_c = np.zeros((n_c, 3), np.int64)
85
+ p = self.p_role()
86
+ self.stats["pools"] += 1
87
+ if n_c:
88
+ starts = np.flatnonzero(np.r_[True, group[1:] != group[:-1]])
89
+ ends = np.r_[starts[1:], n_c]
90
+ else:
91
+ starts = ends = np.zeros(0, np.int64)
92
+ for a, b in zip(starts.tolist(), ends.tolist()):
93
+ q = b - a
94
+ if q < 2:
95
+ continue
96
+ self.stats["groups"] += 1
97
+ if rng.random() >= p:
98
+ continue
99
+ m = int(mech[a])
100
+ r = root[a:b]
101
+ if m in (MECH["lag"], MECH["event"]) or (m == MECH["func"] and r.any()):
102
+ cov = r & (rng.random(q) < s["root_p"])
103
+ else:
104
+ share = rng.uniform(*s["sibling_p"])
105
+ cov = rng.random(q) < share
106
+ if cov.all():
107
+ cov[int(rng.integers(q))] = False
108
+ if cov.sum() > s["max_cov"]:
109
+ on = np.flatnonzero(cov)
110
+ cov[:] = False
111
+ cov[rng.choice(on, s["max_cov"], replace=False)] = True
112
+ if not cov.any():
113
+ continue
114
+ block = meta_c[a:b]
115
+ block[cov, 0] = 1
116
+ if rng.random() < s["end_block"]:
117
+ block[~cov, 1] = int(rng.integers(1, s["end_block_max"] + 1))
118
+ self.stats["end_blocks"] += 1
119
+ cut = cov & (rng.random(q) < s["partial_future"])
120
+ if cut.any():
121
+ block[cut, 2] = rng.integers(int(0.75 * length), length, size=int(cut.sum()))
122
+ self.stats["cuts"] += int(cut.sum())
123
+ self.stats["role_groups"] += 1
124
+ self.stats["cov_slots"] += int(cov.sum())
125
+ self.stats["target_slots"] += int((~cov).sum())
126
+ key = MECHANISMS[m]
127
+ self.stats["by_mech"][key] = self.stats["by_mech"].get(key, 0) + 1
128
+ meta = np.zeros((n_pool, 3), np.int64)
129
+ c = 0
130
+ for k, is_coupled in enumerate(kinds):
131
+ if is_coupled:
132
+ meta[k * WIDTH:(k + 1) * WIDTH] = meta_c[c * WIDTH:(c + 1) * WIDTH]
133
+ c += 1
134
+ return meta
135
+
136
+
137
+ def effect_row(s, rng, bases, length):
138
+ """Return a 32-slot row: values [32,L], meta [32,3], group [32], first [32], family counts.
139
+ Metadata holds (role,end block,cut); group -1 marks empty slots; first is an observed patch."""
140
+ from simons.synth.covariates import families, generic
141
+
142
+ values = np.full((WIDTH, length), np.nan, np.float32)
143
+ meta = np.zeros((WIDTH, 3), np.int64)
144
+ group = np.full(WIDTH, -1, np.int64)
145
+ slot, g, tries = 0, 0, 0
146
+ names, p = families.parse_mix(s["effect_mix"])
147
+ counts = np.zeros(len(families.FAMILIES), np.int64)
148
+ while slot < WIDTH - 1 and tries < 64:
149
+ tries += 1
150
+ family = names[int(rng.choice(len(names), p=p))]
151
+ k = (min(generic.MAX_COV, int(rng.geometric(0.35)), WIDTH - slot - 1)
152
+ if family == "generic" else min(generic.MAX_COV, WIDTH - slot - 1))
153
+ H = families.horizon(family, rng, s["effect_horizons"]) * PATCH
154
+ observed = length
155
+ if rng.random() < s["effect_pad"]:
156
+ lo = max(s["effect_min_observed"], H + 256)
157
+ observed = int(math.exp(rng.uniform(math.log(lo), math.log(length))))
158
+ observed = min(length, max(lo, observed // PATCH * PATCH))
159
+ hist = observed - H
160
+ b = bases.window(observed)
161
+ if np.isfinite(b[:hist]).sum() < 64 or np.isfinite(b[hist:]).sum() < H // 4:
162
+ continue
163
+ y, c = families.make_task(family, b, rng, hist, H, k, bases.window)
164
+ if len(c) == 0 or y.shape[-1] != observed or c.shape[-1] != observed:
165
+ continue
166
+ k = len(c)
167
+ if not np.isfinite(y[:hist]).any():
168
+ continue
169
+ counts[families.FAMILIES.index(family)] += 1
170
+ if rng.random() < s["effect_flip"]:
171
+ y = -y
172
+ start = length - observed
173
+ values[slot, start:] = y
174
+ values[slot + 1:slot + 1 + k, start:] = c
175
+ meta[slot, 1] = H // PATCH
176
+ meta[slot + 1:slot + 1 + k, 0] = 1
177
+ for i in range(k):
178
+ if rng.random() < s["partial_future"]:
179
+ meta[slot + 1 + i, 2] = start + hist + int(rng.integers(1, H))
180
+ group[slot:slot + 1 + k] = g
181
+ g += 1
182
+ slot += 1 + k
183
+ seen = np.isfinite(values).reshape(WIDTH, -1, PATCH).any(-1)
184
+ patches = seen.shape[1]
185
+ first = np.where(seen.any(1), seen.argmax(1), patches).astype(np.int64)
186
+ return {"values": torch.from_numpy(values), "meta": torch.from_numpy(meta),
187
+ "group": torch.from_numpy(group), "first": torch.from_numpy(first),
188
+ "families": torch.from_numpy(counts)}
189
+
190
+
191
+ class SynthBases:
192
+ """Draw synthetic base windows for effect rows using a private CPU torch generator."""
193
+
194
+ def __init__(self, s, gen):
195
+ self.gen = gen
196
+ self.families = tuple(str(s["base_families"]).split(","))
197
+ self.weights = [float(w) for w in str(s["base_weights"]).split(",")]
198
+ self.calendar = float(s["synth_calendar"])
199
+ self.pool, self.used = None, 0
200
+
201
+ def refill(self, n, length):
202
+ from simons.synth import draw
203
+
204
+ n_cal = round(n * self.calendar)
205
+ parts = [draw(n - n_cal, length, self.gen, "cpu", self.families, self.weights)]
206
+ if n_cal:
207
+ parts.append(draw(n_cal, length, self.gen, "cpu", ("calendar",)))
208
+ x = torch.cat(parts)
209
+ self.pool = x[torch.randperm(len(x), generator=self.gen)].double().numpy()
210
+ self.used = 0
211
+
212
+ def window(self, length):
213
+ if self.pool is None or self.used >= len(self.pool) or self.pool.shape[1] < length:
214
+ self.refill(64, max(length, 1024))
215
+ x = self.pool[self.used]
216
+ self.used += 1
217
+ return x[len(x) - length:]
218
+
219
+
220
+ class EffectRows(IterableDataset):
221
+ """Stream synthetic effect rows with one numpy generator per loader worker."""
222
+
223
+ def __init__(self, s, seed, first_step, length):
224
+ from simons.synth import augment
225
+
226
+ self.s, self.seed, self.first_step, self.length = s, seed, first_step, length
227
+ self.augment = augment.CONFIG
228
+
229
+ def __iter__(self):
230
+ from simons.synth import augment
231
+
232
+ augment.CONFIG = self.augment
233
+ info = get_worker_info()
234
+ worker = info.id if info is not None else 0
235
+ rng = np.random.default_rng([int(self.seed), 6113, worker, int(self.first_step)])
236
+ torch.set_num_threads(1)
237
+ gen = torch.Generator()
238
+ gen.manual_seed(int(rng.integers(2 ** 62)))
239
+ bases = SynthBases(self.s, gen)
240
+ bases.refill(64, self.length)
241
+ while True:
242
+ if bases.used >= len(bases.pool):
243
+ bases.refill(64, self.length)
244
+ yield effect_row(self.s, rng, bases, self.length)
245
+
246
+
247
+ class RoleBatch:
248
+ """Hold one batch's covariate roles, end blocks and visibility masks on device."""
249
+
250
+ def __init__(self, role, role_ids, endk, fixed):
251
+ self.role, self.role_ids, self.endk, self.fixed = role, role_ids, endk, fixed
252
+
253
+ def hidden(self, hidden):
254
+ """CPM mask [B,V,P] with the role groups' end blocks hidden and covariates never hidden."""
255
+ patches = hidden.shape[-1]
256
+ position = torch.arange(patches, device=hidden.device)
257
+ end = (self.endk[..., None] > 0) & (position >= patches - self.endk[..., None])
258
+ return (hidden | end) & ~self.role[..., None]
259
+
260
+ def target(self, target):
261
+ """Loss targets [B,V,S,patch]: none on covariate rows."""
262
+ return target.masked_fill(self.role[..., None, None], float("nan"))
263
+
264
+ def token_roles(self, size):
265
+ return self.role_ids[..., None].expand(*self.role_ids.shape, size)
266
+
267
+
268
+ class Hook:
269
+ """Plan synthetic covariate roles and effect rows, then prepare packed batches."""
270
+
271
+ def __init__(self, spec, seed: int, first_step: int, device, stage_steps: int, length: int):
272
+ self.s = settings(spec)
273
+ self.device = torch.device(device)
274
+ self.stage_steps = max(1, int(stage_steps))
275
+ self.length = int(length)
276
+ self.planner = RolePlanner(self.s, seed * 31 + 4417 + first_step, stage_steps)
277
+ self.rng = np.random.default_rng([int(seed), 9049, int(first_step)])
278
+ self.effects = None
279
+ if max(self.s["p_eff"]) > 0:
280
+ workers = int(self.s["effect_workers"])
281
+ private = torch.Generator()
282
+ private.manual_seed(int(seed) * 1013 + 9049 + int(first_step))
283
+ loader = DataLoader(EffectRows(self.s, seed, first_step, self.length),
284
+ batch_size=None, generator=private, num_workers=workers,
285
+ pin_memory=self.device.type == "cuda",
286
+ persistent_workers=workers > 0,
287
+ prefetch_factor=8 if workers > 0 else None)
288
+ self.effects = iter(loader)
289
+ self.stats = {"steps": 0, "effect_rows": 0, "effect_groups": 0, "binary_rows": 0,
290
+ "role_slots": 0}
291
+ self._pending = []
292
+
293
+ def p_eff(self, step):
294
+ return float(phase_value(self.s["p_eff"], self.s["boundaries"], step / self.stage_steps))
295
+
296
+ def prepare(self, step, mixer, sequence, series_ids, host_slots, far_offset=0):
297
+ """Return (sequence,series_ids,host_slots,RoleBatch) at `step` from role-phase start.
298
+ `far_offset` is the NaN prefix in steps before synthetic rows; zero in stage 2."""
299
+ rows, width, length = sequence.shape
300
+ device = sequence.device
301
+ meta = torch.zeros((rows, width, 3), dtype=torch.long, device=device)
302
+ got = mixer.last_meta()
303
+ count = round(mixer.fraction * rows)
304
+ if got is not None and count:
305
+ meta[rows - count:] = got.view(count, width, 3).to(device)
306
+ n_eff = 0
307
+ if self.effects is not None:
308
+ share = self.p_eff(step) * rows
309
+ n_eff = int(math.floor(share) + (self.rng.random() < share - math.floor(share)))
310
+ n_eff = min(n_eff, rows)
311
+ eff_ids = eff_first = None
312
+ if n_eff:
313
+ parts = [next(self.effects) for _ in range(n_eff)]
314
+ values = torch.stack([p["values"] for p in parts])
315
+ if values.shape[-1] != length:
316
+ raise ValueError(f"effect rows of length {values.shape[-1]} for a {length} step")
317
+ group = torch.stack([p["group"] for p in parts]) # [n, W]
318
+ offset = (torch.arange(n_eff)[:, None] * WIDTH)
319
+ ids = torch.where(group >= 0, EFFECT_ID + offset + group, -1)
320
+ eff_ids, eff_first = ids.numpy(), torch.stack([p["first"] for p in parts]).numpy()
321
+ sequence = sequence.clone()
322
+ series_ids = series_ids.clone()
323
+ sequence[:n_eff] = values.to(device, sequence.dtype, non_blocking=True)
324
+ series_ids[:n_eff] = ids.to(device, series_ids.dtype, non_blocking=True)
325
+ meta[:n_eff] = torch.stack([p["meta"] for p in parts]).to(device, non_blocking=True)
326
+ self.stats["effect_rows"] += n_eff
327
+ self.stats["effect_groups"] += int(sum(int(p["group"].max()) + 1 for p in parts))
328
+ from simons.synth.covariates.families import FAMILIES
329
+
330
+ total = torch.stack([p["families"] for p in parts]).sum(0).tolist()
331
+ fam = self.stats.setdefault("families", dict.fromkeys(FAMILIES, 0))
332
+ for f, n in zip(FAMILIES, total):
333
+ fam[f] += int(n)
334
+ role = meta[..., 0] > 0
335
+ cut = meta[..., 2]
336
+ if far_offset:
337
+ cut = torch.where(cut > 0, cut + int(far_offset), cut)
338
+ position = torch.arange(length, device=device)
339
+ drop = role[..., None] & (cut[..., None] > 0) & (position >= cut[..., None])
340
+ sequence = sequence.masked_fill(drop, float("nan"))
341
+ shifted, two = known_rows(sequence, role, True, PATCH)
342
+ sequence = torch.where(role[..., None], shifted, sequence)
343
+ role_ids = (ROLE_KNOWN + (ROLE_BINARY - ROLE_KNOWN) * two.long()) * role.long()
344
+ self.stats["steps"] += 1
345
+ self._pending.append(torch.stack([role.sum(), two.sum()]))
346
+ if len(self._pending) >= 200:
347
+ self._flush()
348
+
349
+ if eff_ids is not None:
350
+ inner = host_slots
351
+
352
+ def host_slots(inner=inner, eff_ids=eff_ids, eff_first=eff_first, n=n_eff):
353
+ ids, first = inner()
354
+ ids[:n] = eff_ids
355
+ first[:n] = eff_first
356
+ return ids, first
357
+
358
+ batch = RoleBatch(role, role_ids, meta[..., 1], two)
359
+ return sequence, series_ids, host_slots, batch
360
+
361
+ def _flush(self):
362
+ if self._pending:
363
+ total = torch.stack(self._pending).sum(0).tolist()
364
+ self.stats["role_slots"] += int(total[0])
365
+ self.stats["binary_rows"] += int(total[1])
366
+ self._pending = []
367
+
368
+ def summary(self):
369
+ self._flush()
370
+ return {"batch": dict(self.stats), "plan": dict(self.planner.stats)}
@@ -0,0 +1,243 @@
1
+ """Compute weighted auxiliary losses on synthetic, sibling and real covariate windows."""
2
+
3
+ import time
4
+ import warnings
5
+
6
+ import numpy as np
7
+ import torch
8
+ from torch.utils.data import DataLoader, IterableDataset, get_worker_info
9
+
10
+ from simons.model import QUANTILES
11
+ from simons.synth.covariates import effects
12
+ from simons.training.covariates import windows as W
13
+
14
+ PATCH = 32
15
+ FUTURE = 512
16
+ DEFAULTS = {
17
+ "base": None,
18
+ "real": None,
19
+ "weight": 0.025,
20
+ "history_weight": 0.1,
21
+ "mix": {"synthetic": 0.63, "sibling": 0.25, "real": 0.12},
22
+ "hists": [128, 256, 512, 1024, 2048, 4096],
23
+ "hist_weights": [0.1, 0.15, 0.2, 0.2, 0.2, 0.15],
24
+ "tokens": 4096,
25
+ "max_batch": 128,
26
+ "max_cov": 8,
27
+ "horizons": [1, 2, 3, 4, 6, 8, 12, 16],
28
+ "drop_all": 0.15,
29
+ "drop_each": 0.15,
30
+ "drop_fit": 0.2,
31
+ "flip": 0.3,
32
+ "sqrt": 0.2,
33
+ "workers": 3,
34
+ "source_weights": None,
35
+ "exclude": None,
36
+ "min_length": 0,
37
+ "min_observed": 0.0,
38
+ "future": FUTURE,
39
+ "fovea_tokens": False,
40
+ "fovea_near": 4096,
41
+ "fovea_pool": 8,
42
+ # Separate the long pass's random stream from the main pass.
43
+ "stream_tag": 3232,
44
+ }
45
+ LONG = {"mix": {"real": 1.0}, "hists": [2048, 4096], "hist_weights": [0.5, 0.5],
46
+ "fovea_tokens": True, "drop_all": 0.05, "stream_tag": 4242}
47
+
48
+
49
+ def long_spec(main: dict, overrides: dict) -> dict:
50
+ """Apply long-pass overrides to the main spec, dropping per-source weights."""
51
+ spec = {k: v for k, v in main.items() if k != "source_weights"}
52
+ spec.update(LONG)
53
+ spec.update(overrides)
54
+ return spec
55
+
56
+
57
+ def tokens_per_window(hist: int, near: int = 4096, pool: int = 8, patch: int = PATCH,
58
+ future: int = FUTURE) -> int:
59
+ """Count near, pooled-far and future tokens for one window."""
60
+ near_steps = min(hist, near) if near else hist
61
+ far = (hist - near_steps) // (patch * pool) if near else 0
62
+ return near_steps // patch + far + future // patch
63
+
64
+
65
+ def real_corpus(s):
66
+ """Load the pass's covariate corpus, or return None when disabled; reject empty corpora."""
67
+ if not s["mix"].get("real", 0) > 0 or not s["real"]:
68
+ return None
69
+ exclude = W.load_items(s["exclude"]) if s["exclude"] else None
70
+ corpus = W.CovariateCorpus(s["real"], exclude=exclude, min_length=int(s["min_length"]),
71
+ weights=s["source_weights"])
72
+ if not corpus.recs:
73
+ raise ValueError(f"covariate corpus {s['real']}: no usable rows (train-*.parquet rows "
74
+ f"with covariates, at least {s['min_length']} steps)")
75
+ return corpus
76
+
77
+
78
+ class Batches(IterableDataset):
79
+ """An endless stream of covariate batches (one numpy generator per loader worker)."""
80
+
81
+ def __init__(self, spec, seed: int, first_step: int):
82
+ self.spec, self.seed, self.first_step = spec, seed, first_step
83
+
84
+ def __iter__(self):
85
+ info = get_worker_info()
86
+ worker = info.id if info is not None else 0
87
+ rng = np.random.default_rng([self.seed, int(self.spec["stream_tag"]), worker,
88
+ self.first_step])
89
+ s = self.spec
90
+ base = W.BaseSeries(W.base_files(s["base"])) if s["base"] else None
91
+ real = real_corpus(s)
92
+ kinds = [k for k in s["mix"] if s["mix"][k] > 0 and (k != "real" or real is not None)
93
+ and (k != "sibling" or (base is not None and base.multi))
94
+ and (k != "synthetic" or base is not None)]
95
+ if not kinds:
96
+ raise ValueError(f"the covariate pass (mix {s['mix']}) has no windows: no base "
97
+ f"series and no covariate-corpus series of at least "
98
+ f"{s['min_length']} steps")
99
+ dropped = [k for k in s["mix"] if s["mix"][k] > 0 and k not in kinds]
100
+ if dropped and worker == 0:
101
+ warnings.warn(f"covariate pass: no {' or '.join(dropped)} windows (sibling windows "
102
+ f"need base rows with several channels of equal length, real windows "
103
+ f"a covariate corpus); its mix is renormalized over {kinds}",
104
+ stacklevel=1)
105
+ p = np.array([s["mix"][k] for k in kinds], float)
106
+ p /= p.sum()
107
+ hw = np.array(s["hist_weights"], float)
108
+ hw /= hw.sum()
109
+ while True:
110
+ yield make_batch(s, rng, base, real, kinds, p, hw)
111
+
112
+
113
+ def make_batch(s, rng, base, real, kinds, p, hw):
114
+ hist = int(rng.choice(s["hists"], p=hw))
115
+ future_steps = int(s["future"])
116
+ per_window = (hist + future_steps) // PATCH
117
+ if s["fovea_tokens"]:
118
+ per_window = tokens_per_window(hist, s["fovea_near"], s["fovea_pool"],
119
+ future=future_steps)
120
+ count = int(np.clip(round(s["tokens"] / per_window), 4, s["max_batch"]))
121
+ samples, kind_count, misses = [], dict.fromkeys(kinds, 0), 0
122
+ while len(samples) < count:
123
+ if misses == 10_000:
124
+ raise ValueError(f"the covariate pass (kinds {kinds}) found no usable window in "
125
+ f"10,000 draws at history {hist}: its series are too short or too "
126
+ f"sparsely observed (min_length {s['min_length']}, min_observed "
127
+ f"{s['min_observed']})")
128
+ misses += 1
129
+ kind = kinds[rng.choice(len(kinds), p=p)]
130
+ if kind == "real":
131
+ got = real.train_sample(rng, hist, float(s["min_observed"]))
132
+ if got is None:
133
+ continue
134
+ y, c, H = got
135
+ else:
136
+ H = int(rng.choice(s["horizons"]) * PATCH)
137
+ maker = W.sibling if kind == "sibling" else effects.synthetic
138
+ y, c = maker(base, rng, hist, H)
139
+ if np.isfinite(y[-H:]).sum() < H // 4 or np.isfinite(y[:hist]).sum() < 32:
140
+ continue
141
+ misses = 0
142
+ c = c[: s["max_cov"]]
143
+ if rng.random() < s["drop_all"]:
144
+ c = c[:0]
145
+ elif len(c):
146
+ c = c[rng.random(len(c)) >= s["drop_each"]]
147
+ y = np.asarray(y, "float64")
148
+ fin = np.isfinite(y)
149
+ if s["sqrt"] and fin.any() and (y[fin] >= 0).all() and rng.random() < s["sqrt"]:
150
+ y = np.sqrt(np.clip(y, 0, None))
151
+ if rng.random() < s["flip"]:
152
+ y = -y
153
+ samples.append((y.astype("float32"), np.asarray(c, "float32"), H))
154
+ kind_count[kind] += 1
155
+ L = hist + future_steps
156
+ B = len(samples)
157
+ C = max(1, max(len(c) for _, c, _ in samples))
158
+ values = np.full((B, 1, L), np.nan, "float32")
159
+ covs = np.full((B, C, L), np.nan, "float32")
160
+ future = np.zeros((B, L), bool)
161
+ for b, (y, c, H) in enumerate(samples):
162
+ lo = hist - (len(y) - H)
163
+ values[b, 0, lo:lo + len(y)] = y
164
+ if len(c):
165
+ covs[b, : len(c), lo:lo + len(y)] = c
166
+ future[b, hist:hist + H] = True
167
+ fit_keep = rng.random(B) >= s["drop_fit"]
168
+ return {"values": torch.from_numpy(values), "future": torch.from_numpy(future),
169
+ "covs": torch.from_numpy(covs), "fit_keep": torch.from_numpy(fit_keep),
170
+ "kinds": kind_count, "hist": hist}
171
+
172
+
173
+ def batch_loss(model, batch, history_weight: float, device):
174
+ """(weighted mean pinball loss, summed target weight) of one covariate batch."""
175
+ from simons.training import network
176
+
177
+ values = batch["values"].to(device, non_blocking=True)
178
+ future = batch["future"].to(device, non_blocking=True)
179
+ covs = batch["covs"].to(device, non_blocking=True)
180
+ fit_keep = batch["fit_keep"].to(device, non_blocking=True)
181
+ inputs = values.masked_fill(future[:, None], float("nan"))
182
+ ids = torch.zeros(values.shape[:2], dtype=torch.long, device=device)
183
+ q, loc, scale = network.covariate_forward(model, inputs, ids, covs, fit_keep)
184
+ q = q[:, :, :-1].float()
185
+ target = values.unflatten(-1, (-1, PATCH))[:, :, 1:].double()
186
+ target = torch.asinh((target - loc[..., :-1, None]) / scale[..., :-1, None]).float()
187
+ seen = torch.isfinite(inputs).unflatten(-1, (-1, PATCH)).any(-1).cummax(-1).values
188
+ target = target.masked_fill(~seen[..., :-1, None], float("nan"))
189
+ fut = future.unflatten(-1, (-1, PATCH))[:, 1:].any(-1)[:, None, :, None]
190
+ weight = torch.where(fut, 1.0, float(history_weight))
191
+ observed = torch.isfinite(target)
192
+ levels = q.new_tensor(QUANTILES)
193
+ err = torch.where(observed, target, 0.0).unsqueeze(-1) - torch.nan_to_num(q)
194
+ loss = torch.maximum(levels * err, (levels - 1) * err).mean(-1)
195
+ w = weight * observed
196
+ return (loss * w).sum() / w.sum().clamp_min(1), w.sum().detach()
197
+
198
+
199
+ class CovariateStream:
200
+ """One covariate pass of a run (per rank): its loader and its loss."""
201
+
202
+ def __init__(self, spec, seed: int, first_step: int, device):
203
+ unknown = set(spec) - set(DEFAULTS)
204
+ if unknown:
205
+ raise ValueError(f"covariate pass: unknown fields {sorted(unknown)}")
206
+ self.spec = {**DEFAULTS, **spec}
207
+ self.weight = float(self.spec["weight"])
208
+ self.device = device
209
+ workers = int(self.spec["workers"])
210
+ # A private generator keeps loader creation independent of the global random stream.
211
+ private = torch.Generator()
212
+ tag = int(self.spec["stream_tag"])
213
+ private.manual_seed(int(seed) * 1009 + 3304 + int(first_step)
214
+ + (0 if tag == 3232 else 7 * tag))
215
+ self.loader = DataLoader(Batches(self.spec, seed, first_step), batch_size=None,
216
+ generator=private, num_workers=workers,
217
+ pin_memory=device.type == "cuda",
218
+ persistent_workers=workers > 0,
219
+ prefetch_factor=4 if workers > 0 else None)
220
+ self.batches = iter(self.loader)
221
+ self.last_weight_sum = None
222
+ self.stats = {"batches": 0, "windows": 0, "wait_seconds": 0.0, "kinds": {}}
223
+
224
+ def loss(self, model):
225
+ """The pass's loss on its next batch (its summed target weight in `last_weight_sum`)."""
226
+ begin = time.perf_counter()
227
+ batch = next(self.batches)
228
+ self.stats["wait_seconds"] += time.perf_counter() - begin
229
+ self.stats["batches"] += 1
230
+ self.stats["windows"] += len(batch["values"])
231
+ for k, n in batch["kinds"].items():
232
+ self.stats["kinds"][k] = self.stats["kinds"].get(k, 0) + int(n)
233
+ loss, self.last_weight_sum = batch_loss(model, batch, self.spec["history_weight"],
234
+ self.device)
235
+ return loss
236
+
237
+ def summary(self):
238
+ return {**self.stats, "wait_seconds": round(self.stats["wait_seconds"], 2)}
239
+
240
+ def close(self):
241
+ self.batches = None
242
+ self.loader = None
243
+