Skip to content

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

Python

fix(timesfm3/mlx): honor ff_activation, v_norm, causal_attention, use_rope_var, and use_memory_efficient_attention

Mathis Doutred9c47b7c8bdb
diff --git a/src/timesfm3/mlx/configs.py b/src/timesfm3/mlx/configs.py
index 180c392..699e3bf 100644
--- a/src/timesfm3/mlx/configs.py
+++ b/src/timesfm3/mlx/configs.py
@@ -44,6 +44,12 @@ class TimesFM3MlxConfig:
residual_activation: str = "relu"
residual_prenorm: str = "none"
residual_identity_skip: bool = False
+ ff_activation: str = "relu"
+ v_norm: str = "none"
+ causal_attention: bool = True
+ use_rope_seq: bool = True
+ use_rope_var: bool = False
+ use_memory_efficient_attention: bool = True
@property
def head_dim(self) -> int:
@@ -89,4 +95,10 @@ class TimesFM3MlxConfig:
residual_activation=resblock.get("activation", "relu"),
residual_prenorm=resblock.get("prenorm", "none"),
residual_identity_skip=resblock.get("identity_skip", False),
+ ff_activation=inner.get("ff_activation", "relu"),
+ v_norm=inner.get("v_norm", "none"),
+ causal_attention=inner.get("causal_attention", True),
+ use_rope_seq=inner.get("use_rope_seq", True),
+ use_rope_var=inner.get("use_rope_var", False),
+ use_memory_efficient_attention=inner.get("use_memory_efficient_attention", True),
)
diff --git a/src/timesfm3/mlx/model_parity_test.py b/src/timesfm3/mlx/model_parity_test.py
index f539cb3..bd59dcf 100644
--- a/src/timesfm3/mlx/model_parity_test.py
+++ b/src/timesfm3/mlx/model_parity_test.py
@@ -69,6 +69,11 @@ def _build_torch_model(
use_stitching: bool = True,
use_iterative_cpm_revin: bool = True,
activation: str = "relu",
+ ff_activation: str = "relu",
+ v_norm: str = "none",
+ causal_attention: bool = True,
+ use_rope_var: bool = False,
+ use_memory_efficient_attention: bool = True,
seed: int = 0,
):
import torch
@@ -93,12 +98,15 @@ def _build_torch_model(
attention_norm="rms",
feedforward_norm="rms",
qk_norm="rms",
+ v_norm=v_norm,
use_rope_seq=True,
- use_rope_var=False,
+ use_rope_var=use_rope_var,
use_bias=False,
- ff_activation="relu",
+ ff_activation=ff_activation,
deterministic=True,
use_sdpa=True,
+ causal_attention=causal_attention,
+ use_memory_efficient_attention=use_memory_efficient_attention,
),
)
model = torch_model_lib.TimesFM3Torch(
@@ -121,6 +129,11 @@ def _build_mlx_model(
use_stitching: bool = True,
use_iterative_cpm_revin: bool = True,
residual_activation: str = "relu",
+ ff_activation: str = "relu",
+ v_norm: str = "none",
+ causal_attention: bool = True,
+ use_rope_var: bool = False,
+ use_memory_efficient_attention: bool = True,
) -> "mlx_model_lib.TimesFM3Mlx":
cfg = mlx_configs.TimesFM3MlxConfig(
input_patch_len=_INPUT_PATCH_LEN,
@@ -137,6 +150,11 @@ def _build_mlx_model(
value_clip=1e20,
use_iterative_cpm_revin=use_iterative_cpm_revin,
residual_activation=residual_activation,
+ ff_activation=ff_activation,
+ v_norm=v_norm,
+ causal_attention=causal_attention,
+ use_rope_var=use_rope_var,
+ use_memory_efficient_attention=use_memory_efficient_attention,
)
return mlx_model_lib.TimesFM3Mlx(cfg, compile=False)
@@ -160,6 +178,11 @@ def _build_pair(**torch_kwargs):
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"),
+ ff_activation=torch_kwargs.get("ff_activation", "relu"),
+ v_norm=torch_kwargs.get("v_norm", "none"),
+ causal_attention=torch_kwargs.get("causal_attention", True),
+ use_rope_var=torch_kwargs.get("use_rope_var", False),
+ use_memory_efficient_attention=torch_kwargs.get("use_memory_efficient_attention", True),
)
_transplant(torch_model, mlx_model)
return torch_model, mlx_model
@@ -211,7 +234,7 @@ class TimesFM3ParityTest(unittest.TestCase):
@unittest.skipUnless(_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).
+ fixed in the MLX backend.
"""
def test_use_stitching_false_is_ignored_by_mlx(self):
@@ -247,6 +270,47 @@ class TimesFM3KnownDivergenceTest(unittest.TestCase):
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)
+ def test_ff_activation_is_ignored_by_mlx(self):
+ # mlx/transformer.py's MixingTransformer reads its FFN activation from
+ # TimesFM3MlxConfig.ff_activation, matching torch's TransformerConfig.ff_activation.
+ torch_model, mlx_model = _build_pair(ff_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_v_norm_is_not_implemented_by_mlx(self):
+ # mlx/transformer.py's MultiHeadAttention applies value normalization when
+ # cfg.v_norm == "rms", including through the single-variate (n==1) attention shortcut.
+ torch_model, mlx_model = _build_pair(v_norm="rms")
+ 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_causal_attention_false_is_ignored_by_mlx(self):
+ # mlx/transformer.py's sequence attention reads causality from cfg.causal_attention instead
+ # of always being causal.
+ torch_model, mlx_model = _build_pair(causal_attention=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_memory_efficient_attention_false_is_ignored_by_mlx(self):
+ # mlx/transformer.py's attention logit scale follows cfg.use_memory_efficient_attention
+ # instead of always assuming it's True.
+ torch_model, mlx_model = _build_pair(use_memory_efficient_attention=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_rope_var_true_is_ignored_by_mlx(self):
+ # mlx/transformer.py's variate attention reads its RoPE flag from cfg.use_rope_var. A
+ # 1-variate context can't detect this: softmax over a single key is always 1.0 regardless of
+ # RoPE, so this needs >=2 variates to actually exercise variate attention.
+ torch_model, mlx_model = _build_pair(use_rope_var=True)
+ ctx = np.random.RandomState(2).randn(1, 2, 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)
+
if __name__ == "__main__":
unittest.main()
diff --git a/src/timesfm3/mlx/transformer.py b/src/timesfm3/mlx/transformer.py
index e1621a5..f910c6a 100644
--- a/src/timesfm3/mlx/transformer.py
+++ b/src/timesfm3/mlx/transformer.py
@@ -25,7 +25,13 @@ import math
import mlx.core as mx
import mlx.nn as nn
-from . import configs, normalization
+from . import configs, normalization, util
+
+_ACTIVATIONS = {
+ "relu": nn.relu,
+ "swish": nn.silu,
+ "none": lambda x: x,
+}
def rope(
@@ -49,8 +55,9 @@ def rope(
class MultiHeadAttention(nn.Module):
"""Multi-head attention with RoPE, per-head QK RMSNorm and PerDimScale.
- ``rescale_logits`` is False (memory-efficient-attention parity): the query is pre-multiplied by
+ When ``cfg.use_memory_efficient_attention`` (the default), the query is pre-multiplied by
``sqrt(head_dim)`` with no internal division, so the net logit scale is ``sqrt(head_dim)``.
+ Otherwise the net scale is ``1.0``, matching torch's ``rescale_logits=True`` path.
"""
def __init__(self, cfg: configs.TimesFM3MlxConfig, use_rope: bool, causal: bool):
@@ -67,12 +74,15 @@ class MultiHeadAttention(nn.Module):
self.query_ln = normalization.RMSNorm(self.head_dim)
self.key_ln = normalization.RMSNorm(self.head_dim)
self.per_dim_scale = normalization.PerDimScale(self.head_dim)
+ self.v_norm = cfg.v_norm
+ self.qk_scale = math.sqrt(self.head_dim) if cfg.use_memory_efficient_attention else 1.0
def __call__(self, x: mx.array, patch_mask: mx.array) -> mx.array:
b, n, _ = x.shape
# Single-position attention (variate attention over one variate): softmax over a single key is
- # exactly 1, so the output equals the value projection. Skip Q/K/RoPE/norms/softmax.
- if n == 1:
+ # exactly 1, so the output equals the value projection (still needs v_norm applied). Skip
+ # Q/K/RoPE/norms/softmax.
+ if n == 1 and self.v_norm != "rms":
return self.out_proj(self.value_proj(x))
h, hd = self.num_heads, self.head_dim
q = self.query_proj(x).reshape(b, n, h, hd)
@@ -85,6 +95,10 @@ class MultiHeadAttention(nn.Module):
q = self.query_ln(q)
k = self.key_ln(k)
q = self.per_dim_scale(q)
+ if self.v_norm == "rms":
+ v = util.rms_norm(v, None)
+ if n == 1:
+ return self.out_proj(v.reshape(b, n, h * hd))
q = q.transpose(0, 2, 1, 3)
k = k.transpose(0, 2, 1, 3)
v = v.transpose(0, 2, 1, 3)
@@ -96,7 +110,7 @@ class MultiHeadAttention(nn.Module):
else:
attend = mx.broadcast_to(kv_valid, (b, 1, n, n))
bias = mx.where(attend, 0.0, -1e9)
- q = q * math.sqrt(hd)
+ q = q * self.qk_scale
logits = (q @ k.transpose(0, 1, 3, 2)) + bias
w = mx.softmax(logits, axis=-1)
out = w @ v
@@ -112,16 +126,17 @@ class MixingTransformer(nn.Module):
d = cfg.model_dims
self.pre_seq_attn_ln = normalization.RMSNorm(d)
self.post_seq_attn_ln = normalization.RMSNorm(d)
- self.seq_attn = MultiHeadAttention(cfg, use_rope=True, causal=True)
+ self.seq_attn = MultiHeadAttention(cfg, use_rope=cfg.use_rope_seq, causal=cfg.causal_attention)
self.use_var = cfg.use_variate_attention
if self.use_var:
self.pre_var_attn_ln = normalization.RMSNorm(d)
self.post_var_attn_ln = normalization.RMSNorm(d)
- self.var_attn = MultiHeadAttention(cfg, use_rope=False, causal=False)
+ self.var_attn = MultiHeadAttention(cfg, use_rope=cfg.use_rope_var, causal=False)
self.pre_ff_ln = normalization.RMSNorm(d)
self.post_ff_ln = normalization.RMSNorm(d)
self.ff0 = nn.Linear(d, cfg.hidden_dims, bias=False)
self.ff1 = nn.Linear(cfg.hidden_dims, d, bias=False)
+ self.ff_activation = _ACTIVATIONS[cfg.ff_activation]
def __call__(self, x: mx.array, patch_mask: mx.array) -> mx.array:
b, v, n, d = x.shape
@@ -137,7 +152,7 @@ class MixingTransformer(nn.Module):
h2 = self.post_var_attn_ln(va) + h1
else:
h2 = h1
- ff = self.ff1(nn.relu(self.ff0(self.pre_ff_ln(h2))))
+ ff = self.ff1(self.ff_activation(self.ff0(self.pre_ff_ln(h2))))
return self.post_ff_ln(ff) + h2