simons-forecasting 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. simons/__init__.py +10 -0
  2. simons/config.py +82 -0
  3. simons/covariates.py +338 -0
  4. simons/forecast.py +578 -0
  5. simons/model.py +696 -0
  6. simons/periodicity.py +188 -0
  7. simons/predictor.py +56 -0
  8. simons/synth/__init__.py +5 -0
  9. simons/synth/augment.py +143 -0
  10. simons/synth/base.py +448 -0
  11. simons/synth/calendar.py +157 -0
  12. simons/synth/causal.py +193 -0
  13. simons/synth/covariates/__init__.py +1 -0
  14. simons/synth/covariates/classical.py +637 -0
  15. simons/synth/covariates/effects.py +155 -0
  16. simons/synth/covariates/energy.py +528 -0
  17. simons/synth/covariates/families.py +296 -0
  18. simons/synth/covariates/generic.py +342 -0
  19. simons/synth/heavy.py +234 -0
  20. simons/synth/mech.py +636 -0
  21. simons/synth/multi.py +274 -0
  22. simons/synth/nonstat.py +204 -0
  23. simons/synth/observe.py +117 -0
  24. simons/training/__init__.py +1 -0
  25. simons/training/__main__.py +77 -0
  26. simons/training/augment.py +125 -0
  27. simons/training/clusters.py +215 -0
  28. simons/training/config.py +321 -0
  29. simons/training/covariates/__init__.py +1 -0
  30. simons/training/covariates/roles.py +370 -0
  31. simons/training/covariates/stream.py +243 -0
  32. simons/training/covariates/windows.py +239 -0
  33. simons/training/data.py +319 -0
  34. simons/training/distributed.py +124 -0
  35. simons/training/mixture.py +140 -0
  36. simons/training/network.py +115 -0
  37. simons/training/objective.py +193 -0
  38. simons/training/optim.py +164 -0
  39. simons/training/packing.py +94 -0
  40. simons/training/schedule.py +117 -0
  41. simons/training/soup.py +93 -0
  42. simons/training/stitching.py +50 -0
  43. simons/training/trainer.py +571 -0
  44. simons/training/warp.py +144 -0
  45. simons_forecasting-0.1.3.dist-info/METADATA +156 -0
  46. simons_forecasting-0.1.3.dist-info/RECORD +49 -0
  47. simons_forecasting-0.1.3.dist-info/WHEEL +4 -0
  48. simons_forecasting-0.1.3.dist-info/licenses/LICENSE +202 -0
  49. simons_forecasting-0.1.3.dist-info/licenses/NOTICE +57 -0
@@ -0,0 +1,125 @@
1
+ """Augment real windows on device with mixup, censoring, amplitude, sign and time flips."""
2
+
3
+ import torch
4
+
5
+
6
+ class RealAugmenter:
7
+ def __init__(self, gen, censor=0.0, amplitude=0.0, sign_flip=0.0, time_flip=0.0, mixup=0.0,
8
+ mixup_alpha=1.5):
9
+ self.gen = gen
10
+ self.censor, self.amplitude = censor, amplitude
11
+ self.sign_flip, self.time_flip = sign_flip, time_flip
12
+ self.mixup, self.mixup_alpha = mixup, mixup_alpha
13
+
14
+ @property
15
+ def active(self):
16
+ return max(self.censor, self.amplitude, self.sign_flip, self.time_flip, self.mixup) > 0
17
+
18
+ def _u(self, shape, device):
19
+ return torch.rand(shape, generator=self.gen, device=device)
20
+
21
+ def __call__(self, sequence, series_ids, real_rows):
22
+ if not self.active or real_rows <= 0:
23
+ return sequence
24
+ _, width, length = sequence.shape
25
+ device = sequence.device
26
+ x = sequence[:real_rows].reshape(real_rows * width, length).float()
27
+ ids = series_ids[:real_rows].reshape(-1)
28
+ n = x.shape[0]
29
+ # Draw per series so related variates share transforms; id -1 uses a padding bucket.
30
+ buckets = int(series_ids.shape[0] * width) + 1
31
+ index = torch.where(ids >= 0, ids, buckets - 1).clamp(max=buckets - 1)
32
+ draws = self._u((buckets, 8), device)[index] # [n, 8]
33
+ finite = torch.isfinite(x)
34
+ valid = (ids >= 0) & finite.any(-1)
35
+ position = torch.arange(length, device=device)
36
+ first = torch.where(finite, position, length).amin(-1)
37
+
38
+ if self.mixup > 0:
39
+ alpha = torch.full((buckets,), float(self.mixup_alpha), device=device)
40
+ g1 = _gamma(alpha, self.gen)
41
+ g2 = _gamma(alpha, self.gen)
42
+ lam = (g1 / (g1 + g2)).clamp(0.2, 0.8)[index]
43
+ # Require a partner whose observed span covers this slot.
44
+ key = torch.where(valid, first, length + 1).float() + 1e-3 * self._u((n,), device)
45
+ order = torch.argsort(key)
46
+ rank = torch.empty_like(order)
47
+ rank[order] = torch.arange(n, device=device)
48
+ pick = (self._u((n,), device) * (rank + 1).float()).floor().long().clamp(max=n - 1)
49
+ partner = order[pick]
50
+ xb = x[partner]
51
+ sa = _mean_abs(x, finite)
52
+ sb = _mean_abs(xb, torch.isfinite(xb))
53
+ mixed = sa[:, None] * (lam[:, None] * x / sa[:, None]
54
+ + (1 - lam[:, None]) * xb / sb[:, None])
55
+ use = ((draws[:, 0] < self.mixup) & valid & valid[partner]
56
+ & (partner != torch.arange(n, device=device)))
57
+ x = torch.where(use[:, None], mixed, x)
58
+ finite = torch.isfinite(x)
59
+ first = torch.where(finite, position, length).amin(-1)
60
+
61
+ if self.censor > 0:
62
+ count = finite.sum(-1)
63
+ ordered = torch.sort(torch.where(finite, x, float("inf")), dim=-1).values
64
+ bottom = self._u((n,), device) < 0.5
65
+ q = torch.where(bottom, 0.4 * self._u((n,), device), 0.6 + 0.4 * self._u((n,), device))
66
+ rank = (q * (count - 1).clamp_min(0).float()).round().long()
67
+ c = ordered.gather(-1, rank[:, None].clamp(max=length - 1))
68
+ censored = torch.where(bottom[:, None], torch.maximum(x, c), torch.minimum(x, c))
69
+ use = (self._u((n,), device) < self.censor) & valid & (count > 1)
70
+ x = torch.where(use[:, None] & finite, censored, x)
71
+
72
+ if self.amplitude > 0:
73
+ knots = torch.sort(self._u((buckets, 2), device), -1).values
74
+ pos = torch.cat([torch.zeros(buckets, 1, device=device), knots,
75
+ torch.ones(buckets, 1, device=device)], -1)[index]
76
+ val = torch.exp(0.3 * torch.randn((buckets, 4), generator=self.gen,
77
+ device=device))[index]
78
+ span = (length - first).clamp_min(1).float()
79
+ t = ((position[None] - first[:, None]).float() / span[:, None]).clamp(0, 1)
80
+ seg = torch.searchsorted(pos[:, 1:3].contiguous(), t.contiguous(), right=True)
81
+ p0, p1 = pos.gather(-1, seg), pos.gather(-1, seg + 1)
82
+ v0, v1 = val.gather(-1, seg), val.gather(-1, seg + 1)
83
+ w = ((t - p0) / (p1 - p0).clamp_min(1e-6)).clamp(0, 1)
84
+ envelope = v0 + w * (v1 - v0)
85
+ use = (draws[:, 1] < self.amplitude) & valid
86
+ x = torch.where(use[:, None], x * envelope, x)
87
+
88
+ if self.sign_flip > 0:
89
+ use = (draws[:, 2] < self.sign_flip) & valid
90
+ x = torch.where(use[:, None], -x, x)
91
+
92
+ if self.time_flip > 0:
93
+ start = torch.full((buckets,), length, device=device, dtype=torch.long)
94
+ start = start.scatter_reduce(0, index, first, reduce="amin")[index]
95
+ source = torch.where(position[None] >= start[:, None],
96
+ start[:, None] + (length - 1 - position[None]), position[None])
97
+ reversed_ = x.gather(-1, source.clamp(0, length - 1))
98
+ use = (draws[:, 3] < self.time_flip) & valid
99
+ x = torch.where(use[:, None], reversed_, x)
100
+
101
+ sequence = sequence.clone()
102
+ sequence[:real_rows] = x.view(real_rows, width, length).to(sequence.dtype)
103
+ return sequence
104
+
105
+
106
+ def _mean_abs(x, finite):
107
+ total = torch.where(finite, x.abs(), 0.0).sum(-1)
108
+ return (total / finite.sum(-1).clamp_min(1)).clamp_min(1e-6)
109
+
110
+
111
+ def _gamma(alpha, gen):
112
+ """Draw Gamma(alpha,1) for alpha >= 1 using fixed rejection rounds on device."""
113
+ d = alpha - 1.0 / 3.0
114
+ c = 1.0 / torch.sqrt(9.0 * d)
115
+ out = d.clone()
116
+ done = torch.zeros_like(alpha, dtype=torch.bool)
117
+ for _ in range(8):
118
+ z = torch.randn(alpha.shape, generator=gen, device=alpha.device)
119
+ u = torch.rand(alpha.shape, generator=gen, device=alpha.device)
120
+ v = (1 + c * z) ** 3
121
+ ok = (v > 0) & (torch.log(u.clamp_min(1e-12))
122
+ < 0.5 * z**2 + d - d * v + d * torch.log(v.clamp_min(1e-12)))
123
+ out = torch.where(ok & ~done, d * v, out)
124
+ done |= ok
125
+ return out
@@ -0,0 +1,215 @@
1
+ """Sample real windows by shape clusters within per-source token budgets."""
2
+
3
+ import hashlib
4
+ import json
5
+ import math
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+ from simons.model import time_blocks
12
+ from simons.training import network
13
+ from simons.training.mixture import waterfill
14
+
15
+ LABELS_FORMAT = "simons-clusters-1"
16
+
17
+
18
+ def features(model, values: torch.Tensor) -> torch.Tensor:
19
+ """Return mean final-norm features [B,D] over observed patches of histories [B,H].
20
+ H must be a patch-length multiple within near context; leading NaN marks padding."""
21
+ c = model.config
22
+ patch = c.patch_length
23
+ batch, history = values.shape
24
+ full = torch.nn.functional.pad(values, (0, network.future_steps(c)), value=float("nan"))
25
+ tokens, rotary, started, _, _, _, _ = network.front(model, full[:, None])
26
+ p = history // patch
27
+ tokens, started = tokens[:, :, :p], started[:, :, :p]
28
+ cos, sin = (t[:, :, :p] for t in rotary)
29
+ x = (model.embed(tokens) + model.embed_mlp(tokens)).reshape(batch, p, -1)
30
+ x = time_blocks(model.time_blocks, x, started.reshape(batch, p), (cos, sin), None)
31
+ vb, width = model.variate_block, x.shape[-1]
32
+ x = x + vb.out(vb.qkv(vb.attention_norm(x))[..., 2 * width:])
33
+ x = x + vb.mlp(vb.mlp_norm(x))
34
+ h = model.norm(x).float()
35
+ seen = tokens[:, 0, :, patch:].amax(-1) > 0
36
+ weight = seen.float()
37
+ return (h * weight[..., None]).sum(1) / weight.sum(1, keepdim=True).clamp_min(1)
38
+
39
+
40
+ class Rows:
41
+ """Flat row index over a `data.Windows` sampler's sources: (source, position) per row."""
42
+
43
+ def __init__(self, windows):
44
+ self.sizes = np.array([len(s) for s in windows.sources], dtype=np.int64)
45
+ self.offsets = np.concatenate([[0], np.cumsum(self.sizes)])
46
+ self.source = np.repeat(np.arange(len(self.sizes)), self.sizes)
47
+ shapes = np.concatenate(windows.shapes)
48
+ self.channels, self.length = shapes[:, 0], shapes[:, 1]
49
+ self.windows = windows
50
+
51
+ def __len__(self):
52
+ return int(self.offsets[-1])
53
+
54
+ def array(self, flat: int):
55
+ s = self.source[flat]
56
+ return self.windows.sources[s][flat - self.offsets[s]]
57
+
58
+
59
+ def embed_rows(model, rows: Rows, flat: np.ndarray, variate: np.ndarray, context: int, device,
60
+ tokens_per_batch: int = 65536, max_rows: int = 8192) -> torch.Tensor:
61
+ """[len(flat), D] fp32 features (on `device`) of the given rows, batched by patch count."""
62
+ patch = model.config.patch_length
63
+ hist = np.minimum(rows.length[flat], context)
64
+ patches = -(-hist // patch)
65
+ out = torch.empty(len(flat), model.config.width, device=device)
66
+ order = np.argsort(patches, kind="stable")
67
+ sorted_patches = patches[order]
68
+ i = 0
69
+ while i < len(order):
70
+ p = int(patches[order[i]])
71
+ size = max(1, min(max_rows, tokens_per_batch // p))
72
+ same = int(np.searchsorted(sorted_patches, p, side="right"))
73
+ j = min(same, i + size)
74
+ chunk = order[i:j]
75
+ buf = np.full((len(chunk), p * patch), np.nan, dtype=np.float32)
76
+ for r, k in enumerate(chunk):
77
+ a = rows.array(flat[k])
78
+ h = int(hist[k])
79
+ buf[r, p * patch - h:] = a[variate[k], a.shape[1] - h:]
80
+ values = torch.from_numpy(buf).to(device, non_blocking=True)
81
+ out[torch.from_numpy(chunk).to(device)] = features(model, values)
82
+ i = j
83
+ return out
84
+
85
+
86
+ def kmeans(x: torch.Tensor, k: int, iters: int, seed: int):
87
+ """Spherical k-means of unit rows x [N, D]: (centroids [k, D], cluster sizes)."""
88
+ gen = torch.Generator().manual_seed(seed)
89
+ n = x.shape[0]
90
+ centroids = x[torch.randperm(n, generator=gen)[:k].to(x.device)].clone()
91
+ for _ in range(iters):
92
+ labels = assign(x, centroids)
93
+ sums = torch.zeros_like(centroids).index_add_(0, labels, x)
94
+ counts = torch.bincount(labels, minlength=k)
95
+ empty = counts == 0
96
+ if empty.any():
97
+ pick = torch.randint(n, (int(empty.sum()),), generator=gen).to(x.device)
98
+ sums[empty] = x[pick]
99
+ centroids = torch.nn.functional.normalize(sums, dim=-1)
100
+ return centroids, torch.bincount(assign(x, centroids), minlength=k)
101
+
102
+
103
+ def assign(x: torch.Tensor, centroids: torch.Tensor, chunk: int = 65536) -> torch.Tensor:
104
+ return torch.cat([(x[i:i + chunk] @ centroids.T).argmax(-1)
105
+ for i in range(0, x.shape[0], chunk)])
106
+
107
+
108
+ @torch.no_grad()
109
+ def build_labels(model, windows, k: int, anchors: int, context: int, seed: int, shards: int,
110
+ device):
111
+ """Cluster label (int32) of every row of `windows`, and build facts."""
112
+ rows = Rows(windows)
113
+ n = len(rows)
114
+ rng = np.random.default_rng(np.random.SeedSequence([int(seed), 8017]))
115
+ variate = (rng.random(n) * rows.channels).astype(np.int64)
116
+ per = math.ceil(int(anchors) / len(rows.sizes))
117
+ anchor_rows = np.concatenate([rows.offsets[s] + rng.integers(rows.sizes[s], size=per)
118
+ for s in range(len(rows.sizes))])
119
+ if len(anchor_rows) < k:
120
+ raise ValueError(f"shape_anchors ({anchors}) gives {len(anchor_rows)} anchor rows: it "
121
+ f"must be at least shape_k ({k})")
122
+ was_training = model.training
123
+ model.eval()
124
+ with torch.autocast("cuda", torch.bfloat16, enabled=torch.device(device).type == "cuda"):
125
+ x = torch.cat([embed_rows(model, rows, anchor_rows[r::shards],
126
+ variate[anchor_rows[r::shards]], context, device)
127
+ for r in range(shards)])
128
+ mean = x.mean(0)
129
+ x = torch.nn.functional.normalize(x - mean, dim=-1)
130
+ centroids, sizes = kmeans(x, k, 40, int(seed))
131
+ hist_p = -(-np.minimum(rows.length, context) // model.config.patch_length)
132
+ order = np.argsort(hist_p, kind="stable")
133
+ labels = np.empty(n, dtype=np.int32)
134
+ step = 1 << 20
135
+ for r in range(shards):
136
+ shard = order[r::shards]
137
+ out = np.empty(len(shard), dtype=np.int32)
138
+ for i in range(0, len(shard), step):
139
+ part = shard[i:i + step]
140
+ f = embed_rows(model, rows, part, variate[part], context, device)
141
+ f = torch.nn.functional.normalize(f - mean, dim=-1)
142
+ out[i:i + len(part)] = assign(f, centroids).int().cpu().numpy()
143
+ labels[shard] = out
144
+ model.train(was_training)
145
+ info = {"rows": n, "k": k, "anchors": len(anchor_rows), "shards": shards,
146
+ "anchor_cluster_sizes_q": np.quantile(sizes.cpu().numpy(), [0, .1, .5, .9, 1]).tolist(),
147
+ "row_clusters_nonempty": int((np.bincount(labels, minlength=k) > 0).sum())}
148
+ return labels, info
149
+
150
+
151
+ def fingerprint(windows) -> str:
152
+ """Hash of the rows the labels index: source names and (variates, steps) of every row."""
153
+ digest = hashlib.sha256()
154
+ for name, shapes in zip(windows.names, windows.shapes):
155
+ digest.update(name.encode() + b"\0")
156
+ digest.update(np.ascontiguousarray(shapes, dtype=np.int64).tobytes())
157
+ return digest.hexdigest()
158
+
159
+
160
+ def save(path, labels, info, windows):
161
+ path = Path(path)
162
+ path.parent.mkdir(parents=True, exist_ok=True)
163
+ meta = {"format": LABELS_FORMAT, "fingerprint": fingerprint(windows), **info}
164
+ with open(path, "wb") as file: # Opening the path prevents np.savez from appending .npz.
165
+ np.savez(file, labels=labels, meta=json.dumps(meta))
166
+
167
+
168
+ def load(path, windows):
169
+ """(labels, k) of a clusters file, checked against the corpus rows of `windows`."""
170
+ with np.load(path) as data:
171
+ labels, meta = data["labels"], json.loads(str(data["meta"]))
172
+ if meta.get("format") != LABELS_FORMAT:
173
+ raise ValueError(f"{path} is not a Simons clusters file")
174
+ if meta["fingerprint"] != fingerprint(windows) or len(labels) != meta["rows"]:
175
+ raise ValueError(f"{path} was built on different corpus rows; rebuild it for this corpus")
176
+ return labels, int(meta["k"])
177
+
178
+
179
+ class StageTable:
180
+ """The cluster stream of one curriculum phase (picklable, for loader workers)."""
181
+
182
+ def __init__(self, labels: np.ndarray, windows, source_weights, k: int, cap: float,
183
+ mix: float):
184
+ rows = Rows(windows)
185
+ sizes, source = rows.sizes, rows.source
186
+ w = np.asarray(source_weights if source_weights is not None
187
+ else np.full(len(sizes), 1.0 / len(sizes)), dtype=np.float64)
188
+ r = w[source] / sizes[source]
189
+ mass = np.bincount(labels, weights=r, minlength=k)
190
+ mass = mass / mass.sum()
191
+ p = waterfill(1.0, cap * mass)
192
+ p = np.where(mass > 0, p, 0.0)
193
+ p = p / p.sum()
194
+ order = np.argsort(labels, kind="stable")
195
+ self.order = order.astype(np.int64)
196
+ self.row_cum = np.cumsum(r[order])
197
+ counts = np.bincount(labels, minlength=k)
198
+ self.end = np.cumsum(counts)
199
+ self.start = self.end - counts
200
+ self.p_cum = np.cumsum(p)
201
+ self.p_cum[-1] = 1.0
202
+ self.offsets, self.source = rows.offsets, source.astype(np.int32)
203
+ self.mix = float(mix)
204
+
205
+ def draw(self, rng) -> tuple[int, int]:
206
+ """(source index, position) of one cluster-stream row."""
207
+ c = int(np.searchsorted(self.p_cum, rng.random(), side="right"))
208
+ c = min(c, len(self.p_cum) - 1)
209
+ lo, hi = int(self.start[c]), int(self.end[c])
210
+ base = self.row_cum[lo - 1] if lo > 0 else 0.0
211
+ u = base + rng.random() * (self.row_cum[hi - 1] - base)
212
+ j = int(np.searchsorted(self.row_cum, u, side="right"))
213
+ flat = int(self.order[min(max(j, lo), hi - 1)])
214
+ s = int(self.source[flat])
215
+ return s, flat - int(self.offsets[s])
@@ -0,0 +1,321 @@
1
+ """Training YAML: `model` contains SimonsConfig fields; `training` contains the keys below.
2
+
3
+ `stage1` trains on synthetic series; `stage2` mixes real and synthetic data.
4
+ Keys ending in `_stage` or `_stages` refer to context-curriculum phases within a run.
5
+ See docs/TRAINING.md for the four-stage recipe."""
6
+
7
+ from pathlib import Path
8
+
9
+ import yaml
10
+
11
+ from simons.config import SimonsConfig
12
+
13
+ FAMILIES = ("kernel", "sarima", "sde", "step", "spike", "cauker", "rhythm", "wave", "fpfn", "levy",
14
+ "ets", "pulse", "chaos", "epi", "hydro", "queue", "thermal", "calendar")
15
+
16
+ DEFAULTS = {
17
+ "stage": None, # stage1 (synthetic) | stage2 (real + synthetic)
18
+ "steps": None, # optimizer steps of the full plan
19
+ "seed": None,
20
+ "device": "auto", # auto | cuda | cpu
21
+ "max_steps": None, # stop early after this many steps of this run (smoke tests; None: none)
22
+ "checkpoint_every": 1000,
23
+ "log_every": 25,
24
+ # Optimizer (optim.py)
25
+ "muon_lr": 0.002, # peak LR of the hidden matrices (NorMuon)
26
+ "adam_lr": 0.0005, # peak LR of embeddings, head, biases and norms (AdamW)
27
+ "muon_weight_decay": 0.05, # decoupled, scaled with the LR, hidden matrices only
28
+ "mup_base_width": 704, # width transfer base d0
29
+ # Learning-rate schedule (schedule.py)
30
+ "lr_schedule": "warmup_decay", # warmup_decay | wsd | linear
31
+ "warmup_steps": 1000, # warmup_decay
32
+ "decay_steps": 5000, # warmup_decay
33
+ "decay_shape": "linear", # warmup_decay and wsd: linear | sqrt
34
+ "warmup_fraction": 0.05, # wsd, linear
35
+ "decay_fraction": 0.3, # wsd
36
+ "final_lr_fraction": 0.0,
37
+ # Objective (objective.py)
38
+ "mask_rate_max": 0.4,
39
+ "mask_span_max": 8,
40
+ # Packing (packing.py); exact, so this changes speed only
41
+ "pack_row_tokens": 288, # packed row length in stages with far tokens (0: window length)
42
+ # Recompute the first K time blocks during backward to save memory (0: off).
43
+ "checkpoint_blocks": 0,
44
+ # Split each GPU's packed rows into chunks to save memory (1: off).
45
+ "micro_batches": 1,
46
+ # Synthetic series (simons.synth)
47
+ "synthetic_families": "kernel,sarima,sde,step,spike,cauker,rhythm,wave,fpfn",
48
+ "synthetic_family_weights": None, # one weight per family (None: equal)
49
+ "synthetic_noise": 0.3, # share of series through the count / shock / spike noisers
50
+ "synthetic_pad": 0.4, # share of series with a short (left-padded) history
51
+ "synthetic_pool_steps": 6, # steps of series drawn per pool
52
+ "synthetic_pool_steps_long": 2, # the same in stages after the first
53
+ "synthetic_augment": "mix,season,filter,lattice", # simons.synth.augment ("" = off)
54
+ "synthetic_augment_rate": 0.4,
55
+ "synthetic_augment_weights": "0.35,0.25,0.2,0.2",
56
+ "synthetic_observe": "", # simons.synth.observe categories ("" = off)
57
+ "synthetic_observe_rate": 0.1,
58
+ "synthetic_observe_duty_periodic": 0.5,
59
+ "synthetic_multi_fraction": 0.5, # share of synthetic rows holding coupled groups
60
+ "mech_bank": 16384, # simons.synth.mech: chaos trajectories (other banks: half)
61
+ "mech_length": 9216,
62
+ "mech_refresh": 400, # maker calls between bank refreshes (0: never)
63
+ "mech_refresh_part": 1, # a refresh re-simulates 1/part of the bank
64
+ # `stage1` runs (synthetic)
65
+ "synthetic_rows": 36, # rows of 32 series per step, over all devices
66
+ "synthetic_context": 8192, # history steps of the synthetic windows
67
+ # `stage2` runs (real + synthetic): real data (data.py, mixture.py)
68
+ "data": None, # corpus folder (train-*.parquet) or "toy"
69
+ "validation_data": None, # folder with validation-*.parquet (None: no validation)
70
+ "batch_size": 784, # real windows per step, over all devices
71
+ "context_schedule": None, # phases, e.g. "1024:0.15,7680:0.45,32768:0.40" (None: one)
72
+ "synthetic_fraction": 0.4, # share of packed rows that are synthetic
73
+ "synthetic_only_stages": 0, # leading curriculum phases replaced by `stage1` runs
74
+ "synthetic_ramp_steps": 0, # share ramp 1 -> synthetic_fraction after them
75
+ "mixture_cap_epochs": 6.0, # UniMax over (domain, subdomain) groups; max passes over a source
76
+ "stitch_from_stage": -1, # phases >= k stitch consecutive segments (-1: never)
77
+ "far_from_stage": 0, # phases >= k keep far tokens; other phases use far history for stats
78
+ "augment_downsample": 0.4, # augment.py / warp.py: real-window augmentation rates
79
+ "augment_downsample_max": 8,
80
+ "augment_stretch": 0.25,
81
+ "augment_stretch_up": 0.5,
82
+ "augment_warp": 0.2,
83
+ "augment_warp_convex": 0.65,
84
+ "augment_censor": 0.2,
85
+ "augment_amplitude": 0.2,
86
+ "augment_sign_flip": 0.2,
87
+ "augment_time_flip": 0.1,
88
+ "augment_mixup": 0.2,
89
+ "augment_mixup_alpha": 1.5,
90
+ "loader_workers": 16,
91
+ # Shape-cluster sampling (clusters.py): draw share, mass cap, labels and build settings.
92
+ "shape_mix": 0.0,
93
+ "shape_cap": 10.0,
94
+ "shape_clusters": None,
95
+ "shape_k": 1024,
96
+ "shape_anchors": 200000,
97
+ "shape_context": 1024,
98
+ "shape_table_seed": 0,
99
+ "shape_shards": 1,
100
+ # Warm start
101
+ "warm_start": None, # checkpoint.pt or model folder to load
102
+ "warm_start_stage": 1, # the run starts at this phase of its context curriculum
103
+ "rewarm_from": 0.15,
104
+ "rewarm_steps": 300,
105
+ # Start step (None: warm_start_stage's first step for stage2, 0 for stage1); LR scale.
106
+ "warm_start_step": None,
107
+ "warm_lr_scale": 1.0,
108
+ # Read initialization: keep saved weights, or copy the variate block with zero writes.
109
+ # Missing read weights use the variate initialization.
110
+ "covariate_read_init": "keep",
111
+ # Role/effect shares per phase (fractions of run steps); stage1 supports effect rows.
112
+ # effect_mix orders generic, classical, energy, retail, lagged. Worker count affects draws.
113
+ "role_phases": None,
114
+ "role_share": "0",
115
+ "effect_share": "0",
116
+ "effect_mix": None,
117
+ "effect_workers": 4,
118
+ # Main covariate pass (stage2): weight 0 disables it; mix orders synthetic, sibling, real.
119
+ # Base data: first train file or first rows per dataset subfolder (None: data).
120
+ # Source weights: {source: weight} JSON; exclusions: {"items": {source: [item_id, ...]}}.
121
+ # Norm: global weighted mean or mean of rank means. Worker count affects draws.
122
+ "covariate_weight": 0.0,
123
+ "covariate_data": None,
124
+ "covariate_base_data": None,
125
+ "covariate_mix": "0.63,0.25,0.12",
126
+ "covariate_tokens": 4096, # per step over all GPUs, split evenly between them
127
+ "covariate_max_batch": 128, # windows per GPU and step
128
+ "covariate_workers": 3,
129
+ "covariate_history_weight": 0.1,
130
+ "covariate_source_weights": None,
131
+ "covariate_exclude": None,
132
+ "covariate_norm": "global",
133
+ # Long pass: real series meeting length/observed-share limits; weight 0 disables it.
134
+ # long_tokens=None uses covariate_tokens.
135
+ "long_weight": 0.0,
136
+ "long_tokens": None,
137
+ "long_workers": 2,
138
+ "long_min_length": 16384,
139
+ "long_min_observed": 0.75,
140
+ # Export
141
+ "export_context_length": None, # context_length of the exported model (None: the model's)
142
+ }
143
+
144
+ FRACTIONS = ("synthetic_noise", "synthetic_pad", "synthetic_augment_rate", "synthetic_observe_rate",
145
+ "synthetic_observe_duty_periodic", "synthetic_multi_fraction", "synthetic_fraction",
146
+ "final_lr_fraction", "warmup_fraction", "decay_fraction", "mask_rate_max",
147
+ "augment_downsample", "augment_stretch", "augment_stretch_up", "augment_warp",
148
+ "augment_warp_convex", "augment_censor", "augment_amplitude", "augment_sign_flip",
149
+ "augment_time_flip", "augment_mixup", "rewarm_from", "covariate_history_weight",
150
+ "long_min_observed")
151
+
152
+
153
+ def weights(value, count: int, name: str):
154
+ """A "w1,w2,..." string as floats (None stays None), one per item."""
155
+ if value is None:
156
+ return None
157
+ out = [float(w) for w in str(value).split(",")]
158
+ if len(out) != count or min(out) < 0 or sum(out) <= 0:
159
+ raise ValueError(f"{name} needs {count} nonnegative weights")
160
+ return out
161
+
162
+
163
+ def shares(value, name: str) -> list[float]:
164
+ """A "p1,p2,..." string (or one number) as a list of fractions."""
165
+ out = [float(v) for v in str(value).split(",")]
166
+ if min(out) < 0 or max(out) > 1:
167
+ raise ValueError(f"{name} must hold fractions from 0 to 1")
168
+ return out
169
+
170
+
171
+ def covariate_roles(s) -> dict | None:
172
+ """The role settings of `covariates.roles` from the config keys, or None when off."""
173
+ role = shares(s["role_share"], "role_share")
174
+ effect = shares(s["effect_share"], "effect_share")
175
+ if max(role) <= 0 and max(effect) <= 0:
176
+ return None
177
+ phases = shares(s["role_phases"], "role_phases") if s["role_phases"] is not None else []
178
+ if len(effect) == 1 and len(role) > 1:
179
+ effect = effect * len(role)
180
+ mix = None
181
+ if s["effect_mix"] is not None:
182
+ from simons.synth.covariates.families import FAMILIES
183
+
184
+ mix = dict(zip(FAMILIES, weights(s["effect_mix"], len(FAMILIES), "effect_mix")))
185
+ return {"boundaries": phases, "p_role": role, "p_eff": effect, "effect_mix": mix,
186
+ "effect_workers": int(s["effect_workers"])}
187
+
188
+
189
+ def check_far_region(model, context: int):
190
+ """A training context longer than near_context needs a far region of whole far tokens."""
191
+ block = model.patch_length * model.far_pool
192
+ if context > model.near_context and (context - model.near_context) % block:
193
+ raise ValueError(f"context {context}: context - near_context must be a multiple of "
194
+ f"patch_length * far_pool ({block})")
195
+
196
+
197
+ def load(path: Path, overrides: dict | None = None):
198
+ """(SimonsConfig, training settings dict) from a YAML file, validated; `overrides` values
199
+ that are not None replace the file's training keys."""
200
+ raw = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
201
+ if not isinstance(raw, dict) or set(raw) != {"model", "training"}:
202
+ raise ValueError("The config must contain exactly a model and a training section")
203
+ model_keys, training = raw["model"] or {}, raw["training"] or {}
204
+ if not isinstance(model_keys, dict) or not isinstance(training, dict):
205
+ raise ValueError("The model and training sections must be mappings of keys")
206
+ model = SimonsConfig(**model_keys)
207
+ unknown = set(training) - set(DEFAULTS)
208
+ if unknown:
209
+ raise ValueError(f"Unknown training keys: {sorted(unknown)}")
210
+ given = {k: v for k, v in (overrides or {}).items() if v is not None}
211
+ return model, validate(model, {**DEFAULTS, **training, **given})
212
+
213
+
214
+ def validate(model, s: dict) -> dict:
215
+ if s["stage"] not in ("stage1", "stage2"):
216
+ raise ValueError("stage must be stage1 (synthetic) or stage2 (real + synthetic)")
217
+ for key in ("steps", "seed", "checkpoint_every", "log_every"):
218
+ low = 0 if key == "seed" else 1
219
+ if isinstance(s[key], bool) or not isinstance(s[key], int) or s[key] < low:
220
+ kind = "nonnegative" if low == 0 else "positive"
221
+ raise ValueError(f"{key} must be a {kind} integer, got {s[key]!r}")
222
+ if s["max_steps"] is not None and (isinstance(s["max_steps"], bool)
223
+ or not isinstance(s["max_steps"], int)
224
+ or s["max_steps"] < 1):
225
+ raise ValueError(f"max_steps must be a positive integer or null, got {s['max_steps']!r}")
226
+ for key in FRACTIONS:
227
+ if not isinstance(s[key], (int, float)) or not 0 <= s[key] <= 1:
228
+ raise ValueError(f"{key} must be a number from 0 to 1")
229
+ if s["augment_mixup"] > 0 and not s["augment_mixup_alpha"] >= 1:
230
+ raise ValueError("augment_mixup_alpha must be at least 1")
231
+ if s["lr_schedule"] not in ("warmup_decay", "wsd", "linear"):
232
+ raise ValueError("lr_schedule must be warmup_decay, wsd or linear")
233
+ if s["decay_shape"] not in ("linear", "sqrt"):
234
+ raise ValueError("decay_shape must be linear or sqrt")
235
+ if s["warm_start_step"] is not None and not 0 <= s["warm_start_step"] < s["steps"]:
236
+ raise ValueError("warm_start_step must be a step of the plan")
237
+ if s["warm_lr_scale"] <= 0:
238
+ raise ValueError("warm_lr_scale must be positive")
239
+ width = s["mup_base_width"]
240
+ if isinstance(width, bool) or not isinstance(width, (int, float)) or width <= 0:
241
+ raise ValueError(f"mup_base_width must be a positive number, got {width!r}")
242
+ if s["covariate_read_init"] not in ("keep", "variate"):
243
+ raise ValueError("covariate_read_init must be keep or variate")
244
+ if s["covariate_norm"] not in ("global", "rank"):
245
+ raise ValueError("covariate_norm must be global or rank")
246
+ roles = covariate_roles(s)
247
+ passes = s["covariate_weight"] > 0 or s["long_weight"] > 0
248
+ if (roles or passes) and not model.covariates:
249
+ raise ValueError("covariate roles and passes need a model with covariates: true")
250
+ if (roles or passes) and model.patch_length != 32:
251
+ raise ValueError("covariate roles and passes need a model with patch_length 32")
252
+ if roles:
253
+ from simons.training.covariates.roles import settings as role_settings
254
+
255
+ role_settings(roles)
256
+ if s["stage"] == "stage2" and max(roles["p_eff"]) > 0:
257
+ raise ValueError("effect rows belong to stage1 runs (effect_share 0 in stage2 runs)")
258
+ if s["synthetic_multi_fraction"] <= 0:
259
+ raise ValueError("covariate roles need coupled synthetic groups "
260
+ "(synthetic_multi_fraction > 0)")
261
+ if model.read_after < 0:
262
+ raise ValueError("covariate roles need a model with the one-way read "
263
+ "(read_after >= 0)")
264
+ if not model.binary_rows:
265
+ raise ValueError("covariate roles need a model with binary_rows: true")
266
+ if passes and s["stage"] != "stage2":
267
+ raise ValueError("the covariate passes belong to stage2 runs")
268
+ if passes and model.prediction_length < 512:
269
+ raise ValueError("the covariate passes draw horizons of up to 512 steps: they need "
270
+ "prediction_length >= 512")
271
+ if s["long_weight"] > 0 and s["covariate_weight"] <= 0:
272
+ raise ValueError("the long pass runs with the main covariate pass")
273
+ weights(s["covariate_mix"], 3, "covariate_mix")
274
+ if not isinstance(s["micro_batches"], int) or s["micro_batches"] < 1:
275
+ raise ValueError("micro_batches must be a positive integer")
276
+ if (not isinstance(s["checkpoint_blocks"], int)
277
+ or not 0 <= s["checkpoint_blocks"] <= model.layers):
278
+ raise ValueError("checkpoint_blocks must be from 0 to the model's layers")
279
+ augment = [c for c in str(s["synthetic_augment"] or "").split(",") if c]
280
+ if augment and s["synthetic_augment_rate"] > 0:
281
+ from simons.synth.augment import CATEGORIES
282
+
283
+ if not set(augment) <= set(CATEGORIES):
284
+ raise ValueError(f"synthetic_augment must list some of {CATEGORIES}")
285
+ weights(s["synthetic_augment_weights"], len(augment), "synthetic_augment_weights")
286
+ families = s["synthetic_families"].split(",")
287
+ if not set(families) <= set(FAMILIES):
288
+ raise ValueError(f"synthetic_families must list some of {FAMILIES}")
289
+ weights(s["synthetic_family_weights"], len(families), "synthetic_family_weights")
290
+ if s["stage"] == "stage1":
291
+ if (s["synthetic_context"] > model.context_length
292
+ or s["synthetic_context"] % model.patch_length):
293
+ raise ValueError("synthetic_context must be a multiple of patch_length within the "
294
+ "model's context")
295
+ check_far_region(model, s["synthetic_context"])
296
+ if s["synthetic_rows"] < 1:
297
+ raise ValueError("synthetic_rows must be positive")
298
+ else:
299
+ if not s["data"]:
300
+ raise ValueError("a stage2 run needs data")
301
+ from simons.training.schedule import parse_schedule
302
+
303
+ stages = parse_schedule(s["context_schedule"], s["steps"], model.context_length,
304
+ model.patch_length)
305
+ for context, _, _ in stages:
306
+ check_far_region(model, context)
307
+ if s["synthetic_only_stages"] >= len(stages):
308
+ raise ValueError("synthetic_only_stages must leave at least one real stage")
309
+ if s["warm_start"] is not None and not 0 <= s["warm_start_stage"] < len(stages):
310
+ raise ValueError("warm_start_stage must be a phase of the context schedule")
311
+
312
+ if not 0 <= s["shape_mix"] <= 1 or s["shape_cap"] <= 0:
313
+ raise ValueError("shape_mix must be from 0 to 1 and shape_cap positive")
314
+ if s["shape_mix"] > 0 and not s["shape_clusters"]:
315
+ raise ValueError("shape_mix needs shape_clusters (python -m simons.training "
316
+ "clusters writes it)")
317
+ if s["shape_mix"] > 0 and (s["shape_context"] % model.patch_length
318
+ or s["shape_context"] > model.near_context):
319
+ raise ValueError("shape_context must be a multiple of patch_length within "
320
+ "near_context")
321
+ return s
@@ -0,0 +1 @@
1
+ """Covariate training roles, window sampling and auxiliary losses."""