TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google Research for time-series forecasting.
Python
fix(timesfm3/mlx): match torch on stitching, cpm revin, residual activation, and NaN handling
Mathis Doutre3114393ec78e
diff --git a/src/timesfm3/mlx/configs.py b/src/timesfm3/mlx/configs.pyindex 9f963cc..180c392 100644--- a/src/timesfm3/mlx/configs.py+++ b/src/timesfm3/mlx/configs.py@@ -40,6 +40,10 @@ class TimesFM3MlxConfig:use_linear_detrending: bool = Truelinear_detrending_threshold: float = 0.5value_clip: float = 1e20+ use_iterative_cpm_revin: bool = True+ residual_activation: str = "relu"+ residual_prenorm: str = "none"+ residual_identity_skip: bool = False@propertydef head_dim(self) -> int:@@ -67,6 +71,7 @@ class TimesFM3MlxConfig:)transformer = cfg.get("transformer_config", {})inner = transformer.get("transformer", {})+ resblock = cfg.get("residual_block_config", {})return cls(input_patch_len=cfg.get("input_patch_len", 32),output_patch_len=cfg.get("output_patch_len", 64),@@ -80,4 +85,8 @@ class TimesFM3MlxConfig:use_linear_detrending=cfg.get("use_linear_detrending", True),linear_detrending_threshold=cfg.get("linear_detrending_threshold", 0.5),value_clip=cfg.get("value_clip", 1e20),+ use_iterative_cpm_revin=cfg.get("use_iterative_cpm_revin", True),+ residual_activation=resblock.get("activation", "relu"),+ residual_prenorm=resblock.get("prenorm", "none"),+ residual_identity_skip=resblock.get("identity_skip", False),)diff --git a/src/timesfm3/mlx/dense.py b/src/timesfm3/mlx/dense.pyindex 1a2a11e..4f5f1e9 100644--- a/src/timesfm3/mlx/dense.py+++ b/src/timesfm3/mlx/dense.py@@ -19,19 +19,43 @@ from __future__ import annotationsimport mlx.core as mximport mlx.nn as nn+from . import normalization++_ACTIVATIONS = {+ "relu": nn.relu,+ "swish": nn.silu,+ "none": lambda x: x,+}-class ResidualBlock(nn.Module):- """Two linear layers with a linear residual connection (no bias, no prenorm).- ``output_layer(relu(hidden_layer(x))) + residual_layer(x)`` -- matches the pre-transformer+class ResidualBlock(nn.Module):+ """Two linear layers with a residual connection (no bias) -- matches the pre-transformerresidual block of the PyTorch backend.++ ``output_layer(activation(hidden_layer(prenorm(x)))) + residual_layer(x)`` (or ``+ x`` when+ ``identity_skip``)."""- def __init__(self, in_dim: int, out_dim: int):+ def __init__(+ self,+ in_dim: int,+ out_dim: int,+ activation: str = "relu",+ prenorm: str = "none",+ identity_skip: bool = False,+ ):super().__init__()self.hidden_layer = nn.Linear(in_dim, out_dim, bias=False)self.output_layer = nn.Linear(out_dim, out_dim, bias=False)- self.residual_layer = nn.Linear(in_dim, out_dim, bias=False)+ self.identity_skip = identity_skip+ if not identity_skip:+ self.residual_layer = nn.Linear(in_dim, out_dim, bias=False)+ self.activation = _ACTIVATIONS[activation]+ self.pre_norm = normalization.RMSNorm(in_dim) if prenorm == "rms" else Nonedef __call__(self, x: mx.array) -> mx.array:- return self.output_layer(nn.relu(self.hidden_layer(x))) + self.residual_layer(x)+ hidden_input = self.pre_norm(x) if self.pre_norm is not None else x+ hidden = self.activation(self.hidden_layer(hidden_input))+ if self.identity_skip:+ return self.output_layer(hidden) + x+ return self.output_layer(hidden) + self.residual_layer(x)diff --git a/src/timesfm3/mlx/model.py b/src/timesfm3/mlx/model.pyindex 9eaad08..2e6e6a2 100644--- a/src/timesfm3/mlx/model.py+++ b/src/timesfm3/mlx/model.py@@ -43,7 +43,11 @@ class TimesFM3Mlx(nn.Module):cfg = config or configs.TimesFM3MlxConfig()self.config = cfgself.pre_transformer_resblock = ResidualBlock(- 2 * (cfg.input_patch_len + cfg.output_patch_len), cfg.model_dims+ 2 * (cfg.input_patch_len + cfg.output_patch_len),+ cfg.model_dims,+ activation=cfg.residual_activation,+ prenorm=cfg.residual_prenorm,+ identity_skip=cfg.residual_identity_skip,)self.transformer_stack = transformer.StackedMixingTransformer(cfg)self.output_head = nn.Linear(@@ -56,6 +60,8 @@ class TimesFM3Mlx(nn.Module):# ---- full-sequence forward over patched inputs (target-only path) ----def _forward_logits(self, values, masks, patch_is_target, patch_cpm_mask=None):cfg = self.config+ values = mx.where(mx.isnan(values), 0.0, values)+ values = mx.clip(values, -cfg.value_clip, cfg.value_clip)running_n, mu, sigma = util.get_running_stats(values, masks)vals_norm = util.revin(values, mu, sigma)vals_norm = mx.where(masks, 0.0, vals_norm)@@ -74,7 +80,7 @@ class TimesFM3Mlx(nn.Module):) # mask leading patches onlyx = self.transformer_stack(x, eff)raw = self.output_head(x).astype(mx.float32)- if patch_cpm_mask is not None:+ if patch_cpm_mask is not None and cfg.use_iterative_cpm_revin:ref_mu, ref_sigma = cpm_revin_refine_lib.cpm_iterative_revin_refine(raw,running_n,@@ -176,12 +182,17 @@ class TimesFM3Mlx(nn.Module):context = context + ctx_padnum_ctx_patches = context // p- extract_len = min(2 * p, cfg.output_patch_len)- overlap = extract_len - p- num_forecast_patches = max(math.ceil((horizon - overlap) / p), 1)- num_hor_patches = num_forecast_patches + cfg.rolls - 1- padded_h = num_hor_patches * p- hor_pad = padded_h - horizon+ if cfg.use_stitching:+ extract_len = min(2 * p, cfg.output_patch_len)+ overlap = extract_len - p+ num_forecast_patches = max(math.ceil((horizon - overlap) / p), 1)+ num_hor_patches = num_forecast_patches + cfg.rolls - 1+ padded_h = num_hor_patches * p+ hor_pad = padded_h - horizon+ else:+ hor_pad = (-horizon) % cfg.output_patch_len+ padded_h = horizon + hor_pad+ num_hor_patches = padded_h // p# 2. Stack targets + covariates on the variate axis.if target_mask is None:@@ -274,9 +285,17 @@ class TimesFM3Mlx(nn.Module):)logits = self._forward_fn()(values_bvnp, masks_bvnp, patch_is_target, horizon_cpm)- fidx = mx.arange(num_forecast_patches) + (num_ctx_patches - 1)- patch_preds = mx.take(logits, fidx, axis=2)[:, :, :, :extract_len, :]- horizon_logits = util.stitch_patches(patch_preds, p)[:, :, :horizon, :]+ if cfg.use_stitching:+ fidx = mx.arange(num_forecast_patches) + (num_ctx_patches - 1)+ patch_preds = mx.take(logits, fidx, axis=2)[:, :, :, :extract_len, :]+ horizon_logits = util.stitch_patches(patch_preds, p)[:, :, :horizon, :]+ else:+ num_forecast_chunks = padded_h // cfg.output_patch_len+ fidx = mx.arange(num_forecast_chunks) * cfg.rolls + (num_ctx_patches - 1)+ forecast_logits = mx.take(logits, fidx, axis=2)+ horizon_logits = forecast_logits.reshape(b, num_variates, -1, cfg.num_quantiles)[+ :, :, :horizon, :+ ]if cfg.use_linear_detrending:tf = mx.arange(1, horizon + 1).astype(mx.float32) / contextdiff --git a/src/timesfm3/mlx/model_parity_test.py b/src/timesfm3/mlx/model_parity_test.pynew file mode 100644index 0000000..f539cb3--- /dev/null+++ b/src/timesfm3/mlx/model_parity_test.py@@ -0,0 +1,252 @@+# Copyright 2026 Google LLC+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Numerical parity tests between the MLX and PyTorch TimesFM3 backends.++These tests build tiny (model_dims=32, 2-layer) randomly-initialized models on CPU -- no+pretrained checkpoint download and no GPU/Metal requirement -- transplant the PyTorch model's+weights into the MLX model via a temporary safetensors file (the two backends use an+identical parameter-name/shape scheme by design, see ``TimesFM3Mlx.load_safetensors``), and+compare ``decode()`` outputs directly.++``TimesFM3ParityTest`` checks configurations both backends are meant to support identically.+``TimesFM3KnownDivergenceTest`` is a regression suite for specific MLX/PyTorch divergences found+during review (``use_stitching=False``, ``use_iterative_cpm_revin=False``, residual block+``activation``, and unmasked NaN in the context) and since fixed in the MLX backend.+"""++from __future__ import annotations++import os+import tempfile+import unittest++import numpy as np++try:+ import mlx.core as mx+ from mlx.utils import tree_flatten++ from . import configs as mlx_configs+ from . import model as mlx_model_lib++ _HAS_MLX = True+except ImportError:+ _HAS_MLX = False+++def _torch_available() -> bool:+ try:+ import torch # noqa: F401++ return True+ except ImportError:+ return False+++_INPUT_PATCH_LEN = 8+_OUTPUT_PATCH_LEN = 16+_MODEL_DIMS = 32+_HIDDEN_DIMS = 32+_NUM_HEADS = 4+_NUM_LAYERS = 2+_QUANTILES = [0.1, 0.5, 0.9]+++def _build_torch_model(+ *,+ use_stitching: bool = True,+ use_iterative_cpm_revin: bool = True,+ activation: str = "relu",+ seed: int = 0,+):+ import torch++ from ..torch import configs as torch_configs+ from ..torch import model as torch_model_lib++ torch.manual_seed(seed)+ resblock_cfg = torch_configs.ResidualBlockConfig(+ hidden_dims=_MODEL_DIMS,+ output_dims=_MODEL_DIMS,+ use_bias=False,+ activation=activation,+ )+ transformer_cfg = torch_configs.StackedTransformersConfig(+ num_layers=_NUM_LAYERS,+ use_remat=False,+ transformer=torch_configs.TransformerConfig(+ model_dims=_MODEL_DIMS,+ hidden_dims=_HIDDEN_DIMS,+ num_heads=_NUM_HEADS,+ attention_norm="rms",+ feedforward_norm="rms",+ qk_norm="rms",+ use_rope_seq=True,+ use_rope_var=False,+ use_bias=False,+ ff_activation="relu",+ deterministic=True,+ use_sdpa=True,+ ),+ )+ model = torch_model_lib.TimesFM3Torch(+ input_patch_len=_INPUT_PATCH_LEN,+ output_patch_len=_OUTPUT_PATCH_LEN,+ quantiles=_QUANTILES,+ residual_block_config=resblock_cfg,+ transformer_config=transformer_cfg,+ use_stitching=use_stitching,+ use_linear_detrending=True,+ use_iterative_cpm_revin=use_iterative_cpm_revin,+ use_frozen_running_stats=False,+ )+ model.eval()+ return model+++def _build_mlx_model(+ *,+ use_stitching: bool = True,+ use_iterative_cpm_revin: bool = True,+ residual_activation: str = "relu",+) -> "mlx_model_lib.TimesFM3Mlx":+ cfg = mlx_configs.TimesFM3MlxConfig(+ input_patch_len=_INPUT_PATCH_LEN,+ output_patch_len=_OUTPUT_PATCH_LEN,+ model_dims=_MODEL_DIMS,+ hidden_dims=_HIDDEN_DIMS,+ num_layers=_NUM_LAYERS,+ num_heads=_NUM_HEADS,+ quantiles=tuple(_QUANTILES),+ use_variate_attention=True,+ use_stitching=use_stitching,+ use_linear_detrending=True,+ linear_detrending_threshold=0.5,+ value_clip=1e20,+ use_iterative_cpm_revin=use_iterative_cpm_revin,+ residual_activation=residual_activation,+ )+ return mlx_model_lib.TimesFM3Mlx(cfg, compile=False)+++def _transplant(torch_model, mlx_model) -> "mlx_model_lib.TimesFM3Mlx":+ """Copies ``torch_model``'s weights into ``mlx_model`` via a safetensors round-trip."""+ from safetensors.torch import save_file++ state_dict = torch_model.state_dict()+ with tempfile.TemporaryDirectory() as tmpdir:+ path = os.path.join(tmpdir, "model.safetensors")+ save_file({k: v.contiguous() for k, v in state_dict.items()}, path)+ mlx_model.load_safetensors(path)+ return mlx_model+++def _build_pair(**torch_kwargs):+ """Builds a (torch_model, mlx_model) pair sharing identical weights."""+ torch_model = _build_torch_model(**torch_kwargs)+ mlx_model = _build_mlx_model(+ use_stitching=torch_kwargs.get("use_stitching", True),+ use_iterative_cpm_revin=torch_kwargs.get("use_iterative_cpm_revin", True),+ residual_activation=torch_kwargs.get("activation", "relu"),+ )+ _transplant(torch_model, mlx_model)+ return torch_model, mlx_model+++def _decode_both(torch_model, mlx_model, ctx: np.ndarray, horizon: int, **kwargs):+ import torch++ torch_kwargs = {k: torch.from_numpy(v) for k, v in kwargs.items()}+ mlx_kwargs = {k: mx.array(v) for k, v in kwargs.items()}+ with torch.no_grad():+ torch_out = torch_model.decode(+ target=torch.from_numpy(ctx), horizon=horizon, **torch_kwargs+ ).numpy()+ mlx_out = np.array(mlx_model.decode(mx.array(ctx), horizon=horizon, **mlx_kwargs))+ return torch_out, mlx_out++[email protected](_HAS_MLX, "mlx is not installed (Apple silicon only)")[email protected](_torch_available(), "requires torch as the parity oracle")+class TimesFM3ParityTest(unittest.TestCase):+ """Configurations both backends claim to support identically -- must match closely."""++ def test_decode_univariate_matches(self):+ torch_model, mlx_model = _build_pair()+ ctx = np.random.RandomState(0).randn(1, 1, 128).astype(np.float32)+ torch_out, mlx_out = _decode_both(torch_model, mlx_model, ctx, horizon=24)+ np.testing.assert_allclose(torch_out, mlx_out, atol=1e-4)++ def test_decode_multivariate_with_covariates_matches(self):+ torch_model, mlx_model = _build_pair()+ rng = np.random.RandomState(1)+ target = rng.randn(1, 2, 128).astype(np.float32)+ po = rng.randn(1, 1, 128).astype(np.float32)+ pf = rng.randn(1, 1, 128 + 24).astype(np.float32)+ torch_out, mlx_out = _decode_both(+ torch_model,+ mlx_model,+ target,+ horizon=24,+ past_only_covariates=po,+ past_future_covariates=pf,+ )+ self.assertEqual(torch_out.shape, (1, 4, 24, 3))+ np.testing.assert_allclose(torch_out, mlx_out, atol=1e-4)++[email protected](_HAS_MLX, "mlx is not installed (Apple silicon only)")[email protected](_torch_available(), "requires torch as the parity oracle")+class TimesFM3KnownDivergenceTest(unittest.TestCase):+ """Regression tests for specific MLX/PyTorch numerical divergences found during review, now+ fixed in the MLX backend (mlx/model.py, mlx/dense.py, mlx/configs.py).+ """++ def test_use_stitching_false_is_ignored_by_mlx(self):+ # mlx/model.py's decode() branches on cfg.use_stitching the same way torch/model.py does.+ torch_model, mlx_model = _build_pair(use_stitching=False)+ ctx = np.random.RandomState(0).randn(1, 1, 128).astype(np.float32)+ torch_out, mlx_out = _decode_both(torch_model, mlx_model, ctx, horizon=24)+ np.testing.assert_allclose(torch_out, mlx_out, atol=1e-4)++ def test_use_iterative_cpm_revin_false_is_ignored_by_mlx(self):+ # torch/model.py only calls cpm_iterative_revin_refine when use_iterative_cpm_revin is True;+ # mlx/model.py mirrors this via TimesFM3MlxConfig.use_iterative_cpm_revin.+ torch_model, mlx_model = _build_pair(use_iterative_cpm_revin=False)+ ctx = np.random.RandomState(0).randn(1, 1, 128).astype(np.float32)+ torch_out, mlx_out = _decode_both(torch_model, mlx_model, ctx, horizon=24)+ np.testing.assert_allclose(torch_out, mlx_out, atol=1e-4)++ def test_residual_block_activation_is_ignored_by_mlx(self):+ # mlx/dense.py's ResidualBlock reads its activation from+ # TimesFM3MlxConfig.residual_activation, matching torch's ResidualBlockConfig.activation.+ torch_model, mlx_model = _build_pair(activation="swish")+ ctx = np.random.RandomState(0).randn(1, 1, 128).astype(np.float32)+ torch_out, mlx_out = _decode_both(torch_model, mlx_model, ctx, horizon=24)+ np.testing.assert_allclose(torch_out, mlx_out, atol=1e-4)++ def test_nan_context_is_not_sanitized_by_mlx(self):+ # torch/model.py's forward() runs `values = torch.nan_to_num(values, nan=0.0)` (then clamps)+ # before computing RevIN running stats; mlx/model.py's _forward_logits mirrors this.+ torch_model, mlx_model = _build_pair()+ ctx = np.random.RandomState(0).randn(1, 1, 128).astype(np.float32)+ ctx[0, 0, 50] = np.nan+ torch_out, mlx_out = _decode_both(torch_model, mlx_model, ctx, horizon=24)+ self.assertFalse(np.isnan(mlx_out).any(), "mlx output contains NaN where torch's does not")+ np.testing.assert_allclose(torch_out, mlx_out, atol=1e-4)+++if __name__ == "__main__":+ unittest.main()