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/synth/multi.py ADDED
@@ -0,0 +1,274 @@
1
+ """Couple synthetic series into groups sharing a series ID."""
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch
7
+
8
+ from simons.synth.base import SYNTHETIC_ID, _spectral, _standardise, draw, post
9
+
10
+ MECHANISMS = ("identity", "mix", "lag", "coint", "func", "event")
11
+ WIDTH = 32
12
+ PULSE_PERIODS = (7, 12, 24, 48, 52, 96, 168, 288, 336)
13
+
14
+
15
+ def fft_length(n):
16
+ """Return the smallest even 7-smooth length >= n for efficient cuFFT grids."""
17
+ m = n + (n % 2)
18
+ while True:
19
+ r = m
20
+ for p in (2, 3, 5, 7):
21
+ while r % p == 0:
22
+ r //= p
23
+ if r == 1:
24
+ return m
25
+ m += 2
26
+
27
+
28
+ def _logu(rng, lo, hi):
29
+ return float(math.exp(rng.uniform(math.log(lo), math.log(hi))))
30
+
31
+
32
+ def _group_sizes(rng, max_variates, width=WIDTH):
33
+ sizes, used = [], 0
34
+ while used < width:
35
+ q = min(int(_logu(rng, 2, max_variates + 1)), max_variates, width - used)
36
+ sizes.append(q)
37
+ used += q
38
+ return sizes
39
+
40
+
41
+ def plan(rng, chunks, max_variates, mechanisms, lag_max):
42
+ """Return per-slot, per-edge and per-driver numpy arrays for `chunks` coupled 32-slot rows.
43
+ Each group owns two driver rows; edge parents index [drivers; slots], with -1 for no parent."""
44
+ mech_ids = [MECHANISMS.index(m) for m in mechanisms]
45
+ cum = np.cumsum(np.full(len(mech_ids), 1.0 / len(mech_ids)))
46
+ n = chunks * WIDTH
47
+ group = np.zeros(n, np.int64)
48
+ mech = np.zeros(n, np.int64)
49
+ own_kind = np.zeros(n, np.int64)
50
+ ou = np.ones(n, np.float32)
51
+ rho = np.zeros(n, np.float32)
52
+ fkind = np.zeros(n, np.int64)
53
+ fparam = np.zeros((n, 4), np.float32)
54
+ parent = np.full((n, 3), -1, np.int64)
55
+ tau = np.zeros((n, 3), np.float32)
56
+ decay = np.zeros((n, 3), np.float32)
57
+ coef = np.zeros((n, 3), np.float32)
58
+ dkind = np.full(n, -1, np.int64)
59
+ dparam = np.zeros((n, 3), np.float32)
60
+ root = np.zeros(n, bool)
61
+ sizes = [q for _ in range(chunks) for q in _group_sizes(rng, max_variates)]
62
+ groups = len(sizes)
63
+ slot = 0
64
+ for g, q in enumerate(sizes):
65
+ m = (mech_ids[min(int(np.searchsorted(cum, rng.random(), side='right')), len(cum) - 1)]
66
+ if q > 1 else 0)
67
+ d0 = slot
68
+ k_drivers = 1 if m in (4, 5) else int(rng.integers(1, 3))
69
+ for k in range(2):
70
+ if m == 0 or k >= k_drivers:
71
+ kind = -1
72
+ elif m == 3:
73
+ kind = 1 if rng.random() < 0.6 else 2
74
+ elif m == 5:
75
+ kind = 3 if rng.random() < 0.6 else 4
76
+ else:
77
+ kind = 0
78
+ if kind >= 0:
79
+ dkind[d0 + k] = kind
80
+ dparam[d0 + k] = (_logu(rng, 0.003, 0.05),
81
+ float(PULSE_PERIODS[int(rng.integers(len(PULSE_PERIODS)))]),
82
+ float(rng.integers(1, 5)))
83
+ members = np.arange(slot, slot + q)
84
+ group[members] = g
85
+ mech[members] = m
86
+ plain = []
87
+ observed_root = m == 2 or m == 5 or (m == 4 and rng.random() < 0.5)
88
+ for i, j in enumerate(members):
89
+ if m == 0:
90
+ continue
91
+ if observed_root and i < (k_drivers if m == 2 else 1):
92
+ parent[j, 0], coef[j, 0] = d0 + i, 1.0
93
+ rho[j] = rng.uniform(0.85, 1.0)
94
+ root[j] = True
95
+ plain.append(j)
96
+ continue
97
+ if m == 1:
98
+ for k in range(k_drivers):
99
+ parent[j, k] = d0 + k
100
+ coef[j, k] = rng.normal() * (1.0 if k == 0 else rng.uniform(0.2, 1.0))
101
+ rho[j] = rng.uniform(0.3, 0.95)
102
+ elif m == 2:
103
+ if plain and rng.random() < 0.4:
104
+ parent[j, 0] = n + plain[int(rng.integers(len(plain)))]
105
+ else:
106
+ parent[j, 0] = d0 + int(rng.integers(k_drivers))
107
+ plain.append(j)
108
+ tau[j, 0] = round(_logu(rng, 4, lag_max))
109
+ decay[j, 0] = 0.0 if rng.random() < 0.6 else _logu(rng, 1, 48)
110
+ coef[j, 0] = (1.0 if rng.random() < 0.5 else -1.0) * rng.uniform(0.5, 1.5)
111
+ if rng.random() < 0.3:
112
+ parent[j, 1] = d0 + int(rng.integers(k_drivers))
113
+ tau[j, 1] = round(_logu(rng, 4, lag_max))
114
+ decay[j, 1] = 0.0 if rng.random() < 0.6 else _logu(rng, 1, 48)
115
+ coef[j, 1] = (1.0 if rng.random() < 0.5 else -1.0) * rng.uniform(0.3, 1.0)
116
+ rho[j] = rng.uniform(0.4, 0.95)
117
+ elif m == 3:
118
+ for k in range(k_drivers):
119
+ parent[j, k] = d0 + k
120
+ tau[j, k] = 0.0 if rng.random() < 0.7 else round(_logu(rng, 1, 64))
121
+ coef[j, k] = (1.0 if rng.random() < 0.5 else -1.0) * rng.uniform(0.5, 2.0)
122
+ own_kind[j], ou[j] = 1, _logu(rng, 2, 100)
123
+ rho[j] = rng.uniform(0.6, 0.97)
124
+ elif m == 4:
125
+ parent[j, 0], coef[j, 0] = d0, 1.0
126
+ tau[j, 0] = 0.0 if rng.random() < 0.4 else round(_logu(rng, 4, lag_max))
127
+ decay[j, 0] = 0.0 if rng.random() < 0.7 else _logu(rng, 1, 32)
128
+ fkind[j] = int(rng.integers(1, 7))
129
+ fparam[j] = (_logu(rng, 0.5, 3.0), rng.uniform(-1, 1), rng.uniform(-1, 1),
130
+ rng.uniform(-2, 2))
131
+ rho[j] = rng.uniform(0.5, 0.95)
132
+ else:
133
+ for e in range(1 + (rng.random() < 0.3)):
134
+ parent[j, e] = d0
135
+ tau[j, e] = round(_logu(rng, 1, 128)) if rng.random() < 0.8 else 0.0
136
+ decay[j, e] = _logu(rng, 1, 100)
137
+ coef[j, e] = (1.0 if rng.random() < 0.5 else -1.0) * rng.uniform(0.5, 2.0)
138
+ rho[j] = rng.uniform(0.3, 0.9)
139
+ slot += q
140
+ return dict(group=group, mech=mech, own_kind=own_kind, ou=ou, rho=rho, fkind=fkind,
141
+ fparam=fparam, parent=parent, tau=tau, decay=decay, coef=coef,
142
+ dkind=dkind, dparam=dparam, root=root,
143
+ groups=groups)
144
+
145
+
146
+ def _to_device(array, device):
147
+ t = torch.from_numpy(np.ascontiguousarray(array))
148
+ if torch.device(device).type == "cuda":
149
+ return t.pin_memory().to(device, non_blocking=True)
150
+ return t
151
+
152
+
153
+ def _transform(y, kind, p):
154
+ """Apply per-row transforms; p [n,4] holds gain, b, s0, s1; kind 0 is identity."""
155
+ g, b, s0, s1 = (p[:, i : i + 1] for i in range(4))
156
+ out = y
157
+ out = torch.where(kind == 1, torch.tanh(g * y), out)
158
+ out = torch.where(kind == 2, torch.nn.functional.softplus(g * y), out)
159
+ out = torch.where(kind == 3, y.abs(), out)
160
+ clip = 0.2 + b.abs() * 1.3
161
+ out = torch.where(kind == 4, torch.minimum(torch.maximum(y, -clip), clip), out)
162
+ out = torch.where(kind == 5, torch.round(y * (1 + 3 * b.abs())) / (1 + 3 * b.abs()), out)
163
+ out = torch.where(kind == 6, s0 * y + s1 * torch.relu(y - b), out)
164
+ return out
165
+
166
+
167
+ def couple(structure, gen, length, device, families, weights, lag_max, extra=0):
168
+ """Return standardized coupled [n_c,length] and plain [extra,length] float32 series.
169
+ `structure` comes from `plan`; both outputs share the same base draw."""
170
+ s = {k: (_to_device(v, device) if isinstance(v, np.ndarray) else v)
171
+ for k, v in structure.items()}
172
+ n = s["group"].shape[0]
173
+ full = fft_length(length + lag_max)
174
+ # Reuse bases round-robin to keep pool shapes fixed for FFT-plan reuse.
175
+ quota_d, quota_o = max(1, n // 4), max(1, n // 3)
176
+ bases = draw(extra + n + quota_d, full, gen, device, families, weights)
177
+ plain = _standardise(bases[:extra, -length:]) if extra else bases[:0, -length:]
178
+ own = bases[extra : extra + n]
179
+ use_base = structure["dkind"] == 0
180
+ driver_src = np.zeros(n, np.int64)
181
+ driver_src[use_base] = np.arange(int(use_base.sum())) % quota_d
182
+ dbase = bases[extra + n :][_to_device(driver_src, device)]
183
+ t = torch.arange(full, device=device, dtype=torch.float32)[None]
184
+ dk = s["dkind"][:, None]
185
+ rate, period, width = (s["dparam"][:, i : i + 1] for i in range(3))
186
+ steps = torch.randn((n, full), generator=gen, device=device)
187
+ walk = _standardise(steps.cumsum(-1))
188
+ drift = _standardise((steps + 4 * (rate - 0.025) / 0.025 * 0.05).cumsum(-1))
189
+ impulses = (torch.rand((n, full), generator=gen, device=device) < rate) * torch.exp(
190
+ 0.5 * steps)
191
+ phase = torch.rand((n, 1), generator=gen, device=device) * period
192
+ pulses = (torch.remainder(t + phase, period) < width) * torch.exp(0.3 * steps)
193
+ drivers = torch.where(dk == 1, walk, torch.where(dk == 2, drift, dbase))
194
+ drivers = torch.where(dk == 3, _standardise(impulses), drivers)
195
+ drivers = _standardise(torch.where(dk == 4, _standardise(pulses), drivers))
196
+ is_ou = structure["own_kind"] == 1
197
+ ou_src = np.zeros(n, np.int64)
198
+ ou_src[is_ou] = np.arange(int(is_ou.sum())) % quota_o
199
+ ou_scale = np.ones(quota_o, np.float32)
200
+ ou_scale[ou_src[is_ou][::-1]] = structure["ou"][is_ou][::-1]
201
+ scale = _to_device(ou_scale, device)[:, None]
202
+ noise = _spectral(gen, full, device, lambda w: 1.0 / (1.0 + (w[None] * scale) ** 2))
203
+ own = torch.where(s["own_kind"][:, None] == 1, noise[_to_device(ou_src, device)], own)
204
+ grid = 2 * full
205
+ omega = 2 * math.pi * torch.arange(grid // 2 + 1, device=device, dtype=torch.float32) / grid
206
+ tau, decay, coef = s["tau"], s["decay"], s["coef"]
207
+ r = torch.where(decay > 0, torch.exp(-1.0 / decay.clamp_min(1e-3)), torch.zeros_like(decay))
208
+ delay = torch.polar(torch.ones_like(tau[..., None] * omega), -tau[..., None] * omega)
209
+ smooth = (1 - r)[..., None] / (1 - r[..., None] * torch.polar(
210
+ torch.ones_like(omega), -omega))
211
+ weight = torch.where(s["parent"] >= 0, coef, torch.zeros_like(coef))[..., None]
212
+ response = weight * delay * smooth # [n, 3, F]
213
+ parent = s["parent"].clamp_min(0)
214
+ rho = s["rho"][:, None]
215
+ spec_d = torch.fft.rfft(drivers, n=grid)
216
+
217
+ def combine(slots):
218
+ table = torch.cat([spec_d, torch.fft.rfft(slots, n=grid)])
219
+ mixed = (table[parent] * response).sum(1)
220
+ signal = torch.fft.irfft(mixed, n=grid)[:, :full]
221
+ signal = _standardise(_transform(signal, s["fkind"][:, None], s["fparam"]))
222
+ return rho.sqrt() * signal + (1 - rho).sqrt() * own
223
+
224
+ x = combine(combine(own)) # A second pass lets chain followers read their parents' outputs.
225
+ return _standardise(x[:, -length:]), plain
226
+
227
+
228
+ class MultiPool:
229
+ """Build 32-slot pools with a `fraction` of rows containing coupled groups."""
230
+
231
+ def __init__(self, fraction, max_variates=16, mechanisms=MECHANISMS, lag_max=256, seed=0):
232
+ if not mechanisms or not set(mechanisms) <= set(MECHANISMS):
233
+ raise ValueError(f"mechanisms must list some of {MECHANISMS}")
234
+ if int(lag_max) != lag_max or lag_max < 4:
235
+ raise ValueError("lag_max must be an integer of at least 4")
236
+ self.fraction, self.max_variates = fraction, int(max_variates)
237
+ self.mechanisms, self.lag_max = tuple(mechanisms), int(lag_max)
238
+ self.rng = np.random.default_rng(seed)
239
+ self.roles = None
240
+
241
+ def build(self, n, length, gen, device, families, noise, pad, weights):
242
+ """Return (pool [N,length], host IDs [N], device IDs [N][, role metadata [N,3]]).
243
+ N >= n is divisible by 32; metadata holds role, end block and future cut; NaN marks gaps."""
244
+ chunks = -(-n // WIDTH)
245
+ coupled = round(self.fraction * chunks)
246
+ structure_host = plan(self.rng, coupled, self.max_variates, self.mechanisms,
247
+ self.lag_max)
248
+ n_c, n_u = coupled * WIDTH, (chunks - coupled) * WIDTH
249
+ x_c, x_u = couple(structure_host, gen, length, device, families, weights,
250
+ self.lag_max, extra=n_u)
251
+ kinds = self.rng.permutation(np.r_[np.ones(coupled, bool), np.zeros(chunks - coupled,
252
+ bool)])
253
+ order = np.empty(chunks * WIDTH, np.int64)
254
+ group = np.empty(chunks * WIDTH, np.int64)
255
+ c = u = 0
256
+ base_u = structure_host["groups"]
257
+ for k, is_coupled in enumerate(kinds):
258
+ dest = slice(k * WIDTH, (k + 1) * WIDTH)
259
+ if is_coupled:
260
+ order[dest] = np.arange(c * WIDTH, (c + 1) * WIDTH)
261
+ group[dest] = structure_host["group"][c * WIDTH : (c + 1) * WIDTH]
262
+ c += 1
263
+ else:
264
+ order[dest] = n_c + np.arange(u * WIDTH, (u + 1) * WIDTH)
265
+ group[dest] = base_u + np.arange(u * WIDTH, (u + 1) * WIDTH)
266
+ u += 1
267
+ x = torch.cat([x_c, x_u])[_to_device(order, device)]
268
+ x, flip = post(x, gen, noise, pad, group=_to_device(group, device), return_flip=True)
269
+ ids = SYNTHETIC_ID + group
270
+ if self.roles is None:
271
+ return x, ids, _to_device(ids, device)
272
+ meta = _to_device(self.roles.plan_pool(structure_host, kinds, length, len(group)), device)
273
+ # Time-flipped groups reverse causality, so they receive no covariate roles.
274
+ return x, ids, _to_device(ids, device), meta * (~flip).long()
@@ -0,0 +1,204 @@
1
+ """Non-stationary OU paths, changepoints and spike priors, batched on device."""
2
+
3
+ import math
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+ from simons.synth.base import (
9
+ PERIOD_BANK,
10
+ _categorical,
11
+ _choice,
12
+ _logu,
13
+ _periodic,
14
+ _randn,
15
+ _smooth,
16
+ _spectral,
17
+ _standardise,
18
+ _u,
19
+ )
20
+
21
+ CHUNK = 256
22
+
23
+
24
+ def _laplace(gen, shape, device):
25
+ u = _u(gen, shape, -0.5 + 1e-6, 0.5 - 1e-6, device)
26
+ return -torch.sign(u) * torch.log1p(-2 * u.abs())
27
+
28
+
29
+ def _trend(gen, n, length, device):
30
+ s = torch.arange(length, device=device, dtype=torch.float32)[None] / length
31
+ kind = torch.randint(0, 4, (n, 1), generator=gen, device=device)
32
+ c1, c2 = _randn(gen, (n, 1), device), _randn(gen, (n, 1), device)
33
+ poly = c1 * (s - 0.5) * 2 + c2 * ((s - 0.5) * 2) ** 2
34
+ centre, rate = _u(gen, (n, 1), 0.1, 0.9, device), _logu(gen, (n, 1), 5.0, 50.0, device)
35
+ logistic = 2 * c1 * torch.sigmoid(rate * (s - centre))
36
+ cycles = _logu(gen, (n, 1), 0.3, 3.0, device)
37
+ sine = c1 * torch.sin(2 * math.pi * cycles * s + _u(gen, (n, 1), 0, 2 * math.pi, device))
38
+ knot = _u(gen, (n, 1), 0.1, 0.9, device)
39
+ piece = c1 * s + (c2 - c1) * (s - knot).clamp_min(0)
40
+ return torch.where(kind == 0, poly, torch.where(kind == 1, logistic,
41
+ torch.where(kind == 2, sine, piece)))
42
+
43
+
44
+ def _ou_scan(a, drive, y0):
45
+ """Solve y_t = a_t y_{t-1} + drive_t from y_{-1} = y0 in float64 chunks."""
46
+ n, length = a.shape
47
+ pad = (-length) % CHUNK
48
+ a = F.pad(a, (0, pad), value=1.0).view(n, -1, CHUNK)
49
+ drive = F.pad(drive, (0, pad)).view(n, -1, CHUNK)
50
+ # Chunked exp(-log_p) stays finite in float64 for a >= e^-2.7; callers use a >= e^-1.
51
+ log_p = torch.log(a).cumsum(-1)
52
+ p = torch.exp(log_p)
53
+ local = p * (drive * torch.exp(-log_p)).cumsum(-1)
54
+ carry = y0
55
+ starts = []
56
+ for c in range(a.shape[1]):
57
+ starts.append(carry)
58
+ carry = local[:, c, -1] + p[:, c, -1] * carry
59
+ start = torch.stack(starts, 1)[..., None]
60
+ return (local + p * start).flatten(1)[:, :length]
61
+
62
+
63
+ def sde_family(gen, n, length, device):
64
+ """Return float32 regime-switching OU paths [n,length] with varying drift and volatility."""
65
+ t = torch.arange(length, device=device, dtype=torch.float32)[None]
66
+ hazard = _logu(gen, (n, 1), 1 / 8192, 1 / 256, device)
67
+ switches = (_u(gen, (n, length), device=device) < hazard).long().cumsum(-1)
68
+ first = torch.randint(0, 2, (n, 1), generator=gen, device=device)
69
+ regime = ((switches + first) % 2).bool()
70
+ theta = torch.where(regime, _u(gen, (n, 1), 0.05, 0.5, device),
71
+ _u(gen, (n, 1), 1.0, 5.0, device))
72
+ side = torch.where(_u(gen, (n, 1), device=device) < 0.5, -1.0, 1.0)
73
+ mu0 = side * 2 + _randn(gen, (n, 1), device)
74
+ mu1 = -side * 2 + _randn(gen, (n, 1), device)
75
+ mu = torch.where(regime, mu1, mu0)
76
+ s0 = 0.3 * torch.exp(0.5 * _randn(gen, (n, 1), device))
77
+ s1 = 1.5 * torch.exp(0.5 * _randn(gen, (n, 1), device))
78
+ sigma = torch.where(regime, s1, s0)
79
+ use = lambda p: _u(gen, (n, 1), device=device) < p # noqa: E731
80
+ mu = mu + use(0.7) * 2 * _trend(gen, n, length, device)
81
+ period = _choice(gen, PERIOD_BANK, (n,), device)
82
+ mu = (mu + use(0.6) * _logu(gen, (n, 1), 0.2, 2.0, device)
83
+ * _periodic(gen, period, length, device))
84
+ theta = theta * torch.exp(use(0.2) * _randn(gen, (n, 1), device) * (t / length - 0.5) * 2)
85
+ sigma = sigma * torch.exp(use(0.3) * 0.7 * _trend(gen, n, length, device).clamp(-2, 2))
86
+ period2 = _choice(gen, PERIOD_BANK, (n,), device)
87
+ phase = _u(gen, (n, 1), 0, 2 * math.pi, device)
88
+ sigma = sigma * torch.exp(use(0.3) * _u(gen, (n, 1), 0.2, 0.8, device)
89
+ * torch.sin(2 * math.pi * t / period2[:, None] + phase))
90
+ sigma = sigma * torch.exp(use(0.5) * _u(gen, (n, 1), 0.0, 0.7, device)
91
+ * _smooth(gen, n, length, device))
92
+ hurst = _u(gen, (n, 1), 0.3, 0.8, device)
93
+ fgn = _spectral(gen, length, device,
94
+ lambda w: w[None].clamp_min(1e-4) ** (1 - 2 * hurst))
95
+ eps = torch.where(use(0.2), fgn, _randn(gen, (n, length), device))
96
+ dt = _logu(gen, (n, 1), 0.005, 0.05, device)
97
+ theta = torch.minimum(theta.clamp_min(1e-3), 0.25 / dt).double()
98
+ a = torch.exp(-theta * dt.double())
99
+ drive = ((1 - a) * mu.double()
100
+ + sigma.double() * torch.sqrt((1 - a**2) / (2 * theta)) * eps.double())
101
+ y0 = mu[:, 0].double() + (sigma[:, 0] / (2 * theta[:, 0].float()).sqrt()).double() * _randn(
102
+ gen, (n,), device).double()
103
+ y = _ou_scan(a, drive, y0)
104
+ return y.float()
105
+
106
+
107
+ def step_family(gen, n, length, device, max_changes=10):
108
+ """Return float32 changepoint series [n,length] with optional intermittency and seasonality."""
109
+ t = torch.arange(length, device=device)[None]
110
+ tf = t.float()
111
+ count = torch.randint(1, max_changes + 1, (n, 1), generator=gen, device=device)
112
+ positions = torch.randint(1, length, (n, max_changes), generator=gen, device=device)
113
+ valid = torch.arange(max_changes, device=device)[None] < count
114
+ positions = torch.where(valid, positions, 0)
115
+ marks = torch.zeros((n, length), device=device).scatter_(1, positions, 1.0)
116
+ marks[:, 0] = 1.0
117
+ segment = marks.long().cumsum(-1) - 1
118
+ start = torch.where(marks > 0, t, 0).cummax(-1).values
119
+ slots = max_changes + 1
120
+ levels = _laplace(gen, (n, slots), device).cumsum(-1)
121
+ kind = _categorical(gen, (0.5, 0.3, 0.2), n * slots, device).view(n, slots)
122
+ slope = _randn(gen, (n, slots), device) * _logu(gen, (n, 1), 0.3, 3.0, device) / length
123
+ walk = (_randn(gen, (n, length), device) * _logu(gen, (n, 1), 0.01, 0.1, device)).cumsum(-1)
124
+ seg_kind = kind.gather(1, segment)
125
+ since = tf - start.float()
126
+ x = levels.gather(1, segment)
127
+ x = x + torch.where(seg_kind == 1, slope.gather(1, segment) * since * 3, 0.0)
128
+ x = x + torch.where(seg_kind == 2, walk - walk.gather(1, start), 0.0)
129
+ onoff = _u(gen, (n, 1), device=device) < 0.2
130
+ on = (segment % 2 == 1) ^ (_u(gen, (n, 1), device=device) < 0.5)
131
+ x = torch.where(onoff, on * (x.abs() + 0.5), x)
132
+ smooth = _u(gen, (n, 1), device=device) < 0.3
133
+ width = _logu(gen, (n, 1), 1.0, 30.0, device)
134
+ pad = length // 2
135
+ padded = F.pad(x[:, None], (pad, pad), mode="replicate")[:, 0]
136
+ grid = padded.shape[-1]
137
+ omega = 2 * math.pi * torch.arange(grid // 2 + 1, device=device, dtype=torch.float32) / grid
138
+ blurred = torch.fft.irfft(torch.fft.rfft(padded) * torch.exp(-(omega[None] * width) ** 2 / 2),
139
+ n=grid)[:, pad : pad + length]
140
+ x = torch.where(smooth, blurred, x)
141
+ unit = x.std(-1, keepdim=True).clamp_min(0.3)
142
+ period = _choice(gen, PERIOD_BANK, (n,), device)
143
+ seasonal = _u(gen, (n, 1), device=device) < 0.5
144
+ x = (x + seasonal * unit * _logu(gen, (n, 1), 0.05, 0.7, device)
145
+ * _periodic(gen, period, length, device))
146
+ x = x + unit * _logu(gen, (n, 1), 0.01, 0.4, device) * _randn(gen, (n, length), device)
147
+ return x
148
+
149
+
150
+ def _nearest_event_distance(events, t):
151
+ big = 10**6
152
+ left = torch.where(events, t, -big).cummax(-1).values
153
+ right = torch.where(events, t, 2 * big).flip(-1).cummin(-1).values.flip(-1)
154
+ return torch.minimum(t - left, right - t).float()
155
+
156
+
157
+ def spike_family(gen, n, length, device):
158
+ """Return float32 spike, sawtooth and anomaly series [n,length] in equal shares."""
159
+ t = torch.arange(length, device=device)[None]
160
+ tf = t.float()
161
+ sub = torch.randint(0, 3, (n, 1), generator=gen, device=device)
162
+ period = _choice(gen, PERIOD_BANK, (n,), device)[:, None]
163
+ phase = _u(gen, (n, 1), device=device)
164
+ m = torch.remainder(tf / period + phase, 1.0) * period
165
+ periodic_d = torch.minimum(m, period - m)
166
+ rate = _logu(gen, (n, 1), 1 / 500, 1 / 20, device)
167
+ burst = (_u(gen, (n, length), device=device) < rate)
168
+ random_d = _nearest_event_distance(burst, t)
169
+ is_burst = _u(gen, (n, 1), device=device) < 0.4
170
+ d = torch.where(is_burst, random_d, periodic_d)
171
+ halfwidth = torch.minimum(_logu(gen, (n, 1), 1.0, 40.0, device), period / 3).clamp_min(1.0)
172
+ shape = _categorical(gen, (0.4, 0.3, 0.3), n, device)[:, None]
173
+ tri = (1 - d / halfwidth).clamp_min(0)
174
+ ramp = _u(gen, (n, 1), 0.1, 0.5, device)
175
+ plateau = ((1 - d / halfwidth) / ramp).clamp(0, 1)
176
+ pulse = torch.where(shape == 0, tri, torch.where(shape == 1, -tri, plateau))
177
+ amplitude = _logu(gen, (n, 1), 1.0, 10.0, device)
178
+ modulation = torch.exp(0.3 * _smooth(gen, n, length, device))
179
+ baseline = _randn(gen, (n, 1), device) * (tf / length - 0.5)
180
+ white = _randn(gen, (n, length), device)
181
+ brown = _standardise(white.cumsum(-1))
182
+ pink = _spectral(gen, length, device, lambda w: 1 / w[None].clamp_min(1e-4))
183
+ noise = torch.where(_u(gen, (n, 1), device=device) < 0.5, brown, pink)
184
+ spikes = (baseline + amplitude * modulation * pulse
185
+ + _logu(gen, (n, 1), 0.02, 0.5, device) * noise)
186
+ direction = torch.where(_u(gen, (n, 1), device=device) < 0.5, -1.0, 1.0)
187
+ saw = direction * torch.remainder(tf / period + phase, 1.0)
188
+ sine_period = _choice(gen, PERIOD_BANK, (n,), device)[:, None]
189
+ saw = (saw + _randn(gen, (n, 1), device) * 0.5 * (tf / length - 0.5)
190
+ + _u(gen, (n, 1), 0.0, 0.2, device) * torch.sin(2 * math.pi * tf / sine_period)
191
+ + _logu(gen, (n, 1), 0.005, 0.1, device) * white)
192
+ spike_w = torch.randint(1, 4, (n, 1), generator=gen, device=device).float()
193
+ hit = (periodic_d < spike_w / 2 + 0.5).float()
194
+ s = tf / length
195
+ trend = 1 + _u(gen, (n, 1), -0.8, 2.0, device) * s
196
+ cycle = 1 + 0.6 * torch.sin(2 * math.pi * s * _logu(gen, (n, 1), 0.5, 4.0, device)
197
+ + _u(gen, (n, 1), 0, 2 * math.pi, device))
198
+ magnitude = torch.where(_u(gen, (n, 1), device=device) < 0.5, trend, cycle).clamp_min(0.05)
199
+ sign = torch.where(_u(gen, (n, 1), device=device) < 0.7, 1.0, -1.0)
200
+ anomaly = sign * amplitude * magnitude * hit + _logu(gen, (n, 1), 0.01, 0.3, device) * white
201
+ return torch.where(sub == 0, spikes, torch.where(sub == 1, saw, anomaly))
202
+
203
+
204
+ MAKERS = {"sde": sde_family, "step": step_family, "spike": spike_family}
@@ -0,0 +1,117 @@
1
+ """Map synthetic latent paths to recorded values while preserving count rows."""
2
+
3
+ import torch
4
+
5
+ from simons.synth.base import _logu, _standardise, _u
6
+
7
+ CATEGORIES = ("link", "mult", "duty")
8
+ CONFIG = None
9
+ LAMBDAS = (0.0, 0.25, 0.5, 0.75, 1.0)
10
+ SEGMENTS = 256
11
+
12
+
13
+ def make_config(categories, rate=0.5, duty_periodic=0.0):
14
+ """Return observation settings for comma-separated categories, or None when disabled."""
15
+ cats = tuple(c for c in str(categories or "").split(",") if c)
16
+ if not cats or rate <= 0:
17
+ return None
18
+ if not set(cats) <= set(CATEGORIES):
19
+ raise ValueError(f"synthetic_observe must list some of {CATEGORIES}")
20
+ if "mult" in cats and "link" not in cats:
21
+ raise ValueError("synthetic_observe: mult needs link")
22
+ if not 0 <= duty_periodic <= 1:
23
+ raise ValueError("synthetic_observe_duty_periodic must be from 0 to 1")
24
+ return {"categories": cats, "rate": float(rate), "duty_periodic": float(duty_periodic)}
25
+
26
+
27
+ def choose(gen, n, device, is_count):
28
+ """[n, C] bool: the configured categories each row takes."""
29
+ cats = CONFIG["categories"]
30
+ active = (_u(gen, (n, 1), device=device) < CONFIG["rate"]) & ~is_count
31
+ count = torch.where(_u(gen, (n, 1), device=device) < 0.4, 2, 1)
32
+ # Gumbel top-k samples categories uniformly without replacement.
33
+ gumbel = -torch.log(-torch.log(_u(gen, (n, len(cats)), device=device).clamp(1e-12, 1 - 1e-7)))
34
+ rank = gumbel.argsort(-1, descending=True).argsort(-1)
35
+ chosen = active & (rank < count)
36
+ if "mult" in cats:
37
+ mult, link = cats.index("mult"), cats.index("link")
38
+ chosen[:, link] |= chosen[:, mult]
39
+ return chosen
40
+
41
+
42
+ def has(chosen, name):
43
+ """[n, 1] bool column of category `name` (False if not configured)."""
44
+ cats = CONFIG["categories"]
45
+ if name not in cats:
46
+ return torch.zeros_like(chosen[:, :1])
47
+ i = cats.index(name)
48
+ return chosen[:, i : i + 1]
49
+
50
+
51
+ def link(gen, x, use_mult):
52
+ """Positive inverse Box-Cox of the standardised path (unit level), with optional mult noise."""
53
+ n, length = x.shape
54
+ device = x.device
55
+ z = _standardise(torch.where(torch.isfinite(x), x, 0))
56
+ lam = torch.tensor(LAMBDAS, device=device)[
57
+ torch.randint(len(LAMBDAS), (n, 1), generator=gen, device=device)]
58
+ c = _logu(gen, (n, 1), 0.05, 1.0, device)
59
+ safe = lam.clamp_min(1e-3)
60
+ base = (1 + safe * c * z).clamp_min(0)
61
+ power = torch.where(base > 0, base.clamp_min(1e-30) ** (1 / safe), torch.zeros_like(base))
62
+ y = torch.where(lam < 1e-3, torch.exp((c * z).clamp_max(30)), power)
63
+ sigma = _logu(gen, (n, 1), 0.01, 0.3, device)
64
+ noise = torch.exp(sigma * torch.randn((n, length), generator=gen, device=device))
65
+ y = torch.where(use_mult, y * noise, y)
66
+ return y / y.mean(-1, keepdim=True).clamp_min(1e-12)
67
+
68
+
69
+ def _duty(gen, x):
70
+ n, length = x.shape
71
+ device = x.device
72
+ mean_on = _logu(gen, (n, 1), 4.0, 512.0, device)
73
+ mean_off = _logu(gen, (n, 1), 4.0, 512.0, device)
74
+ k = torch.arange(SEGMENTS, device=device)[None]
75
+ start_on = _u(gen, (n, 1), device=device) < mean_on / (mean_on + mean_off)
76
+ on_k = (k % 2 == 0) == start_on
77
+ mean = torch.where(on_k, mean_on, mean_off)
78
+ p = (1 / mean).clamp(1e-6, 1 - 1e-6)
79
+ u = _u(gen, (n, SEGMENTS), device=device).clamp_min(1e-12)
80
+ runs = torch.floor(torch.log(u) / torch.log1p(-p)) + 1
81
+ edges = runs.cumsum(-1).contiguous()
82
+ t = torch.arange(length, device=device, dtype=edges.dtype)[None].expand(n, length).contiguous()
83
+ seg = torch.searchsorted(edges, t, right=True).clamp_max(SEGMENTS - 1)
84
+ on = on_k.gather(-1, seg)
85
+ if CONFIG["duty_periodic"] > 0: # Skip draws at zero to preserve the Markov-only stream.
86
+ on = torch.where(_u(gen, (n, 1), device=device) < CONFIG["duty_periodic"],
87
+ _periodic_on(gen, n, length, device), on)
88
+ shifted = x - x.amin(-1, keepdim=True).clamp_max(0)
89
+ return shifted * on
90
+
91
+
92
+ DUTY_PERIODS = (24.0, 24.0, 48.0, 96.0, 96.0, 144.0, 288.0, 168.0, 12.0, 7.0, 52.0, 60.0)
93
+
94
+
95
+ def _periodic_on(gen, n, length, device):
96
+ """Draw periodic on/off masks with switch-off jitter up to 5% of the period."""
97
+ period = torch.tensor(DUTY_PERIODS, device=device)[
98
+ torch.randint(len(DUTY_PERIODS), (n, 1), generator=gen, device=device)]
99
+ share = _u(gen, (n, 1), 0.3, 0.8, device)
100
+ phase = _u(gen, (n, 1), device=device)
101
+ t = torch.arange(length, device=device, dtype=torch.float32)[None]
102
+ cycle_pos = t / period + phase
103
+ cycle = torch.floor(cycle_pos)
104
+ frac = cycle_pos - cycle
105
+ # Hash cycle indices for shared within-cycle jitter without another [n,L] draw.
106
+ seed = _u(gen, (n, 1), 0.0, 1000.0, device)
107
+ jitter = 0.05 * torch.sin(12.9898 * cycle + seed)
108
+ return frac < (share + jitter)
109
+
110
+
111
+ def record(gen, x, chosen):
112
+ """`duty` on the rows that chose it; x in original units, no NaN."""
113
+ if "duty" not in CONFIG["categories"]:
114
+ return x
115
+ y = _duty(gen, x)
116
+ y = torch.where(torch.isfinite(y), y, x)
117
+ return torch.where(has(chosen, "duty"), y, x)
@@ -0,0 +1 @@
1
+ """Train, average and export Simons models using synthetic and real time series."""
@@ -0,0 +1,77 @@
1
+ """Command-line entry point for training, clustering, checkpoint averaging and export."""
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+
6
+ from simons.training.trainer import build_clusters, export, train
7
+
8
+
9
+ def main():
10
+ parser = argparse.ArgumentParser(prog="python -m simons.training")
11
+ commands = parser.add_subparsers(dest="command", required=True)
12
+ run = commands.add_parser("train", help="run one stage of a recipe")
13
+ run.add_argument("--config", type=Path, required=True,
14
+ help="the stage's YAML config (model and training sections)")
15
+ run.add_argument("--output", type=Path, required=True,
16
+ help="run folder for config.json, training.jsonl, checkpoint.pt and "
17
+ "run.json; must be new or empty, also with --resume")
18
+ run.add_argument("--data",
19
+ help="override the config's corpus folder (train-*.parquet, or toy); it is "
20
+ "also the covariate pass's base corpus unless covariate_base_data is "
21
+ "set")
22
+ run.add_argument("--warm-start",
23
+ help="override the config's warm start (a checkpoint.pt or model folder): "
24
+ "its weights only, with a fresh optimizer, from warm_start_step "
25
+ "(default: the first step of phase warm_start_stage in a stage2 run, "
26
+ "step 0 in a stage1 run), with the re-warm LR ramp")
27
+ run.add_argument("--resume", type=Path,
28
+ help="continue an interrupted run from its checkpoint.pt, with the same "
29
+ "config and overrides: restores weights, optimizer, step and elapsed "
30
+ "time; LR schedule and context phases continue from that step, the "
31
+ "role phases start again over the remaining steps; random streams "
32
+ "start afresh, as for a run that starts at that step")
33
+ run.add_argument("--covariate-data",
34
+ help="override the config's covariate corpus folder (the real windows of "
35
+ "the covariate pass)")
36
+ run.add_argument("--shape-clusters",
37
+ help="override the config's shape-cluster labels file (written by the "
38
+ "clusters command)")
39
+ run.add_argument("--max-steps", type=int,
40
+ help="stop after this many steps of this run and write the checkpoint; the "
41
+ "plan and its schedules are unchanged (smoke tests; run.json says "
42
+ "partial when the run stops before the plan's last step)")
43
+ cl = commands.add_parser("clusters", help="build the shape-cluster labels of a config")
44
+ cl.add_argument("--config", type=Path, required=True)
45
+ cl.add_argument("--embedder", type=Path, required=True,
46
+ help="frozen embedder: the run's warm start (checkpoint.pt) or a model folder")
47
+ cl.add_argument("--output", type=Path, required=True, help="labels file (.npz)")
48
+ cl.add_argument("--data", help="override the config's corpus folder")
49
+ mix = commands.add_parser("soup", help="average trained checkpoints into one checkpoint")
50
+ mix.add_argument("members", type=Path, nargs="+", help="checkpoint.pt files")
51
+ mix.add_argument("--output", type=Path, required=True, help="checkpoint file to write")
52
+ mix.add_argument("--wise", type=float, metavar="ALPHA",
53
+ help="two members ANCHOR MODEL: (1 - ALPHA) * ANCHOR + ALPHA * MODEL "
54
+ "instead of the uniform average")
55
+ out = commands.add_parser("export", help="write a checkpoint as a model folder")
56
+ out.add_argument("--checkpoint", type=Path, required=True)
57
+ out.add_argument("--output", type=Path, required=True)
58
+ out.add_argument("--context-length", type=int,
59
+ help="history steps the exported model reads (default: the config's "
60
+ "export_context_length, else the model's context)")
61
+ args = parser.parse_args()
62
+ if args.command == "clusters":
63
+ print(build_clusters(args.config, args.embedder, args.output, args.data))
64
+ elif args.command == "soup":
65
+ from simons.training.soup import write
66
+
67
+ print(write(args.members, args.output, args.wise))
68
+ elif args.command == "train":
69
+ print(train(args.config, args.output, data=args.data, warm_start=args.warm_start,
70
+ resume=args.resume, covariate_data=args.covariate_data,
71
+ max_steps=args.max_steps, shape_clusters=args.shape_clusters))
72
+ else:
73
+ print(export(args.checkpoint, args.output, args.context_length))
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()