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.
- simons/__init__.py +10 -0
- simons/config.py +82 -0
- simons/covariates.py +338 -0
- simons/forecast.py +578 -0
- simons/model.py +696 -0
- simons/periodicity.py +188 -0
- simons/predictor.py +56 -0
- simons/synth/__init__.py +5 -0
- simons/synth/augment.py +143 -0
- simons/synth/base.py +448 -0
- simons/synth/calendar.py +157 -0
- simons/synth/causal.py +193 -0
- simons/synth/covariates/__init__.py +1 -0
- simons/synth/covariates/classical.py +637 -0
- simons/synth/covariates/effects.py +155 -0
- simons/synth/covariates/energy.py +528 -0
- simons/synth/covariates/families.py +296 -0
- simons/synth/covariates/generic.py +342 -0
- simons/synth/heavy.py +234 -0
- simons/synth/mech.py +636 -0
- simons/synth/multi.py +274 -0
- simons/synth/nonstat.py +204 -0
- simons/synth/observe.py +117 -0
- simons/training/__init__.py +1 -0
- simons/training/__main__.py +77 -0
- simons/training/augment.py +125 -0
- simons/training/clusters.py +215 -0
- simons/training/config.py +321 -0
- simons/training/covariates/__init__.py +1 -0
- simons/training/covariates/roles.py +370 -0
- simons/training/covariates/stream.py +243 -0
- simons/training/covariates/windows.py +239 -0
- simons/training/data.py +319 -0
- simons/training/distributed.py +124 -0
- simons/training/mixture.py +140 -0
- simons/training/network.py +115 -0
- simons/training/objective.py +193 -0
- simons/training/optim.py +164 -0
- simons/training/packing.py +94 -0
- simons/training/schedule.py +117 -0
- simons/training/soup.py +93 -0
- simons/training/stitching.py +50 -0
- simons/training/trainer.py +571 -0
- simons/training/warp.py +144 -0
- simons_forecasting-0.1.3.dist-info/METADATA +156 -0
- simons_forecasting-0.1.3.dist-info/RECORD +49 -0
- simons_forecasting-0.1.3.dist-info/WHEEL +4 -0
- simons_forecasting-0.1.3.dist-info/licenses/LICENSE +202 -0
- simons_forecasting-0.1.3.dist-info/licenses/NOTICE +57 -0
simons/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Simons: small, open time series foundation models for probabilistic forecasting."""
|
|
2
|
+
|
|
3
|
+
from .config import SimonsConfig
|
|
4
|
+
from .covariates import encode_categorical, prepare_covariates
|
|
5
|
+
from .forecast import QUANTILES, forecast, forecast_items, forecast_series
|
|
6
|
+
from .model import Simons
|
|
7
|
+
|
|
8
|
+
__all__ = ["QUANTILES", "Simons", "SimonsConfig", "encode_categorical", "forecast",
|
|
9
|
+
"forecast_items", "forecast_series", "prepare_covariates"]
|
|
10
|
+
__version__ = "0.1.3"
|
simons/config.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from dataclasses import asdict, dataclass, fields
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class SimonsConfig:
|
|
8
|
+
"""Architecture and forecasting settings of a Simons checkpoint (its config.json)."""
|
|
9
|
+
|
|
10
|
+
# Transformer
|
|
11
|
+
context_length: int = 32768 # raw history steps the model reads
|
|
12
|
+
prediction_length: int = 512 # steps forecast in one pass; longer horizons roll out
|
|
13
|
+
patch_length: int = 32
|
|
14
|
+
width: int = 1024
|
|
15
|
+
layers: int = 12 # causal time layers; one variate (cross-series) layer follows them
|
|
16
|
+
heads: int = 16
|
|
17
|
+
# Long context: the last `near_context` steps are patched at full resolution, older steps
|
|
18
|
+
# are mean-pooled by `far_pool` into coarser tokens.
|
|
19
|
+
near_context: int = 4096
|
|
20
|
+
far_pool: int = 8
|
|
21
|
+
far_min_history: int = 7680 # far tokens only for series observed further back than this
|
|
22
|
+
stats_window: int = 8192 # causal mean/std over a sliding window of this many steps
|
|
23
|
+
# Period-locked rotary embedding
|
|
24
|
+
period_slots: int = 4
|
|
25
|
+
period_alpha: float = 0.05
|
|
26
|
+
period_local: float = 5.0
|
|
27
|
+
detector_mid: int = 7680 # series observed only within this many steps use a detector over them
|
|
28
|
+
# Test-time rules (forecast only; they change no weights)
|
|
29
|
+
views: bool = True # median of native, sign-flipped and square-root views; pooled tail
|
|
30
|
+
# Quantile paths rolled out past prediction_length: fixed to the 0.2, 0.5 and 0.8 paths.
|
|
31
|
+
tail_paths: tuple[int, ...] = (1, 4, 7)
|
|
32
|
+
sign_clip: bool = True # clip forecasts to the sign of a one-signed history
|
|
33
|
+
integer_snap: bool = True # round forecasts of non-negative integer histories
|
|
34
|
+
# Covariate modules (simons.covariates); unused when no covariates are supplied.
|
|
35
|
+
covariates: bool = False # covariate rows: covariates join the target's variate group
|
|
36
|
+
binary_rows: bool = False # two-level known-future covariates enter unscaled in [0, 1]
|
|
37
|
+
fit_row: bool = True # single-target rows: add the in-context ridge fit as one more row
|
|
38
|
+
past_rows: bool = False # always False: past-only covariates are ignored
|
|
39
|
+
read_after: int = -1 # >= 0: target rows read the covariate rows after this time block
|
|
40
|
+
read_binary: bool = True # always True: the read also keys on two-level (indicator) rows
|
|
41
|
+
xreg: bool = False # forecast y - x'beta (in-context ridge) and add x'beta back
|
|
42
|
+
xreg_gate: float = 0.05 # keep a row's ridge fit only if its held-out R^2 exceeds this
|
|
43
|
+
xreg_square: bool = False # always False: XReg regresses on the covariates themselves
|
|
44
|
+
xreg_guard: bool = False # per row, XReg only if it wins a one-origin backtest
|
|
45
|
+
xreg_guard_margin: float = 0.9 # drop XReg iff loss(no XReg) < margin * loss(XReg)
|
|
46
|
+
xreg_guard_min: int = 0 # rows with fewer observed steps than max(this, H + 64) keep XReg
|
|
47
|
+
rows_only_history: int = 0 # > 0: rows observed for more steps than this: no XReg, no guard
|
|
48
|
+
|
|
49
|
+
def __post_init__(self):
|
|
50
|
+
object.__setattr__(self, "tail_paths", tuple(int(p) for p in self.tail_paths))
|
|
51
|
+
if self.read_after >= self.layers - 1:
|
|
52
|
+
raise ValueError("read_after must name a time block before the last")
|
|
53
|
+
if self.xreg_guard and not self.xreg:
|
|
54
|
+
raise ValueError("xreg_guard needs xreg")
|
|
55
|
+
if self.past_rows or not self.read_binary or self.xreg_square:
|
|
56
|
+
raise ValueError("only past_rows: false, read_binary: true and xreg_square: false "
|
|
57
|
+
"are supported")
|
|
58
|
+
if self.rows_only_history < 0 or self.xreg_guard_min < 0:
|
|
59
|
+
raise ValueError("rows_only_history and xreg_guard_min must be nonnegative")
|
|
60
|
+
if self.context_length % self.patch_length or self.width % self.heads:
|
|
61
|
+
raise ValueError("context_length must divide into patches and width into heads")
|
|
62
|
+
if (self.width // self.heads) % 2:
|
|
63
|
+
raise ValueError("head size must be even")
|
|
64
|
+
far = self.context_length - self.near_context
|
|
65
|
+
if far <= 0 or far % (self.patch_length * self.far_pool):
|
|
66
|
+
raise ValueError("context_length - near_context must be a positive multiple of "
|
|
67
|
+
"patch_length * far_pool")
|
|
68
|
+
if 2 * self.period_slots > self.width // self.heads:
|
|
69
|
+
raise ValueError("too many period slots for the head size")
|
|
70
|
+
if self.tail_paths != (1, 4, 7):
|
|
71
|
+
raise ValueError("tail_paths must be (1, 4, 7)")
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
def from_json(cls, path) -> "SimonsConfig":
|
|
75
|
+
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
76
|
+
known = {f.name for f in fields(cls)}
|
|
77
|
+
return cls(**{k: v for k, v in data.items() if k in known})
|
|
78
|
+
|
|
79
|
+
def to_dict(self) -> dict:
|
|
80
|
+
data = asdict(self)
|
|
81
|
+
data["tail_paths"] = list(self.tail_paths)
|
|
82
|
+
return {"model_type": "simons", **data}
|
simons/covariates.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""Prepare known-future covariate rows and in-context ridge fits for forecasting."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import torch
|
|
5
|
+
from torch import nn
|
|
6
|
+
from torch.nn import functional as F
|
|
7
|
+
|
|
8
|
+
ROLE_TARGET, ROLE_KNOWN, ROLE_PAST, ROLE_FIT, ROLE_BINARY = 0, 1, 2, 3, 4
|
|
9
|
+
MAX_COVARIATES = 16
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class CovariateModules(nn.Module):
|
|
13
|
+
"""Role vectors (zero for target rows) and the optional read block."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, config, block_type):
|
|
16
|
+
super().__init__()
|
|
17
|
+
self.role = nn.Parameter(torch.zeros(5 if config.binary_rows else 4, config.width))
|
|
18
|
+
self.read = block_type(config, causal=False) if config.read_after >= 0 else None
|
|
19
|
+
|
|
20
|
+
def role_vectors(self, roles: torch.Tensor) -> torch.Tensor:
|
|
21
|
+
"""[B,V,W] additive role vectors (target rows get exactly 0)."""
|
|
22
|
+
return self.role[roles] * (roles > 0)[..., None].to(self.role.dtype)
|
|
23
|
+
|
|
24
|
+
def read_rows(self, x, related, batch: int, variates: int, size: int, roles):
|
|
25
|
+
"""x [B*V,S,W] -> x with target rows updated by the read (every other row unchanged)."""
|
|
26
|
+
xm = x.reshape(batch, variates, size, -1).transpose(1, 2).reshape(batch * size, variates,
|
|
27
|
+
-1)
|
|
28
|
+
mask, update = read_mask(roles, related, size)
|
|
29
|
+
y = read_forward(self.read, xm, mask)
|
|
30
|
+
u = update.to(xm.dtype)
|
|
31
|
+
out = xm + u * (y - xm)
|
|
32
|
+
return out.reshape(batch, size, variates, -1).transpose(1, 2).reshape(batch * variates,
|
|
33
|
+
size, -1)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def read_mask(roles, related, size: int):
|
|
37
|
+
"""(mask [B*S,1,V,V], update [B*S,V,1]) from roles [B,V] and related [B*S,1,V,V]: a target
|
|
38
|
+
row reads itself and its group's known-future, indicator and fit rows."""
|
|
39
|
+
variates = roles.shape[1]
|
|
40
|
+
r = roles.repeat_interleave(size, 0)
|
|
41
|
+
key = (r == ROLE_KNOWN) | (r == ROLE_FIT) | (r == ROLE_BINARY)
|
|
42
|
+
cross = (r == ROLE_TARGET)[:, :, None] & key[:, None, :] & related[:, 0]
|
|
43
|
+
eye = torch.eye(variates, dtype=torch.bool, device=roles.device)[None]
|
|
44
|
+
return (cross | eye)[:, None], cross.any(-1)[..., None]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def read_forward(block, x, mask):
|
|
48
|
+
"""The read block (pre-norm attention + MLP) with an explicit fp32 softmax over few keys."""
|
|
49
|
+
n, s, width = x.shape
|
|
50
|
+
q, k, v = block.qkv(block.attention_norm(x)).view(n, s, 3, block.heads, -1).unbind(2)
|
|
51
|
+
q, k, v = (t.transpose(1, 2) for t in (q, k, v))
|
|
52
|
+
scores = (q @ k.transpose(-1, -2)) * q.shape[-1] ** -0.5
|
|
53
|
+
weights = scores.float().masked_fill(~mask, float("-inf")).softmax(-1)
|
|
54
|
+
attended = (weights.to(v.dtype) @ v).transpose(1, 2).reshape(n, s, width)
|
|
55
|
+
x = x + block.out(attended)
|
|
56
|
+
return x + block.mlp(block.mlp_norm(x))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def ridge_fit(y: torch.Tensor, cov: torch.Tensor, use: torch.Tensor, skip: int = 0):
|
|
60
|
+
"""Fit y [B,L] on cov [B,C,L] selected by use [B,C], with a held-out R^2 check.
|
|
61
|
+
Return (fit [B,skip+L] in target units, valid [B]); skipped missing steps get the intercept."""
|
|
62
|
+
obs = torch.isfinite(y)
|
|
63
|
+
w = obs.double()
|
|
64
|
+
n = w.sum(-1, keepdim=True).clamp_min(1)
|
|
65
|
+
yy = torch.where(obs, y, 0).double()
|
|
66
|
+
mu = (yy * w).sum(-1, keepdim=True) / n
|
|
67
|
+
sd = ((((yy - mu) * w) ** 2).sum(-1, keepdim=True) / n).sqrt().clamp_min(1e-8)
|
|
68
|
+
ys = (yy - mu) / sd * w
|
|
69
|
+
cobs = torch.isfinite(cov) & use[..., None]
|
|
70
|
+
cc = torch.where(cobs, cov, 0).double()
|
|
71
|
+
cn = cobs.sum(-1, keepdim=True).clamp_min(1)
|
|
72
|
+
cm = cc.sum(-1, keepdim=True) / cn
|
|
73
|
+
cs = ((torch.where(cobs, cc - cm, 0) ** 2).sum(-1, keepdim=True) / cn).sqrt()
|
|
74
|
+
xs = torch.where(cobs & (cs > 0), (cc - cm) / cs.clamp_min(1e-8), 0)
|
|
75
|
+
x = torch.cat([torch.ones_like(xs[:, :1]), xs], 1) # [B,K,L]
|
|
76
|
+
k = 1 + use.sum(-1, keepdim=True).double()
|
|
77
|
+
eye = torch.eye(x.shape[1], dtype=x.dtype, device=x.device)
|
|
78
|
+
lam = 1.0 + 0.05 * n * k / 16 + 2.0 * k
|
|
79
|
+
|
|
80
|
+
def fit_on(weight):
|
|
81
|
+
xw = x * weight[:, None]
|
|
82
|
+
gram = xw @ x.transpose(-1, -2)
|
|
83
|
+
xty = (xw @ ys[..., None])[..., 0]
|
|
84
|
+
return torch.linalg.solve(gram + lam[..., None] * eye, xty[..., None])[..., 0]
|
|
85
|
+
|
|
86
|
+
beta = fit_on(w)
|
|
87
|
+
whole = x
|
|
88
|
+
if skip: # the skipped steps: intercept 1, covariates 0
|
|
89
|
+
whole = torch.cat([F.pad(x[:, :1], (skip, 0), value=1.0), F.pad(x[:, 1:], (skip, 0))], 1)
|
|
90
|
+
fit = torch.einsum("bk,bkl->bl", beta, whole)
|
|
91
|
+
rank = w.cumsum(-1)
|
|
92
|
+
early = w * (rank <= 0.8 * n)
|
|
93
|
+
late = w - early
|
|
94
|
+
pred = torch.einsum("bk,bkl->bl", fit_on(early), x)
|
|
95
|
+
ln = late.sum(-1).clamp_min(1)
|
|
96
|
+
err = (((ys - pred) * late) ** 2).sum(-1) / ln
|
|
97
|
+
var = (((ys - (ys * late).sum(-1, keepdim=True) / ln[..., None]) * late) ** 2).sum(-1) / ln
|
|
98
|
+
r2 = 1 - err / var.clamp_min(1e-6)
|
|
99
|
+
ok = (n[:, 0] >= 3 * k[:, 0] + 16) & (late.sum(-1) >= 8) & (r2 > 0) & use.any(-1)
|
|
100
|
+
return (fit * sd + mu).float(), ok
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def known_rows(cov: torch.Tensor, known: torch.Tensor, binary: bool, patch: int):
|
|
104
|
+
"""Known-future rows of cov [..., L] (known [...]): two-level rows as (x - min) / (max - min)
|
|
105
|
+
when `binary`, then every row shifted one patch left. Returns (rows, two-level flags)."""
|
|
106
|
+
if binary:
|
|
107
|
+
finite = torch.isfinite(cov)
|
|
108
|
+
lo = torch.where(finite, cov, float("inf")).amin(-1, keepdim=True)
|
|
109
|
+
hi = torch.where(finite, cov, float("-inf")).amax(-1, keepdim=True)
|
|
110
|
+
two = ((cov == lo) | (cov == hi) | ~finite).all(-1) & known & (hi[..., 0] > lo[..., 0])
|
|
111
|
+
rows = torch.where(two[..., None], (cov - lo) / (hi - lo).clamp_min(1e-12), cov)
|
|
112
|
+
else:
|
|
113
|
+
two = torch.zeros_like(known)
|
|
114
|
+
rows = cov
|
|
115
|
+
return F.pad(rows[..., patch:], (0, patch), value=float("nan")), two
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def varying(cov: torch.Tensor, finite: torch.Tensor) -> torch.Tensor:
|
|
119
|
+
"""[..., C] covariates (`finite`: their observed steps) with at least two observed values and
|
|
120
|
+
a nonzero spread."""
|
|
121
|
+
count = finite.sum(-1)
|
|
122
|
+
mean = torch.where(finite, cov, 0).sum(-1) / count.clamp_min(1)
|
|
123
|
+
spread = (torch.where(finite, cov - mean[..., None], 0) ** 2).sum(-1)
|
|
124
|
+
return (count >= 2) & (spread > 0)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def covariate_rows(config, values: torch.Tensor, series_ids: torch.Tensor,
|
|
128
|
+
covariates: torch.Tensor, fit_keep: torch.Tensor | None = None,
|
|
129
|
+
skip: int = 0):
|
|
130
|
+
"""Append covariates [B,C,>=L] to values [B,V,L]; return values [B,V',L], ids/roles [B,V'].
|
|
131
|
+
Return None if unusable; fit_keep [B] selects fits. Inputs omit `skip` all-missing steps.
|
|
132
|
+
With `skip`, append the fit prefix [B,skip] (NaN if invalid), or None without a fit row."""
|
|
133
|
+
patch = config.patch_length
|
|
134
|
+
batch, variates, length = values.shape
|
|
135
|
+
cov = covariates.to(device=values.device, dtype=values.dtype)
|
|
136
|
+
if cov.shape[-1] < length:
|
|
137
|
+
cov = F.pad(cov, (0, length - cov.shape[-1]), value=float("nan"))
|
|
138
|
+
cov = cov[..., :length]
|
|
139
|
+
position = torch.arange(length, device=values.device)
|
|
140
|
+
last = torch.where(torch.isfinite(values), position, -1).amax(-1).amax(-1)
|
|
141
|
+
finite = torch.isfinite(cov)
|
|
142
|
+
valid = varying(cov, finite)
|
|
143
|
+
known = valid & (finite & (position > last[:, None, None])).any(-1) # [B,C]
|
|
144
|
+
keep = known.any(0)
|
|
145
|
+
if not bool(keep.any()):
|
|
146
|
+
return None
|
|
147
|
+
cov, known = cov[:, keep], known[:, keep]
|
|
148
|
+
shifted, two = known_rows(cov, known, config.binary_rows, patch)
|
|
149
|
+
roles = torch.where(two, ROLE_BINARY, ROLE_KNOWN)
|
|
150
|
+
rows = torch.where(known[..., None], shifted, float("nan"))
|
|
151
|
+
extra, extra_roles, extra_used = [rows], [roles], [known]
|
|
152
|
+
head = None
|
|
153
|
+
if config.fit_row and variates == 1:
|
|
154
|
+
fit, ok = ridge_fit(values[:, 0], cov, known, skip=skip)
|
|
155
|
+
if fit_keep is not None:
|
|
156
|
+
ok = ok & fit_keep.to(ok.device)
|
|
157
|
+
fit = torch.where(ok[:, None], F.pad(fit[..., patch:], (0, patch), value=float("nan")),
|
|
158
|
+
float("nan"))
|
|
159
|
+
head, fit = fit[..., :skip], fit[..., skip:]
|
|
160
|
+
extra.append(fit[:, None])
|
|
161
|
+
extra_roles.append(torch.full_like(roles[:, :1], ROLE_FIT))
|
|
162
|
+
extra_used.append(ok[:, None])
|
|
163
|
+
rows = torch.cat(extra, 1)
|
|
164
|
+
roles = torch.cat(extra_roles, 1)
|
|
165
|
+
used = torch.cat(extra_used, 1)
|
|
166
|
+
rows = torch.where(used[..., None], rows, float("nan"))
|
|
167
|
+
# Callers' IDs become 0, 1, ...; negative IDs and zero role vectors isolate unused rows.
|
|
168
|
+
k = rows.shape[1]
|
|
169
|
+
series_ids = torch.unique(series_ids, return_inverse=True)[1]
|
|
170
|
+
lone = (-1 - torch.arange(k, device=values.device))[None].expand(batch, k)
|
|
171
|
+
ids = torch.where(used, series_ids[:, :1].expand(batch, k), lone)
|
|
172
|
+
roles = torch.where(used, roles, ROLE_TARGET)
|
|
173
|
+
target_roles = torch.zeros(batch, variates, dtype=roles.dtype, device=roles.device)
|
|
174
|
+
grown = (torch.cat([values, rows], 1), torch.cat([series_ids, ids], 1),
|
|
175
|
+
torch.cat([target_roles, roles], 1))
|
|
176
|
+
return (*grown, head) if skip else grown
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def xreg_fit(values: torch.Tensor, covariates: torch.Tensor, future: torch.Tensor,
|
|
180
|
+
gate: float = 0.05) -> torch.Tensor:
|
|
181
|
+
"""Return ridge contributions [B,V,L] without intercepts, in target units; zero without a fit.
|
|
182
|
+
Inputs are values [B,V,L], covariates [B,C,L] and future flags [L]; `gate` is held-out R^2."""
|
|
183
|
+
batch, _, length = values.shape
|
|
184
|
+
if future.ndim == 1:
|
|
185
|
+
future = future[None].expand(batch, length)
|
|
186
|
+
obs = torch.isfinite(values) & ~future[:, None]
|
|
187
|
+
w = obs.double()
|
|
188
|
+
n = w.sum(-1)
|
|
189
|
+
y = torch.where(obs, values, 0).double()
|
|
190
|
+
mu = (y * w).sum(-1, keepdim=True) / n.clamp_min(1)[..., None]
|
|
191
|
+
sd = ((((y - mu) * w) ** 2).sum(-1, keepdim=True) / n.clamp_min(1)[..., None]).sqrt()
|
|
192
|
+
sd = sd.clamp_min(1e-8)
|
|
193
|
+
ys = (y - mu) / sd * w
|
|
194
|
+
cobs = torch.isfinite(covariates)
|
|
195
|
+
known = (cobs & future[:, None]).any(-1)
|
|
196
|
+
cc = torch.where(cobs, covariates, 0).double()
|
|
197
|
+
cn = cobs.sum(-1, keepdim=True).clamp_min(1)
|
|
198
|
+
cm = cc.sum(-1, keepdim=True) / cn
|
|
199
|
+
cs = ((torch.where(cobs, cc - cm, 0) ** 2).sum(-1, keepdim=True) / cn).sqrt()
|
|
200
|
+
valid = known & (cs[..., 0] > 1e-12)
|
|
201
|
+
xs = torch.where(cobs & valid[..., None], (cc - cm) / cs.clamp_min(1e-12), 0)
|
|
202
|
+
x = torch.cat([torch.ones_like(xs[:, :1]), xs], 1) # [B,K,L]
|
|
203
|
+
k = valid.sum(-1).double() + 1
|
|
204
|
+
lam = 1.0 + 0.05 * n * k[:, None] / 16 + 2.0 * k[:, None]
|
|
205
|
+
eye = torch.eye(x.shape[1], dtype=x.dtype, device=x.device)
|
|
206
|
+
|
|
207
|
+
def fit_on(weight):
|
|
208
|
+
xw = x[:, None] * weight[:, :, None]
|
|
209
|
+
gram = xw @ x[:, None].transpose(-1, -2)
|
|
210
|
+
xty = (xw @ ys[..., None])[..., 0]
|
|
211
|
+
return torch.linalg.solve(gram + lam[..., None, None] * eye, xty[..., None])[..., 0]
|
|
212
|
+
|
|
213
|
+
beta = fit_on(w)
|
|
214
|
+
rank = w.cumsum(-1)
|
|
215
|
+
early = w * (rank <= 0.8 * n[..., None])
|
|
216
|
+
late = w - early
|
|
217
|
+
pred = torch.einsum("bvk,bkl->bvl", fit_on(early), x)
|
|
218
|
+
lnc = late.sum(-1).clamp_min(1)
|
|
219
|
+
err = (((ys - pred) * late) ** 2).sum(-1) / lnc
|
|
220
|
+
lmean = (ys * late).sum(-1, keepdim=True) / lnc[..., None]
|
|
221
|
+
var = (((ys - lmean) * late) ** 2).sum(-1) / lnc
|
|
222
|
+
r2 = (1 - err / var.clamp_min(1e-6)).clamp(-1, 1)
|
|
223
|
+
keep = (late.sum(-1) >= 8) & (r2 > gate) & (n >= 3 * k[:, None] + 16)
|
|
224
|
+
keep = keep & valid.any(-1)[:, None]
|
|
225
|
+
fitted = torch.einsum("bvk,bkl->bvl", beta[..., 1:], x[:, 1:]) * sd
|
|
226
|
+
return torch.where(keep[..., None], fitted, 0.0).float()
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _missing(x) -> bool:
|
|
230
|
+
if x is None:
|
|
231
|
+
return True
|
|
232
|
+
try:
|
|
233
|
+
return bool(np.isnan(x))
|
|
234
|
+
except (TypeError, ValueError):
|
|
235
|
+
return str(x) in ("<NA>", "NaT")
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def encode_categorical(values, categories=None) -> np.ndarray:
|
|
239
|
+
"""Convert a 1-D column to float64 values or sorted category codes; missing/unknown -> NaN.
|
|
240
|
+
A numeric column containing pandas NA/NaT is coded as categories; cast it to float
|
|
241
|
+
before calling."""
|
|
242
|
+
try:
|
|
243
|
+
return np.asarray(values, dtype="float64")
|
|
244
|
+
except (TypeError, ValueError):
|
|
245
|
+
pass
|
|
246
|
+
if categories is None:
|
|
247
|
+
categories = sorted({str(x) for x in values if not _missing(x)})
|
|
248
|
+
codes = {v: i for i, v in enumerate(categories)}
|
|
249
|
+
return np.asarray([np.nan if _missing(x) else codes.get(str(x), np.nan) for x in values],
|
|
250
|
+
dtype="float64")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _known_future(column, length: int, shared: bool) -> np.ndarray:
|
|
254
|
+
if shared:
|
|
255
|
+
return encode_categorical(column)
|
|
256
|
+
return np.concatenate([encode_categorical(column[:length]),
|
|
257
|
+
encode_categorical(column[length:])])
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _columns(block) -> list:
|
|
261
|
+
if block is None:
|
|
262
|
+
return []
|
|
263
|
+
if isinstance(block, np.ndarray) or torch.is_tensor(block):
|
|
264
|
+
array = np.asarray(block)
|
|
265
|
+
return [array] if array.ndim == 1 else list(array)
|
|
266
|
+
if getattr(block, "ndim", None) == 1:
|
|
267
|
+
return [np.asarray(block)]
|
|
268
|
+
if hasattr(block, "items"):
|
|
269
|
+
return [np.asarray(column) for _, column in block.items()]
|
|
270
|
+
return [np.asarray(column) for column in block]
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def prepare_covariates(length: int, horizon: int, future=None, past=None,
|
|
274
|
+
max_covariates: int = MAX_COVARIATES, shared_categories: bool = True):
|
|
275
|
+
"""Return float32 covariates [C,length+horizon], or None; NaN marks missing values.
|
|
276
|
+
`future` spans history and horizon; `past` spans history; columns align by position.
|
|
277
|
+
Columns without two distinct values are dropped, and at most `max_covariates` are kept."""
|
|
278
|
+
future, past = _columns(future), _columns(past)
|
|
279
|
+
if any(column.ndim != 1 for column in future + past):
|
|
280
|
+
raise ValueError("each covariate must be a 1-D column: per series, pass a 1-D array or "
|
|
281
|
+
"pandas Series (one covariate), a 2-D array [C, length], a list of 1-D "
|
|
282
|
+
"arrays, a dict of name -> 1-D array or a pandas DataFrame")
|
|
283
|
+
rows = []
|
|
284
|
+
for column in future:
|
|
285
|
+
column = np.asarray(column)
|
|
286
|
+
if len(column) != length + horizon:
|
|
287
|
+
raise ValueError(f"a known-future covariate needs {length + horizon} values "
|
|
288
|
+
f"(history {length} + horizon {horizon}), got {len(column)}")
|
|
289
|
+
rows.append(_known_future(column, length, shared_categories))
|
|
290
|
+
for column in past:
|
|
291
|
+
column = np.asarray(column)
|
|
292
|
+
if len(column) != length:
|
|
293
|
+
raise ValueError(f"a past covariate needs {length} values, got {len(column)}")
|
|
294
|
+
rows.append(np.concatenate([encode_categorical(column), np.full(horizon, np.nan)]))
|
|
295
|
+
if not rows:
|
|
296
|
+
return None
|
|
297
|
+
covs = np.stack(rows)
|
|
298
|
+
finite = np.isfinite(covs)
|
|
299
|
+
with np.errstate(all="ignore"):
|
|
300
|
+
spread = np.nanstd(np.where(finite, covs, np.nan), 1) if finite.any() else 0
|
|
301
|
+
# Check variation in forecast precision before selecting columns.
|
|
302
|
+
single = covs.astype("float32")
|
|
303
|
+
low = np.where(finite, single, np.inf).min(1)
|
|
304
|
+
high = np.where(finite, single, -np.inf).max(1)
|
|
305
|
+
covs = single[(high > low) & (np.nan_to_num(spread) > 0)][:max_covariates]
|
|
306
|
+
return covs if len(covs) else None
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def usable_covariates(history: torch.Tensor, covariates: torch.Tensor, horizon: int):
|
|
310
|
+
"""Keep usable covariates [B,C,T+horizon] for history [B,V,T]; return None when empty."""
|
|
311
|
+
t = history.shape[-1]
|
|
312
|
+
cov = covariates.clone()
|
|
313
|
+
finite = torch.isfinite(cov)
|
|
314
|
+
position = torch.arange(t, device=history.device)
|
|
315
|
+
seen = torch.isfinite(history).any(1) # [B,T]
|
|
316
|
+
last = torch.where(seen, position, -1).amax(-1) # [B]
|
|
317
|
+
hist = finite[..., :t]
|
|
318
|
+
late = hist & (position > last[:, None])[:, None]
|
|
319
|
+
keep = finite[..., t:].any(-1) | late.any(-1)
|
|
320
|
+
if t > horizon:
|
|
321
|
+
cut = position < t - horizon
|
|
322
|
+
last_b = torch.where(seen & cut, position, -1).amax(-1)
|
|
323
|
+
in_block = cut & (position > last_b[:, None])
|
|
324
|
+
keep |= (hist & in_block[:, None]).any(-1)
|
|
325
|
+
cov = torch.where(keep[..., None], cov, float("nan"))
|
|
326
|
+
finite = torch.isfinite(cov)
|
|
327
|
+
# Compare values exactly; floating-point variance can be nonzero for a constant.
|
|
328
|
+
low = torch.where(finite, cov, float("inf")).amin(-1)
|
|
329
|
+
high = torch.where(finite, cov, float("-inf")).amax(-1)
|
|
330
|
+
cov = torch.where((high == low)[..., None], float("nan"), cov)
|
|
331
|
+
finite = torch.isfinite(cov)
|
|
332
|
+
usable = varying(cov, finite)
|
|
333
|
+
beyond = usable & (usable.cumsum(-1) > MAX_COVARIATES)
|
|
334
|
+
cov = torch.where(beyond[..., None], float("nan"), cov)
|
|
335
|
+
columns = torch.isfinite(cov).any(-1).any(0)
|
|
336
|
+
if not bool(columns.any()):
|
|
337
|
+
return None
|
|
338
|
+
return cov[:, columns]
|