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,571 @@
1
+ """Train synthetic or mixed real/synthetic batches and export model checkpoints."""
2
+
3
+ import copy
4
+ import json
5
+ import os
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import torch
10
+ from torch.utils.data import DataLoader, Subset
11
+
12
+ from simons.model import Simons
13
+ from simons.synth import SyntheticMixer, mech, observe
14
+ from simons.synth import augment as synthetic_augment
15
+ from simons.training import config as config_module
16
+ from simons.training import network, objective, schedule
17
+ from simons.training.augment import RealAugmenter
18
+ from simons.training.data import (
19
+ MAX_VARIATES,
20
+ StepIndices,
21
+ Windows,
22
+ collate,
23
+ load,
24
+ pack_windows,
25
+ write_json,
26
+ )
27
+ from simons.training.distributed import Rank
28
+ from simons.training.optim import NorMuonAdamW
29
+ from simons.training.warp import power_warp
30
+
31
+ CHECKPOINT_FORMAT = "simons-train-1"
32
+ VALIDATION_WINDOWS = 1024
33
+
34
+
35
+ def device_for(name: str) -> torch.device:
36
+ if name == "auto":
37
+ name = "cuda" if torch.cuda.is_available() else "cpu"
38
+ return torch.device(name)
39
+
40
+
41
+ def read_checkpoint(path) -> dict:
42
+ """A training checkpoint.pt (or soup) on the CPU; raises unless it has the format."""
43
+ checkpoint = torch.load(path, map_location="cpu", weights_only=True)
44
+ if checkpoint.get("format") != CHECKPOINT_FORMAT:
45
+ raise ValueError(f"{path} is not a Simons training checkpoint")
46
+ return checkpoint
47
+
48
+
49
+ def write_checkpoint(path: Path, payload: dict):
50
+ """Save `payload` to `path` atomically (a temporary file, then a rename)."""
51
+ temporary = path.with_suffix(".pt.tmp")
52
+ torch.save(payload, temporary)
53
+ temporary.replace(path)
54
+
55
+
56
+ def save_checkpoint(path: Path, model, optimizer, settings, step, seconds):
57
+ write_checkpoint(path, {
58
+ "format": CHECKPOINT_FORMAT,
59
+ "model_config": model.config.to_dict(),
60
+ "training": settings,
61
+ "model": model.state_dict(),
62
+ "optimizer": optimizer.state_dict(),
63
+ "step": step,
64
+ "elapsed_seconds": seconds,
65
+ })
66
+
67
+
68
+ def load_weights(model, path, read_init: str = "keep") -> dict:
69
+ """Load checkpoint/model-folder weights, allowing missing covariate modules.
70
+ `read_init="variate"` resets the read from the variate block; "keep" retains saved weights."""
71
+ path = Path(path)
72
+ if path.is_dir():
73
+ from safetensors.torch import load_file
74
+
75
+ state = load_file(path / "model.safetensors")
76
+ info = {"source": str(path)}
77
+ else:
78
+ checkpoint = read_checkpoint(path)
79
+ state = checkpoint["model"]
80
+ info = {"source": str(path), "step": checkpoint["step"]}
81
+ if model.covariates is None:
82
+ model.load_state_dict(state, strict=True)
83
+ return info
84
+ missing, unexpected = model.load_state_dict(state, strict=False)
85
+ if unexpected or any(not k.startswith("covariates.") for k in missing):
86
+ raise ValueError(f"{path}: missing weights {missing[:4]}, unexpected {unexpected[:4]}")
87
+ read = model.covariates.read
88
+ if read is not None:
89
+ saved = any(k.startswith("covariates.read.") for k in state)
90
+ if read_init == "variate" or not saved:
91
+ init_read(read, model.variate_block)
92
+ info["read"] = "from the variate block"
93
+ else:
94
+ info["read"] = "kept"
95
+ return info
96
+
97
+
98
+ @torch.no_grad()
99
+ def init_read(read, variate_block):
100
+ """Copy the variate block into the one-way read with zero output writes."""
101
+ read.load_state_dict(variate_block.state_dict())
102
+ torch.nn.init.zeros_(read.out.weight)
103
+ torch.nn.init.zeros_(read.mlp[2].weight)
104
+ torch.nn.init.zeros_(read.mlp[2].bias)
105
+
106
+
107
+ def multi_pool(s, seed):
108
+ """Return a coupled multivariate synthetic pool, or None when disabled."""
109
+ if s["synthetic_multi_fraction"] <= 0:
110
+ return None
111
+ from simons.synth.multi import MultiPool
112
+
113
+ return MultiPool(s["synthetic_multi_fraction"], seed=seed * 6271 + 29)
114
+
115
+
116
+ def make_mixer(s, device, seed, first_step, pool_scale, fraction):
117
+ families = s["synthetic_families"].split(",")
118
+ gen = torch.Generator(device=device)
119
+ offset = (7883, 29) if s["stage"] == "stage1" else (7919, 17)
120
+ gen.manual_seed(seed * offset[0] + offset[1] + first_step)
121
+ view = None
122
+ if s["synthetic_observe"]:
123
+ view = observe.make_config(s["synthetic_observe"], s["synthetic_observe_rate"],
124
+ s["synthetic_observe_duty_periodic"])
125
+ return SyntheticMixer(
126
+ fraction, gen, families, s["synthetic_noise"], s["synthetic_pad"],
127
+ s["synthetic_pool_steps"] * pool_scale,
128
+ weights=config_module.weights(s["synthetic_family_weights"], len(families),
129
+ "synthetic_family_weights"),
130
+ multi=multi_pool(s, seed), observe=view,
131
+ )
132
+
133
+
134
+ def train(config_path: Path, output: Path, data: str | None = None,
135
+ warm_start: str | None = None, resume: Path | None = None,
136
+ covariate_data: str | None = None, max_steps: int | None = None,
137
+ shape_clusters: str | None = None):
138
+ """Train one YAML-configured stage and return its final checkpoint.pt path.
139
+ `output` must be new or empty; `max_steps` limits execution without changing the plan.
140
+ `warm_start` loads weights with a fresh optimizer; `resume` restores optimizer and step
141
+ but restarts random streams and role phases over the remaining steps."""
142
+ # Expandable CUDA segments avoid fragmentation from packed shapes changing every step.
143
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
144
+ model_config, s = config_module.load(config_path, {
145
+ "data": data, "warm_start": warm_start, "covariate_data": covariate_data,
146
+ "max_steps": max_steps, "shape_clusters": shape_clusters})
147
+ device = device_for(s["device"])
148
+ rank = Rank.from_env(device.type)
149
+ if rank.active and device.type == "cuda":
150
+ device = torch.device("cuda", rank.local)
151
+ stage1 = s["stage"] == "stage1"
152
+
153
+ torch.manual_seed(s["seed"])
154
+ torch.set_num_threads(min(torch.get_num_threads(), 4))
155
+ model = Simons(model_config).to(device)
156
+ warm = s["warm_start"] is not None
157
+ warm_info = None
158
+ if warm and resume is None:
159
+ warm_info = load_weights(model, s["warm_start"], s["covariate_read_init"])
160
+ rank.broadcast_model(model)
161
+ if not rank.main:
162
+ torch.manual_seed(rank.stream_seed(s["seed"]))
163
+ optimizer = NorMuonAdamW(model, muon_lr=s["muon_lr"], adam_lr=s["adam_lr"],
164
+ weight_decay=s["muon_weight_decay"],
165
+ mup_base_width=s["mup_base_width"])
166
+
167
+ patch = model_config.patch_length
168
+ future = network.future_steps(model_config)
169
+ if stage1:
170
+ stages = [(s["synthetic_context"], 0, s["steps"])]
171
+ else:
172
+ stages = schedule.parse_schedule(s["context_schedule"], s["steps"],
173
+ model_config.context_length, patch)
174
+ # Retain the re-warm origin on resume to preserve the learning-rate schedule.
175
+ warm_first = 0
176
+ if warm and s["warm_start_step"] is not None:
177
+ warm_first = s["warm_start_step"]
178
+ elif warm and not stage1:
179
+ warm_first = stages[s["warm_start_stage"]][1]
180
+ first_step, previous_seconds = warm_first, 0.0
181
+ if resume is not None:
182
+ state = read_checkpoint(resume)
183
+ model.load_state_dict(state["model"])
184
+ optimizer.load_state_dict(state["optimizer"])
185
+ first_step, previous_seconds = state["step"], state["elapsed_seconds"]
186
+ del state
187
+ if first_step >= s["steps"]:
188
+ raise ValueError("Nothing to train: the start step is past the plan's steps")
189
+ if rank.main:
190
+ if output.exists() and any(output.iterdir()):
191
+ raise FileExistsError("Use a fresh output directory, including for resume")
192
+ output.mkdir(parents=True, exist_ok=True)
193
+ write_json(output / "config.json", {"model": model_config.to_dict(), "training": s,
194
+ "first_step": first_step, "warm_start": warm_info})
195
+
196
+ synthetic_augment.configure(s["synthetic_augment"], s["synthetic_augment_rate"],
197
+ s["synthetic_augment_weights"])
198
+ mech.configure(s["mech_bank"], s["mech_length"], s["mech_refresh"], s["mech_refresh_part"])
199
+ stream = rank.stream_seed(s["seed"])
200
+ base_share = 1.0 if stage1 else s["synthetic_fraction"]
201
+ mixer = None
202
+ if base_share > 0:
203
+ mixer = make_mixer(s, device, stream, first_step, rank.world, base_share)
204
+ mixer.track_first = patch
205
+ share = schedule.share_function(stages, 0 if stage1 else s["synthetic_only_stages"],
206
+ s["synthetic_ramp_steps"], base_share)
207
+
208
+ roles_hook, passes = None, []
209
+ role_spec = config_module.covariate_roles(s)
210
+ if role_spec is not None:
211
+ from simons.training.covariates.roles import Hook
212
+
213
+ if mixer is None or mixer.multi is None:
214
+ raise ValueError("covariate roles need the run's synthetic mixer with coupled groups")
215
+ roles_hook = Hook(role_spec, stream, first_step, device, s["steps"] - first_step,
216
+ s["synthetic_context"] + future)
217
+ mixer.multi.roles = roles_hook.planner
218
+ if s["covariate_weight"] > 0:
219
+ passes = covariate_passes(s, model_config, rank, stream, first_step, device)
220
+
221
+ global_batch = s["synthetic_rows"] if stage1 else s["batch_size"]
222
+ rank_offset, rank_batch = rank.split(global_batch)
223
+ windows, mixture, validation = None, None, []
224
+ if not stage1:
225
+ train_set = load(s["data"], "train")
226
+ windows = Windows(train_set, model_config.context_length + future - 1, 1,
227
+ s["steps"] * global_batch, s["seed"],
228
+ downsample=s["augment_downsample"],
229
+ downsample_max=s["augment_downsample_max"],
230
+ stretch=s["augment_stretch"], stretch_up=s["augment_stretch_up"],
231
+ stitch_index=s["stitch_from_stage"] >= 0)
232
+ mixture = plan_mixture(s, model_config, windows, train_set, stages, share, future,
233
+ global_batch)
234
+ if s["shape_mix"] > 0:
235
+ from simons.training import clusters
236
+
237
+ windows.shape_labels = clusters.load(s["shape_clusters"], windows)
238
+ if s["validation_data"] and rank.main:
239
+ held_out = Windows(load(s["validation_data"], "validation"),
240
+ model_config.context_length, model_config.prediction_length,
241
+ VALIDATION_WINDOWS, 0)
242
+ samples = [held_out[i] for i in range(len(held_out))]
243
+ validation = [pack_windows(samples[i: i + 64]) for i in range(0, len(samples), 64)]
244
+
245
+ def stage_loader(index, context, start, end):
246
+ if stage1:
247
+ rows = (rank_batch, MAX_VARIATES, context + future)
248
+ empty = (torch.full(rows, float("nan")), torch.full(rows[:2], -1, dtype=torch.long),
249
+ torch.zeros(rows[:2], dtype=torch.long))
250
+ return (empty for _ in range(max(start, first_step), end))
251
+ staged = stage_window_sampler(s, model_config, windows, mixture, index, context, future)
252
+ return DataLoader(
253
+ Subset(staged, StepIndices(max(start, first_step), end, global_batch, rank_offset,
254
+ rank_batch)),
255
+ batch_size=rank_batch, collate_fn=collate(patch),
256
+ num_workers=rank.loader_workers(s["loader_workers"]) if device.type == "cuda" else 0,
257
+ pin_memory=device.type == "cuda", generator=torch.Generator(),
258
+ )
259
+
260
+ def batches():
261
+ for index, (context, start, end) in enumerate(stages):
262
+ if end > first_step:
263
+ for item in stage_loader(index, context, start, end):
264
+ yield index, item
265
+
266
+ augmenter = RealAugmenter(None, s["augment_censor"], s["augment_amplitude"],
267
+ s["augment_sign_flip"], s["augment_time_flip"], s["augment_mixup"],
268
+ s["augment_mixup_alpha"])
269
+ warp_gen = None
270
+ if not stage1:
271
+ if augmenter.active:
272
+ augmenter.gen = torch.Generator(device=device)
273
+ augmenter.gen.manual_seed(stream * 104729 + 31 + first_step)
274
+ if s["augment_warp"] > 0:
275
+ warp_gen = torch.Generator(device=device)
276
+ warp_gen.manual_seed(stream * 7907 + 43 + first_step)
277
+
278
+ bf16 = device.type == "cuda" and torch.cuda.is_bf16_supported(including_emulation=False)
279
+ autocast = torch.autocast("cuda", torch.bfloat16, enabled=bf16)
280
+ model.train()
281
+ started, paused = time.monotonic(), 0.0
282
+ step, logged, pass_logged = first_step, [], {}
283
+ nonfinite = torch.zeros((), dtype=torch.bool, device=device)
284
+
285
+ def check_finite():
286
+ if bool(nonfinite) or not all(bool(torch.isfinite(x)) for x in logged):
287
+ raise FloatingPointError(f"Non-finite loss or gradient by step {step}")
288
+
289
+ def elapsed():
290
+ return previous_seconds + time.monotonic() - started - paused
291
+
292
+ def sync():
293
+ if device.type == "cuda":
294
+ torch.cuda.synchronize(device)
295
+
296
+ log = (output / "training.jsonl").open("w") if rank.main else None
297
+
298
+ def write_log(rate, stage):
299
+ """Log interval means with every rank participating in covariate-loss reductions."""
300
+ nonlocal logged, pass_logged
301
+ check_finite()
302
+ losses = torch.stack(logged).float()
303
+ record = {"step": step, "loss": float(losses.mean())}
304
+ for name, values in pass_logged.items():
305
+ value = torch.stack(values).float().mean()
306
+ if rank.active:
307
+ value = rank.mean_value(value)
308
+ record[f"{name}_loss"] = float(value)
309
+ if rank.main:
310
+ log.write(json.dumps({**record, "lr_multiplier": round(rate, 6), "phase": stage,
311
+ "seconds": round(elapsed(), 1)}) + "\n")
312
+ log.flush()
313
+ logged, pass_logged = [], {}
314
+
315
+ try:
316
+ for stage, (sequence, series_ids, slot_first) in batches():
317
+ far_on = stage1 or stage >= s["far_from_stage"]
318
+ if mixer is not None:
319
+ if stage > 0:
320
+ mixer.pool_steps = s["synthetic_pool_steps_long"] * rank.world
321
+ mixer.fraction = share(step)
322
+ keep = None
323
+ if mixer.fraction > base_share:
324
+ rows = len(sequence)
325
+ keep = schedule.ramp_rows(rows, mixer.fraction, base_share)
326
+ if keep is not None and len(keep):
327
+ sequence, series_ids, slot_first = (sequence[keep], series_ids[keep],
328
+ slot_first[keep])
329
+ mixer.fraction = schedule.ramp_fraction(rows, len(keep), base_share)
330
+ if roles_hook is not None:
331
+ # Prefetched pools use the preceding step's role phase, except at the first step.
332
+ roles_hook.planner.step = max(step - 1, first_step) - first_step
333
+ host_ids = series_ids.numpy().copy()
334
+ host_first = slot_first.numpy().copy()
335
+ sequence = sequence.to(device, non_blocking=True)
336
+ series_ids = series_ids.to(device, non_blocking=True)
337
+ synthetic_rows = round(mixer.fraction * len(sequence)) if mixer is not None else 0
338
+ if warp_gen is not None:
339
+ sequence = power_warp(sequence, series_ids, len(sequence) - synthetic_rows,
340
+ warp_gen, s["augment_warp"],
341
+ convex=s["augment_warp_convex"])
342
+ if augmenter.active:
343
+ sequence = augmenter(sequence, series_ids, len(sequence) - synthetic_rows)
344
+ far_len = 0
345
+ if not stage1:
346
+ spec = network.layout(model_config, sequence.shape[-1])
347
+ far_len = spec[0] if spec is not None else 0
348
+ if mixer is not None and far_len:
349
+ rows = len(sequence)
350
+ tail, series_ids = mixer(sequence[..., far_len:], series_ids)
351
+ sequence = torch.cat([sequence[..., :far_len], tail], -1)
352
+ sequence[rows - round(mixer.fraction * rows):, :, :far_len] = float("nan")
353
+ mixer.first_offset = far_len // patch
354
+ elif mixer is not None:
355
+ mixer.first_offset = 0
356
+ sequence, series_ids = mixer(sequence, series_ids)
357
+
358
+ def host_slots(host_ids=host_ids, host_first=host_first):
359
+ if mixer is not None and mixer.last_first is not None:
360
+ rows, width = host_ids.shape
361
+ count = round(mixer.fraction * rows)
362
+ host_ids[rows - count:] = mixer.host_ids(count, width)
363
+ host_first[rows - count:] = mixer.first_rows().reshape(count, width)
364
+ return host_ids, host_first
365
+
366
+ roles = None
367
+ if roles_hook is not None:
368
+ sequence, series_ids, host_slots, roles = roles_hook.prepare(
369
+ step - first_step, mixer, sequence, series_ids, host_slots,
370
+ far_offset=far_len)
371
+ rate = schedule.multiplier(step, s, warm_first, warm)
372
+ for group in optimizer.param_groups:
373
+ group["lr"] = group["peak_lr"] * rate
374
+ optimizer.zero_grad(set_to_none=True)
375
+ with autocast:
376
+ loss, count = objective.packed_loss(
377
+ model, sequence, host_slots, s["mask_rate_max"], s["mask_span_max"],
378
+ far_on=far_on, row_tokens=s["pack_row_tokens"] if far_on else 0,
379
+ checkpoint_blocks=s["checkpoint_blocks"], roles=roles,
380
+ micro_batches=s["micro_batches"], rank=rank)
381
+ if s["micro_batches"] > 1:
382
+ mean_loss = loss
383
+ else:
384
+ objective_loss, mean_loss = rank.scale_loss(loss, count)
385
+ objective_loss.backward()
386
+ for name, cov_pass in passes:
387
+ with autocast:
388
+ cov_loss = cov_pass.loss(model)
389
+ (cov_pass.weight * pass_objective(cov_loss, cov_pass, s, rank, name)).backward()
390
+ pass_logged.setdefault(name, []).append(cov_loss.detach())
391
+ rank.average_gradients(model)
392
+ norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
393
+ nonfinite |= ~torch.isfinite(norm)
394
+ optimizer.step()
395
+ step += 1
396
+ logged.append(mean_loss.detach())
397
+ if step % s["log_every"] == 0 or step == s["steps"]:
398
+ write_log(rate, stage)
399
+ if s["max_steps"] is not None and step - first_step >= s["max_steps"]:
400
+ break
401
+ if step % s["checkpoint_every"] == 0 and step < s["steps"]:
402
+ sync()
403
+ check_finite()
404
+ pause = time.monotonic()
405
+ if rank.main:
406
+ checkpoint(output, model, optimizer, s, step, elapsed(), validation, device,
407
+ autocast, log)
408
+ rank.barrier()
409
+ paused += time.monotonic() - pause
410
+ sync()
411
+ if logged:
412
+ write_log(rate, stage)
413
+ check_finite()
414
+ if rank.main:
415
+ checkpoint(output, model, optimizer, s, step, elapsed(), validation, device, autocast,
416
+ log)
417
+ covariates = {}
418
+ if roles_hook is not None:
419
+ covariates["roles"] = roles_hook.summary()
420
+ for name, cov_pass in passes:
421
+ covariates[name] = cov_pass.summary()
422
+ write_json(output / "run.json", {
423
+ "status": "completed" if step == s["steps"] else "partial",
424
+ "steps": step, "steps_this_run": step - first_step,
425
+ "elapsed_seconds": elapsed(),
426
+ "parameters": sum(p.numel() for p in model.parameters()),
427
+ **({"peak_memory_gb": round(torch.cuda.max_memory_allocated(device) / 2**30, 2)}
428
+ if device.type == "cuda" else {}),
429
+ **({"covariates": covariates} if covariates else {}),
430
+ })
431
+ rank.barrier()
432
+ finally:
433
+ if log is not None:
434
+ log.close()
435
+ for _, cov_pass in passes:
436
+ cov_pass.close()
437
+ rank.close()
438
+ return output / "checkpoint.pt"
439
+
440
+
441
+ def covariate_passes(s, model_config, rank, stream_seed, first_step, device):
442
+ """[(name, CovariateStream)] of a stage2 run: the main pass and, with `long_weight`, the
443
+ long pass. Each GPU draws its share of the pass's tokens from its own random stream."""
444
+ from simons.training.covariates import stream
445
+
446
+ mix = config_module.weights(s["covariate_mix"], 3, "covariate_mix")
447
+ main = {
448
+ "future": network.future_steps(model_config), "fovea_near": model_config.near_context,
449
+ "fovea_pool": model_config.far_pool,
450
+ "base": s["covariate_base_data"] or s["data"], "real": s["covariate_data"],
451
+ "weight": s["covariate_weight"], "history_weight": s["covariate_history_weight"],
452
+ "mix": dict(zip(("synthetic", "sibling", "real"), mix)),
453
+ "tokens": -(-int(s["covariate_tokens"]) // rank.world),
454
+ "max_batch": int(s["covariate_max_batch"]), "workers": int(s["covariate_workers"]),
455
+ "source_weights": s["covariate_source_weights"], "exclude": s["covariate_exclude"],
456
+ }
457
+ # Keep worker count fixed: each worker contributes its own random stream.
458
+ out = [("covariate", stream.CovariateStream(main, stream_seed, first_step, device))]
459
+ if s["long_weight"] > 0:
460
+ tokens = s["long_tokens"] or s["covariate_tokens"]
461
+ long = stream.long_spec(main, {
462
+ "weight": s["long_weight"], "tokens": -(-int(tokens) // rank.world),
463
+ "workers": int(s["long_workers"]), "min_length": int(s["long_min_length"]),
464
+ "min_observed": float(s["long_min_observed"])})
465
+ out.append(("long", stream.CovariateStream(long, stream_seed, first_step, device)))
466
+ return out
467
+
468
+
469
+ def pass_objective(loss, cov_pass, s, rank, name):
470
+ """Scale covariate loss for gradient averaging using a global weighted mean or rank means."""
471
+ if not rank.active or (name == "covariate" and s["covariate_norm"] == "rank"):
472
+ return loss
473
+ import torch.distributed as dist
474
+
475
+ local = cov_pass.last_weight_sum.to(torch.float64).reshape(1)
476
+ total = local.clone()
477
+ dist.all_reduce(total)
478
+ return loss * (rank.world * local[0] / total[0].clamp_min(1.0)).to(loss.dtype)
479
+
480
+
481
+ def checkpoint(output, model, optimizer, s, step, seconds, validation, device, autocast, log):
482
+ if validation:
483
+ loss = objective.validation_loss(model, validation, device, autocast)
484
+ log.write(json.dumps({"step": step, "validation_loss": loss}) + "\n")
485
+ log.flush()
486
+ save_checkpoint(output / "checkpoint.pt", model, optimizer, s, step, seconds)
487
+
488
+
489
+ def stage_window_sampler(s, model_config, windows, mixture, index, context, future):
490
+ """The window sampler of curriculum phase `index` (context `context`)."""
491
+ staged = copy.copy(windows)
492
+ staged.context = context + future - 1
493
+ near = model_config.near_context
494
+ if context > near:
495
+ staged.end_min = near + future
496
+ if 0 <= s["stitch_from_stage"] <= index:
497
+ staged.stitch = True
498
+ if mixture is not None:
499
+ staged.weights, _ = mixture.weights(*stage_spec(staged, context, future, near))
500
+ labels = getattr(windows, "shape_labels", None)
501
+ if labels is not None:
502
+ from simons.training.clusters import StageTable
503
+
504
+ staged.shape = StageTable(labels[0], windows, staged.weights, labels[1], s["shape_cap"],
505
+ s["shape_mix"])
506
+ return staged
507
+
508
+
509
+ def stage_spec(staged, context, future, near):
510
+ """Mixture.weights arguments for a phase: window length, window ends, downsampling,
511
+ loss-bearing steps and stretching."""
512
+ trained = near + future if context > near else context + future
513
+ return (context + future, staged.end_min, staged.downsample, staged.downsample_max,
514
+ staged.downsample_min_points, trained, staged.stretch, staged.stretch_up)
515
+
516
+
517
+ def plan_mixture(s, model_config, windows, train_set, stages, share, future, global_batch):
518
+ """Build the UniMax mixture matching the run's expected real-token budget."""
519
+ from simons.training.mixture import Mixture, plan_budget, source_meta
520
+
521
+ meta = source_meta(train_set)
522
+
523
+ def make(budget):
524
+ return Mixture(windows.names, windows.shapes, meta, float(s["mixture_cap_epochs"]), budget)
525
+
526
+ specs = []
527
+ near = model_config.near_context
528
+ for index, (context, start, end) in enumerate(stages):
529
+ staged = stage_window_sampler({**s, "stitch_from_stage": -1}, model_config, windows,
530
+ None, index, context, future)
531
+ specs.append((end - start, stage_spec(staged, context, future, near)))
532
+ budget, _ = plan_budget(make, specs, global_batch, schedule.stage_shares(share, stages))
533
+ return make(float(budget))
534
+
535
+
536
+ def build_clusters(config_path: Path, embedder: Path, output: Path, data: str | None = None):
537
+ """Write shape-cluster labels for a stage2 corpus using a frozen checkpoint/model folder."""
538
+ from simons.training import clusters
539
+
540
+ model_config, s = config_module.load(config_path,
541
+ {"data": None if data is None else str(data)})
542
+ device = device_for(s["device"])
543
+ model = Simons(model_config).to(device)
544
+ info = {"embedder": str(embedder), **load_weights(model, embedder)}
545
+ future = network.future_steps(model_config)
546
+ windows = Windows(load(s["data"], "train"), model_config.context_length + future - 1, 1, 1,
547
+ 0)
548
+ labels, built = clusters.build_labels(model, windows, s["shape_k"], s["shape_anchors"],
549
+ s["shape_context"], s["shape_table_seed"],
550
+ s["shape_shards"], device)
551
+ clusters.save(output, labels, {**built, **info}, windows)
552
+ return output
553
+
554
+
555
+ def export(checkpoint_path: Path, output: Path, context_length: int | None = None):
556
+ """Export a checkpoint or soup to config.json and model.safetensors; return `output`."""
557
+ from dataclasses import replace
558
+
559
+ from simons.config import SimonsConfig
560
+
561
+ checkpoint = read_checkpoint(checkpoint_path)
562
+ known = {k: v for k, v in checkpoint["model_config"].items() if k != "model_type"}
563
+ config = SimonsConfig(**known)
564
+ model = Simons(config)
565
+ model.load_state_dict(checkpoint["model"], strict=True)
566
+ context_length = context_length or checkpoint["training"].get("export_context_length")
567
+ if context_length:
568
+ model.config = replace(config, context_length=int(context_length))
569
+ model.save_pretrained(output)
570
+ return output
571
+