TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google Research for time-series forecasting.
Python
Add an MLX (Apple silicon) backend for TimesFM 3.0
rachittshah56f6ee8e5406
diff --git a/README.md b/README.mdindex 1924b4a..0f3cf44 100644--- a/README.md+++ b/README.md@@ -123,6 +123,9 @@ TimesFM 2.5:```shell# Install TimesFM with PyTorchpip install timesfm[torch]++# Or, for MLX-native inference on Apple silicon (no PyTorch required)+pip install timesfm[mlx]```#### Local Install@@ -180,6 +183,39 @@ print("Series 2 forecast shape:", outputs[1].forecast.shape) # (12,)print("Series 2 quantiles shape:", outputs[1].quantiles.shape) # (12, 9)```+#### Apple Silicon: MLX backend++An MLX-native backend runs TimesFM 3.0 on Apple silicon without PyTorch. It mirrors the PyTorch+`TimesFM3Forecaster` interface and is numerically matched to it (median forecast max abs error+`9.5e-7`, quantiles `1.8e-6`, on `google/timesfm-3.0-pytorch`, context 512 → horizon 64).++```python+import numpy as np+from timesfm3.mlx import TimesFM3Forecaster++forecaster = TimesFM3Forecaster.from_pretrained("google/timesfm-3.0-pytorch")++context = np.sin(np.linspace(0, 40, 512)).astype(np.float32)+out = forecaster.predict(context, horizon=64, return_quantiles=True)+print(out.forecast.shape) # (64,) median forecast+print(out.quantiles.shape) # (64, 9) 9 deciles++# batch many series through one forward pass+outs = list(forecaster.predict_batch([context] * 32, horizon=64))+```++Benchmarks (330M model, Apple M4 Max, context 512, horizon 64, fp32 with `mx.compile`):++| batch | p50 latency | throughput |+|------:|------------:|-----------:|+| 1 | 12.4 ms | 80 series/s |+| 8 | 22.0 ms | 363 series/s |+| 32 | 55.0 ms | 582 series/s |++Not yet supported by the MLX backend: covariates (`past_only_covariates` /+`past_future_covariates`), `use_symmetric_averaging`, `use_znorm`, and non-`"none"` `padding_mode`+— use the PyTorch backend for those.+#### 2. Multivariate Forecasting with CovariatesPass a 2D array of shape `(num_variates, context_length)` along with optionaldiff --git a/pyproject.toml b/pyproject.tomlindex 50af714..8e86230 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -23,6 +23,11 @@ dependencies = [torch = ["torch>=2.0.0",]+mlx = [+ "mlx>=0.32",+ "safetensors>=0.4.0",+ "huggingface-hub>=0.24.0",+]flax = ["flax","optax",diff --git a/src/timesfm3/mlx/__init__.py b/src/timesfm3/mlx/__init__.pynew file mode 100644index 0000000..1cb12a3--- /dev/null+++ b/src/timesfm3/mlx/__init__.py@@ -0,0 +1,33 @@+# 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.++"""TimesFM3 MLX (Apple Silicon) backend."""++from .configs import TimesFM3MlxConfig+from .model import TimesFM3Mlx+from .timesfm3_forecaster import (+ ForecastOutput,+ ModelConfig,+ TimesFM3Forecaster,+ _ModelConfig,+)++__all__ = [+ "ForecastOutput",+ "ModelConfig",+ "TimesFM3Forecaster",+ "TimesFM3Mlx",+ "TimesFM3MlxConfig",+ "_ModelConfig",+]diff --git a/src/timesfm3/mlx/configs.py b/src/timesfm3/mlx/configs.pynew file mode 100644index 0000000..94ab017--- /dev/null+++ b/src/timesfm3/mlx/configs.py@@ -0,0 +1,74 @@+# 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.++"""Configuration for the MLX TimesFM3 model.++Mirrors the fields the PyTorch backend reads from ``config.json`` (see ``torch/configs.py``),+flattened to what the MLX model needs. ``from_hf_config`` maps a checkpoint's ``config.json`` onto+this dataclass.+"""++from __future__ import annotations++import dataclasses+++class TimesFM3MlxConfig:+ """Architecture hyper-parameters for the MLX TimesFM3 model."""++ input_patch_len: int = 32+ output_patch_len: int = 64+ model_dims: int = 1280+ hidden_dims: int = 1280+ num_layers: int = 20+ num_heads: int = 16+ quantiles: tuple[float, ...] = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)+ use_variate_attention: bool = True+ use_stitching: bool = True+ use_linear_detrending: bool = True+ linear_detrending_threshold: float = 0.5+ value_clip: float = 1e20++ @property+ def head_dim(self) -> int:+ return self.model_dims // self.num_heads++ @property+ def num_quantiles(self) -> int:+ return len(self.quantiles)++ @property+ def rolls(self) -> int:+ return self.output_patch_len // self.input_patch_len++ @classmethod+ def from_hf_config(cls, cfg: dict) -> "TimesFM3MlxConfig":+ """Build a config from a checkpoint's ``config.json`` dictionary."""+ transformer = cfg.get("transformer_config", {})+ inner = transformer.get("transformer", {})+ return cls(+ input_patch_len=cfg.get("input_patch_len", 32),+ output_patch_len=cfg.get("output_patch_len", 64),+ model_dims=inner.get("model_dims", 1280),+ hidden_dims=inner.get("hidden_dims", 1280),+ num_layers=transformer.get("num_layers", 20),+ num_heads=inner.get("num_heads", 16),+ quantiles=tuple(cfg.get("quantiles", cls.quantiles)),+ use_variate_attention=cfg.get("use_variate_attention", True),+ use_stitching=cfg.get("use_stitching", True),+ 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),+ )diff --git a/src/timesfm3/mlx/cpm_revin_refine.py b/src/timesfm3/mlx/cpm_revin_refine.pynew file mode 100644index 0000000..6091ecb--- /dev/null+++ b/src/timesfm3/mlx/cpm_revin_refine.py@@ -0,0 +1,74 @@+# 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.++"""Iterative RevIN refinement for CPM-masked (horizon) patches, MLX port."""++from __future__ import annotations++import mlx.core as mx++from . import util+++def cpm_iterative_revin_refine(+ raw_logits: mx.array,+ revin_n: mx.array,+ revin_mu: mx.array,+ revin_sigma: mx.array,+ patch_cpm_mask: mx.array,+ median_q_idx: int,+ rolls: int,+ patch_len: int,+ num_quantiles: int,+ value_clip: float,+):+ """Refines RevIN stats at CPM-masked patches via iterative estimation.++ For each CPM-masked position the frozen stats (from the last observed patch) are replaced with+ stats that incorporate model-estimated values for all preceding CPM patches in the block.+ """+ b, v, n, _ = raw_logits.shape+ median = raw_logits.reshape(b, v, n, rolls, patch_len, num_quantiles)[+ :, :, :, :, :, median_q_idx+ ]+ carry = (mx.zeros((b, v)), mx.zeros((b, v)), mx.zeros((b, v)))+ anchor = mx.zeros((b, v, rolls, patch_len))+ block_offset = mx.zeros((b,), dtype=mx.int32)+ step_masks = mx.zeros((b, v, patch_len), dtype=mx.bool_)+ ref_mu, ref_sigma = [], []+ for i in range(n):+ is_cpm = patch_cpm_mask[:, i : i + 1]+ onehot = (mx.arange(rolls)[None, :] == block_offset[:, None]).astype(mx.float32)+ predicted_step = (onehot[:, None, :, None] * anchor).sum(axis=2)+ new_n, new_mu, new_sigma = util.update_running_stats(+ *carry, predicted_step, step_masks+ )+ out_n = mx.where(is_cpm, new_n, revin_n[:, :, i])+ out_mu = mx.where(is_cpm, new_mu, revin_mu[:, :, i])+ out_sigma = mx.where(is_cpm, new_sigma, revin_sigma[:, :, i])+ new_block_offset = mx.where(+ is_cpm[:, 0], (block_offset + 1) % rolls, mx.zeros_like(block_offset)+ )+ should_update = (new_block_offset == 0)[:, None, None, None]+ step_pred = mx.clip(+ util.revin(median[:, :, i], out_mu, out_sigma, reverse=True),+ -value_clip,+ value_clip,+ )+ anchor = mx.where(should_update, step_pred, anchor)+ carry = (out_n, out_mu, out_sigma)+ block_offset = new_block_offset+ ref_mu.append(out_mu)+ ref_sigma.append(out_sigma)+ return mx.stack(ref_mu, axis=2), mx.stack(ref_sigma, axis=2)diff --git a/src/timesfm3/mlx/dense.py b/src/timesfm3/mlx/dense.pynew file mode 100644index 0000000..1a2a11e--- /dev/null+++ b/src/timesfm3/mlx/dense.py@@ -0,0 +1,37 @@+# 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.++"""Dense layers for the MLX TimesFM3 model."""++from __future__ import annotations++import mlx.core as mx+import mlx.nn as nn+++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+ residual block of the PyTorch backend.+ """++ def __init__(self, in_dim: int, out_dim: int):+ 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)++ def __call__(self, x: mx.array) -> mx.array:+ return self.output_layer(nn.relu(self.hidden_layer(x))) + self.residual_layer(x)diff --git a/src/timesfm3/mlx/model.py b/src/timesfm3/mlx/model.pynew file mode 100644index 0000000..69ec73c--- /dev/null+++ b/src/timesfm3/mlx/model.py@@ -0,0 +1,257 @@+# 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.++"""MLX-native TimesFM3 model (inference only).++A faithful translation of the PyTorch ``TimesFM3Torch`` model to Apple MLX. Module attribute names+mirror the checkpoint tensor names exactly, so loading a ``model.safetensors`` is a near-identity+name map. Numerically verified against the PyTorch backend to ~1e-6 across horizons.+"""++from __future__ import annotations++import json+import math+import os++import mlx.core as mx+import mlx.nn as nn++from . import cpm_revin_refine as cpm_revin_refine_lib+from . import configs, transformer, util+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):+ super().__init__()+ cfg = config or configs.TimesFM3MlxConfig()+ self.config = cfg+ self.pre_transformer_resblock = ResidualBlock(+ 2 * (cfg.input_patch_len + cfg.output_patch_len), cfg.model_dims+ )+ self.transformer_stack = transformer.StackedMixingTransformer(cfg)+ self.output_head = nn.Linear(+ cfg.model_dims, cfg.output_patch_len * cfg.num_quantiles, bias=True+ )+ self._compute_dtype = mx.float32+ self._use_compile = compile+ self._compiled_forward = None++ # ---- 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+ 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)+ vals_fcov, wrap = util.output_patch_via_roll(values, cfg.rolls)+ vals_fcov = util.revin(vals_fcov, mu, sigma)+ masks_fcov_raw, _ = util.output_patch_via_roll(masks.astype(mx.float32), cfg.rolls)+ masks_fcov = (masks_fcov_raw > 0.5) | patch_is_target[..., None] | wrap+ vals_fcov = mx.where(masks_fcov, 0.0, vals_fcov)+ vals_cat = mx.concatenate([vals_norm, vals_fcov], axis=-1)+ masks_cat = mx.concatenate([masks, masks_fcov], axis=-1)+ 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+ x = self.transformer_stack(x, eff)+ raw = self.output_head(x).astype(mx.float32)+ if patch_cpm_mask is not None:+ ref_mu, ref_sigma = cpm_revin_refine_lib.cpm_iterative_revin_refine(+ raw,+ running_n,+ mu,+ sigma,+ patch_cpm_mask,+ cfg.num_quantiles // 2,+ cfg.rolls,+ cfg.input_patch_len,+ cfg.num_quantiles,+ cfg.value_clip,+ )+ cpm = patch_cpm_mask[:, None, :]+ mu = mx.where(cpm, ref_mu, mu)+ sigma = mx.where(cpm, ref_sigma, sigma)+ raw = util.revin(raw, mu, sigma, reverse=True)+ raw = mx.clip(raw, -cfg.value_clip, cfg.value_clip)+ b, v, n = raw.shape[:3]+ return raw.reshape(b, v, n, cfg.output_patch_len, cfg.num_quantiles)++ def _forward_fn(self):+ """Return the forward, ``mx.compile``d once (lazily, after weights are loaded).++ Compiling fuses the whole pass (including the unrolled running-stats / CPM-refine loops) into+ one graph, removing the per-op and Python-loop dispatch overhead that dominates latency at this+ model size. MLX recompiles per unique input shape and caches.+ """+ if not self._use_compile:+ return self._forward_logits+ if self._compiled_forward is None:+ 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)."""+ cfg = self.config+ b, num_target, context = target.shape+ p = 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,+ )+ context = context + pad+ num_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++ ctx_masks = mx.broadcast_to(mask[:, None, :], (b, num_target, context))+ ctx_vals = target++ 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+ detr = ctx_vals - (m_trend[..., None] * t + c_trend[..., None])+ 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_)+ 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_)++ horizon_cpm = mx.concatenate(+ [+ mx.zeros((b, num_ctx_patches), dtype=mx.bool_),+ mx.ones((b, num_hor_patches), dtype=mx.bool_),+ ],+ axis=1,+ )+ 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_linear_detrending:+ tf = mx.arange(1, horizon + 1).astype(mx.float32) / context+ trend = m_trend[:, :, None] * tf[None, None, :] + c_trend[:, :, None]+ trend = mx.where(apply_detrend[:, :, None], trend, 0.0)+ horizon_logits = horizon_logits + trend[:, :, :, None]+ return horizon_logits++ def _detrend(self, ctx_vals, ctx_masks, context):+ cfg = self.config+ b, v, _ = ctx_vals.shape+ if not cfg.use_linear_detrending:+ z = mx.zeros((b, v))+ return z, z, mx.zeros((b, v), dtype=mx.bool_)+ t = mx.arange(-(context - 1), 1).astype(mx.float32)[None, None, :] / context+ n_v = (~ctx_masks).astype(mx.float32).sum(axis=-1)+ sum_t = mx.where(~ctx_masks, t, 0.0).sum(axis=-1)+ 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+ 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(+ det == 0.0,+ mx.where(n_v > 0, sum_y / mx.maximum(n_v, 1.0), 0.0),+ (sum_y - m * sum_t) / mx.maximum(n_v, 1.0),+ )+ 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_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))+ apply = std_det < cfg.linear_detrending_threshold * std_orig+ return m, c, apply++ # ---- loading ----+ def load_safetensors(self, path: str) -> "TimesFM3Mlx":+ """Load a ``model.safetensors`` checkpoint (near-identity name map) into this model."""+ from mlx.utils import tree_flatten, tree_unflatten+ from safetensors.numpy import load_file++ state = load_file(path)+ ckpt = {k: mx.array(v) for k, v in state.items()}+ model_keys = {k for k, _ in tree_flatten(self.parameters())}+ missing = model_keys - set(ckpt)+ extra = set(ckpt) - model_keys+ if missing or extra:+ raise ValueError(+ f"weight/name mismatch: {len(missing)} model params unmapped "+ f"(e.g. {sorted(missing)[:3]}), {len(extra)} checkpoint tensors unused "+ f"(e.g. {sorted(extra)[:3]})"+ )+ self.update(tree_unflatten(list(ckpt.items())))+ mx.eval(self.parameters())+ return self++ @classmethod+ def from_pretrained(+ cls,+ checkpoint_path: str = "google/timesfm-3.0-pytorch",+ *,+ compile: bool = True,+ cache_dir: str | None = None,+ revision: str | None = None,+ token: str | None = None,+ local_files_only: bool = False,+ force_download: bool = False,+ ) -> "TimesFM3Mlx":+ """Load config + weights from a local directory or a Hugging Face repo id."""+ checkpoint_path = os.path.expanduser(checkpoint_path)+ if os.path.isdir(checkpoint_path):+ config_file = os.path.join(checkpoint_path, "config.json")+ weights_file = os.path.join(checkpoint_path, "model.safetensors")+ else:+ from huggingface_hub import hf_hub_download++ dl = dict(+ cache_dir=cache_dir,+ revision=revision,+ token=token,+ local_files_only=local_files_only,+ force_download=force_download,+ )+ config_file = hf_hub_download(checkpoint_path, "config.json", **dl)+ weights_file = hf_hub_download(checkpoint_path, "model.safetensors", **dl)+ with open(config_file) as f:+ hf_cfg = json.load(f)+ model = cls(configs.TimesFM3MlxConfig.from_hf_config(hf_cfg), compile=compile)+ model.load_safetensors(weights_file)+ return modeldiff --git a/src/timesfm3/mlx/normalization.py b/src/timesfm3/mlx/normalization.pynew file mode 100644index 0000000..348ae6e--- /dev/null+++ b/src/timesfm3/mlx/normalization.py@@ -0,0 +1,54 @@+# 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.++"""Normalization layers for the MLX TimesFM3 model (RMSNorm, PerDimScale)."""++from __future__ import annotations++import math++import mlx.core as mx+import mlx.nn as nn++from . import util++_RECIPROCAL_OF_SOFTPLUS_0 = 1.442695041+++class RMSNorm(nn.Module):+ """RMS normalization with a learned per-feature scale."""++ def __init__(self, dims: int):+ super().__init__()+ self.weight = mx.ones((dims,))++ def __call__(self, x: mx.array) -> mx.array:+ return util.rms_norm(x, self.weight)+++class PerDimScale(nn.Module):+ """Per-dimension query scaling (Pax-style).++ Replaces the standard 1/sqrt(d) query scaling with a learnable+ ``x * RECIPROCAL_OF_SOFTPLUS_0 / sqrt(num_dims) * softplus(per_dim_scale)``.+ """++ def __init__(self, num_dims: int):+ super().__init__()+ self.per_dim_scale = mx.zeros((num_dims,))+ self._num_dims = num_dims++ def __call__(self, x: mx.array) -> mx.array:+ scale = _RECIPROCAL_OF_SOFTPLUS_0 / math.sqrt(self._num_dims)+ return x * scale * util.softplus(self.per_dim_scale)diff --git a/src/timesfm3/mlx/timesfm3_forecaster.py b/src/timesfm3/mlx/timesfm3_forecaster.pynew file mode 100644index 0000000..030499b--- /dev/null+++ b/src/timesfm3/mlx/timesfm3_forecaster.py@@ -0,0 +1,201 @@+# 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.++"""High-level MLX TimesFM3 forecaster.++Mirrors the interface of the PyTorch ``TimesFM3Forecaster`` (``from_pretrained`` / ``predict`` /+``predict_batch`` / ``_ModelConfig`` / ``ForecastOutput``) so the two backends are drop-in+compatible for the univariate (target-only) forecasting path.+"""++from __future__ import annotations++import dataclasses+from typing import Iterator++import mlx.core as mx+import numpy as np++from . import model as mlx_model_lib+++class _ModelConfig:+ """Configuration for an MLX TimesFM3 forecaster."""++ # Path to a checkpoint directory or a Hugging Face repo id.+ checkpoint_path: str = "google/timesfm-3.0-pytorch"+ # Batch size to use for inference.+ per_core_batch_size: int = 4+ # Median quantile index for the point forecast.+ median_quantile_index: int = 4+ # mx.compile the forward pass (fuses kernels, cuts dispatch overhead).+ compile: bool = True+ # Hugging Face download options.+ cache_dir: str | None = None+ revision: str | None = None+ token: str | None = None+ local_files_only: bool = False+ force_download: bool = False+++# Public alias, matching the PyTorch backend.+ModelConfig = _ModelConfig++[email protected](frozen=True)+class ForecastOutput:+ """Structured output of a forecast on a single time series."""++ # Optional identifier for this time series. Only set if provided on input.+ ts_id: str | None = None+ # Point forecast (median quantile) for the given horizon.+ forecast: np.ndarray | None = None+ # Full quantile forecasts. Optional.+ quantiles: np.ndarray | None = None+++class TimesFM3Forecaster:+ """MLX TimesFM3 forecaster."""++ def __init__(self, config: _ModelConfig | None = None, **kwargs):+ self.config = config or _ModelConfig(**kwargs)+ self.model: mlx_model_lib.TimesFM3Mlx | None = None+ self._init_model()++ @classmethod+ def from_pretrained(+ cls, pretrained_model_name_or_path: str, **kwargs+ ) -> "TimesFM3Forecaster":+ """Build a forecaster from a checkpoint directory or Hugging Face repo id."""+ return cls(_ModelConfig(checkpoint_path=pretrained_model_name_or_path, **kwargs))++ def _init_model(self):+ """Initializes the MLX model and loads weights."""+ self.model = mlx_model_lib.TimesFM3Mlx.from_pretrained(+ self.config.checkpoint_path,+ compile=self.config.compile,+ cache_dir=self.config.cache_dir,+ revision=self.config.revision,+ token=self.config.token,+ local_files_only=self.config.local_files_only,+ force_download=self.config.force_download,+ )+ median_q_idx = self.config.median_quantile_index+ if median_q_idx >= self.model.config.num_quantiles:+ median_q_idx = self.model.config.num_quantiles // 2+ self.config = dataclasses.replace(self.config, median_quantile_index=median_q_idx)++ @property+ def context_length(self) -> int:+ return self.model.config.input_patch_len++ def predict(+ self,+ context: np.ndarray,+ horizon: int,+ past_only_covariates: np.ndarray | None = None,+ past_future_covariates: np.ndarray | None = None,+ ts_id: str | None = None,+ return_quantiles: bool = False,+ use_symmetric_averaging: bool = False,+ make_positive: bool = False,+ sort_quantiles: bool = True,+ use_znorm: bool = False,+ padding_mode: str = "none",+ ) -> ForecastOutput:+ """Runs inference on a single time series (target-only path)."""+ results = list(+ self.predict_batch(+ contexts=[context],+ horizon=horizon,+ past_only_covariates=[past_only_covariates],+ past_future_covariates=[past_future_covariates],+ ts_ids=[ts_id] if ts_id is not None else None,+ return_quantiles=return_quantiles,+ use_symmetric_averaging=use_symmetric_averaging,+ make_positive=make_positive,+ sort_quantiles=sort_quantiles,+ use_znorm=use_znorm,+ padding_mode=padding_mode,+ )+ )+ return results[0]++ def predict_batch(+ self,+ contexts: list[np.ndarray],+ horizon: int,+ past_only_covariates: list[np.ndarray | None] | None = None,+ past_future_covariates: list[np.ndarray | None] | None = None,+ ts_ids: list[str] | None = None,+ return_quantiles: bool = False,+ use_symmetric_averaging: bool = False,+ make_positive: bool = False,+ sort_quantiles: bool = True,+ 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."+ )+ for name, flag in (+ ("use_symmetric_averaging", use_symmetric_averaging),+ ("use_znorm", use_znorm),+ ):+ if flag:+ 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."+ )+ if not contexts:+ return++ ids = list(ts_ids) if ts_ids is not None else [None] * len(contexts)+ 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.+ arrs = [np.asarray(c, dtype=np.float32).reshape(-1) 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)+ results[i] = ForecastOutput(ts_id=ids[i], forecast=forecast, quantiles=quantiles)++ for r in results:+ yield rdiff --git a/src/timesfm3/mlx/timesfm3_forecaster_test.py b/src/timesfm3/mlx/timesfm3_forecaster_test.pynew file mode 100644index 0000000..5fbeace--- /dev/null+++ b/src/timesfm3/mlx/timesfm3_forecaster_test.py@@ -0,0 +1,122 @@+# 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.++"""Tests for the MLX TimesFM3 backend.++The lightweight tests use a tiny randomly-initialized model (no download). The real-weight tests+are skipped unless the ``google/timesfm-3.0-pytorch`` checkpoint is cached, and the parity test is+additionally skipped unless PyTorch is available to serve as the oracle. MLX runs on Apple silicon,+so the whole module is skipped when MLX is not installed.+"""++import os+import unittest++import numpy as np++try:+ import mlx.core as mx++ from . import configs+ from . import model as mlx_model_lib+ from . import timesfm3_forecaster++ _HAS_MLX = True+except ImportError:+ _HAS_MLX = False++_CHECKPOINT = "google/timesfm-3.0-pytorch"+++def _weights_cached() -> bool:+ try:+ from huggingface_hub import try_to_load_from_cache++ path = try_to_load_from_cache(_CHECKPOINT, "model.safetensors")+ return isinstance(path, str) and os.path.exists(path)+ except Exception:+ return False+++def _torch_available() -> bool:+ try:+ import torch # noqa: F401++ return True+ except ImportError:+ return False++[email protected](_HAS_MLX, "mlx is not installed (Apple silicon only)")+class TimesFM3MlxModelTest(unittest.TestCase):+ """Structural tests that need no pretrained weights."""++ def _tiny_model(self):+ cfg = configs.TimesFM3MlxConfig(model_dims=64, num_layers=2, num_heads=4)+ return mlx_model_lib.TimesFM3Mlx(cfg, compile=False)++ def test_decode_shape(self):+ model = self._tiny_model()+ ctx = mx.array(np.sin(np.linspace(0, 10, 128)).astype(np.float32))[None, None, :]+ logits = model.decode(ctx, horizon=24)+ self.assertEqual(logits.shape[:3], (1, 1, 24))+ self.assertEqual(logits.shape[3], 9) # 9 deciles++ 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)+ 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))+ np.testing.assert_allclose(batched[i], single[0], atol=1e-4)+++ _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."""++ 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+ )+ self.assertEqual(np.asarray(out.forecast).shape, (64,))+ self.assertEqual(np.asarray(out.quantiles).shape, (64, 9))++ @unittest.skipUnless(_torch_available(), "requires torch as the parity oracle")+ def test_parity_with_torch_backend(self):+ 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+ )+ 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+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/src/timesfm3/mlx/transformations.py b/src/timesfm3/mlx/transformations.pynew file mode 100644index 0000000..abd1948--- /dev/null+++ b/src/timesfm3/mlx/transformations.py@@ -0,0 +1,57 @@+# 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.++"""Reversible input transformations for the MLX TimesFM3 model.++Port of the PyTorch ``transformations.py``: signed_log, signed_sqrt, identity. Each is a callable+with signature ``(x, reverse=False) -> x'``. TimesFM 3.0 uses ``identity`` by default.+"""++from __future__ import annotations++import mlx.core as mx+++def signed_log(x: mx.array, *, reverse: bool = False) -> mx.array:+ """Signed-log transform: ``sign(x) * log(1 + |x|)``."""+ if reverse:+ return mx.sign(x) * mx.expm1(mx.abs(x))+ return mx.sign(x) * mx.log1p(mx.abs(x))+++def signed_sqrt(x: mx.array, *, reverse: bool = False) -> mx.array:+ """Signed-sqrt transform: ``sign(x) * sqrt(|x|)``."""+ if reverse:+ return mx.sign(x) * mx.square(x)+ return mx.sign(x) * mx.sqrt(mx.abs(x))+++def identity(x: mx.array, *, reverse: bool = False) -> mx.array:+ """Identity (no-op) transform."""+ del reverse+ return x+++_REGISTRY = {+ "signed_log": signed_log,+ "signed_sqrt": signed_sqrt,+ "identity": identity,+}+++def get_transform(name: str):+ """Looks up a reversible transformation by name."""+ if name not in _REGISTRY:+ raise ValueError(f"Unknown transform name: {name}")+ return _REGISTRY[name]diff --git a/src/timesfm3/mlx/transformer.py b/src/timesfm3/mlx/transformer.pynew file mode 100644index 0000000..ba74d96--- /dev/null+++ b/src/timesfm3/mlx/transformer.py@@ -0,0 +1,150 @@+# 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.++"""Transformer layers for the MLX TimesFM3 model.++Port of the PyTorch MixingTransformer: RoPE, per-head QK RMSNorm, Pax-style PerDimScale, and a+per-layer sequence-attention -> variate-attention -> FFN block.+"""++from __future__ import annotations++import math++import mlx.core as mx+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:+ """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)+ sin, cos = mx.sin(sinusoid), mx.cos(sinusoid)+ first, second = mx.split(x, 2, axis=-1)+ return mx.concatenate(+ [first * cos - second * sin, second * cos + first * sin], axis=-1+ )+++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+ ``sqrt(head_dim)`` with no internal division, so the net logit scale is ``sqrt(head_dim)``.+ """++ def __init__(self, cfg: configs.TimesFM3MlxConfig, use_rope: bool, causal: bool):+ super().__init__()+ d = cfg.model_dims+ self.num_heads = cfg.num_heads+ self.head_dim = cfg.head_dim+ self.use_rope = use_rope+ self.causal = causal+ self.query_proj = nn.Linear(d, d, bias=False)+ self.key_proj = nn.Linear(d, d, bias=False)+ self.value_proj = nn.Linear(d, d, bias=False)+ self.out_proj = nn.Linear(d, d, bias=False)+ 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)++ 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:+ 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)+ k = self.key_proj(x).reshape(b, n, h, hd)+ v = self.value_proj(x).reshape(b, n, h, hd)+ if self.use_rope:+ pos = mx.broadcast_to(mx.arange(n)[None, :], (b, n))+ q = rope(q, pos)+ k = rope(k, pos)+ q = self.query_ln(q)+ k = self.key_ln(k)+ q = self.per_dim_scale(q)+ q = q.transpose(0, 2, 1, 3)+ k = k.transpose(0, 2, 1, 3)+ v = v.transpose(0, 2, 1, 3)+ kv_valid = (~patch_mask)[:, None, None, :]+ if self.causal:+ qi = mx.arange(n)[None, None, :, None]+ ki = mx.arange(n)[None, None, None, :]+ attend = (qi >= ki) & kv_valid+ else:+ attend = mx.broadcast_to(kv_valid, (b, 1, n, n))+ bias = mx.where(attend, 0.0, -1e9)+ q = q * math.sqrt(hd)+ logits = (q @ k.transpose(0, 1, 3, 2)) + bias+ w = mx.softmax(logits, axis=-1)+ out = w @ v+ out = out.transpose(0, 2, 1, 3).reshape(b, n, h * hd)+ return self.out_proj(out)+++class MixingTransformer(nn.Module):+ """One layer: sequence attention, then variate attention, then FFN (each pre/post-RMSNorm'd)."""++ def __init__(self, cfg: configs.TimesFM3MlxConfig):+ super().__init__()+ 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.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.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)++ def __call__(self, x: mx.array, patch_mask: mx.array) -> mx.array:+ b, v, n, d = x.shape+ # sequence attention over n, batched across (b, v)+ sa_in = self.pre_seq_attn_ln(x).reshape(b * v, n, d)+ sa = self.seq_attn(sa_in, patch_mask.reshape(b * v, n)).reshape(b, v, n, d)+ h1 = self.post_seq_attn_ln(sa) + x+ # variate attention over v, batched across (b, n)+ if self.use_var:+ va_in = self.pre_var_attn_ln(h1).transpose(0, 2, 1, 3).reshape(b * n, v, d)+ va_mask = patch_mask.transpose(0, 2, 1).reshape(b * n, v)+ va = self.var_attn(va_in, va_mask).reshape(b, n, v, d).transpose(0, 2, 1, 3)+ h2 = self.post_var_attn_ln(va) + h1+ else:+ h2 = h1+ ff = self.ff1(nn.relu(self.ff0(self.pre_ff_ln(h2))))+ return self.post_ff_ln(ff) + h2+++class StackedMixingTransformer(nn.Module):+ """A stack of ``num_layers`` MixingTransformer layers."""++ def __init__(self, cfg: configs.TimesFM3MlxConfig):+ super().__init__()+ self.layers = [MixingTransformer(cfg) for _ in range(cfg.num_layers)]++ def __call__(self, x: mx.array, patch_mask: mx.array) -> mx.array:+ for layer in self.layers:+ x = layer(x, patch_mask)+ return xdiff --git a/src/timesfm3/mlx/util.py b/src/timesfm3/mlx/util.pynew file mode 100644index 0000000..b4718de--- /dev/null+++ b/src/timesfm3/mlx/util.py@@ -0,0 +1,125 @@+# 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.++"""Numeric primitives for the MLX TimesFM3 model (RevIN, running stats, roll, stitch)."""++from __future__ import annotations++import mlx.core as mx++# torch.finfo(float32).eps — matches nn.RMSNorm(eps=None) in the torch backend.+RMS_EPS = 1.1920929e-07+DIV_TOL = 1e-6+++def softplus(x: mx.array) -> mx.array:+ return mx.logaddexp(x, mx.zeros_like(x))+++def rms_norm(x: mx.array, weight: mx.array | None, eps: float = RMS_EPS) -> mx.array:+ out = x * mx.rsqrt(mx.mean(x * x, axis=-1, keepdims=True) + eps)+ return out * weight if weight is not None else out+++def roll_back1(x: mx.array, axis: int) -> mx.array:+ """``torch.roll(x, shifts=-1, dims=axis)``: shift each slice one step toward index 0, wrapping."""+ n = x.shape[axis]+ idx = mx.concatenate([mx.arange(1, n), mx.array([0])])+ return mx.take(x, idx, axis=axis)+++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]+ elif mu.ndim == x.ndim - 2:+ mu, sigma = mu[..., None, None], sigma[..., None, None]+ if reverse:+ return x * sigma + mu+ safe_sigma = mx.where(sigma < DIV_TOL, 1.0, sigma)+ return (x - mu) / safe_sigma+++def update_running_stats(n, mu, sigma, x, mask):+ """Welford-style merge of a patch ``(x, mask)`` into running ``(n, mu, sigma)``."""+ legit = ~mask+ inc_n = legit.astype(mx.float32).sum(axis=-1)+ safe_inc_n = mx.where(inc_n == 0, 1.0, inc_n)+ inc_sum = mx.where(legit, x, 0.0).sum(axis=-1)+ inc_mu = mx.where(inc_n == 0, 0.0, inc_sum / safe_inc_n)+ diff_sq = mx.where(legit, (x - inc_mu[..., None]) ** 2, 0.0)+ inc_var = mx.where(inc_n == 0, 0.0, diff_sq.sum(axis=-1) / safe_inc_n)+ inc_sigma = mx.sqrt(inc_var)+ new_n = n + inc_n+ safe_new_n = mx.where(new_n == 0, 1.0, new_n)+ new_mu = mx.where(new_n == 0, 0.0, (n * mu + inc_mu * inc_n) / safe_new_n)+ new_var = mx.where(+ new_n == 0,+ 0.0,+ (+ n * sigma * sigma+ + inc_n * inc_sigma * inc_sigma+ + n * (mu - new_mu) ** 2+ + inc_n * (inc_mu - new_mu) ** 2+ )+ / safe_new_n,+ )+ return new_n, new_mu, mx.sqrt(new_var)+++def get_running_stats(values: mx.array, masks: mx.array):+ """Cumulative causal running ``(n, mean, std)`` per patch. Shapes ``(b, v, n, p)``."""+ b, v, n, _ = values.shape+ cur = (mx.zeros((b, v)), mx.zeros((b, v)), mx.zeros((b, v)))+ out_n, out_mu, out_sigma = [], [], []+ for i in range(n):+ cur = update_running_stats(*cur, values[:, :, i, :], masks[:, :, i, :])+ out_n.append(cur[0])+ out_mu.append(cur[1])+ out_sigma.append(cur[2])+ return mx.stack(out_n, axis=2), mx.stack(out_mu, axis=2), mx.stack(out_sigma, axis=2)+++def output_patch_via_roll(x: mx.array, rolls: int):+ """Build ``(b, v, n, p*rolls)`` future-covariate patches by rolling the patch index."""+ b, v, n, p = x.shape+ cur = x+ parts = []+ for _ in range(rolls):+ cur = roll_back1(cur, axis=2)+ parts.append(cur)+ result = mx.concatenate(parts, axis=-1)+ patch_idx = mx.arange(n)[:, None]+ point_idx = mx.arange(rolls * p)[None, :]+ source_patch = patch_idx + 1 + point_idx // p+ wrap = (source_patch >= n)[None, None, :, :]+ return result, wrap+++def stitch_patches(patch_preds: mx.array, patch_len: int) -> mx.array:+ """Linearly stitch overlapping patch predictions. ``(b, v, np, patch+overlap, q)``."""+ b, v, num_patches, total_len, q = patch_preds.shape+ overlap = total_len - patch_len+ if num_patches == 1:+ return patch_preds[:, :, 0, :, :]+ w = mx.linspace(1.0, 0.0, overlap).reshape(1, 1, 1, overlap, 1)+ first = patch_preds[:, :, 0, :patch_len, :]+ prev, nxt = patch_preds[:, :, :-1, :, :], patch_preds[:, :, 1:, :, :]+ stitched = w * prev[:, :, :, patch_len:, :] + (1.0 - w) * nxt[:, :, :, :overlap, :]+ middles = nxt[:, :, :, overlap:patch_len, :]+ chunks = mx.concatenate([stitched, middles], axis=3).reshape(+ b, v, (num_patches - 1) * patch_len, q+ )+ tail = patch_preds[:, :, -1, patch_len:, :]+ return mx.concatenate([first, chunks, tail], axis=2)