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
simons/forecast.py ADDED
@@ -0,0 +1,578 @@
1
+ """Forecast rollout, transformed views, post-processing and variable-length batching."""
2
+
3
+ import math
4
+ import operator
5
+
6
+ import numpy as np
7
+ import torch
8
+ from torch.nn import functional as F
9
+
10
+ from .covariates import prepare_covariates, usable_covariates, xreg_fit
11
+ from .model import MAX_VARIATES, QUANTILES, SKIP_TOKENS
12
+
13
+ LEVELS = torch.tensor(QUANTILES, dtype=torch.float64)
14
+ # Per-pass limits on trunk tokens and input steps, summed over all rows and variates.
15
+ FORECAST_TOKENS = 1 << 19
16
+ FORECAST_STEPS = 1 << 26
17
+
18
+
19
+ def rollout(model, history: torch.Tensor, horizon: int, series_ids: torch.Tensor,
20
+ mixed: bool, covariates: torch.Tensor | None = None) -> torch.Tensor:
21
+ """Roll out median paths from history [B,V,T] to quantiles [B,V,horizon,9].
22
+ T >= context_length; optional covariates [B,C,T+horizon] align with history and horizon."""
23
+ c = model.config
24
+ context = c.context_length
25
+ if covariates is not None:
26
+ end = history.shape[-1]
27
+ future = math.ceil(c.prediction_length / c.patch_length) * c.patch_length
28
+ covariates = F.pad(covariates, (0, future), value=float("nan"))
29
+ width, fit = history.shape[1], False
30
+ if covariates is not None:
31
+ fit = c.fit_row and width == 1
32
+ width += covariates.shape[1] + 1
33
+ blocks, remaining = [], horizon
34
+ while remaining:
35
+ window = history[..., -context:]
36
+ cov = None if covariates is None else covariates[..., end - context : end + future]
37
+ steps = min(remaining, c.prediction_length)
38
+ tokens, length = pass_size(c, window, cov, steps, width, fit)
39
+ rows = max(1, min(FORECAST_TOKENS // tokens, FORECAST_STEPS // length))
40
+ prediction = torch.cat([
41
+ model(window[i : i + rows], series_ids[i : i + rows], mixed,
42
+ None if cov is None else cov[i : i + rows], steps=steps)
43
+ for i in range(0, len(window), rows)
44
+ ])
45
+ take = min(remaining, prediction.shape[-2])
46
+ if covariates is not None:
47
+ end += take
48
+ blocks.append(prediction[..., :take, :])
49
+ history = torch.cat([history, prediction[..., 4]], dim=-1)[..., -context:]
50
+ remaining -= take
51
+ return torch.cat(blocks, dim=-2)
52
+
53
+
54
+ def pass_size(c, window: torch.Tensor, covariates: torch.Tensor | None, steps: int,
55
+ width: int, fit: bool):
56
+ """Return (patch tokens, raw steps) per batch row for window [B,V,context_length].
57
+ Count `width` rows after skipping missing prefixes; `fit` adds one full-window row and the
58
+ other rows' inputs up to it."""
59
+ context, patch = c.context_length, c.patch_length
60
+ seen = torch.isfinite(window).flatten(0, -2).any(0)
61
+ if covariates is not None: # known-future rows hold each covariate one patch earlier
62
+ cov = torch.isfinite(covariates[..., :context]).flatten(0, -2).any(0)
63
+ seen |= cov | F.pad(cov[patch:], (0, patch), value=False)
64
+ position = torch.arange(context, device=window.device)
65
+ first = int(torch.where(seen, position, context - 1).amin())
66
+ far_len = max(0, context - c.near_context)
67
+ far = math.ceil(max(0, far_len - first) / (patch * c.far_pool))
68
+ near = math.ceil((context - max(first, far_len)) / patch)
69
+ unit = SKIP_TOKENS * patch * c.far_pool
70
+ future = math.ceil(c.prediction_length / patch) * patch
71
+ length = context - min(first, far_len) // unit * unit + future
72
+ tokens = far + near + math.ceil(steps / patch)
73
+ if not fit:
74
+ return width * tokens, width * length
75
+ whole = (far_len // (patch * c.far_pool) + (context - far_len) // patch
76
+ + math.ceil(steps / patch))
77
+ # An accepted fit row spans the window. The trunk computes and stores the other rows from
78
+ # their own start, but their input tokens and rotary tables are padded up to the fit row:
79
+ # about 2 KB per empty token on a GPU, a tenth of a computed token of the smallest model.
80
+ # They are charged a quarter of a token, which also keeps the step-domain work in bounds.
81
+ if not torch.isfinite(window).flatten(1).any(1).all():
82
+ return width * whole, width * (context + future) # an unobserved item's rows run whole
83
+ spent = (width - 1) * tokens + whole
84
+ return spent + (width * whole - spent) // 4, (width - 1) * length + context + future
85
+
86
+
87
+ def flip_back(q: torch.Tensor) -> torch.Tensor:
88
+ """Quantiles of -y from quantiles of y."""
89
+ return -q.flip(-1)
90
+
91
+
92
+ def squared(q: torch.Tensor) -> torch.Tensor:
93
+ """Quantiles of y from quantiles of sqrt(y) (the square-root views; sign kept)."""
94
+ return (q.double().sign() * q.double() ** 2).float()
95
+
96
+
97
+ def median_of_views(members: list) -> torch.Tensor:
98
+ """Per quantile, the mean of the middle two of the four views' sorted quantiles."""
99
+ return torch.stack([m.sort(-1).values for m in members]).sort(0).values[1:3].mean(0)
100
+
101
+
102
+ def pool(history: torch.Tensor, k: int, points: int) -> torch.Tensor:
103
+ """NaN-mean pool the last k * points steps of [B,V,T] into [B,V,points] block means, the last
104
+ block ending at the forecast origin; empty blocks are NaN."""
105
+ raw = history[..., -k * points :]
106
+ short = k * points - raw.shape[-1]
107
+ if short > 0:
108
+ raw = F.pad(raw, (short, 0), value=float("nan"))
109
+ blocks = raw.unflatten(-1, (points, k))
110
+ observed = torch.isfinite(blocks)
111
+ count = observed.sum(-1)
112
+ total = torch.where(observed, blocks, 0).sum(-1)
113
+ mean = total / count.clamp_min(1)
114
+ return torch.where(count > 0, mean, torch.full_like(mean, float("nan")))
115
+
116
+
117
+ def interpolate(coarse: torch.Tensor, k: int, horizon: int) -> torch.Tensor:
118
+ """Coarse forecasts [B,V,Hc,Q] of block means -> raw leads [B,V,H,Q]: coarse point j sits at
119
+ raw lead (j + 1/2) k - 1/2, linear in between, nearest value outside."""
120
+ count = coarse.shape[-2]
121
+ lead = torch.arange(horizon, device=coarse.device, dtype=torch.float64)
122
+ u = ((lead - (k - 1) / 2) / k).clamp(0, count - 1)
123
+ low = u.floor().long().clamp(max=count - 1)
124
+ high = (low + 1).clamp(max=count - 1)
125
+ frac = (u - low.double()).float()[:, None]
126
+ return coarse[..., low, :] * (1 - frac) + coarse[..., high, :] * frac
127
+
128
+
129
+ def linear_pool(members: list) -> torch.Tensor:
130
+ """Return [...,9] quantiles of an equal-weight mixture of piecewise-linear quantile CDFs.
131
+ Tails reach probabilities 0 and 1 one outer-quantile spacing beyond each endpoint."""
132
+ qs = [m.double().sort(-1).values for m in members]
133
+ levels = torch.cat([LEVELS.new_zeros(1), LEVELS, LEVELS.new_ones(1)]).to(qs[0].device)
134
+ knots = []
135
+ for q in qs:
136
+ lo = q[..., :1] - (q[..., 1:2] - q[..., :1])
137
+ hi = q[..., 8:9] + (q[..., 8:9] - q[..., 7:8])
138
+ k = torch.cat([lo, q, hi], -1)
139
+ eps = 1e-9 * (k.abs().amax(-1, keepdim=True) + 1) # Keep knots strictly increasing.
140
+ knots.append(k + torch.arange(11, device=k.device) * eps)
141
+ pts = torch.cat(knots, -1).sort(-1).values
142
+ cdf = 0
143
+ for k in knots:
144
+ idx = torch.searchsorted(k.contiguous(), pts.contiguous(), right=True)
145
+ i0 = (idx - 1).clamp(0, 10)
146
+ i1 = idx.clamp(0, 10)
147
+ k0, k1 = k.gather(-1, i0), k.gather(-1, i1)
148
+ l0, l1 = levels[i0], levels[i1]
149
+ frac = torch.where(k1 > k0, (pts - k0) / torch.where(k1 > k0, k1 - k0, 1), 0)
150
+ val = l0 + frac * (l1 - l0)
151
+ val = torch.where(idx == 0, 0.0, torch.where(idx >= 11, 1.0, val))
152
+ cdf = cdf + val / len(knots)
153
+ cdf = cdf.cummax(-1).values
154
+ tau = LEVELS.to(pts.device).expand(*pts.shape[:-1], 9).contiguous()
155
+ j = torch.searchsorted(cdf.contiguous(), tau, right=False).clamp(1, pts.shape[-1] - 1)
156
+ f0, f1 = cdf.gather(-1, j - 1), cdf.gather(-1, j)
157
+ p0, p1 = pts.gather(-1, j - 1), pts.gather(-1, j)
158
+ fr = torch.where(f1 > f0, (tau - f0) / torch.where(f1 > f0, f1 - f0, 1), 0).clamp(0, 1)
159
+ return (p0 + fr * (p1 - p0)).float()
160
+
161
+
162
+ def views_forecast(model, x: torch.Tensor, horizon: int, series_ids: torch.Tensor,
163
+ mixed: bool, covariates: torch.Tensor | None = None) -> torch.Tensor:
164
+ """Combine transformed views of history [B,V,context_length] into quantiles [B,V,H,9].
165
+ Optional covariates [B,C,context_length+H] align with history and horizon."""
166
+ c = model.config
167
+ context, pred = c.context_length, c.prediction_length
168
+ first = min(horizon, pred)
169
+ observed = torch.isfinite(x)
170
+ nonneg = observed.any(-1) & torch.where(observed, x >= 0, True).all(-1) # [B,V]
171
+ if covariates is not None:
172
+ # With covariates, a row with at most one nonzero value gets no square-root views:
173
+ # normalized, [0,...,0,v] and [0,...,0,sqrt(v)] look the same, so squaring the
174
+ # square-root forecast back would square its relative growth.
175
+ given = torch.isfinite(covariates).flatten(1).any(-1)[:, None] # [B,1]
176
+ nonneg = nonneg & ~(given & ((observed & (x != 0)).sum(-1) <= 1))
177
+
178
+ def run(values, steps, ids=series_ids, cov=None):
179
+ if cov is not None:
180
+ cov = cov[..., : values.shape[-1] + steps]
181
+ return rollout(model, values, steps, ids, mixed, cov)
182
+
183
+ rows = nonneg.any(-1)
184
+ if horizon <= pred:
185
+ # Adjacent views share period detection and covariate computation.
186
+ root = torch.where(torch.isfinite(x), x.clamp_min(0).sqrt(), float("nan"))
187
+ batch = x.shape[0]
188
+ views = torch.stack([x, -x, root, -root], 1).flatten(0, 1)
189
+ every = torch.ones_like(rows)
190
+ take = torch.stack([every, every, rows, rows], 1).flatten()
191
+ q = run(views[take], first, series_ids.repeat_interleave(4, 0)[take],
192
+ None if covariates is None else covariates.repeat_interleave(4, 0)[take])
193
+ out = q.new_full((batch * 4, *q.shape[1:]), float("nan"))
194
+ out[take] = q
195
+ out = out.unflatten(0, (batch, 4))
196
+ native, flip = out[:, 0], flip_back(out[:, 1])
197
+ members = [native, flip]
198
+ keep = nonneg[..., None, None]
199
+ for q, fallback in ((out[:, 2], native), (flip_back(out[:, 3]), flip)):
200
+ members.append(torch.where(keep, squared(q), fallback))
201
+ return median_of_views(members).sort(-1).values
202
+ native_full = run(x, horizon, cov=covariates)
203
+ native = native_full[..., :first, :]
204
+ flip = flip_back(run(-x, first, cov=covariates))
205
+ members = [native, flip]
206
+ if rows.any():
207
+ xs = x[rows]
208
+ root = torch.where(torch.isfinite(xs), xs.clamp_min(0).sqrt(), float("nan"))
209
+ ids = series_ids[rows]
210
+ keep = nonneg[rows][..., None, None]
211
+ cr = None if covariates is None else covariates[rows]
212
+ for q, fallback in ((run(root, first, ids, cr), native),
213
+ (flip_back(run(-root, first, ids, cr)), flip)):
214
+ full = fallback.clone()
215
+ full[rows] = torch.where(keep, squared(q), fallback[rows])
216
+ members.append(full)
217
+ else:
218
+ members += [native, flip]
219
+ near = median_of_views(members)
220
+ if horizon <= pred:
221
+ return near.sort(-1).values
222
+ rest = horizon - pred
223
+ paths = torch.cat([torch.cat([x, native[..., p]], -1)[..., -context:] for p in (1, 7)])
224
+ tail = [native_full[..., pred:, :], *run(paths, rest, series_ids.repeat(2, 1)).chunk(2)]
225
+ pooled = pool(x, 2, context)
226
+ steps = math.ceil(horizon / 2)
227
+ coarse = 0.5 * (run(pooled, steps) + flip_back(run(-pooled, steps)))
228
+ tail.append(interpolate(coarse, 2, horizon)[..., pred:, :])
229
+ far = linear_pool(tail)
230
+ return torch.cat([near, far], -2).sort(-1).values
231
+
232
+
233
+ def clip_to_sign(history: torch.Tensor, result: torch.Tensor) -> torch.Tensor:
234
+ """Clip [B,V,H,Q] forecasts to the sign of a one-signed [B,V,T] history."""
235
+ seen = torch.isfinite(history)
236
+ low = torch.where(seen, history, math.inf).amin(-1)
237
+ high = torch.where(seen, history, -math.inf).amax(-1)
238
+ any_seen = seen.any(-1)
239
+ nonneg = (any_seen & (low >= 0))[..., None, None]
240
+ nonpos = (any_seen & (high <= 0) & (low < 0))[..., None, None]
241
+ result = torch.where(nonneg, result.clamp_min(0), result)
242
+ return torch.where(nonpos, result.clamp_max(0), result)
243
+
244
+
245
+ def integer_snap(history: torch.Tensor, result: torch.Tensor) -> torch.Tensor:
246
+ """Round forecasts for variates with non-negative integer-valued observed histories."""
247
+ seen = torch.isfinite(history)
248
+ integral = torch.where(seen, history == history.round(), True).all(-1)
249
+ nonneg = torch.where(seen, history >= 0, True).all(-1)
250
+ flag = integral & nonneg & seen.any(-1)
251
+ return torch.where(flag[..., None, None], result.round(), result)
252
+
253
+
254
+ def _float32(x) -> torch.Tensor:
255
+ if torch.is_tensor(x):
256
+ return x.to(torch.float32)
257
+ return torch.from_numpy(np.ascontiguousarray(x, dtype=np.float32))
258
+
259
+
260
+ def stack_covariates(covariates, batch: int, length: int, device):
261
+ """Stack covariates into float32 [B,C,length], padding with NaN; return None when empty.
262
+ Accept a tensor/array [B,C,length] or B entries of None or [C_b,length]."""
263
+ if covariates is None:
264
+ return None
265
+ if torch.is_tensor(covariates) or isinstance(covariates, np.ndarray):
266
+ covariates = list(covariates)
267
+ rows = [None if c is None else _float32(c) for c in covariates]
268
+ if len(rows) != batch:
269
+ raise ValueError("covariates must have one entry per batch row")
270
+ width = max((len(r) for r in rows if r is not None), default=0)
271
+ if not width:
272
+ return None
273
+ out = torch.full((batch, width, length), float("nan"), device=device)
274
+ for b, r in enumerate(rows):
275
+ if r is None:
276
+ continue
277
+ if r.ndim != 2 or r.shape[-1] != length:
278
+ raise ValueError(f"covariates row {b}: expected [C, {length}], got {tuple(r.shape)}")
279
+ out[b, : len(r)] = r
280
+ return out
281
+
282
+
283
+ def backtest_loss(truth: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
284
+ """Scaled pinball loss per batch row of q [B,V,H,9] against truth [B,V,H] (NaN skipped)."""
285
+ levels = LEVELS.to(q.device)
286
+ ok = torch.isfinite(truth)
287
+ err = torch.where(ok, truth, 0)[..., None] - q
288
+ pin = torch.maximum(levels * err, (levels - 1) * err).mean(-1) * ok
289
+ return pin.sum((1, 2)) / torch.where(ok, truth.abs(), 0).sum((1, 2)).clamp_min(1e-9)
290
+
291
+
292
+ def _post_process(model, history, result):
293
+ c = model.config
294
+ if c.sign_clip:
295
+ result = clip_to_sign(history, result)
296
+ if c.integer_snap:
297
+ result = integer_snap(history, result)
298
+ return result
299
+
300
+
301
+ def covariate_variants(model, history: torch.Tensor, horizon: int, series_ids: torch.Tensor,
302
+ covariates: torch.Tensor, rows: torch.Tensor, xreg: torch.Tensor,
303
+ views: bool, mixed: bool) -> torch.Tensor:
304
+ """Forecast selected history rows [J,V,T] as [J,V,H,9], with per-row XReg flags [J].
305
+ Covariates [B,C,T+horizon] align with history [B,V,T]; T <= context_length."""
306
+ c = model.config
307
+ context = c.context_length
308
+ left = max(0, context - history.shape[-1])
309
+ history = F.pad(history, (left, 0), value=float("nan"))
310
+ covariates = F.pad(covariates, (left, 0), value=float("nan"))
311
+ original = values = history[rows]
312
+ fitted = None
313
+ if bool(xreg.any()):
314
+ future = torch.zeros(covariates.shape[-1], dtype=torch.bool, device=history.device)
315
+ future[-horizon:] = True
316
+ full = F.pad(history, (0, horizon), value=float("nan"))
317
+ fitted = xreg_fit(full, covariates, future, c.xreg_gate)[rows]
318
+ values = torch.where(xreg[:, None, None], original - fitted[..., : original.shape[-1]],
319
+ original)
320
+ cov, ids = covariates[rows], series_ids[rows]
321
+ if views:
322
+ result = views_forecast(model, values, horizon, ids, mixed, cov)
323
+ else:
324
+ result = rollout(model, values, horizon, ids, mixed, cov)
325
+ if fitted is not None:
326
+ result = torch.where(xreg[:, None, None, None],
327
+ result + fitted[..., -horizon:, None].to(result.dtype), result)
328
+ return _post_process(model, original, result)
329
+
330
+
331
+ def _backtest_covariates(covariates: torch.Tensor, horizon: int) -> torch.Tensor:
332
+ """Hide past-only covariates over the backtest horizon as well as the real horizon."""
333
+ past = covariates[..., :-horizon].clone()
334
+ later = ~torch.isfinite(covariates[..., -horizon:]).any(-1)
335
+ past[..., -horizon:] = torch.where(later[..., None], float("nan"), past[..., -horizon:])
336
+ return past
337
+
338
+
339
+ def _covariate_rules(model, history, horizon, series_ids, covariates, views, mixed):
340
+ """Select XReg per row using history length and a held-out pinball-loss comparison."""
341
+ c = model.config
342
+ batch, device = history.shape[0], history.device
343
+ observed = torch.isfinite(history).sum(-1).amin(-1)
344
+ if not c.xreg:
345
+ long = torch.ones(batch, dtype=torch.bool, device=device)
346
+ elif c.rows_only_history > 0:
347
+ long = observed > c.rows_only_history
348
+ else:
349
+ long = torch.zeros(batch, dtype=torch.bool, device=device)
350
+ guard = ~long & (observed >= max(c.xreg_guard_min, horizon + 64))
351
+ if not c.xreg_guard:
352
+ guard = torch.zeros_like(guard)
353
+ index = torch.arange(batch, device=device)
354
+ # Slots 0/1 use full history with/without XReg; 2/3 use the backtest at T - horizon.
355
+ parts = [(index[~long], 0), (index[guard | long], 1), (index[guard], 2), (index[guard], 3)]
356
+ rows = torch.cat([r + (batch if slot >= 2 else 0) for r, slot in parts])
357
+ slots = torch.cat([torch.full_like(r, slot) for r, slot in parts])
358
+ item = rows % batch
359
+ order = torch.argsort(item * 4 + slots)
360
+ rows, slots, item = rows[order], slots[order], item[order]
361
+ if bool(guard.any()):
362
+ cut = F.pad(history[..., :-horizon], (horizon, 0), value=float("nan"))
363
+ past = F.pad(_backtest_covariates(covariates, horizon), (horizon, 0), value=float("nan"))
364
+ history2 = torch.cat([history, cut])
365
+ covariates2 = torch.cat([covariates, past])
366
+ ids2 = torch.cat([series_ids, series_ids])
367
+ else:
368
+ history2, covariates2, ids2 = history, covariates, series_ids
369
+ out = covariate_variants(model, history2, horizon, ids2, covariates2, rows, slots % 2 == 0,
370
+ views, mixed)
371
+
372
+ def part(slot):
373
+ mask = slots == slot
374
+ return item[mask], out[mask]
375
+
376
+ result = out.new_empty((batch, *out.shape[1:]))
377
+ rows_x, with_x = part(0)
378
+ result[rows_x] = with_x
379
+ rows_n, no_x = part(1)
380
+ result[rows_n[long[rows_n]]] = no_x[long[rows_n]]
381
+ if bool(guard.any()):
382
+ rows_g, bt_x = part(2)
383
+ _, bt_n = part(3)
384
+ truth = history[rows_g][..., -horizon:].cpu().double()
385
+ use = backtest_loss(truth, bt_n.cpu().double()) < c.xreg_guard_margin * backtest_loss(
386
+ truth, bt_x.cpu().double())
387
+ result[rows_g] = torch.where(use.to(device)[:, None, None, None], no_x[guard[rows_n]],
388
+ result[rows_g])
389
+ return result
390
+
391
+
392
+ @torch.inference_mode()
393
+ def forecast(model, history, horizon: int, series_ids=None, covariates=None,
394
+ views: bool | None = None, mixed: bool | None = None) -> torch.Tensor:
395
+ """[B,T]/[B,V,T] history -> [B,H,9]/[B,V,H,9] quantiles; NaN = missing, V <= 32.
396
+ Equal series_ids [B,V] group variates; covariates [B,C,T+horizon] or B None/[C_b,T+horizon].
397
+ Read <= context_length steps and 16 usable covariates; rescale if std is below about 1e-4."""
398
+ if not torch.is_tensor(history):
399
+ history = _float32(history)
400
+ horizon = operator.index(horizon)
401
+ if history.ndim not in (2, 3) or 0 in history.shape or horizon <= 0:
402
+ raise ValueError("Provide nonempty [B,T] or [B,V,T] history and a positive horizon")
403
+ univariate = history.ndim == 2
404
+ if univariate:
405
+ history = history[:, None]
406
+ if history.shape[1] > MAX_VARIATES:
407
+ raise ValueError(f"Split related variates into groups of at most {MAX_VARIATES}")
408
+ device = next(model.parameters()).device
409
+ history = history.to(device=device, dtype=torch.float32)
410
+ if series_ids is None:
411
+ series_ids = torch.zeros(history.shape[:2], dtype=torch.long, device=device)
412
+ series_ids = torch.as_tensor(series_ids, device=device)
413
+ if series_ids.shape != history.shape[:2]:
414
+ raise ValueError("series_ids must match the batch and variate dimensions")
415
+ c = model.config
416
+ context = c.context_length
417
+ if covariates is not None and not c.covariates:
418
+ raise ValueError("this checkpoint has no covariate weights; forecast without covariates")
419
+ covariates = stack_covariates(covariates, history.shape[0], history.shape[-1] + horizon,
420
+ device)
421
+ history = history[..., -context:]
422
+ if covariates is not None:
423
+ covariates = usable_covariates(history, covariates[..., -(history.shape[-1] + horizon):],
424
+ horizon)
425
+ if covariates is not None:
426
+ several = (series_ids != series_ids[:, :1]).any(-1)
427
+ if bool((several & torch.isfinite(covariates).flatten(1).any(-1)).any()):
428
+ raise ValueError("a row with covariates must hold one series (one series id); put "
429
+ "each series in its own row")
430
+ views = c.views if views is None else views
431
+ mixed = history.is_cuda if mixed is None else mixed and history.is_cuda
432
+ was_training = model.training
433
+ model.eval()
434
+ try:
435
+ if covariates is not None:
436
+ result = _covariate_rules(model, history, horizon, series_ids, covariates, views,
437
+ mixed)
438
+ else:
439
+ history = F.pad(history, (context - history.shape[-1], 0), value=float("nan"))
440
+ if views:
441
+ result = views_forecast(model, history, horizon, series_ids, mixed)
442
+ else:
443
+ result = rollout(model, history, horizon, series_ids, mixed)
444
+ result = _post_process(model, history, result)
445
+ finally:
446
+ model.train(was_training)
447
+ observed = torch.isfinite(history).any(-1) # [B,V]: a variate with no observed value gets 0
448
+ result = torch.where(observed[..., None, None], result, 0.0)
449
+ return result[:, 0] if univariate else result
450
+
451
+
452
+ def pack(histories: list, context: int):
453
+ """Pack [V,T] histories into (history [R,W,context], ids [R,W], input (row,slot) positions).
454
+ V and W <= 32; histories are right-aligned and cropped; id -1 marks padding."""
455
+ rows, row, used = [], [], 0
456
+ for index, h in enumerate(histories):
457
+ if used + len(h) > MAX_VARIATES:
458
+ rows.append(row)
459
+ row, used = [], 0
460
+ row.append(index)
461
+ used += len(h)
462
+ rows.append(row)
463
+ width = max(sum(len(histories[i]) for i in row) for row in rows)
464
+ batch = torch.full((len(rows), width, context), float("nan"))
465
+ ids = torch.full((len(rows), width), -1, dtype=torch.long)
466
+ places = [None] * len(histories)
467
+ for r, row in enumerate(rows):
468
+ offset = 0
469
+ for index in row:
470
+ h = histories[index]
471
+ n = min(context, h.shape[-1])
472
+ batch[r, offset : offset + len(h), context - n :] = torch.from_numpy(h[:, -n:])
473
+ ids[r, offset : offset + len(h)] = index
474
+ places[index] = (r, offset)
475
+ offset += len(h)
476
+ return batch, ids, places
477
+
478
+
479
+ def forecast_series(model, series: list, horizon: int, batch_size: int = 1024,
480
+ future_covariates: list | None = None, past_covariates: list | None = None,
481
+ shared_categories: bool = True, **options) -> list:
482
+ """[T]/[V,T] histories -> float32 CPU numpy [H,9]/[V,H,9] forecasts; NaN = missing.
483
+ Future/past covariates [C,T+horizon]/[C,T] align by position; >32 variates split into groups.
484
+ `shared_categories=False` codes history and horizon separately; options go to `forecast`."""
485
+ for s in series:
486
+ if np.ndim(s) not in (1, 2) or 0 in np.shape(s):
487
+ raise ValueError("Each series must be a nonempty [T] or [V,T] array")
488
+ if future_covariates is None and past_covariates is None:
489
+ return _forecast_packed(model, series, horizon, batch_size, **options)
490
+ for name, given in (("future_covariates", future_covariates),
491
+ ("past_covariates", past_covariates)):
492
+ if hasattr(given, "items"):
493
+ raise ValueError(f"{name} takes a list with one entry per series, got a "
494
+ f"{type(given).__name__}; for one series, wrap its covariates in a "
495
+ f"list: {name}=[...]")
496
+ count = len(series)
497
+ future_covariates = [None] * count if future_covariates is None else list(future_covariates)
498
+ past_covariates = [None] * count if past_covariates is None else list(past_covariates)
499
+ if len(future_covariates) != count or len(past_covariates) != count:
500
+ raise ValueError("future_covariates / past_covariates need one entry per series")
501
+ items = []
502
+ for s, future, past in zip(series, future_covariates, past_covariates):
503
+ s = np.asarray(s, dtype=np.float32)
504
+ targets = s[None] if s.ndim == 1 else s
505
+ items.append((targets, prepare_covariates(targets.shape[-1], horizon, future, past,
506
+ shared_categories=shared_categories)))
507
+ outputs = forecast_items(model, items, horizon, batch_size, **options)
508
+ return [out[0] if np.ndim(s) == 1 else out for s, out in zip(series, outputs)]
509
+
510
+
511
+ def forecast_items(model, items: list, horizon: int, batch_size: int = 256, **options) -> list:
512
+ """Return [V,H,9] forecasts per item with targets [V,T] and covariates [C,T+horizon] or None.
513
+ Related variates share covariates and are split into groups of at most 32."""
514
+ if batch_size < 1:
515
+ raise ValueError("batch_size must be at least 1")
516
+ context = model.config.context_length
517
+ rows = []
518
+ for index, (targets, covs) in enumerate(items):
519
+ bad = np.ndim(targets) != 2 or 0 in np.shape(targets)
520
+ if not bad and covs is not None:
521
+ bad = np.ndim(covs) != 2 or np.shape(covs)[-1] != np.shape(targets)[-1] + horizon
522
+ if bad:
523
+ raise ValueError(f"item {index}: expected nonempty targets [V, T] and covariates "
524
+ f"[C, T + {horizon}] or None")
525
+ for first in range(0, len(targets), MAX_VARIATES):
526
+ rows.append((index, first, targets[first : first + MAX_VARIATES], covs))
527
+ out = [np.zeros((len(t), horizon, len(QUANTILES)), dtype=np.float32) for t, _ in items]
528
+ groups = {}
529
+ for row in rows:
530
+ groups.setdefault(row[2].shape[0], []).append(row)
531
+ for variates, group in groups.items():
532
+ for begin in range(0, len(group), batch_size):
533
+ chunk = group[begin : begin + batch_size]
534
+ width = min(context, max(r[2].shape[-1] for r in chunk))
535
+ history = np.full((len(chunk), variates, width), np.nan, dtype="float32")
536
+ covs = []
537
+ for b, (_, _, block, c) in enumerate(chunk):
538
+ w = min(width, block.shape[-1])
539
+ history[b, :, width - w :] = block[:, block.shape[-1] - w :]
540
+ if c is None:
541
+ covs.append(None)
542
+ continue
543
+ full = np.full((len(c), width + horizon), np.nan, dtype="float32")
544
+ full[:, width - w :] = c[:, block.shape[-1] - w :]
545
+ covs.append(full)
546
+ cov_arg = covs if any(c is not None for c in covs) else None
547
+ prediction = forecast(model, torch.from_numpy(history), horizon,
548
+ covariates=cov_arg, **options).cpu().numpy()
549
+ for b, (index, first, block, _) in enumerate(chunk):
550
+ out[index][first : first + len(block)] = prediction[b]
551
+ return out
552
+
553
+
554
+ def _forecast_packed(model, series: list, horizon: int, batch_size: int, **options) -> list:
555
+ if batch_size < 1:
556
+ raise ValueError("batch_size must be at least 1")
557
+ context = model.config.context_length
558
+ results = []
559
+ for start in range(0, len(series), batch_size):
560
+ chunk = [np.ascontiguousarray(s, dtype=np.float32)
561
+ for s in series[start : start + batch_size]]
562
+ blocks, owner = [], []
563
+ for index, s in enumerate(chunk):
564
+ s = s[None] if s.ndim == 1 else s
565
+ for first in range(0, len(s), MAX_VARIATES):
566
+ blocks.append(s[first : first + MAX_VARIATES])
567
+ owner.append(index)
568
+ outputs = []
569
+ for first in range(0, len(blocks), batch_size):
570
+ group = blocks[first : first + batch_size]
571
+ history, ids, places = pack(group, context)
572
+ prediction = forecast(model, history, horizon, ids, **options).cpu().numpy()
573
+ outputs += [prediction[r, o : o + len(h)] for (r, o), h in zip(places, group)]
574
+ for index, s in enumerate(chunk):
575
+ parts = [out for out, i in zip(outputs, owner) if i == index]
576
+ stacked = np.concatenate(parts)
577
+ results.append(stacked[0] if s.ndim == 1 else stacked)
578
+ return results