Skip to content

TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google Research for time-series forecasting.

Python

style(timesfm3): use the repo's 2-space indentation in the MLX backend

rachittshah3a66516cafae
diff --git a/src/timesfm3/__init__.py b/src/timesfm3/__init__.py
index 67390a5..08aa9ab 100644
--- a/src/timesfm3/__init__.py
+++ b/src/timesfm3/__init__.py
@@ -20,7 +20,8 @@ The PyTorch backend lives in ``timesfm3.torch`` and the MLX (Apple Silicon) back
``timesfm3`` — or ``timesfm3.mlx`` — does not require PyTorch to be installed.
"""
-_TORCH_EXPORTS = frozenset({
+_TORCH_EXPORTS = frozenset(
+ {
"ForecastOutput",
"ModelConfig",
"ResidualBlockConfig",
@@ -30,14 +31,15 @@ _TORCH_EXPORTS = frozenset({
"TimesFM3Torch",
"TransformerConfig",
"_ModelConfig",
-})
+ }
+)
__all__ = sorted(_TORCH_EXPORTS)
def __getattr__(name): # PEP 562: lazily re-export the torch backend at the top level
- if name in _TORCH_EXPORTS:
- from . import torch as _torch_backend
+ if name in _TORCH_EXPORTS:
+ from . import torch as _torch_backend
- return getattr(_torch_backend, name)
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+ return getattr(_torch_backend, name)
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/src/timesfm3/mlx/__init__.py b/src/timesfm3/mlx/__init__.py
index 1cb12a3..b2a141a 100644
--- a/src/timesfm3/mlx/__init__.py
+++ b/src/timesfm3/mlx/__init__.py
@@ -17,17 +17,17 @@
from .configs import TimesFM3MlxConfig
from .model import TimesFM3Mlx
from .timesfm3_forecaster import (
- ForecastOutput,
- ModelConfig,
- TimesFM3Forecaster,
- _ModelConfig,
+ ForecastOutput,
+ ModelConfig,
+ TimesFM3Forecaster,
+ _ModelConfig,
)
__all__ = [
- "ForecastOutput",
- "ModelConfig",
- "TimesFM3Forecaster",
- "TimesFM3Mlx",
- "TimesFM3MlxConfig",
- "_ModelConfig",
+ "ForecastOutput",
+ "ModelConfig",
+ "TimesFM3Forecaster",
+ "TimesFM3Mlx",
+ "TimesFM3MlxConfig",
+ "_ModelConfig",
]
diff --git a/src/timesfm3/mlx/model.py b/src/timesfm3/mlx/model.py
index 69ec73c..c470f33 100644
--- a/src/timesfm3/mlx/model.py
+++ b/src/timesfm3/mlx/model.py
@@ -36,7 +36,9 @@ from .dense import ResidualBlock
class TimesFM3Mlx(nn.Module):
"""MLX TimesFM3. Use :meth:`from_pretrained` to load real weights from a checkpoint."""
- def __init__(self, config: configs.TimesFM3MlxConfig | None = None, compile: bool = True):
+ def __init__(
+ self, config: configs.TimesFM3MlxConfig | None = None, compile: bool = True
+ ):
super().__init__()
cfg = config or configs.TimesFM3MlxConfig()
self.config = cfg
@@ -67,7 +69,9 @@ class TimesFM3Mlx(nn.Module):
resblock_in = mx.concatenate([vals_cat, masks_cat.astype(mx.float32)], axis=-1)
x = self.pre_transformer_resblock(resblock_in.astype(self._compute_dtype))
patch_mask = masks_cat.astype(mx.float32).min(axis=3) > 0.5
- eff = mx.cumprod(patch_mask.astype(mx.int32), axis=2) > 0 # mask leading patches only
+ eff = (
+ mx.cumprod(patch_mask.astype(mx.int32), axis=2) > 0
+ ) # mask leading patches only
x = self.transformer_stack(x, eff)
raw = self.output_head(x).astype(mx.float32)
if patch_cpm_mask is not None:
@@ -181,7 +185,7 @@ class TimesFM3Mlx(nn.Module):
sum_t2 = mx.where(~ctx_masks, t * t, 0.0).sum(axis=-1)
sum_y = mx.where(~ctx_masks, ctx_vals, 0.0).sum(axis=-1)
sum_ty = mx.where(~ctx_masks, t * ctx_vals, 0.0).sum(axis=-1)
- det = n_v * sum_t2 - sum_t ** 2
+ det = n_v * sum_t2 - sum_t**2
safe = mx.where(det == 0.0, 1.0, det)
m = mx.where(det == 0.0, 0.0, (n_v * sum_ty - sum_t * sum_y) / safe)
c = mx.where(
@@ -191,12 +195,12 @@ class TimesFM3Mlx(nn.Module):
)
detr = ctx_vals - (m[..., None] * t + c[..., None])
mean_y = sum_y / mx.maximum(n_v, 1.0)
- sum_y2 = mx.where(~ctx_masks, ctx_vals ** 2, 0.0).sum(axis=-1)
- std_orig = mx.sqrt(mx.maximum(sum_y2 / mx.maximum(n_v, 1.0) - mean_y ** 2, 0.0))
+ sum_y2 = mx.where(~ctx_masks, ctx_vals**2, 0.0).sum(axis=-1)
+ std_orig = mx.sqrt(mx.maximum(sum_y2 / mx.maximum(n_v, 1.0) - mean_y**2, 0.0))
sum_yd = mx.where(~ctx_masks, detr, 0.0).sum(axis=-1)
mean_yd = sum_yd / mx.maximum(n_v, 1.0)
- sum_yd2 = mx.where(~ctx_masks, detr ** 2, 0.0).sum(axis=-1)
- std_det = mx.sqrt(mx.maximum(sum_yd2 / mx.maximum(n_v, 1.0) - mean_yd ** 2, 0.0))
+ sum_yd2 = mx.where(~ctx_masks, detr**2, 0.0).sum(axis=-1)
+ std_det = mx.sqrt(mx.maximum(sum_yd2 / mx.maximum(n_v, 1.0) - mean_yd**2, 0.0))
apply = std_det < cfg.linear_detrending_threshold * std_orig
return m, c, apply
diff --git a/src/timesfm3/mlx/timesfm3_forecaster.py b/src/timesfm3/mlx/timesfm3_forecaster.py
index 030499b..bbfb5b7 100644
--- a/src/timesfm3/mlx/timesfm3_forecaster.py
+++ b/src/timesfm3/mlx/timesfm3_forecaster.py
@@ -160,7 +160,9 @@ class TimesFM3Forecaster:
("use_znorm", use_znorm),
):
if flag:
- raise NotImplementedError(f"{name}=True is not yet supported by the MLX backend.")
+ raise NotImplementedError(
+ f"{name}=True is not yet supported by the MLX backend."
+ )
if padding_mode != "none":
raise NotImplementedError(
f"padding_mode={padding_mode!r} is not yet supported by the MLX backend."
@@ -195,7 +197,9 @@ class TimesFM3Forecaster:
quantiles = np.array(q)
if make_positive:
quantiles = np.maximum(quantiles, 0.0)
- results[i] = ForecastOutput(ts_id=ids[i], forecast=forecast, quantiles=quantiles)
+ results[i] = ForecastOutput(
+ ts_id=ids[i], forecast=forecast, quantiles=quantiles
+ )
for r in results:
yield r
diff --git a/src/timesfm3/mlx/timesfm3_forecaster_test.py b/src/timesfm3/mlx/timesfm3_forecaster_test.py
index 5fbeace..193ebee 100644
--- a/src/timesfm3/mlx/timesfm3_forecaster_test.py
+++ b/src/timesfm3/mlx/timesfm3_forecaster_test.py
@@ -76,9 +76,9 @@ class TimesFM3MlxModelTest(unittest.TestCase):
def test_batched_decode_matches_single(self):
# decode() is per-series independent, so a batched call must equal looping series-by-series.
model = self._tiny_model()
- ctxs = np.stack(
- [np.sin(np.linspace(0, 10 + i, 128)) for i in range(3)]
- ).astype(np.float32)
+ ctxs = np.stack([np.sin(np.linspace(0, 10 + i, 128)) for i in range(3)]).astype(
+ np.float32
+ )
batched = np.array(model.decode(mx.array(ctxs)[:, None, :], horizon=24))
for i in range(3):
single = np.array(model.decode(mx.array(ctxs[i])[None, None, :], horizon=24))
@@ -86,7 +86,8 @@ class TimesFM3MlxModelTest(unittest.TestCase):
@unittest.skipUnless(
- _HAS_MLX and _weights_cached(), "requires the cached google/timesfm-3.0-pytorch checkpoint"
+ _HAS_MLX and _weights_cached(),
+ "requires the cached google/timesfm-3.0-pytorch checkpoint",
)
class TimesFM3MlxRealWeightsTest(unittest.TestCase):
"""End-to-end tests on the real pretrained weights."""
@@ -94,7 +95,9 @@ class TimesFM3MlxRealWeightsTest(unittest.TestCase):
def test_predict_shapes(self):
forecaster = timesfm3_forecaster.TimesFM3Forecaster.from_pretrained(_CHECKPOINT)
out = forecaster.predict(
- np.sin(np.linspace(0, 40, 512)).astype(np.float32), horizon=64, return_quantiles=True
+ np.sin(np.linspace(0, 40, 512)).astype(np.float32),
+ horizon=64,
+ return_quantiles=True,
)
self.assertEqual(np.asarray(out.forecast).shape, (64,))
self.assertEqual(np.asarray(out.quantiles).shape, (64, 9))
@@ -104,17 +107,18 @@ class TimesFM3MlxRealWeightsTest(unittest.TestCase):
from ..torch import timesfm3_forecaster as torch_forecaster
ctx = np.sin(np.linspace(0, 40, 512)).astype(np.float32)
- mlx_out = timesfm3_forecaster.TimesFM3Forecaster.from_pretrained(_CHECKPOINT).predict(
- ctx, horizon=64, return_quantiles=True
- )
- torch_out = torch_forecaster.TimesFM3Forecaster.from_pretrained(_CHECKPOINT).predict(
- ctx, horizon=64, return_quantiles=True
- )
+ mlx_out = timesfm3_forecaster.TimesFM3Forecaster.from_pretrained(
+ _CHECKPOINT
+ ).predict(ctx, horizon=64, return_quantiles=True)
+ torch_out = torch_forecaster.TimesFM3Forecaster.from_pretrained(
+ _CHECKPOINT
+ ).predict(ctx, horizon=64, return_quantiles=True)
self.assertLess(
np.abs(np.asarray(mlx_out.forecast) - np.asarray(torch_out.forecast)).max(), 1e-3
)
self.assertLess(
- np.abs(np.asarray(mlx_out.quantiles) - np.asarray(torch_out.quantiles)).max(), 1e-3
+ np.abs(np.asarray(mlx_out.quantiles) - np.asarray(torch_out.quantiles)).max(),
+ 1e-3,
)
diff --git a/src/timesfm3/mlx/transformer.py b/src/timesfm3/mlx/transformer.py
index ba74d96..e1621a5 100644
--- a/src/timesfm3/mlx/transformer.py
+++ b/src/timesfm3/mlx/transformer.py
@@ -28,13 +28,17 @@ import mlx.nn as nn
from . import configs, normalization
-def rope(x: mx.array, position: mx.array, min_ts: float = 1.0, max_ts: float = 10000.0) -> mx.array:
+def rope(
+ x: mx.array, position: mx.array, min_ts: float = 1.0, max_ts: float = 10000.0
+) -> mx.array:
"""Rotary positional embedding on ``(b, n, h, hd)`` with ``position`` ``(b, n)`` (half-split)."""
hd = x.shape[-1]
half = hd // 2
fraction = 2.0 * mx.arange(half).astype(mx.float32) / hd
timescale = min_ts * (max_ts / min_ts) ** fraction
- sinusoid = position[:, :, None, None].astype(mx.float32) / timescale.reshape(1, 1, 1, -1)
+ sinusoid = position[:, :, None, None].astype(mx.float32) / timescale.reshape(
+ 1, 1, 1, -1
+ )
sin, cos = mx.sin(sinusoid), mx.cos(sinusoid)
first, second = mx.split(x, 2, axis=-1)
return mx.concatenate(
diff --git a/src/timesfm3/mlx/util.py b/src/timesfm3/mlx/util.py
index b4718de..1b87ea9 100644
--- a/src/timesfm3/mlx/util.py
+++ b/src/timesfm3/mlx/util.py
@@ -39,7 +39,9 @@ def roll_back1(x: mx.array, axis: int) -> mx.array:
return mx.take(x, idx, axis=axis)
-def revin(x: mx.array, mu: mx.array, sigma: mx.array, reverse: bool = False) -> mx.array:
+def revin(
+ x: mx.array, mu: mx.array, sigma: mx.array, reverse: bool = False
+) -> mx.array:
"""Reversible per-instance normalization; mu/sigma have 1 or 2 fewer dims than x."""
if mu.ndim == x.ndim - 1:
mu, sigma = mu[..., None], sigma[..., None]