TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google Research for time-series forecasting.
Python
feat(timesfm3/mlx): support multivariate targets and covariates
rachittshah1bad88bdd285
diff --git a/src/timesfm3/mlx/model.py b/src/timesfm3/mlx/model.pyindex c470f33..9eaad08 100644--- a/src/timesfm3/mlx/model.py+++ b/src/timesfm3/mlx/model.py@@ -108,23 +108,72 @@ class TimesFM3Mlx(nn.Module):self._compiled_forward = mx.compile(self._forward_logits)return self._compiled_forward- def decode(self, target: mx.array, horizon: int) -> mx.array:- """``target`` ``(b, 1, context)`` -> logits ``(b, 1, horizon, num_quantiles)`` (target-only)."""+ def decode(+ self,+ target: mx.array,+ horizon: int = 0,+ past_only_covariates: mx.array | None = None,+ past_future_covariates: mx.array | None = None,+ target_mask: mx.array | None = None,+ past_only_mask: mx.array | None = None,+ past_future_mask: mx.array | None = None,+ mask: mx.array | None = None,+ ) -> mx.array:+ """Non-autoregressive single-pass decode, mirroring the torch backend.++ Args:+ target: ``(b, u, context)`` target variates.+ horizon: forecast horizon; inferred from ``past_future_covariates`` if given.+ past_only_covariates: ``(b, v_po, context)`` covariates known only in the past.+ past_future_covariates: ``(b, w, context + horizon)`` covariates known into the future.+ target_mask / past_only_mask / past_future_mask: optional per-value bool masks+ (``True`` = masked), same shape as their arrays.+ mask: optional global ``(b, context)`` bool mask.++ Targets, past-only and past-future covariates are stacked on the variate axis+ (in that order) and mixed by variate attention. Returns logits+ ``(b, num_variates, horizon, num_quantiles)``; the caller keeps the target rows.+ """cfg = self.config- b, num_target, context = target.shapep = cfg.input_patch_len- pad = (p - (context % p)) % p- mask = mx.zeros((b, context + pad), dtype=mx.bool_)- if pad:- target = mx.concatenate([mx.zeros((b, num_target, pad)), target], axis=-1)- mask = mx.concatenate(- [- mx.ones((b, pad), dtype=mx.bool_),- mx.zeros((b, context), dtype=mx.bool_),- ],- axis=-1,+ b, num_target, context = target.shape++ if past_future_covariates is not None:+ horizon = past_future_covariates.shape[-1] - context+ if horizon <= 0:+ raise ValueError(+ "decode requires horizon > 0 (pass horizon= or past_future_covariates).")- context = context + pad++ # 1. Left-pad the context to a whole number of patches.+ ctx_pad = (p - (context % p)) % p++ def _lpad(x, value):+ if ctx_pad == 0:+ return x+ fill = mx.full((b, x.shape[1], ctx_pad), value, dtype=x.dtype)+ return mx.concatenate([fill, x], axis=-1)++ if ctx_pad:+ target = _lpad(target, 0.0)+ if past_only_covariates is not None:+ past_only_covariates = _lpad(past_only_covariates, 0.0)+ if past_future_covariates is not None:+ past_future_covariates = _lpad(past_future_covariates, 0.0)+ if target_mask is not None:+ target_mask = _lpad(target_mask, True)+ if past_only_mask is not None:+ past_only_mask = _lpad(past_only_mask, True)+ if past_future_mask is not None:+ past_future_mask = _lpad(past_future_mask, True)++ if mask is None:+ lead = mx.ones((b, ctx_pad), dtype=mx.bool_)+ body = mx.zeros((b, context), dtype=mx.bool_)+ mask = mx.concatenate([lead, body], axis=-1) if ctx_pad else body+ elif ctx_pad:+ mask = mx.concatenate([mx.ones((b, ctx_pad), dtype=mx.bool_), mask], axis=-1)+ context = context + ctx_padnum_ctx_patches = context // pextract_len = min(2 * p, cfg.output_patch_len)@@ -132,10 +181,31 @@ class TimesFM3Mlx(nn.Module):num_forecast_patches = max(math.ceil((horizon - overlap) / p), 1)num_hor_patches = num_forecast_patches + cfg.rolls - 1padded_h = num_hor_patches * p+ hor_pad = padded_h - horizon- ctx_masks = mx.broadcast_to(mask[:, None, :], (b, num_target, context))- ctx_vals = target+ # 2. Stack targets + covariates on the variate axis.+ if target_mask is None:+ target_mask = mx.zeros_like(target).astype(mx.bool_)+ gmask = mask[:, None, :]+ all_ctx_vals = [target]+ all_ctx_masks = [target_mask | gmask]+ num_past_only = 0+ if past_only_covariates is not None:+ num_past_only = past_only_covariates.shape[1]+ if past_only_mask is None:+ past_only_mask = mx.zeros_like(past_only_covariates).astype(mx.bool_)+ all_ctx_vals.append(past_only_covariates)+ all_ctx_masks.append(past_only_mask | gmask)+ if past_future_covariates is not None:+ if past_future_mask is None:+ past_future_mask = mx.zeros_like(past_future_covariates).astype(mx.bool_)+ all_ctx_vals.append(past_future_covariates[..., :context])+ all_ctx_masks.append(past_future_mask[..., :context] | gmask)+ ctx_vals = mx.concatenate(all_ctx_vals, axis=1)+ ctx_masks = mx.concatenate(all_ctx_masks, axis=1)+ num_variates = ctx_vals.shape[1]+ # 3. Per-variate linear detrend (context part).m_trend, c_trend, apply_detrend = self._detrend(ctx_vals, ctx_masks, context)if cfg.use_linear_detrending:t = mx.arange(-(context - 1), 1).astype(mx.float32)[None, None, :] / context@@ -143,15 +213,57 @@ class TimesFM3Mlx(nn.Module):ctx_vals = mx.where(apply_detrend[..., None], detr, ctx_vals)ctx_vals = mx.where(ctx_masks, 0.0, ctx_vals)- hor_vals = mx.zeros((b, num_target, padded_h))- hor_masks = mx.ones((b, num_target, padded_h), dtype=mx.bool_)+ # 4. Horizon side: targets and past-only are unknown (masked); past-future+ # carries its real future values (detrended with that variate's trend).+ all_hor_vals = [+ mx.zeros((b, num_target, padded_h)),+ mx.zeros((b, num_past_only, padded_h)),+ ]+ all_hor_masks = [+ mx.ones((b, num_target, padded_h), dtype=mx.bool_),+ mx.ones((b, num_past_only, padded_h), dtype=mx.bool_),+ ]+ if past_future_covariates is not None:+ pf_future_vals = past_future_covariates[..., context : context + horizon]+ pf_future_masks = past_future_mask[..., context : context + horizon]+ if cfg.use_linear_detrending:+ base = num_target + num_past_only+ m_pf = m_trend[:, base:][:, :, None]+ c_pf = c_trend[:, base:][:, :, None]+ apply_pf = apply_detrend[:, base:][:, :, None]+ t_hor = mx.arange(1, horizon + 1).astype(mx.float32)[None, None, :] / context+ pf_trend = m_pf * t_hor + c_pf+ pf_future_vals = mx.where(apply_pf, pf_future_vals - pf_trend, pf_future_vals)+ pf_future_vals = mx.where(pf_future_masks, 0.0, pf_future_vals)+ if hor_pad > 0:+ w = pf_future_vals.shape[1]+ pf_future_vals = mx.concatenate(+ [pf_future_vals, mx.zeros((b, w, hor_pad))], axis=-1+ )+ pf_future_masks = mx.concatenate(+ [pf_future_masks, mx.ones((b, w, hor_pad), dtype=mx.bool_)], axis=-1+ )+ all_hor_vals.append(pf_future_vals)+ all_hor_masks.append(pf_future_masks)+ hor_vals = mx.concatenate(all_hor_vals, axis=1)+ hor_masks = mx.concatenate(all_hor_masks, axis=1)+all_vals = mx.concatenate([ctx_vals, hor_vals], axis=-1)all_masks = mx.concatenate([ctx_masks, hor_masks], axis=-1)n_tot = num_ctx_patches + num_hor_patches- values_bvnp = all_vals.reshape(b, num_target, n_tot, p)- masks_bvnp = all_masks.reshape(b, num_target, n_tot, p)- patch_is_target = mx.ones((b, num_target, n_tot), dtype=mx.bool_)+ values_bvnp = all_vals.reshape(b, num_variates, n_tot, p)+ masks_bvnp = all_masks.reshape(b, num_variates, n_tot, p)+ # Targets and past-only covariates are reconstructed by the model; past-future+ # covariates are only conditioning, so they are not "target" patches.+ num_pred = num_target + num_past_only+ patch_is_target = mx.concatenate(+ [+ mx.ones((b, num_pred, n_tot), dtype=mx.bool_),+ mx.zeros((b, num_variates - num_pred, n_tot), dtype=mx.bool_),+ ],+ axis=1,+ )horizon_cpm = mx.concatenate([diff --git a/src/timesfm3/mlx/timesfm3_forecaster.py b/src/timesfm3/mlx/timesfm3_forecaster.pyindex f88038f..8815014 100644--- a/src/timesfm3/mlx/timesfm3_forecaster.py+++ b/src/timesfm3/mlx/timesfm3_forecaster.py@@ -156,14 +156,13 @@ class TimesFM3Forecaster:use_znorm: bool = False,padding_mode: str = "none",) -> Iterator[ForecastOutput]:- """Runs inference on a batch of univariate time series."""- if any(c is not None for c in (past_only_covariates or [])) or any(- c is not None for c in (past_future_covariates or [])- ):- raise NotImplementedError(- "Covariate forecasting is not yet supported by the MLX backend; use the torch backend "- "for covariates. Follow-up: add the multivariate/covariate path to the MLX model."- )+ """Runs inference on a batch of series.++ Each context is a 1D univariate series or a 2D ``(num_variates, context)``+ multivariate series, optionally with per-series past-only and past-future+ covariates. A 1D input yields ``forecast`` of shape ``(horizon,)``; a 2D+ input yields ``(num_variates, horizon)``, matching the torch backend.+ """for name, flag in (("use_symmetric_averaging", use_symmetric_averaging),("use_znorm", use_znorm),@@ -179,34 +178,87 @@ class TimesFM3Forecaster:if not contexts:return- ids = list(ts_ids) if ts_ids is not None else [None] * len(contexts)+ n = len(contexts)+ ids = list(ts_ids) if ts_ids is not None else [None] * n+ po_list = past_only_covariates if past_only_covariates is not None else [None] * n+ pf_list = (+ past_future_covariates if past_future_covariates is not None else [None] * n+ )median_idx = self.config.median_quantile_index-- # Group same-length contexts so each group runs through a single batched forward pass.- # decode() is per-series independent (running stats, RevIN, detrending are per-batch-row), so- # batching is numerically identical to looping but scales throughput near-linearly.cap = self.config.max_context_length- arrs = [np.asarray(c, dtype=np.float32).reshape(-1)[-cap:] for c in contexts]- groups: dict[int, list[int]] = {}- for i, a in enumerate(arrs):- groups.setdefault(a.shape[0], []).append(i)-- results: list[ForecastOutput | None] = [None] * len(arrs)- for _length, idxs in groups.items():- batch = mx.array(np.stack([arrs[i] for i in idxs]))[:, None, :] # (B, 1, length)- logits = self.model.decode(batch, horizon) # (B, 1, horizon, num_quantiles)- for bi, i in enumerate(idxs):- q = logits[bi, 0] # (horizon, num_quantiles)- if sort_quantiles:- q = mx.sort(q, axis=-1)- forecast = np.array(q[:, median_idx])- if make_positive:- forecast = np.maximum(forecast, 0.0)- quantiles = None- if return_quantiles:- quantiles = np.array(q)- if make_positive:- quantiles = np.maximum(quantiles, 0.0)++ def _shape_output(raw, num_target, was_1d, ctx_2d):+ # raw: (num_variates, horizon, num_quantiles). Keep only the target rows.+ tgt = raw[:num_target]+ if sort_quantiles:+ tgt = np.sort(tgt, axis=-1)+ forecast = np.array(tgt[..., median_idx]) # (num_target, horizon)+ quantiles = np.array(tgt) if return_quantiles else None+ if make_positive:+ # Match torch: clamp a variate only when its own input is nonnegative.+ nonneg = (ctx_2d >= 0).all(axis=1)+ for r in range(num_target):+ if nonneg[r]:+ forecast[r] = np.maximum(forecast[r], 0.0)+ if quantiles is not None:+ quantiles[r] = np.maximum(quantiles[r], 0.0)+ if was_1d:+ forecast = forecast[0]+ quantiles = quantiles[0] if quantiles is not None else None+ return forecast, quantiles++ results: list[ForecastOutput | None] = [None] * n+ has_cov = any(po is not None for po in po_list) or any(+ pf is not None for pf in pf_list+ )+ all_univariate = all(np.ndim(c) == 1 for c in contexts)++ if not has_cov and all_univariate:+ # Fast path: univariate, no covariates. Group by length so each group runs+ # through a single batched forward pass. decode() is per-series independent+ # (running stats, RevIN, detrending are per row), so this is numerically+ # identical to looping but scales throughput near-linearly.+ arrs = [np.asarray(c, dtype=np.float32).reshape(-1)[-cap:] for c in contexts]+ groups: dict[int, list[int]] = {}+ for i, a in enumerate(arrs):+ groups.setdefault(a.shape[0], []).append(i)+ for _length, idxs in groups.items():+ batch = mx.array(np.stack([arrs[i] for i in idxs]))[:, None, :]+ logits = np.array(self.model.decode(batch, horizon)) # (B, 1, h, q)+ for bi, i in enumerate(idxs):+ forecast, quantiles = _shape_output(logits[bi], 1, True, arrs[i][None, :])+ results[i] = ForecastOutput(+ ts_id=ids[i], forecast=forecast, quantiles=quantiles+ )+ else:+ # General path: multivariate targets and/or covariates, one series at a time.+ for i, c in enumerate(contexts):+ was_1d = np.ndim(c) == 1+ tgt = np.atleast_2d(np.asarray(c, dtype=np.float32)) # (u, ctx)+ ctx_len = tgt.shape[-1]+ po = po_list[i]+ pf = pf_list[i]+ po = np.atleast_2d(np.asarray(po, dtype=np.float32)) if po is not None else None+ pf = np.atleast_2d(np.asarray(pf, dtype=np.float32)) if pf is not None else None+ # global_context truncation, keeping covariate windows aligned with the+ # target window (as the torch Query.format does).+ if ctx_len > cap:+ tgt = tgt[:, -cap:]+ if po is not None:+ po = po[:, -cap:]+ if pf is not None:+ future_len = pf.shape[-1] - ctx_len+ pf = pf[:, -(cap + future_len) :]+ ctx_len = cap+ logits = np.array(+ self.model.decode(+ mx.array(tgt)[None],+ horizon,+ past_only_covariates=mx.array(po)[None] if po is not None else None,+ past_future_covariates=mx.array(pf)[None] if pf is not None else None,+ )+ )[0] # (num_variates, h, q)+ forecast, quantiles = _shape_output(logits, tgt.shape[0], was_1d, tgt)results[i] = ForecastOutput(ts_id=ids[i], forecast=forecast, quantiles=quantiles)diff --git a/src/timesfm3/mlx/timesfm3_forecaster_test.py b/src/timesfm3/mlx/timesfm3_forecaster_test.pyindex b5c1fe1..17b5e0d 100644--- a/src/timesfm3/mlx/timesfm3_forecaster_test.py+++ b/src/timesfm3/mlx/timesfm3_forecaster_test.py@@ -84,6 +84,52 @@ class TimesFM3MlxModelTest(unittest.TestCase):single = np.array(model.decode(mx.array(ctxs[i])[None, None, :], horizon=24))np.testing.assert_allclose(batched[i], single[0], atol=1e-4)+ def test_decode_multivariate_targets_shape(self):+ # Two target variates in, two forecasts out.+ model = self._tiny_model()+ ctx = mx.array(np.random.RandomState(0).randn(1, 2, 128).astype(np.float32))+ logits = model.decode(ctx, horizon=24)+ self.assertEqual(logits.shape, (1, 2, 24, 9))++ def test_decode_with_covariates_returns_all_variates(self):+ # decode() stacks targets, past-only and past-future covariates on the+ # variate axis, mirroring the torch backend, and returns one row per variate.+ model = self._tiny_model()+ rng = np.random.RandomState(0)+ target = mx.array(rng.randn(1, 2, 128).astype(np.float32))+ po = mx.array(rng.randn(1, 1, 128).astype(np.float32))+ pf = mx.array(rng.randn(1, 1, 128 + 24).astype(np.float32))+ logits = model.decode(+ target, horizon=24, past_only_covariates=po, past_future_covariates=pf+ )+ # 2 targets + 1 past-only + 1 past-future = 4 variates.+ self.assertEqual(logits.shape, (1, 4, 24, 9))++ def test_past_future_covariate_infers_horizon(self):+ # When past-future covariates are given, the horizon is read from their width.+ model = self._tiny_model()+ rng = np.random.RandomState(1)+ target = mx.array(rng.randn(1, 1, 128).astype(np.float32))+ pf = mx.array(rng.randn(1, 1, 128 + 30).astype(np.float32))+ logits = model.decode(target, past_future_covariates=pf)+ self.assertEqual(logits.shape[2], 30)++ def test_detrend_activates_on_strong_trend_only(self):+ # Detrend is data-driven (weight-independent): a near-linear series activates+ # it; a stationary oscillation does not.+ model = self._tiny_model()+ masks = mx.zeros((1, 1, 128), dtype=mx.bool_)+ trend = (np.linspace(0, 10, 128) + 0.05 * np.sin(np.linspace(0, 20, 128))).astype(+ np.float32+ )+ flat = np.sin(np.linspace(0, 20, 128)).astype(np.float32)+ self.assertTrue(+ bool(model._detrend(mx.array(trend)[None, None], masks, 128)[2][0, 0])+ )+ self.assertFalse(+ bool(model._detrend(mx.array(flat)[None, None], masks, 128)[2][0, 0])+ )+@unittest.skipUnless(_HAS_MLX and _weights_cached(),@@ -143,5 +189,84 @@ class TimesFM3MlxRealWeightsTest(unittest.TestCase):)+ _HAS_MLX and _weights_cached() and _torch_available(),+ "requires the cached checkpoint and torch as the parity oracle",+)+class TimesFM3MlxCovariateParityTest(unittest.TestCase):+ """Parity of the multivariate / covariate / long-horizon paths against torch."""++ @classmethod+ def setUpClass(cls):+ from ..torch import timesfm3_forecaster as torch_forecaster++ cls.mlx = timesfm3_forecaster.TimesFM3Forecaster.from_pretrained(_CHECKPOINT)+ cls.torch = torch_forecaster.TimesFM3Forecaster.from_pretrained(_CHECKPOINT)++ def _assert_parity(self, mlx_out, torch_out, atol=1e-3):+ np.testing.assert_allclose(+ np.asarray(mlx_out.forecast), np.asarray(torch_out.forecast), atol=atol+ )+ np.testing.assert_allclose(+ np.asarray(mlx_out.quantiles), np.asarray(torch_out.quantiles), atol=atol+ )++ def test_parity_long_horizon(self):+ # Horizon >= 128 exercises multiple output patches + CPM refine + stitching.+ ctx = np.sin(np.linspace(0, 40, 512)).astype(np.float32)+ for horizon in (128, 256):+ mlx_out = self.mlx.predict(ctx, horizon=horizon, return_quantiles=True)+ torch_out = self.torch.predict(ctx, horizon=horizon, return_quantiles=True)+ self.assertEqual(np.asarray(mlx_out.forecast).shape, (horizon,))+ self._assert_parity(mlx_out, torch_out)++ def test_parity_two_targets(self):+ rng = np.random.RandomState(0)+ target = np.stack(+ [+ np.sin(np.linspace(0, 30, 256)),+ np.cos(np.linspace(0, 18, 256)) + 0.1 * rng.randn(256),+ ]+ ).astype(np.float32)+ mlx_out = self.mlx.predict(target, horizon=64, return_quantiles=True)+ torch_out = self.torch.predict(target, horizon=64, return_quantiles=True)+ self.assertEqual(np.asarray(mlx_out.forecast).shape, (2, 64))+ self._assert_parity(mlx_out, torch_out)++ def test_parity_two_targets_with_covariates(self):+ rng = np.random.RandomState(1)+ ctx_len, horizon = 256, 32+ target = np.stack(+ [np.sin(np.linspace(0, 24, ctx_len)), np.sin(np.linspace(1, 26, ctx_len))]+ ).astype(np.float32)+ past_only = (0.5 * rng.randn(1, ctx_len)).astype(np.float32)+ past_future = np.sin(np.linspace(0, 30, ctx_len + horizon))[None, :].astype(+ np.float32+ )+ kw = dict(+ horizon=horizon,+ past_only_covariates=past_only,+ past_future_covariates=past_future,+ return_quantiles=True,+ )+ mlx_out = self.mlx.predict(target, **kw)+ torch_out = self.torch.predict(target, **kw)+ self.assertEqual(np.asarray(mlx_out.forecast).shape, (2, horizon))+ self._assert_parity(mlx_out, torch_out)++ def test_parity_detrend_activated(self):+ # A strong linear trend activates detrend on both backends; outputs must agree.+ ctx = (np.linspace(0, 12, 512) + 0.05 * np.sin(np.linspace(0, 40, 512))).astype(+ np.float32+ )+ masks = mx.zeros((1, 1, 512), dtype=mx.bool_)+ self.assertTrue(+ bool(self.mlx.model._detrend(mx.array(ctx)[None, None], masks, 512)[2][0, 0])+ )+ mlx_out = self.mlx.predict(ctx, horizon=64, return_quantiles=True)+ torch_out = self.torch.predict(ctx, horizon=64, return_quantiles=True)+ self._assert_parity(mlx_out, torch_out)++if __name__ == "__main__":unittest.main()