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,140 @@
1
+ """Token-budgeted real-data mixture with hierarchical UniMax repetition caps."""
2
+
3
+ import numpy as np
4
+
5
+ from simons.training.data import MAX_VARIATES, column
6
+
7
+
8
+ def waterfill(budget: float, caps) -> np.ndarray:
9
+ """Divide a budget equally under per-item caps, redistributing surplus.
10
+ If the budget exceeds all caps, allocate in proportion to caps."""
11
+ caps = np.asarray(caps, dtype=float)
12
+ total = caps.sum()
13
+ if total <= 0:
14
+ return np.zeros_like(caps)
15
+ if budget >= total:
16
+ return caps * (budget / total)
17
+ out = np.empty_like(caps)
18
+ remaining = budget
19
+ order = np.argsort(caps, kind="stable")
20
+ for i, index in enumerate(order):
21
+ take = min(remaining / (len(caps) - i), caps[index])
22
+ out[index] = take
23
+ remaining -= take
24
+ return out
25
+
26
+
27
+ def draw_tokens(shapes: np.ndarray, length: int, end_min: int = 0, downsample: float = 0.0,
28
+ downsample_max: int = 8, min_points: int = 512, trained: int = 0,
29
+ stretch: float = 0.0, stretch_up: float = 0.5) -> float:
30
+ """Return expected observed values per draw for series shapes [n,2] (variates,steps).
31
+ `trained` > 0 counts only the last `trained` window steps."""
32
+ keep = trained or length
33
+ variates = np.minimum(shapes[:, 0], MAX_VARIATES).astype(float)
34
+ steps = shapes[:, 1].astype(float)
35
+ natural = np.minimum(steps, length)
36
+ if end_min:
37
+ a, b = float(end_min), steps
38
+ long = steps > end_min
39
+ mean_end = np.where(
40
+ length >= b, (a + b) / 2,
41
+ np.where(length <= a, length,
42
+ ((length ** 2 - a ** 2) / 2 + length * (b - length)) / np.maximum(b - a, 1)),
43
+ )
44
+ natural = np.where(long, mean_end, natural)
45
+ natural = np.minimum(natural, keep)
46
+ if stretch > 0:
47
+ from simons.training.warp import expected_steps
48
+
49
+ stretched = np.minimum(expected_steps(steps, length, stretch_up, min_points), keep)
50
+ natural = (1 - stretch) * natural + stretch * stretched
51
+ if downsample > 0:
52
+ cap = np.minimum(downsample_max, steps // max(1, min_points))
53
+ pooled = np.minimum(steps, length)
54
+ for c in np.unique(cap[cap >= 2]).astype(int):
55
+ ks = np.arange(2, c + 1)
56
+ p = (np.log(ks + 1) - np.log(ks)) / (np.log(c + 1) - np.log(2))
57
+ rows = cap == c
58
+ per_k = np.minimum(steps[rows, None] // ks[None, :], length)
59
+ pooled[rows] = np.minimum(per_k, keep) @ p
60
+ pooled = np.minimum(pooled, keep)
61
+ natural = (1 - downsample) * natural + downsample * pooled
62
+ return float((variates * natural).mean())
63
+
64
+
65
+ _PER_DRAW = {}
66
+
67
+
68
+ class Mixture:
69
+ """Per-source token budgets for a `Windows` sampler's sources (its `names`, `shapes`)."""
70
+
71
+ def __init__(self, names, shapes, meta, cap_epochs=4.0, budget_tokens=6.4e9):
72
+ self.names, self.shapes = list(names), shapes
73
+ self.capacity = np.array([float((np.minimum(s[:, 0], MAX_VARIATES) * s[:, 1]).sum())
74
+ for s in shapes])
75
+ self.meta = meta
76
+ self.groups = [self.group_of(name) for name in self.names]
77
+ keys = sorted(set(self.groups))
78
+ index = {k: i for i, k in enumerate(keys)}
79
+ member = np.array([index[g] for g in self.groups])
80
+ caps = cap_epochs * self.capacity
81
+ group_caps = np.bincount(member, weights=caps, minlength=len(keys))
82
+ group_budget = waterfill(budget_tokens, group_caps)
83
+ self.budget = np.zeros(len(self.names))
84
+ for g in range(len(keys)):
85
+ rows = np.flatnonzero(member == g)
86
+ self.budget[rows] = waterfill(group_budget[g], caps[rows])
87
+ self.share = self.budget / self.budget.sum()
88
+ self.epochs = self.budget / np.maximum(self.capacity, 1)
89
+
90
+ def group_of(self, name):
91
+ m = self.meta.get(name, {})
92
+ return f"{m.get('domain', '?')}/{m.get('subdomain', '?')}"
93
+
94
+ def weights(self, length, end_min=0, downsample=0.0, downsample_max=8, min_points=512,
95
+ trained=0, stretch=0.0, stretch_up=0.5):
96
+ """Return per-source draw probabilities and expected tokens per draw for a phase."""
97
+ spec = (length, end_min, downsample, downsample_max, min_points, trained, stretch,
98
+ stretch_up)
99
+ cached = _PER_DRAW.get(id(self.shapes))
100
+ if cached is None or cached[0] is not self.shapes:
101
+ cached = (self.shapes, {})
102
+ _PER_DRAW[id(self.shapes)] = cached
103
+ per_draw = cached[1].get(spec)
104
+ if per_draw is None:
105
+ per_draw = np.array([draw_tokens(s, length, end_min, downsample, downsample_max,
106
+ min_points, trained, stretch, stretch_up)
107
+ for s in self.shapes])
108
+ cached[1][spec] = per_draw
109
+ per_draw = per_draw.copy()
110
+ w = self.share / np.maximum(per_draw, 1.0)
111
+ return w / w.sum(), per_draw
112
+
113
+
114
+ def plan_budget(make, stages, batch_size, synthetic_shares, rounds=4, start=6.4e9):
115
+ """Return (expected real-token budget, real tokens per step of each phase).
116
+ `make(B)` builds a Mixture; `stages` holds (steps, draw_tokens arguments) pairs."""
117
+ budget, per_step = float(start), []
118
+ for _ in range(rounds):
119
+ mixture = make(budget)
120
+ total, per_step = 0.0, []
121
+ for (steps, spec), share in zip(stages, synthetic_shares):
122
+ p, t = mixture.weights(*spec)
123
+ tokens = batch_size * (1 - share) * float(p @ t)
124
+ per_step.append(tokens)
125
+ total += steps * tokens
126
+ budget = total
127
+ return budget, per_step
128
+
129
+
130
+ def source_meta(dataset) -> dict:
131
+ """{source: {domain, subdomain}} from the dataset columns (those it has), from each source's
132
+ first row."""
133
+ columns = set(dataset.column_names)
134
+ names = column(dataset, "source")
135
+ cols = {c: column(dataset, c) for c in ("domain", "subdomain") if c in columns}
136
+ meta = {}
137
+ for i, name in enumerate(names):
138
+ if name not in meta:
139
+ meta[name] = {c: cols[c][i] for c in cols}
140
+ return meta
@@ -0,0 +1,115 @@
1
+ """Packed and covariate training passes over the shared Simons model."""
2
+
3
+ import math
4
+
5
+ import torch
6
+ from torch.nn import functional as F
7
+ from torch.utils.checkpoint import checkpoint
8
+
9
+ from simons.model import QUANTILES, front, future_steps, layout # noqa: F401
10
+
11
+
12
+ def trunk(model, tokens: torch.Tensor, rotary, started: torch.Tensor, segments: torch.Tensor,
13
+ far: torch.Tensor | None = None, checkpoint_blocks: int = 0, roles=None,
14
+ fp32_residual: bool = False) -> torch.Tensor:
15
+ """Return packed quantiles [B,V,S,patch,9] in asinh units.
16
+ Inputs: tokens [B,V,S,2p], rotary [B*V,1,S,half], started/segments [B,V,S] (-1: filler).
17
+ Far flags: [B,V,S], [S] or None; roles: [B,V,S], [B,V] or None."""
18
+ batch, variates, patches, _ = tokens.shape
19
+ x = model.embed(tokens) + model.embed_mlp(tokens)
20
+ if far is not None:
21
+ x = x + far[..., None].to(x.dtype) * model.far_type
22
+ if fp32_residual:
23
+ x = x.float()
24
+ read_after = -1
25
+ if roles is not None:
26
+ vectors = model.covariates.role_vectors(roles)
27
+ x = x + (vectors if roles.dim() == 3 else vectors[:, :, None]).to(x.dtype)
28
+ if model.covariates.read is not None:
29
+ read_after = model.config.read_after
30
+ x = x.reshape(batch * variates, patches, -1)
31
+ segment = segments.reshape(batch * variates, patches)
32
+ start = started.reshape(batch * variates, patches)
33
+ position = torch.arange(patches, device=tokens.device)
34
+ query, key = position[:, None], position[None, :]
35
+ allowed = (segment[:, :, None] == segment[:, None, :]) & (key <= query)[None]
36
+ allowed &= start[:, None, :] | (key == query)[None]
37
+ mask = allowed[:, None]
38
+ ids = segments.transpose(1, 2) # [B,S,V]
39
+ related = (ids[..., :, None] == ids[..., None, :]).reshape(batch * patches, 1, variates,
40
+ variates)
41
+ for index, block in enumerate(model.time_blocks):
42
+ if index < checkpoint_blocks and torch.is_grad_enabled():
43
+ x = checkpoint(block, x, mask, rotary, use_reentrant=False)
44
+ else:
45
+ x = block(x, mask, rotary=rotary)
46
+ if index == read_after:
47
+ if roles.dim() == 3:
48
+ x = packed_read(model.covariates.read, x, segments, roles)
49
+ else:
50
+ x = model.covariates.read_rows(x, related, batch, variates, patches, roles)
51
+ x = x.reshape(batch, variates, patches, -1).transpose(1, 2).reshape(batch * patches,
52
+ variates, -1)
53
+ x = model.variate_block(x, related)
54
+ x = x.reshape(batch, patches, variates, -1).transpose(1, 2)
55
+ return quantiles(model, x)
56
+
57
+
58
+ def packed_read(block, x, segments, roles):
59
+ """Update target tokens x [R*V,S,D] from covariates of the same window and position.
60
+ `segments` and `roles` have shape [R,V,S]."""
61
+ from simons.covariates import ROLE_BINARY, ROLE_FIT, ROLE_KNOWN, ROLE_TARGET
62
+
63
+ rows, variates, size = segments.shape
64
+ xm = x.reshape(rows, variates, size, -1).transpose(1, 2).reshape(rows * size, variates, -1)
65
+ ids = segments.transpose(1, 2) # [R,S,V]
66
+ r = roles.transpose(1, 2)
67
+ keys = (r == ROLE_KNOWN) | (r == ROLE_FIT) | (r == ROLE_BINARY)
68
+ queries = (r == ROLE_TARGET) & (ids >= 0)
69
+ related = ids[..., :, None] == ids[..., None, :]
70
+ cross = queries[..., :, None] & keys[..., None, :] & related # [R,S,V,V]
71
+ update = cross.any(-1).reshape(rows * size, variates, 1)
72
+ eye = torch.eye(variates, dtype=torch.bool, device=segments.device)
73
+ mask = (cross | eye).reshape(rows * size, 1, variates, variates)
74
+ y = block(xm, mask)
75
+ out = xm + update.to(xm.dtype) * (y - xm)
76
+ return out.reshape(rows, size, variates, -1).transpose(1, 2).reshape(rows * variates, size,
77
+ -1)
78
+
79
+
80
+ def covariate_forward(model, values: torch.Tensor, series_ids: torch.Tensor,
81
+ covariates: torch.Tensor, fit_keep: torch.Tensor | None = None):
82
+ """Return next-patch quantiles [B,V,P,patch,9], loc/scale [B,V,P]; P = T / patch.
83
+ Values [B,V,T] and covariates [B,C,T] span history and future; `fit_keep` [B] selects fits."""
84
+ from simons.covariates import ROLE_BINARY, covariate_rows
85
+
86
+ c = model.config
87
+ patch = c.patch_length
88
+ variates = values.shape[1]
89
+ grown = covariate_rows(c, values, series_ids, covariates, fit_keep)
90
+ roles, fixed = None, None
91
+ if grown is not None:
92
+ values, series_ids, roles = grown
93
+ fixed = (roles == ROLE_BINARY) if c.binary_rows else None
94
+ tokens, rotary, started, loc, scale, far, far_tokens = front(model, values, fixed=fixed)
95
+ batch, rows, size = started.shape
96
+ # Attention masks isolate skipped prefixes; retain at least the last history token.
97
+ last = size - math.ceil(c.prediction_length / patch) - 1
98
+ any_started = started.reshape(-1, size).any(0)
99
+ crop = int(torch.where(any_started, torch.arange(size, device=values.device), size)
100
+ .amin().clamp_max(last))
101
+ segments = series_ids[:, :, None].expand(batch, rows, size - crop)
102
+ q = trunk(model, tokens[:, :, crop:], tuple(t[:, :, crop:] for t in rotary),
103
+ started[:, :, crop:], segments, None if far is None else far[crop:], roles=roles)
104
+ q = F.pad(q, (0, 0, 0, 0, crop, 0), value=float("nan"))
105
+ if far_tokens:
106
+ pool = c.far_pool
107
+ q, loc, scale = (torch.cat([t[:, :, :far_tokens].repeat_interleave(pool, 2),
108
+ t[:, :, far_tokens:]], 2) for t in (q, loc, scale))
109
+ return q[:, :variates], loc[:, :variates], scale[:, :variates]
110
+
111
+
112
+ def quantiles(model, x: torch.Tensor) -> torch.Tensor:
113
+ """[..., width] features -> [..., patch, 9] sorted quantiles (asinh units), unclamped."""
114
+ raw = model.head(model.norm(x)).float()
115
+ return raw.unflatten(-1, (model.config.patch_length, len(QUANTILES))).sort(dim=-1).values
@@ -0,0 +1,193 @@
1
+ """Masked next-patch pinball loss on packed training rows."""
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch.nn import functional as F
8
+
9
+ from simons.model import QUANTILES
10
+ from simons.training import network, packing
11
+ from simons.training.data import MAX_VARIATES
12
+
13
+ MIN_CONTEXT_PATCHES = 1
14
+
15
+
16
+ def contiguous_patch_mask(shape, device, rate_max: float, span_max: int) -> torch.Tensor:
17
+ """[..., patches] hidden flags: per row a rate ~ U(0, rate_max) and span ~ U{1..span_max};
18
+ spans start at each patch with probability rate / span."""
19
+ patches = shape[-1]
20
+ span = torch.randint(1, span_max + 1, (*shape[:-1], 1), device=device)
21
+ rate = torch.rand(*shape[:-1], 1, device=device) * rate_max
22
+ starts = torch.rand(shape, device=device) < rate / span
23
+ position = torch.arange(patches, device=device)
24
+ latest = torch.where(starts, position, -span_max).cummax(dim=-1).values
25
+ return position - latest < span
26
+
27
+
28
+ def pinball_parts(prediction: torch.Tensor, target: torch.Tensor):
29
+ """(sum of pinball losses over observed targets and quantiles, their count), no host sync."""
30
+ observed = torch.isfinite(target)
31
+ error = torch.where(observed, target, 0.0).unsqueeze(-1) - prediction
32
+ levels = prediction.new_tensor(QUANTILES)
33
+ loss = torch.maximum(levels * error, (levels - 1) * error)
34
+ return (loss * observed.unsqueeze(-1)).sum(), observed.sum() * len(QUANTILES)
35
+
36
+
37
+ def pinball_loss(prediction: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
38
+ if prediction.shape[:-1] != target.shape or prediction.shape[-1] != len(QUANTILES):
39
+ raise ValueError("prediction and target shapes differ")
40
+ total, count = pinball_parts(prediction, target)
41
+ if not bool(count):
42
+ raise ValueError("Need at least one observed target")
43
+ return total / count
44
+
45
+
46
+ def token_first(raw_first, far_len: int, patch: int, pool: int, far_tokens: int):
47
+ """Map first observed raw-patch indices to tokens in the [far,near,future] layout.
48
+ When far tokens are dropped, far steps map to the first near token."""
49
+ step = raw_first * patch
50
+ far = step // (patch * pool) if far_tokens else step * 0
51
+ near = far_tokens + (step - far_len) // patch
52
+ return np.where(step < far_len, far, near)
53
+
54
+
55
+ def packed_loss(model, sequence, host_slots, mask_rate_max, mask_span_max, far_on=True,
56
+ row_tokens=0, checkpoint_blocks=0, roles=None, micro_batches=1, rank=None):
57
+ """Return (mean next-patch pinball loss, observed target count) for sequence [B,V,T].
58
+ `host_slots()` returns numpy window IDs and first observed patch indices [B,V].
59
+ With `micro_batches` > 1, this runs backward internally and returns a detached loss;
60
+ the caller must not back-propagate again."""
61
+ patch = model.config.patch_length
62
+ batch, variates, length = sequence.shape
63
+ spec = network.layout(model.config, length)
64
+ far_len = spec[0] if spec is not None else 0
65
+ near = sequence[..., far_len:]
66
+ patches = near.shape[-1] // patch
67
+ # Far tokens supply context only and must remain unmasked.
68
+ hidden = contiguous_patch_mask((batch, variates, patches), sequence.device, mask_rate_max,
69
+ mask_span_max)
70
+ if roles is not None:
71
+ hidden = roles.hidden(hidden)
72
+ observed = torch.isfinite(near).unflatten(-1, (-1, patch)).any(-1)
73
+ hidden &= observed.cumsum(-1) > MIN_CONTEXT_PATCHES
74
+ mask = hidden.repeat_interleave(patch, -1)
75
+ if far_len:
76
+ mask = F.pad(mask, (far_len, 0), value=False)
77
+ inputs = sequence.masked_fill(mask, float("nan"))
78
+ tokens, rotary, started, loc, scale, far, far_tokens = network.front(
79
+ model, inputs, far_on, fixed=None if roles is None else roles.fixed)
80
+ loc, scale = loc[..., far_tokens:], scale[..., far_tokens:]
81
+ target = near.unflatten(-1, (-1, patch))[:, :, 1:].double()
82
+ target = torch.asinh((target - loc[..., :-1, None]) / scale[..., :-1, None]).float()
83
+ seen = (observed & ~hidden).cummax(-1).values
84
+ target = target.masked_fill(~seen[..., :-1, None], float("nan"))
85
+ # Position i predicts patch i + 1; the last position and far tokens carry no target.
86
+ target = torch.cat([target, target.new_full((batch, variates, 1, patch), float("nan"))], 2)
87
+ if far_tokens:
88
+ target = torch.cat([target.new_full((batch, variates, far_tokens, patch), float("nan")),
89
+ target], 2)
90
+ if roles is not None:
91
+ target = roles.target(target)
92
+ size = far_tokens + patches
93
+
94
+ series_ids, slot_first = host_slots()
95
+ if far_len:
96
+ slot_first = token_first(slot_first, far_len, patch, model.config.far_pool, far_tokens)
97
+ source, segment, rows = packing.plan(series_ids.reshape(-1), slot_first.reshape(-1), size,
98
+ row_tokens=row_tokens)
99
+ unpacked, size = size, max(size, row_tokens)
100
+ source, segment = (torch.from_numpy(a) for a in (source, segment))
101
+ if sequence.is_cuda:
102
+ source, segment = (a.pin_memory().to(sequence.device, non_blocking=True)
103
+ for a in (source, segment))
104
+ shape = (rows, MAX_VARIATES, size)
105
+ gather = packing.gather
106
+ packed_tokens = gather(tokens.reshape(-1, tokens.shape[-1]), source).view(*shape, -1)
107
+ cos, sin = (gather(t.reshape(-1, t.shape[-1]), source) for t in rotary)
108
+ packed_rotary = tuple(t.view(rows * MAX_VARIATES, 1, size, -1) for t in (cos, sin))
109
+ packed_started = gather(started.reshape(-1), source, False).view(shape)
110
+ packed_target = gather(target.reshape(-1, patch), source, float("nan")).view(*shape, patch)
111
+ packed_far = None
112
+ if far is not None:
113
+ packed_far = gather(far.expand(batch, variates, unpacked).reshape(-1), source,
114
+ False).view(shape)
115
+ packed_roles = None
116
+ if roles is not None:
117
+ packed_roles = gather(roles.token_roles(unpacked).reshape(-1), source, 0).view(shape)
118
+ segment = segment.view(shape)
119
+ if micro_batches <= 1:
120
+ prediction = network.trunk(model, packed_tokens, packed_rotary, packed_started, segment,
121
+ packed_far, checkpoint_blocks, roles=packed_roles,
122
+ fp32_residual=True)
123
+ return pinball_loss(prediction, packed_target), torch.isfinite(packed_target).sum()
124
+ count = torch.isfinite(packed_target).sum()
125
+ world = rank.world if rank is not None and rank.active else 1
126
+ total = count.detach().to(torch.float64).reshape(1)
127
+ if world > 1:
128
+ import torch.distributed as dist
129
+
130
+ total = total.clone()
131
+ dist.all_reduce(total)
132
+ total = total[0].clamp_min(1.0)
133
+ chunks = chunk_bounds(rows, micro_batches)
134
+ counts = [int(torch.isfinite(packed_target[a:b]).sum()) for a, b in chunks]
135
+ summed = torch.zeros((), dtype=torch.float64, device=sequence.device)
136
+ for (a, b), n in zip(chunks, counts):
137
+ if n == 0:
138
+ continue
139
+ cut = slice(a * MAX_VARIATES, b * MAX_VARIATES)
140
+ prediction = network.trunk(
141
+ model, packed_tokens[a:b], tuple(t[cut] for t in packed_rotary),
142
+ packed_started[a:b], segment[a:b],
143
+ None if packed_far is None else packed_far[a:b], checkpoint_blocks,
144
+ roles=None if packed_roles is None else packed_roles[a:b], fp32_residual=True)
145
+ part, _ = pinball_parts(prediction, packed_target[a:b])
146
+ (part * (world / (total * len(QUANTILES))).to(part.dtype)).backward()
147
+ summed += part.detach().to(torch.float64)
148
+ if world > 1:
149
+ import torch.distributed as dist
150
+
151
+ dist.all_reduce(summed)
152
+ return (summed / (total * len(QUANTILES))).float(), count
153
+
154
+
155
+ def chunk_bounds(rows: int, chunks: int):
156
+ """Contiguous [a, b) row ranges, as equal as possible, none empty (at most `rows`)."""
157
+ chunks = max(1, min(chunks, rows))
158
+ base, extra = divmod(rows, chunks)
159
+ out, a = [], 0
160
+ for c in range(chunks):
161
+ b = a + base + (1 if c < extra else 0)
162
+ out.append((a, b))
163
+ a = b
164
+ return out
165
+
166
+
167
+ @torch.no_grad()
168
+ def validation_loss(model, batches, device, autocast) -> float | None:
169
+ """Mean pinball loss of the forecast patches of held-out (history, target, ids) batches."""
170
+ if not batches:
171
+ return None
172
+ was_training = model.training
173
+ model.eval()
174
+ patch, total, count = model.config.patch_length, 0.0, 0.0
175
+ for history, target, series_ids in batches:
176
+ history, target = history.to(device), target.to(device)
177
+ series_ids = series_ids.to(device)
178
+ future = math.ceil(target.shape[-1] / patch)
179
+ values = F.pad(history, (0, future * patch), value=float("nan"))
180
+ with autocast:
181
+ tokens, rotary, started, loc, scale, far, _ = network.front(model, values)
182
+ segments = series_ids[:, :, None].expand(*started.shape)
183
+ prediction = network.trunk(model, tokens, rotary, started, segments, far)
184
+ first = tokens.shape[2] - future - 1
185
+ window = slice(first, first + future)
186
+ goal = F.pad(target, (0, future * patch - target.shape[-1]), value=float("nan"))
187
+ goal = goal.unflatten(-1, (future, patch)).double()
188
+ goal = torch.asinh((goal - loc[..., window, None]) / scale[..., window, None]).float()
189
+ part, n = pinball_parts(prediction[:, :, window], goal)
190
+ total += float(part)
191
+ count += float(n)
192
+ model.train(was_training)
193
+ return total / max(count, 1.0)
@@ -0,0 +1,164 @@
1
+ """NorMuon for hidden matrices; AdamW for embeddings, head, norms, biases and covariate modules."""
2
+
3
+ import math
4
+
5
+ import torch
6
+
7
+ MOMENTUM = 0.95
8
+ ROW_BETA2 = 0.95
9
+ ADAM_BETAS = (0.9, 0.95)
10
+ EPS = 1e-8
11
+
12
+ # Polar Express coefficients use l=1e-3 and a 1.01 safety factor.
13
+ # Amsel et al. 2025, github.com/NoahAmsel/PolarExpress
14
+ _POLAR_RAW = [
15
+ (8.28721201814563, -23.595886519098837, 17.300387312530933),
16
+ (4.107059111542203, -2.9478499167379106, 0.5448431082926601),
17
+ (3.9486908534822946, -2.908902115962949, 0.5518191394370137),
18
+ (3.3184196573706015, -2.488488024314874, 0.51004894012372),
19
+ (2.300652019954817, -1.6689039845747493, 0.4188073119525673),
20
+ ]
21
+ POLAR_EXPRESS = [(a / 1.01, b / 1.01**3, c / 1.01**5) for a, b, c in _POLAR_RAW]
22
+
23
+
24
+ @torch.no_grad()
25
+ def orthogonalize(G: torch.Tensor) -> torch.Tensor:
26
+ """Approximate U V^T of a stack [k, m, n] of matrices."""
27
+ X = G.bfloat16()
28
+ tall = X.shape[-2] > X.shape[-1]
29
+ if tall:
30
+ X = X.mT
31
+ X = X / (X.norm(dim=(-2, -1), keepdim=True) * 1.01 + 1e-7)
32
+ for a, b, c in POLAR_EXPRESS:
33
+ A = X @ X.mT
34
+ B = b * A + c * (A @ A)
35
+ X = a * X + B @ X
36
+ if tall:
37
+ X = X.mT
38
+ return X
39
+
40
+
41
+ def split_parameters(model):
42
+ """(hidden matrices with their row-block counts, all other parameters)."""
43
+ hidden, splits = [], []
44
+ for block in [*model.time_blocks, model.variate_block]:
45
+ matrices = [
46
+ (block.qkv.weight, 3), # Orthogonalize fused q, k, v blocks separately.
47
+ (block.out.weight, 1),
48
+ (block.mlp[0].weight, 1),
49
+ (block.mlp[2].weight, 1),
50
+ ]
51
+ for weight, blocks in matrices:
52
+ hidden.append(weight)
53
+ splits.append(blocks)
54
+ hidden.append(model.embed_mlp[2].weight)
55
+ splits.append(1)
56
+ chosen = {id(p) for p in hidden}
57
+ other = [p for p in model.parameters() if id(p) not in chosen]
58
+ return hidden, splits, other
59
+
60
+
61
+ class NorMuonAdamW(torch.optim.Optimizer):
62
+ """NorMuon (hidden matrices) + AdamW (everything else) over a Simons model."""
63
+
64
+ def __init__(self, model, muon_lr: float = 1e-3, adam_lr: float = 1e-3,
65
+ weight_decay: float = 0.01, mup_base_width: int = 704):
66
+ hidden, splits, other = split_parameters(model)
67
+ head = {id(p) for p in model.head.parameters()}
68
+ rest = [p for p in other if id(p) not in head]
69
+ head_params = [p for p in other if id(p) in head]
70
+ hidden_lr = muon_lr * math.sqrt(mup_base_width / model.config.width)
71
+ head_lr = adam_lr * (mup_base_width / model.config.width)
72
+ groups = [
73
+ dict(params=hidden, splits=splits, kind="normuon", peak_lr=hidden_lr, lr=hidden_lr,
74
+ weight_decay=weight_decay),
75
+ dict(params=rest, splits=[1] * len(rest), kind="adamw", peak_lr=adam_lr, lr=adam_lr,
76
+ weight_decay=0.0),
77
+ dict(params=head_params, splits=[1] * len(head_params), kind="adamw", peak_lr=head_lr,
78
+ lr=head_lr, weight_decay=0.0),
79
+ ]
80
+ super().__init__(groups, {})
81
+
82
+ @staticmethod
83
+ def _decay_and_apply(params, updates, lr, wd):
84
+ if wd > 0:
85
+ mask = torch._foreach_mul(updates, params)
86
+ torch._foreach_sign_(mask)
87
+ torch._foreach_clamp_min_(mask, 0.0)
88
+ torch._foreach_mul_(mask, params)
89
+ torch._foreach_add_(updates, mask, alpha=wd)
90
+ torch._foreach_add_(params, updates, alpha=-lr)
91
+
92
+ def _adam(self, group, params):
93
+ beta1, beta2 = ADAM_BETAS
94
+ by_step = {}
95
+ for p in params:
96
+ state = self.state[p]
97
+ if not state:
98
+ state["step"] = 0
99
+ state["exp_avg"] = torch.zeros_like(p)
100
+ state["exp_avg_sq"] = torch.zeros_like(p)
101
+ state["step"] += 1
102
+ by_step.setdefault(state["step"], []).append(p)
103
+ for step, chosen in by_step.items():
104
+ grads = [p.grad for p in chosen]
105
+ m = [self.state[p]["exp_avg"] for p in chosen]
106
+ v = [self.state[p]["exp_avg_sq"] for p in chosen]
107
+ torch._foreach_lerp_(m, grads, 1 - beta1)
108
+ torch._foreach_mul_(v, beta2)
109
+ torch._foreach_addcmul_(v, grads, grads, value=1 - beta2)
110
+ denom = torch._foreach_sqrt(v)
111
+ torch._foreach_div_(denom, math.sqrt(1 - beta2**step))
112
+ torch._foreach_add_(denom, EPS)
113
+ updates = torch._foreach_div(m, denom)
114
+ torch._foreach_mul_(updates, 1 / (1 - beta1**step))
115
+ self._decay_and_apply(chosen, updates, group["lr"], group["weight_decay"])
116
+
117
+ def _normuon(self, group, params, splits):
118
+ bufs, grads = [], []
119
+ for p in params:
120
+ state = self.state[p]
121
+ if not state:
122
+ state["momentum"] = torch.zeros_like(p)
123
+ state["row_v"] = torch.zeros(p.shape[0], 1, device=p.device, dtype=torch.float32)
124
+ bufs.append(state["momentum"])
125
+ grads.append(p.grad)
126
+ torch._foreach_lerp_(bufs, grads, 1 - MOMENTUM)
127
+ nesterov = torch._foreach_lerp(grads, bufs, MOMENTUM)
128
+ by_shape = {}
129
+ for index, (u, blocks) in enumerate(zip(nesterov, splits)):
130
+ pieces = u.view(blocks, u.shape[0] // blocks, u.shape[1])
131
+ tall = pieces.shape[1] > pieces.shape[2]
132
+ if tall:
133
+ pieces = pieces.mT
134
+ by_shape.setdefault(tuple(pieces.shape[1:]), []).append((index, pieces, tall))
135
+ orthogonal = [None] * len(params)
136
+ for items in by_shape.values():
137
+ stack = torch.cat([pieces for _, pieces, _ in items])
138
+ out = orthogonalize(stack).float()
139
+ start = 0
140
+ for index, pieces, tall in items:
141
+ ortho = out[start : start + pieces.shape[0]]
142
+ orthogonal[index] = ortho.mT if tall else ortho
143
+ start += pieces.shape[0]
144
+ updates = []
145
+ for p, ortho in zip(params, orthogonal): # [blocks,m,n]
146
+ v = self.state[p]["row_v"].view(ortho.shape[0], ortho.shape[1], 1)
147
+ v.lerp_(ortho.square().mean(-1, keepdim=True), 1 - ROW_BETA2)
148
+ ortho = ortho / (v.sqrt() + EPS)
149
+ m, n = ortho.shape[1:]
150
+ scale = 0.2 * math.sqrt(m * n) / (ortho.norm(dim=(-2, -1), keepdim=True) + 1e-12)
151
+ updates.append((ortho * scale).reshape(p.shape).to(p.dtype))
152
+ self._decay_and_apply(params, updates, group["lr"], group["weight_decay"])
153
+
154
+ @torch.no_grad()
155
+ def step(self, closure=None):
156
+ for group in self.param_groups:
157
+ pairs = [(p, s) for p, s in zip(group["params"], group["splits"]) if p.grad is not None]
158
+ if not pairs:
159
+ continue
160
+ params = [p for p, _ in pairs]
161
+ if group["kind"] == "normuon":
162
+ self._normuon(group, params, [s for _, s in pairs])
163
+ else:
164
+ self._adam(group, params)