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/model.py ADDED
@@ -0,0 +1,696 @@
1
+ """Patch transformer producing nine quantiles of the next `prediction_length` steps."""
2
+
3
+ import json
4
+ import math
5
+ from contextlib import nullcontext
6
+ from pathlib import Path
7
+
8
+ import torch
9
+ from torch import nn
10
+ from torch.nn import functional as F
11
+
12
+ from .config import SimonsConfig
13
+ from .covariates import ROLE_BINARY, ROLE_TARGET, CovariateModules, covariate_rows, read_mask
14
+ from .periodicity import detect_periods, period_rotary, select_periods
15
+
16
+ QUANTILES = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
17
+ MIN_SCALE = 1e-5
18
+ MAX_VARIATES = 32
19
+
20
+
21
+ def sliding_scale(values: torch.Tensor, window: int):
22
+ """Causal (loc, std) at every step of [..., T] values over the observed values among the last
23
+ `window` steps, frozen across missing steps (loc 0, std MIN_SCALE before the first one)."""
24
+ observed = torch.isfinite(values)
25
+ ref = torch.nanmedian(values.float(), dim=-1, keepdim=True).values.double()
26
+ ref = torch.where(torch.isfinite(ref), ref, 0)
27
+ x = torch.where(observed, values.double() - ref, 0)
28
+ w = observed.double()
29
+
30
+ def windowed(a):
31
+ c = a.cumsum(-1)
32
+ if window >= a.shape[-1]:
33
+ return c
34
+ return c - F.pad(c[..., :-window], (window, 0))
35
+
36
+ n = windowed(w)
37
+ s1 = windowed(x)
38
+ s2 = windowed(x * x)
39
+ mean = s1 / n.clamp_min(1)
40
+ var = ((s2 - s1 * mean) / (n - 1).clamp_min(1)).clamp_min(MIN_SCALE**2)
41
+ loc, std = mean + ref, var.sqrt()
42
+ position = torch.arange(values.shape[-1], device=values.device)
43
+ last = torch.where(observed, position, -1).cummax(-1).values
44
+ loc = torch.where(last >= 0, loc.gather(-1, last.clamp_min(0)), 0)
45
+ std = torch.where(last >= 0, std.gather(-1, last.clamp_min(0)), MIN_SCALE)
46
+ return loc, std
47
+
48
+
49
+ def scale_values(values: torch.Tensor, loc: torch.Tensor, scale: torch.Tensor):
50
+ """asinh of the scaled values (0 where missing) and the observed flags."""
51
+ observed = torch.isfinite(values)
52
+ clean = torch.where(observed, values, 0).double()
53
+ scaled = (clean - loc) / scale
54
+ return torch.where(observed, scaled, 0).asinh().float(), observed
55
+
56
+
57
+ def tokenize(scaled: torch.Tensor, observed: torch.Tensor, patch: int) -> torch.Tensor:
58
+ """[..., T] scaled values and flags -> [..., T / patch, 2 * patch] tokens."""
59
+ return torch.cat([scaled.unflatten(-1, (-1, patch)),
60
+ observed.float().unflatten(-1, (-1, patch))], -1)
61
+
62
+
63
+ def future_steps(config) -> int:
64
+ """Steps covered by the future patches of one pass."""
65
+ patch = config.patch_length
66
+ return math.ceil(config.prediction_length / patch) * patch
67
+
68
+
69
+ def layout(config, length: int):
70
+ """(far_len raw steps, far tokens) for a [.., length] sequence (history + future steps), or
71
+ None when its history fits in the near region (no far tokens)."""
72
+ patch = config.patch_length
73
+ history = length - future_steps(config)
74
+ if history <= config.near_context:
75
+ return None
76
+ far_len = history - config.near_context
77
+ block = patch * config.far_pool
78
+ if far_len % block:
79
+ raise ValueError(f"far region {far_len} must be a multiple of patch * far_pool {block}")
80
+ return far_len, far_len // block
81
+
82
+
83
+ def front(model, values: torch.Tensor, far_on: bool = True, fixed: torch.Tensor | None = None,
84
+ skip: int = 0, periods=None, return_periods: bool = False):
85
+ """[B,V,T] values, fixed [B,V] -> tokens [B,V,S,2p], rotary [B*V,1,S,half],
86
+ started/loc/scale [B,V,S], far [S]/None, far count; optional periods [B*V,slots].
87
+ `skip` omits an all-missing far prefix, keeping full-window positions and period windows."""
88
+ c = model.config
89
+ patch = c.patch_length
90
+ batch, variates, length = values.shape
91
+ history = length + skip - future_steps(c) # of the full window
92
+ half = c.width // c.heads // 2
93
+ spec = layout(c, length + skip)
94
+ if skip and (spec is None or skip % (patch * c.far_pool) or skip > spec[0] or not far_on):
95
+ raise ValueError("skip must be a multiple of the far block within the far region")
96
+ if periods is None:
97
+ if skip:
98
+ raise ValueError("skip needs a periods function")
99
+ periods = lambda v, h, f, _: select_periods(c, v, h, f) # noqa: E731
100
+ loc_all, std_all = sliding_scale(values, c.stats_window)
101
+ if fixed is not None:
102
+ loc_all = torch.where(fixed[..., None], 0.0, loc_all)
103
+ std_all = torch.where(fixed[..., None], 1.0, std_all)
104
+ device = values.device
105
+ if spec is None:
106
+ patches = length // patch
107
+ end = slice(patch - 1, None, patch)
108
+ loc, scale = loc_all[..., end], std_all[..., end]
109
+ scaled, observed = scale_values(values, loc.repeat_interleave(patch, -1),
110
+ scale.repeat_interleave(patch, -1))
111
+ tokens = tokenize(scaled, observed, patch)
112
+ starts = torch.arange(patches, device=device, dtype=torch.float64) * patch
113
+ found = periods(values, history, 0, 0).reshape(batch * variates, -1)
114
+ rotary = period_rotary(found, starts, patch, half)
115
+ started = observed.unflatten(-1, (patches, patch)).any(-1).int().cummax(-1).values.bool()
116
+ out = (tokens, rotary, started, loc, scale, None, 0)
117
+ return (*out, found) if return_periods else out
118
+
119
+ pool = c.far_pool
120
+ block = patch * pool
121
+ far_len, far_tokens = spec[0] - skip, spec[1] - skip // block
122
+ near = values[..., far_len:]
123
+ near_patches = near.shape[-1] // patch
124
+ end = slice(far_len + patch - 1, None, patch)
125
+ near_loc, near_scale = loc_all[..., end], std_all[..., end]
126
+ scaled, near_seen = scale_values(near, near_loc.repeat_interleave(patch, -1),
127
+ near_scale.repeat_interleave(patch, -1))
128
+ near_tok = tokenize(scaled, near_seen, patch)
129
+ raw = values[..., :far_len].unflatten(-1, (far_len // pool, pool))
130
+ seen = torch.isfinite(raw)
131
+ count = seen.sum(-1)
132
+ total = torch.where(seen, raw, 0).double().sum(-1)
133
+ pooled = torch.where(count > 0, total / count.clamp_min(1), float("nan"))
134
+ end = slice(block - 1, far_len, block)
135
+ far_loc, far_scale = loc_all[..., end], std_all[..., end]
136
+ scaled, far_seen = scale_values(pooled, far_loc.repeat_interleave(patch, -1),
137
+ far_scale.repeat_interleave(patch, -1))
138
+ if c.far_min_history < history:
139
+ old = torch.isfinite(values[..., : max(0, history - c.far_min_history - skip)]).any(-1)
140
+ far_seen = far_seen & old[..., None]
141
+ scaled = torch.where(far_seen, scaled, 0)
142
+ else:
143
+ far_seen = torch.zeros_like(far_seen)
144
+ scaled = torch.zeros_like(scaled)
145
+ far_tok = tokenize(scaled, far_seen, patch)
146
+ tokens = torch.cat([far_tok, near_tok], 2)
147
+ loc = torch.cat([far_loc, near_loc], -1)
148
+ scale = torch.cat([far_scale, near_scale], -1)
149
+ tokens_seen = torch.cat([far_seen.unflatten(-1, (far_tokens, patch)).any(-1),
150
+ near_seen.unflatten(-1, (near_patches, patch)).any(-1)], -1)
151
+ started = tokens_seen.int().cummax(-1).values.bool()
152
+ starts = skip + torch.cat([
153
+ torch.arange(far_tokens, device=device, dtype=torch.float64) * block,
154
+ far_len + torch.arange(near_patches, device=device, dtype=torch.float64) * patch])
155
+ found = periods(values, history - skip, far_len, skip).reshape(batch * variates, -1)
156
+ rotary = period_rotary(found, starts, patch, half)
157
+ far = torch.arange(far_tokens + near_patches, device=device) < far_tokens
158
+ if not far_on:
159
+ f = far_tokens
160
+ rotary = tuple(t[:, :, f:] for t in rotary)
161
+ return (tokens[:, :, f:], rotary, started[..., f:], loc[..., f:], scale[..., f:], far[f:],
162
+ 0)
163
+ out = (tokens, rotary, started, loc, scale, far, far_tokens)
164
+ return (*out, found) if return_periods else out
165
+
166
+
167
+ def sign_bounds(values: torch.Tensor, loc: torch.Tensor, scale: torch.Tensor, patch: int,
168
+ far_len: int):
169
+ """Return per-token (lo, hi) [B,V,S] in asinh units from one-signed observed prefixes.
170
+ Far tokens remain unbounded."""
171
+ near = values[..., far_len:]
172
+ seen = torch.isfinite(near).unflatten(-1, (-1, patch))
173
+ blocks = near.unflatten(-1, (-1, patch))
174
+ low = torch.where(seen, blocks, math.inf).amin(-1)
175
+ high = torch.where(seen, blocks, -math.inf).amax(-1)
176
+ far = values[..., :far_len] if far_len else values[..., :1].new_full(
177
+ (*values.shape[:-1], 1), float("nan"))
178
+ far_seen = torch.isfinite(far)
179
+ low = torch.cat([torch.where(far_seen, far, math.inf).amin(-1, keepdim=True), low], -1)
180
+ high = torch.cat([torch.where(far_seen, far, -math.inf).amax(-1, keepdim=True), high], -1)
181
+ low, high = low.cummin(-1).values[..., 1:], high.cummax(-1).values[..., 1:]
182
+ count, tokens = low.shape[-1], loc.shape[-1]
183
+ edge = torch.asinh(-loc[..., tokens - count:].double() / scale[..., tokens - count:].double())
184
+ any_seen = torch.isfinite(low)
185
+ nonneg = any_seen & (low >= 0)
186
+ nonpos = any_seen & (high <= 0) & (low < 0)
187
+ lo = torch.where(nonneg, edge.float(), -math.inf)
188
+ hi = torch.where(nonpos, edge.float(), math.inf)
189
+ lo = F.pad(lo, (tokens - count, 0), value=-math.inf)
190
+ hi = F.pad(hi, (tokens - count, 0), value=math.inf)
191
+ return lo, hi
192
+
193
+
194
+ def rotate(x: torch.Tensor, rotary) -> torch.Tensor:
195
+ cos, sin = (t.to(x.dtype) for t in rotary)
196
+ half = x.shape[-1] // 2
197
+ first, second = x[..., :half], x[..., half:]
198
+ return torch.cat([first * cos - second * sin, first * sin + second * cos], dim=-1)
199
+
200
+
201
+ CROP_STEP = 8
202
+ SKIP_TOKENS = CROP_STEP # forward skips leading missing far tokens in multiples of this many
203
+
204
+
205
+ def row_crops(start: torch.Tensor, roles: torch.Tensor, batch: int, variates: int) -> torch.Tensor:
206
+ """Return [B*V] first required token columns, rounded down to CROP_STEP.
207
+ Each row must retain its own and its targets' observed prefixes."""
208
+ size = start.shape[-1]
209
+ first = torch.where(start.any(-1), start.int().argmax(-1), size).reshape(batch, variates)
210
+ target = torch.where(roles == ROLE_TARGET, first, size).amin(-1, keepdim=True)
211
+ target = torch.where(target < size, target, 0)
212
+ return (torch.minimum(first, target).reshape(-1) // CROP_STEP) * CROP_STEP
213
+
214
+
215
+ def _bits(t: torch.Tensor) -> torch.Tensor:
216
+ t = t.contiguous()
217
+ return t.view({1: torch.uint8, 2: torch.int16, 4: torch.int32,
218
+ 8: torch.int64}[t.element_size()])
219
+
220
+
221
+ def shared_rows(tokens: torch.Tensor, rotary, roles: torch.Tensor, crops: torch.Tensor,
222
+ independent: torch.Tensor):
223
+ """Return (compute [M], source [N]) so row n uses compute[source[n]]; (None,None) if unique.
224
+ Reuse requires equal tokens [N,S,F], rotary tables, roles and crops."""
225
+ n, device = tokens.shape[0], tokens.device
226
+ index = torch.arange(n, device=device)
227
+ parts = [tokens.reshape(n, -1), *(t.reshape(n, -1) for t in rotary)]
228
+ generator = torch.Generator().manual_seed(0)
229
+ keys = [torch.stack([roles.double(), crops.double(),
230
+ torch.where(independent, -1, index).double()], 1)]
231
+ for p in parts:
232
+ weights = torch.rand(p.shape[1], 2, generator=generator, dtype=torch.float64)
233
+ keys.append(p.double() @ weights.to(device))
234
+ _, group = torch.unique(torch.cat(keys, 1), dim=0, return_inverse=True)
235
+ first = torch.full((int(group.max()) + 1,), n, device=device)
236
+ rep = first.scatter_reduce(0, group, index, "amin")[group]
237
+ same = (roles == roles[rep]) & (crops == crops[rep])
238
+ for p in parts:
239
+ bits = _bits(p)
240
+ same &= (bits == bits[rep]).all(-1)
241
+ rep = torch.where(same, rep, index)
242
+ compute = torch.unique(rep)
243
+ if len(compute) == n:
244
+ return None, None
245
+ return compute, torch.searchsorted(compute, rep)
246
+
247
+
248
+ def crop_groups(crops: torch.Tensor) -> list:
249
+ """Return (crop, rows [R]) for each distinct value of crops [N]."""
250
+ return [(crop, torch.nonzero(crops == crop)[:, 0]) for crop in torch.unique(crops).tolist()]
251
+
252
+
253
+ def from_position(x: list, groups: list, before: torch.Tensor, first: int, size: int):
254
+ """Return [N,S-first,W] from the groups' activations x (each [R,S-crop,W], from its crop).
255
+ Positions before a row's crop hold its `before` [N,W] vector."""
256
+ out = before.new_zeros(len(before), size - first, before.shape[-1]) + before[:, None]
257
+ for (crop, rows), xs in zip(groups, x):
258
+ out[rows, max(crop - first, 0):] = xs[:, max(first - crop, 0):]
259
+ return out
260
+
261
+
262
+ def time_blocks(blocks, x, start: torch.Tensor, rotary, groups=None):
263
+ """Run time blocks on x [N,S,W] with started flags [N,S]. With `groups` (see `crop_groups`),
264
+ x and the result list each group's activations [R,S-crop,W] from its crop."""
265
+
266
+ def run(x, start, rotary):
267
+ position = torch.arange(x.shape[1], device=x.device)
268
+ query, key = position[:, None], position[None, :]
269
+ mask = ((key <= query)[None] & (start[:, None, :] | (key == query)[None]))[:, None]
270
+ for block in blocks:
271
+ x = block(x, mask, rotary=rotary)
272
+ return x
273
+
274
+ if groups is None:
275
+ return run(x, start, rotary)
276
+ out = []
277
+ for (crop, rows), xs in zip(groups, x):
278
+ ss = start[rows, crop:]
279
+ rs = tuple(t[rows][:, :, crop:] for t in rotary)
280
+ shared, length = constant_prefix(xs, ss)
281
+ if shared is None:
282
+ out.append(run(xs, ss, rs))
283
+ continue
284
+ rest = torch.ones(len(rows), dtype=torch.bool, device=xs.device)
285
+ rest[shared] = False
286
+ y = torch.empty_like(xs)
287
+ y[shared] = prefix_blocks(blocks, xs[shared], tuple(t[shared] for t in rs), length)
288
+ if bool(rest.any()):
289
+ y[rest] = run(xs[rest], ss[rest], tuple(t[rest] for t in rs))
290
+ out.append(y)
291
+ return out
292
+
293
+
294
+ PREFIX_MIN = 8 # shortest shared prefix (positions) that `time_blocks` runs once
295
+
296
+
297
+ def constant_prefix(x: torch.Tensor, start: torch.Tensor):
298
+ """Return (rows [R], P) sharing one started prefix vector in x [N,S,W], start [N,S].
299
+ PREFIX_MIN <= P < S; return (None, 0) if no rows qualify."""
300
+ size = x.shape[1]
301
+ if size <= PREFIX_MIN:
302
+ return None, 0
303
+ same = (x == x[:, :1]).all(-1) & start
304
+ run = same.int().cumprod(-1).sum(-1)
305
+ candidate = run >= PREFIX_MIN
306
+ if not bool(candidate.any()):
307
+ return None, 0
308
+ first = int(torch.nonzero(candidate)[0, 0])
309
+ candidate &= (x[:, 0] == x[first, 0]).all(-1)
310
+ rows = torch.nonzero(candidate)[:, 0]
311
+ return rows, min(int(run[rows].min()), size - 1)
312
+
313
+
314
+ def prefix_blocks(blocks, x: torch.Tensor, rotary, length: int) -> torch.Tensor:
315
+ """Run causal blocks on x [R,S,W] with a shared, started prefix of `length` positions.
316
+ Prefix attention returns the shared value regardless of weights; compute that state once."""
317
+ n, size, width = x.shape
318
+ prefix, x = x[0, 0], x[:, length:]
319
+ later = size - length
320
+ cos, sin = rotary
321
+ head_rotary = (cos[:, :, :length], sin[:, :, :length])
322
+ tail_rotary = (cos[:, :, length:], sin[:, :, length:])
323
+ query = torch.arange(later, device=x.device)[:, None] + length
324
+ mask = (torch.arange(size, device=x.device)[None] <= query)[None, None]
325
+ for block in blocks:
326
+ heads = block.heads
327
+ qkv = block.qkv(block.attention_norm(prefix[None, None])).view(1, 1, 3, heads, -1)
328
+ key, value = (t.transpose(1, 2) for t in qkv.unbind(2)[1:]) # [1,H,1,D]
329
+ q, k, v = block.qkv(block.attention_norm(x)).view(n, later, 3, heads, -1).unbind(2)
330
+ q, k, v = (t.transpose(1, 2) for t in (q, k, v))
331
+ q, k = rotate(q, tail_rotary), rotate(k, tail_rotary)
332
+ keys = torch.cat([rotate(key.expand(n, heads, length, -1), head_rotary), k], 2)
333
+ values = torch.cat([value.expand(n, heads, length, -1), v], 2)
334
+ attended = F.scaled_dot_product_attention(q, keys, values, attn_mask=mask)
335
+ x = x + block.out(attended.transpose(1, 2).reshape(n, later, width))
336
+ x = x + block.mlp(block.mlp_norm(x))
337
+ prefix = prefix + block.out(value.transpose(1, 2).reshape(1, 1, width))[0, 0]
338
+ prefix = prefix + block.mlp(block.mlp_norm(prefix[None, None]))[0, 0]
339
+ return torch.cat([prefix.expand(n, length, width).to(x.dtype), x], 1)
340
+
341
+
342
+ def attend_targets(block, x, source, mine, mask, batch: int, variates: int, targets: int,
343
+ size: int, explicit: bool = False, first: int = 0) -> torch.Tensor:
344
+ """Apply a cross-row block to each item's first T rows: x [M,S-first,W] -> [B*T,S-first,W].
345
+ x holds positions from `first`; `source` [B*V] and `mine` [B*T] index it; mask [B*S,1,T,V]
346
+ selects keys from all rows. `explicit` uses fp32 softmax."""
347
+ if first:
348
+ mask = mask.view(batch, size, *mask.shape[1:])[:, first:].flatten(0, 1)
349
+ size -= first
350
+ width, heads = x.shape[-1], block.heads
351
+ weight = block.qkv.weight
352
+ kv = F.linear(block.attention_norm(x), weight[width:])[source] # [N,S,2W]
353
+ kv = kv.view(batch, variates, size, 2, heads, -1).permute(3, 0, 2, 4, 1, 5)
354
+ k, v = (t.reshape(batch * size, heads, variates, -1) for t in kv.unbind(0))
355
+ current = x[mine] # [B*T,S,W]
356
+ q = F.linear(block.attention_norm(current), weight[:width])
357
+ q = q.view(batch, targets, size, heads, -1).permute(0, 2, 3, 1, 4).reshape(batch * size, heads,
358
+ targets, -1)
359
+ if explicit:
360
+ scores = (q @ k.transpose(-1, -2)) * q.shape[-1] ** -0.5
361
+ weights = scores.float().masked_fill(~mask, float("-inf")).softmax(-1)
362
+ attended = weights.to(v.dtype) @ v
363
+ else:
364
+ attended = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
365
+ attended = attended.view(batch, size, heads, targets, -1).permute(0, 3, 1, 2, 4).reshape(
366
+ batch * targets, size, width)
367
+ y = current + block.out(attended)
368
+ return y + block.mlp(block.mlp_norm(y))
369
+
370
+
371
+ class Block(nn.Module):
372
+ """Pre-norm attention + GELU MLP block; causal blocks apply the rotary embedding."""
373
+
374
+ def __init__(self, config: SimonsConfig, causal: bool):
375
+ super().__init__()
376
+ self.heads, self.causal = config.heads, causal
377
+ self.attention_norm = nn.RMSNorm(config.width)
378
+ self.qkv = nn.Linear(config.width, 3 * config.width, bias=False)
379
+ self.out = nn.Linear(config.width, config.width, bias=False)
380
+ self.mlp_norm = nn.RMSNorm(config.width)
381
+ self.mlp = nn.Sequential(
382
+ nn.Linear(config.width, 4 * config.width), nn.GELU(),
383
+ nn.Linear(4 * config.width, config.width),
384
+ )
385
+
386
+ def forward(self, x: torch.Tensor, mask: torch.Tensor, rotary=None) -> torch.Tensor:
387
+ n, s, width = x.shape
388
+ q, k, v = self.qkv(self.attention_norm(x)).view(n, s, 3, self.heads, -1).unbind(2)
389
+ q, k, v = (t.transpose(1, 2) for t in (q, k, v))
390
+ if self.causal:
391
+ q, k = rotate(q, rotary), rotate(k, rotary)
392
+ attended = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
393
+ x = x + self.out(attended.transpose(1, 2).reshape(n, s, width))
394
+ return x + self.mlp(self.mlp_norm(x))
395
+
396
+
397
+ class Simons(nn.Module):
398
+ """Patch transformer for quantiles 0.1, ..., 0.9 of the next `prediction_length` steps."""
399
+
400
+ def __init__(self, config: SimonsConfig):
401
+ super().__init__()
402
+ self.config = config
403
+ patch, width = config.patch_length, config.width
404
+ self.embed = nn.Linear(2 * patch, width)
405
+ self.embed_mlp = nn.Sequential(nn.Linear(2 * patch, width), nn.SiLU(),
406
+ nn.Linear(width, width))
407
+ self.far_type = nn.Parameter(torch.zeros(width))
408
+ self.time_blocks = nn.ModuleList(Block(config, causal=True) for _ in range(config.layers))
409
+ self.variate_block = Block(config, causal=False)
410
+ self.norm = nn.RMSNorm(width)
411
+ self.head = nn.Linear(width, patch * len(QUANTILES))
412
+ self.covariates = None
413
+ if config.covariates:
414
+ # A private stream keeps covariate initialization independent of backbone draws.
415
+ with torch.random.fork_rng(devices=[]):
416
+ torch.random.default_generator.manual_seed(32)
417
+ self.covariates = CovariateModules(config, Block)
418
+
419
+ @classmethod
420
+ def from_pretrained(cls, name_or_path, device="cpu", revision=None) -> "Simons":
421
+ """Load config.json and model.safetensors from a local folder or Hub repo, in eval mode.
422
+ `revision` selects a Hub branch, tag or commit; `device` sets the model device."""
423
+ from safetensors.torch import load_file
424
+
425
+ path = Path(name_or_path).expanduser()
426
+ if not path.is_dir():
427
+ if path.exists() or path.is_absolute() or str(name_or_path).startswith((".", "~")):
428
+ raise FileNotFoundError(f"{name_or_path} is not a model folder (config.json and "
429
+ "model.safetensors)")
430
+ from huggingface_hub import snapshot_download
431
+
432
+ path = Path(snapshot_download(str(name_or_path), revision=revision,
433
+ allow_patterns=["config.json", "model.safetensors"]))
434
+ model = cls(SimonsConfig.from_json(path / "config.json"))
435
+ model.load_state_dict(load_file(path / "model.safetensors"))
436
+ return model.to(device).eval()
437
+
438
+ def save_pretrained(self, path):
439
+ from safetensors.torch import save_file
440
+
441
+ path = Path(path)
442
+ path.mkdir(parents=True, exist_ok=True)
443
+ (path / "config.json").write_text(json.dumps(self.config.to_dict(), indent=2) + "\n",
444
+ encoding="utf-8")
445
+ state = {k: v.detach().cpu().contiguous() for k, v in self.state_dict().items()}
446
+ save_file(state, path / "model.safetensors")
447
+
448
+ def forecast(self, history, horizon: int, series_ids=None, covariates=None,
449
+ **options) -> torch.Tensor:
450
+ """Quantile forecasts; see `simons.forecast` (the function)."""
451
+ from .forecast import forecast
452
+
453
+ return forecast(self, history, horizon, series_ids, covariates=covariates, **options)
454
+
455
+ def forward(self, history: torch.Tensor, series_ids: torch.Tensor, mixed: bool = False,
456
+ covariates: torch.Tensor | None = None, steps: int | None = None) -> torch.Tensor:
457
+ """History [B,V,context_length] -> quantiles [B,V,prediction_length,9]; NaN = missing.
458
+ Equal series_ids [B,V] group variates; covariates [B,C,context_length+future patches].
459
+ `steps` limits output to the patches covering it; `mixed` enables a bf16 CUDA trunk."""
460
+ c = self.config
461
+ patch = c.patch_length
462
+ if history.shape[-1] != c.context_length:
463
+ raise ValueError(f"history must have context_length = {c.context_length} steps")
464
+ future = math.ceil(c.prediction_length / patch)
465
+ need = future if steps is None else max(1, min(future, math.ceil(steps / patch)))
466
+ values = F.pad(history, (0, future * patch), value=float("nan"))
467
+ skip = self._skip(values, covariates)
468
+ if skip:
469
+ values = values[..., skip:]
470
+ covariates = None if covariates is None else covariates[..., skip:]
471
+ variates, roles, fixed, head = history.shape[1], None, None, None
472
+ if covariates is not None:
473
+ if self.covariates is None:
474
+ raise ValueError("this checkpoint has no covariate weights")
475
+ grown = covariate_rows(c, values, series_ids, covariates, skip=skip)
476
+ if grown is not None:
477
+ values, series_ids, roles = grown[:3]
478
+ head = grown[3] if skip else None
479
+ fixed = (roles == ROLE_BINARY) if c.binary_rows else None
480
+ with torch.autocast("cuda", torch.bfloat16, enabled=mixed):
481
+ parts = front(self, values, fixed=fixed, skip=skip, periods=self._periods,
482
+ return_periods=True)
483
+ tokens, rotary, started, loc, scale, _, far_tokens, _ = parts
484
+ far_len = c.context_length - c.near_context - skip
485
+ lo, hi = sign_bounds(values, loc, scale, patch, far_len)
486
+ if head is not None and bool(torch.isfinite(head).any()):
487
+ # Fit rows have an observed intercept over the skipped prefix.
488
+ tokens, rotary, started, loc, scale, far_tokens, lo, hi = self._unskip(
489
+ parts, lo, hi, values[:, -1], head, skip)
490
+ size = tokens.shape[2]
491
+ last = size - future - 1
492
+ if need < future:
493
+ size -= future - need
494
+ tokens, started, lo, hi = (t[:, :, :size] for t in (tokens, started, lo, hi))
495
+ rotary = tuple(t[:, :, :size] for t in rotary)
496
+ # Attention isolates unused prefix tokens; keep at least the last history token.
497
+ any_started = started.flatten(0, 1).any(0)
498
+ crop = int(torch.where(any_started, torch.arange(size, device=values.device), size)
499
+ .amin().clamp_max(last))
500
+ # The last history token predicts the first future patch.
501
+ features = self._trunk(tokens[:, :, crop:], tuple(t[:, :, crop:] for t in rotary),
502
+ started[:, :, crop:], series_ids, far_tokens - crop, mixed,
503
+ roles, variates, size - last)
504
+ window = slice(last, last + need)
505
+ quantiles = self._head(features[:, :, :need], lo[:, :variates, window],
506
+ hi[:, :variates, window], mixed)
507
+ location = loc[:, :variates, window, None, None]
508
+ spread = scale[:, :variates, window, None, None]
509
+ out = quantiles.double().sinh() * spread + location
510
+ return out.flatten(2, 3)[:, :, : c.prediction_length].float()
511
+
512
+ def _skip(self, values: torch.Tensor, covariates: torch.Tensor | None) -> int:
513
+ """Return unobserved far-prefix steps in multiples of SKIP_TOKENS far tokens.
514
+ Known-future covariates occupy positions one patch earlier."""
515
+ c = self.config
516
+ patch = c.patch_length
517
+ unit = SKIP_TOKENS * patch * c.far_pool
518
+ far_len = c.context_length - c.near_context
519
+ if far_len < unit:
520
+ return 0
521
+ seen = torch.isfinite(values[..., :far_len]).flatten(0, -2).any(0)
522
+ if covariates is not None:
523
+ cov = torch.isfinite(covariates[..., : far_len + patch]).flatten(0, -2).any(0)
524
+ seen |= cov[:far_len] | cov[patch : far_len + patch]
525
+ first = int(torch.where(seen, torch.arange(far_len, device=values.device), far_len).amin())
526
+ return first // unit * unit
527
+
528
+ def _unskip(self, parts, lo, hi, fit_values, head, skip: int):
529
+ """Restore skipped tokens and the full fit row from head [B,skip] and fit_values [B,L].
530
+ The fit row is last; other rows have missing prefixes."""
531
+ c = self.config
532
+ tokens, _, started, loc, scale, _, far_tokens, periods = parts
533
+ patch, block = c.patch_length, c.patch_length * c.far_pool
534
+ extra = skip // block
535
+ tokens = F.pad(tokens, (0, 0, extra, 0))
536
+ started = F.pad(started, (extra, 0), value=False)
537
+ loc = F.pad(loc, (extra, 0), value=0.0)
538
+ scale = F.pad(scale, (extra, 0), value=MIN_SCALE)
539
+ lo = F.pad(lo, (extra, 0), value=-math.inf)
540
+ hi = F.pad(hi, (extra, 0), value=math.inf)
541
+ far_tokens += extra
542
+ far_len = c.context_length - c.near_context
543
+ device = tokens.device
544
+ starts = torch.cat([
545
+ torch.arange(far_tokens, device=device, dtype=torch.float64) * block,
546
+ far_len + torch.arange(tokens.shape[2] - far_tokens, device=device,
547
+ dtype=torch.float64) * patch])
548
+ cos, sin = period_rotary(periods, starts, patch, c.width // c.heads // 2)
549
+ batch, variates = tokens.shape[:2]
550
+ fit = front(self, torch.cat([head, fit_values], -1)[:, None], periods=self._periods)
551
+ tokens[:, -1:] = fit[0]
552
+ started[:, -1:] = fit[2]
553
+ loc[:, -1:], scale[:, -1:] = fit[3], fit[4]
554
+ cos, sin = (t.view(batch, variates, *t.shape[1:]).clone() for t in (cos, sin))
555
+ cos[:, -1], sin[:, -1] = (t.view(batch, *t.shape[1:]) for t in fit[1])
556
+ rotary = tuple(t.view(batch * variates, *t.shape[2:]) for t in (cos, sin))
557
+ return tokens, rotary, started, loc, scale, far_tokens, lo, hi
558
+
559
+ def _periods(self, values: torch.Tensor, history: int, far_len: int,
560
+ skip: int = 0) -> torch.Tensor:
561
+ """Return periods [B,V,slots] for values [B,V,L], restoring `skip` missing steps as needed.
562
+ The detector is sign-invariant, so equal or negated adjacent histories share periods."""
563
+ c = self.config
564
+
565
+ def detect(x, context):
566
+ return detect_periods(x, context, c.period_slots, c.period_alpha, c.period_local,
567
+ c.patch_length)
568
+
569
+ batch, variates, _ = values.shape
570
+ seen = values[..., :history]
571
+ reuse = torch.zeros(batch, variates, dtype=torch.bool, device=values.device)
572
+ if batch > 1:
573
+ cur, prev = seen[1:], seen[:-1]
574
+ both = torch.isnan(cur) & torch.isnan(prev)
575
+ reuse[1:] = ((cur == prev) | both).all(-1) | ((cur == -prev) | both).all(-1)
576
+ rows = torch.arange(batch, device=values.device)[:, None].expand(batch, variates)
577
+ source = torch.where(reuse, -1, rows).cummax(0).values # first row of each run
578
+ source = (source * variates + torch.arange(variates, device=values.device)).reshape(-1)
579
+ own = torch.nonzero(~reuse.reshape(-1))[:, 0]
580
+ x = seen.reshape(batch * variates, history)[own]
581
+ if not far_len and not skip:
582
+ periods = detect(x, history)
583
+ else:
584
+ periods = detect(x[:, far_len:], history - far_len)
585
+ full = history + skip
586
+ mid = min(c.detector_mid, full)
587
+ mid_start = history - mid # < 0 after a skip into the mid window
588
+ if mid > history - far_len:
589
+ pick = torch.nonzero(torch.isfinite(x[:, :far_len]).any(-1))[:, 0]
590
+ if len(pick):
591
+ window = F.pad(x[pick, max(0, mid_start):], (max(0, -mid_start), 0),
592
+ value=float("nan"))
593
+ periods[pick] = detect(window, mid)
594
+ if mid_start > 0:
595
+ pick = torch.nonzero(torch.isfinite(x[:, :mid_start]).any(-1))[:, 0]
596
+ if len(pick):
597
+ periods[pick] = detect(F.pad(x[pick], (skip, 0), value=float("nan")), full)
598
+ out = periods.new_zeros(batch * variates, periods.shape[-1])
599
+ out[own] = periods
600
+ return out[source].reshape(batch, variates, -1)
601
+
602
+ def _embed(self, tokens, far_tokens: int, mixed: bool, position=None):
603
+ """[..., S, 2p] tokens -> [..., S, width] embeddings (fp32 under `mixed`), far type
604
+ added; with `position` (the tokens' positions), [K, 2p] tokens -> [K, width]."""
605
+ with torch.autocast("cuda", enabled=False) if mixed else nullcontext():
606
+ inputs = tokens.float() if mixed else tokens
607
+ x = self.embed(inputs) + self.embed_mlp(inputs)
608
+ if position is None:
609
+ position = torch.arange(tokens.shape[-2], device=tokens.device)
610
+ far = position < far_tokens
611
+ return x + far[..., None].to(x.dtype) * self.far_type
612
+
613
+ def _trunk(self, tokens, rotary, started, series_ids, far_tokens: int, mixed: bool,
614
+ roles: torch.Tensor | None = None, targets: int | None = None,
615
+ tail: int | None = None):
616
+ """Return [B,T,tail,width] features of the first T = `targets` rows (default: all) at the
617
+ last `tail` positions (default: all); the first `far_tokens` tokens are pooled history.
618
+ `roles` [B,V]: covariate rows' roles (covariate rows follow the targets); the tail must
619
+ then start at or after every target row's first observed token."""
620
+ batch, variates, size, _ = tokens.shape
621
+ tail = size if tail is None else tail
622
+ start = started.reshape(batch * variates, size)
623
+ ids = series_ids[:, None, :].expand(batch, size, variates)
624
+ related = (ids[..., :, None] == ids[..., None, :]).reshape(batch * size, 1, variates,
625
+ variates)
626
+ blocks = list(self.time_blocks)
627
+ if roles is None:
628
+ x = self._embed(tokens, far_tokens, mixed).reshape(batch * variates, size, -1)
629
+ x = time_blocks(blocks, x, start, rotary, None)
630
+ x = x.reshape(batch, variates, size, -1)[:, :, size - tail:]
631
+ related = related.view(batch, size, 1, variates, variates)[:, size - tail:]
632
+ x = x.transpose(1, 2).reshape(batch * tail, variates, -1)
633
+ x = self.variate_block(x, related.flatten(0, 1))
634
+ return x.reshape(batch, tail, variates, -1).transpose(1, 2)
635
+ # Equal rows can share computation only while they read no other row.
636
+ targets = variates if targets is None else targets
637
+ read_after = self.config.read_after if self.covariates.read is not None else -1
638
+ crops = row_crops(start, roles, batch, variates)
639
+ reads = torch.zeros(batch * variates, dtype=torch.bool, device=tokens.device)
640
+ if read_after >= 0:
641
+ _, update = read_mask(roles, related.reshape(batch, size, 1, variates, variates)[:, 0],
642
+ 1)
643
+ reads = update.reshape(-1)
644
+ compute, source = shared_rows(tokens.reshape(batch * variates, size, -1), rotary,
645
+ roles.reshape(-1), crops, ~reads)
646
+ if compute is None:
647
+ compute = source = torch.arange(batch * variates, device=tokens.device)
648
+ # Time blocks ignore positions before each row's crop, so x keeps each crop's rows from
649
+ # it: a whole-window fit row does not make the short rows of its item any longer.
650
+ own = tokens.reshape(batch * variates, size, -1)[compute]
651
+ later = torch.arange(size, device=tokens.device)[None] >= crops[compute][:, None]
652
+ embedded = self._embed(own[later], far_tokens, mixed, torch.nonzero(later)[:, 1])
653
+ role = self.covariates.role_vectors(roles).reshape(batch * variates, -1)[compute].to(
654
+ embedded.dtype)
655
+ index = torch.zeros_like(later, dtype=torch.long)
656
+ index[later] = torch.arange(len(embedded), device=tokens.device)
657
+ groups = crop_groups(crops[compute])
658
+ x = [embedded[index[r, crop:]] + role[r][:, None] for crop, r in groups]
659
+ part = (start[compute], tuple(t[compute] for t in rotary), groups)
660
+ cut = read_after + 1 if read_after >= 0 else len(blocks)
661
+ x = time_blocks(blocks[:cut], x, *part)
662
+ rows = (torch.arange(batch, device=tokens.device)[:, None] * variates
663
+ + torch.arange(targets, device=tokens.device)).reshape(-1) # target rows [B*T]
664
+ if read_after >= 0:
665
+ mask, update = read_mask(roles, related, size)
666
+ mine = source[rows]
667
+ first = int(crops[rows].min())
668
+ seen = from_position(x, groups, role, first, size)
669
+ y = attend_targets(self.covariates.read, seen, source, mine, mask[:, :, :targets],
670
+ batch, variates, targets, size, explicit=True, first=first)
671
+ u = update[:, :targets].reshape(batch, size, targets, 1)[:, first:].transpose(
672
+ 1, 2).reshape(batch * targets, size - first, 1).to(y.dtype)
673
+ current = seen[mine]
674
+ y = current + u * (y - current)
675
+ keep = reads[rows] # Reading targets cannot share rows.
676
+ seen[mine[keep]] = y[keep]
677
+ # Target rows' crops are at or after `first`, and nothing reads a row before its crop.
678
+ x = [xs if crop < first else seen[r, crop - first:]
679
+ for (crop, r), xs in zip(groups, x)]
680
+ x = time_blocks(blocks[cut:], x, *part)
681
+ last = from_position(x, groups, role, size - tail, size)
682
+ y = attend_targets(self.variate_block, last, source, source[rows], related[:, :, :targets],
683
+ batch, variates, targets, size, first=size - tail)
684
+ return y.reshape(batch, targets, tail, -1)
685
+
686
+ def _head(self, x, lo, hi, mixed: bool) -> torch.Tensor:
687
+ """Map [...,width] to [...,patch,9] sorted asinh quantiles with optional sign bounds."""
688
+ with torch.autocast("cuda", enabled=False) if mixed else nullcontext():
689
+ h = self.norm(x.float() if mixed else x)
690
+ raw = self.head(h.float() if mixed else h)
691
+ q = raw.float().unflatten(-1, (self.config.patch_length, len(QUANTILES))).sort(-1).values
692
+ if not self.config.sign_clip:
693
+ return q
694
+ lo = torch.nan_to_num(lo.float(), nan=-math.inf)[..., None, None]
695
+ hi = torch.nan_to_num(hi.float(), nan=math.inf)[..., None, None]
696
+ return torch.minimum(torch.maximum(q, lo), hi)