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,94 @@
1
+ """Pack training windows to skip leading NaN padding while isolating windows with segment masks."""
2
+
3
+ import numpy as np
4
+ import torch
5
+
6
+ from simons.training.data import MAX_VARIATES
7
+
8
+
9
+ def _guillotine(heights, spans, width, patches):
10
+ """Pack taller, then longer rectangles first, splitting free space right and below."""
11
+ n = len(heights)
12
+ order = np.lexsort((-spans, -heights))
13
+ cap = 3 * n + 3 # Each window adds at most a row and two splits.
14
+ big = np.iinfo(np.int64).max
15
+ fr = np.zeros(cap, np.int64)
16
+ fy = np.zeros(cap, np.int64)
17
+ fx = np.zeros(cap, np.int64)
18
+ fh = np.full(cap, -1, np.int64) # Mark unused entries so they never fit.
19
+ fw = np.full(cap, -1, np.int64)
20
+ key = np.full(cap, big, np.int64)
21
+ count, rows = 0, 0
22
+ row_of = np.empty(n, np.int64)
23
+ slot_of = np.empty(n, np.int64)
24
+ time_of = np.empty(n, np.int64)
25
+ stride_y, stride_r = patches + 1, (patches + 1) * (width + 1)
26
+ dead = 0
27
+ for i in order.tolist():
28
+ h, w = int(heights[i]), int(spans[i])
29
+ if dead > 64 and 2 * dead > count: # Unique keys preserve choices during compaction.
30
+ keep = np.flatnonzero(fh[:count] >= 0)
31
+ m = len(keep)
32
+ for a in (fr, fy, fx, fh, fw, key):
33
+ a[:m] = a[keep]
34
+ fh[m:count] = fw[m:count] = -1
35
+ key[m:count] = big
36
+ count, dead = m, 0
37
+ live_h, live_w = fh[:count], fw[:count]
38
+ j = int(np.where((live_h >= h) & (live_w >= w), key[:count], big).argmin()) if count else 0
39
+ if not count or fh[j] < h or fw[j] < w:
40
+ j = count
41
+ fr[j], fy[j], fx[j], fh[j], fw[j], key[j] = rows, 0, 0, width, patches, rows * stride_r
42
+ count += 1
43
+ rows += 1
44
+ r, y, x, H, W = int(fr[j]), int(fy[j]), int(fx[j]), int(fh[j]), int(fw[j])
45
+ fh[j] = fw[j] = -1
46
+ key[j] = big
47
+ dead += 1
48
+ row_of[i], slot_of[i], time_of[i] = r, y, x
49
+ for (ny, nx, nh, nw) in ((y, x + w, h, W - w), (y + h, x, H - h, W)):
50
+ if nh > 0 and nw > 0:
51
+ fr[count], fy[count], fx[count], fh[count], fw[count] = r, ny, nx, nh, nw
52
+ key[count] = r * stride_r + ny * stride_y + nx
53
+ count += 1
54
+ return row_of, slot_of, time_of, rows
55
+
56
+
57
+ def plan(slot_ids: np.ndarray, slot_first: np.ndarray, patches: int, width: int = MAX_VARIATES,
58
+ row_tokens: int = 0):
59
+ """Return (source,segment,rows) for flattened [R,W] IDs and first observed patches.
60
+ `source`/`segment` flatten [rows,width,patches]; -1 marks filler; windows stay aligned."""
61
+ unpacked = patches
62
+ patches = max(patches, row_tokens)
63
+ valid = np.flatnonzero(slot_ids >= 0)
64
+ slots = valid[np.argsort(slot_ids[valid], kind="stable")]
65
+ _, starts, counts = np.unique(slot_ids[slots], return_index=True, return_counts=True)
66
+ window_first = np.minimum.reduceat(slot_first[slots], starts)
67
+ span = unpacked - window_first
68
+ keep = span > 0
69
+ starts, counts, window_first, span = starts[keep], counts[keep], window_first[keep], span[keep]
70
+ windows = len(starts)
71
+ window_row, window_slot, time_offset, rows = _guillotine(counts, span, width, patches)
72
+ window_base = window_row * width + window_slot
73
+ run_window = np.repeat(np.arange(windows), counts)
74
+ run_variate = np.arange(len(run_window)) - np.repeat(np.cumsum(counts) - counts, counts)
75
+ run_slot = slots[np.repeat(starts, counts) + run_variate]
76
+ packed_slot = window_base[run_window] + run_variate
77
+ dest_start = packed_slot * patches + time_offset[run_window]
78
+ source_start = run_slot * unpacked + window_first[run_window]
79
+ length = span[run_window]
80
+ total = int(length.sum())
81
+ within = np.arange(total) - np.repeat(np.cumsum(length) - length, length)
82
+ dest = np.repeat(dest_start, length) + within
83
+ source = np.full(rows * width * patches, -1, dtype=np.int64)
84
+ segment = np.full(rows * width * patches, -1, dtype=np.int64)
85
+ source[dest] = np.repeat(source_start, length) + within
86
+ segment[dest] = np.repeat(run_window, length)
87
+ return source, segment, rows
88
+
89
+
90
+ def gather(tensor: torch.Tensor, source: torch.Tensor, fill=0.0) -> torch.Tensor:
91
+ """Rows of a [N, ...] tensor at `source` (-1 -> `fill`)."""
92
+ picked = tensor[source.clamp_min(0)]
93
+ hole = (source < 0).view(-1, *([1] * (picked.ndim - 1)))
94
+ return picked.masked_fill(hole, fill)
@@ -0,0 +1,117 @@
1
+ """Context-curriculum phases, learning-rate multipliers and synthetic shares."""
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch
7
+
8
+
9
+ def parse_schedule(spec, steps: int, final_context: int, patch: int):
10
+ """[(context, start_step, end_step)] per curriculum phase, covering [0, steps); None gives
11
+ one phase. Every phase must get at least one step."""
12
+ if spec is None:
13
+ return [(final_context, 0, steps)]
14
+ if not isinstance(spec, str) or not spec.strip():
15
+ raise ValueError("context_schedule must be a string like '1024:0.8,4096:0.2'")
16
+ stages = []
17
+ for part in spec.split(","):
18
+ context, fraction = part.split(":")
19
+ context, fraction = int(context), float(fraction)
20
+ if context <= 0 or context % patch or not 0 < fraction <= 1:
21
+ raise ValueError(f"Bad context_schedule stage {part!r}")
22
+ stages.append((context, fraction))
23
+ if abs(sum(f for _, f in stages) - 1) > 1e-6:
24
+ raise ValueError("context_schedule fractions must sum to 1")
25
+ if stages[-1][0] != final_context:
26
+ raise ValueError("The last context_schedule stage must use the model's context_length")
27
+ if max(c for c, _ in stages) > final_context:
28
+ raise ValueError("No stage may exceed the model's context_length")
29
+ out, cumulative, start = [], 0.0, 0
30
+ for index, (context, fraction) in enumerate(stages):
31
+ cumulative += fraction
32
+ end = steps if index == len(stages) - 1 else round(cumulative * steps)
33
+ if end <= start:
34
+ raise ValueError(f"context_schedule phase {index} ({context}:{fraction}) gets no "
35
+ f"step of the {steps}-step plan")
36
+ out.append((context, start, end))
37
+ start = end
38
+ return out
39
+
40
+
41
+ def base_multiplier(step: int, s) -> float:
42
+ """The schedule's LR multiplier at `step` (0-based), before any warm-start ramp."""
43
+ steps = s["steps"]
44
+ warmup = warmup_steps(s)
45
+ if step < warmup:
46
+ return (step + 1) / warmup
47
+ final = s["final_lr_fraction"]
48
+ if s["lr_schedule"] == "warmup_decay":
49
+ decay = max(1, s["decay_steps"])
50
+ start = steps - decay
51
+ if step < start:
52
+ return 1.0
53
+ p = (step - start + 1) / decay
54
+ shape = 1 - math.sqrt(p) if s["decay_shape"] == "sqrt" else 1 - p
55
+ return final + (1 - final) * shape
56
+ if s["lr_schedule"] == "wsd":
57
+ start = steps - max(1, int(s["decay_fraction"] * steps))
58
+ if step < start:
59
+ return 1.0
60
+ progress = (step - start) / max(1, steps - start)
61
+ shape = 1 - math.sqrt(progress) if s["decay_shape"] == "sqrt" else 1 - progress
62
+ return final + (1 - final) * shape
63
+ progress = (step - warmup) / max(1, steps - warmup)
64
+ return final + (1 - final) * (1 - progress)
65
+
66
+
67
+ def warmup_steps(s) -> int:
68
+ if s["lr_schedule"] == "warmup_decay":
69
+ return max(1, s["warmup_steps"])
70
+ return max(1, int(s["warmup_fraction"] * s["steps"]))
71
+
72
+
73
+ def multiplier(step: int, s, first_step: int = 0, warm: bool = False) -> float:
74
+ """Return the LR multiplier at `step`, including warm-start scaling and a re-warm ramp."""
75
+ if not warm:
76
+ return base_multiplier(step, s)
77
+ value = base_multiplier(max(step, warmup_steps(s)), s)
78
+ ramp = s["rewarm_steps"]
79
+ if ramp > 0:
80
+ t = min(1.0, (step - first_step + 1) / ramp)
81
+ value *= s["rewarm_from"] + (1.0 - s["rewarm_from"]) * t
82
+ return value * s.get("warm_lr_scale", 1.0)
83
+
84
+
85
+ def share_function(stages, synthetic_stages: int, ramp: int, base: float):
86
+ """step -> synthetic share: 1 through the first `synthetic_stages` phases, then a linear ramp
87
+ to `base` over `ramp` steps, then `base`."""
88
+ if not synthetic_stages:
89
+ return lambda step: base
90
+ switch = stages[synthetic_stages - 1][2]
91
+
92
+ def share(step):
93
+ if step < switch:
94
+ return 1.0
95
+ if ramp and step < switch + ramp:
96
+ return 1.0 + (base - 1.0) * (step - switch + 1) / ramp
97
+ return base
98
+
99
+ return share
100
+
101
+
102
+ def stage_shares(share, stages):
103
+ """Mean synthetic share over each (context, start, end) phase's steps (for the data plan)."""
104
+ return [float(np.mean([share(t) for t in range(start, end)])) for _, start, end in stages]
105
+
106
+
107
+ def ramp_rows(rows: int, share: float, base: float) -> torch.Tensor:
108
+ """Return kept row indices at `share`, retaining the regular synthetic-row count.
109
+ A ramp step carries no more tokens than a regular step."""
110
+ synthetic = round(base * rows)
111
+ real = min(rows - synthetic, round((1 - share) * rows))
112
+ return torch.cat([torch.arange(real), torch.arange(rows - synthetic, rows)])
113
+
114
+
115
+ def ramp_fraction(rows_before: int, rows_after: int, base: float) -> float:
116
+ """The mixer fraction that makes round(fraction * rows_after) the regular synthetic rows."""
117
+ return round(base * rows_before) / max(1, rows_after)
@@ -0,0 +1,93 @@
1
+ """Average checkpoints uniformly or interpolate an anchor and model with WiSE."""
2
+
3
+ import hashlib
4
+ from pathlib import Path
5
+
6
+ import torch
7
+
8
+ # Forecast settings do not affect weights, so soup members may differ in them.
9
+ FORECAST_FIELDS = ("context_length", "views", "tail_paths", "sign_clip", "integer_snap",
10
+ "fit_row", "xreg", "xreg_gate", "xreg_square", "xreg_guard",
11
+ "xreg_guard_margin", "xreg_guard_min", "rows_only_history")
12
+
13
+
14
+ def sha256(path) -> str:
15
+ digest = hashlib.sha256()
16
+ with open(path, "rb") as handle:
17
+ for block in iter(lambda: handle.read(1 << 24), b""):
18
+ digest.update(block)
19
+ return digest.hexdigest()
20
+
21
+
22
+ def _load(path):
23
+ from simons.training.trainer import read_checkpoint
24
+
25
+ checkpoint = read_checkpoint(path)
26
+ checkpoint.pop("optimizer", None)
27
+ return checkpoint
28
+
29
+
30
+ def _check(members, paths):
31
+ first = members[0]
32
+ reference = {k: v for k, v in first["model_config"].items() if k not in FORECAST_FIELDS}
33
+ for path, member in zip(paths[1:], members[1:]):
34
+ config = {k: v for k, v in member["model_config"].items() if k not in FORECAST_FIELDS}
35
+ if config != reference:
36
+ differ = sorted(k for k in set(config) | set(reference)
37
+ if config.get(k) != reference.get(k))
38
+ raise ValueError(f"{path}: model config differs in {differ}")
39
+ if set(member["model"]) != set(first["model"]):
40
+ raise ValueError(f"{path}: state keys differ")
41
+ for key, tensor in first["model"].items():
42
+ other = member["model"][key]
43
+ if other.shape != tensor.shape or other.dtype != tensor.dtype:
44
+ raise ValueError(f"{path}: tensor {key} {tuple(other.shape)}/{other.dtype} vs "
45
+ f"{tuple(tensor.shape)}/{tensor.dtype}")
46
+
47
+
48
+ def merge(paths, wise_alpha: float | None = None) -> dict:
49
+ """Return an averaged checkpoint without optimizer state.
50
+ With `wise_alpha=a`, paths [anchor,model] yield (1-a)*anchor+a*model."""
51
+ paths = [str(p) for p in paths]
52
+ if not paths:
53
+ raise ValueError("a soup needs at least one member")
54
+ if wise_alpha is not None:
55
+ if len(paths) != 2 or not 0.0 <= wise_alpha <= 1.0:
56
+ raise ValueError("WiSE needs two members (anchor, model) and an alpha in [0, 1]")
57
+ anchor, model = (_load(p) for p in paths)
58
+ _check([model, anchor], [paths[1], paths[0]])
59
+ state = {}
60
+ for key, tensor in model["model"].items():
61
+ if torch.is_floating_point(tensor):
62
+ mix = (1.0 - wise_alpha) * anchor["model"][key].double() \
63
+ + wise_alpha * tensor.double()
64
+ state[key] = mix.to(tensor.dtype)
65
+ else:
66
+ state[key] = tensor.clone()
67
+ merged = {**model, "model": state}
68
+ recipe = {"wise_alpha": float(wise_alpha), "anchor": paths[0], "member": paths[1]}
69
+ else:
70
+ members = [_load(p) for p in paths]
71
+ _check(members, paths)
72
+ state = {}
73
+ for key, tensor in members[0]["model"].items():
74
+ if torch.is_floating_point(tensor) and len(members) > 1:
75
+ total = sum(member["model"][key].double() for member in members)
76
+ state[key] = (total / len(members)).to(tensor.dtype)
77
+ else:
78
+ state[key] = tensor.clone()
79
+ merged = {**members[0], "model": state}
80
+ recipe = {"uniform": paths}
81
+ merged["merge"] = {**recipe, "sha256": [sha256(p) for p in paths]}
82
+ return merged
83
+
84
+
85
+ def write(paths, output, wise_alpha: float | None = None) -> Path:
86
+ """Write `merge(paths, wise_alpha)` to `output` (a checkpoint.pt for `export`)."""
87
+ from simons.training.trainer import write_checkpoint
88
+
89
+ merged = merge(paths, wise_alpha)
90
+ output = Path(output)
91
+ output.parent.mkdir(parents=True, exist_ok=True)
92
+ write_checkpoint(output, merged)
93
+ return output
@@ -0,0 +1,50 @@
1
+ """Extend training windows backward through contiguous `<base>@<offset>` segments."""
2
+
3
+ import re
4
+
5
+ import numpy as np
6
+
7
+ _ID = re.compile(r"^(.*)@(\d+)$")
8
+
9
+
10
+ def positions(item_ids, shapes):
11
+ """Return predecessor positions per series, or -1, for IDs and shapes [n,2] (variates,steps).
12
+ Links require matching base IDs, variate counts and contiguous offsets."""
13
+ matches = [_ID.match(x) for x in item_ids]
14
+ codes, offsets, keep = {}, np.zeros(len(item_ids), np.int64), []
15
+ base = np.full(len(item_ids), -1, np.int64)
16
+ for k, match in enumerate(matches):
17
+ if match is None:
18
+ continue
19
+ base[k] = codes.setdefault(match.group(1), len(codes))
20
+ offsets[k] = int(match.group(2))
21
+ keep.append(k)
22
+ prev = np.full(len(item_ids), -1, np.int64)
23
+ keep = np.asarray(keep, np.int64)
24
+ if len(keep) < 2:
25
+ return prev.tolist()
26
+ order = keep[np.lexsort((keep, offsets[keep], base[keep]))]
27
+ a, b = order[:-1], order[1:]
28
+ shapes = np.asarray(shapes, np.int64)
29
+ link = ((base[a] == base[b]) & (offsets[a] + shapes[a, 1] == offsets[b])
30
+ & (shapes[a, 0] == shapes[b, 0]))
31
+ prev[b[link]] = a[link]
32
+ return prev.tolist()
33
+
34
+
35
+ def extend(source_arrays, prev, position, channels, end, want):
36
+ """Window [channels, :end] of segment `position`, extended backward through its
37
+ predecessors until it holds `want` steps (or the run starts). Returns a float32 copy."""
38
+ group = source_arrays[position]
39
+ parts = [np.asarray(group[channels, :end], dtype="float32")]
40
+ have = end
41
+ p = prev[position]
42
+ while have < want and p >= 0:
43
+ before = source_arrays[p]
44
+ take = min(want - have, before.shape[1])
45
+ parts.append(np.asarray(before[channels, before.shape[1] - take:], dtype="float32"))
46
+ have += take
47
+ p = prev[p] if take == before.shape[1] else -1
48
+ if len(parts) == 1:
49
+ return np.array(parts[0], copy=True)
50
+ return np.concatenate(parts[::-1], axis=1)