Skip to content

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

Python

initial fully functioning torch code for timesfm-3

Rajat Sen0548f5362f6d
diff --git a/pyproject.toml b/pyproject.toml
index fec54ac..743b737 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -7,6 +7,7 @@ authors = [
{name = "Yichen Zhou", email = "[email protected]"},
{name = "Abhimanyu Das", email = "[email protected]"},
{name = "Petros Mol", email = "[email protected]"},
+ {name = "Ayush Jain", email="[email protected]"},
{name = "Michael Chertushkin", email = "[email protected]"},
]
license = {text = "Apache-2.0"}
@@ -39,7 +40,11 @@ xreg = [
line-length = 88
indent-width = 2
+[tool.setuptools.packages.find]
+where = ["src"]
+
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
+
diff --git a/src/timesfm/__init__.py b/src/timesfm/__init__.py
index 361a36d..3b50ed4 100644
--- a/src/timesfm/__init__.py
+++ b/src/timesfm/__init__.py
@@ -27,3 +27,8 @@ try:
TimesFM_2p5_200M_flax = timesfm_2p5_flax.TimesFM_2p5_200M_flax
except ImportError:
pass
+
+try:
+ from timesfm3 import TimesFM3Forecaster, TimesFM3Torch
+except ImportError:
+ pass
diff --git a/src/timesfm3/__init__.py b/src/timesfm3/__init__.py
new file mode 100644
index 0000000..b4a70e6
--- /dev/null
+++ b/src/timesfm3/__init__.py
@@ -0,0 +1,35 @@
+# Copyright 2025 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 PyTorch API."""
+
+from .configs import ResidualBlockConfig
+from .configs import StackedTransformersConfig
+from .configs import TransformerConfig
+from .model import TimesFM3Torch
+from .timesfm3_forecaster import ForecastOutput
+from .timesfm3_forecaster import ModelConfig
+from .timesfm3_forecaster import TimesFM3Forecaster
+from .timesfm3_forecaster import _ModelConfig
+
+__all__ = [
+ "TimesFM3Torch",
+ "TimesFM3Forecaster",
+ "ForecastOutput",
+ "_ModelConfig",
+ "ModelConfig",
+ "ResidualBlockConfig",
+ "TransformerConfig",
+ "StackedTransformersConfig",
+]
diff --git a/src/timesfm3/configs.py b/src/timesfm3/configs.py
new file mode 100644
index 0000000..657c579
--- /dev/null
+++ b/src/timesfm3/configs.py
@@ -0,0 +1,52 @@
+"""Abstract configs for TimesFM-3 layers."""
+
+import dataclasses
+from typing import Literal
+
+
[email protected](frozen=True)
+class ResidualBlockConfig:
+ """Framework-agnostic config for a residual block."""
+
+ hidden_dims: int
+ output_dims: int
+ use_bias: bool
+ activation: Literal["relu", "swish", "none"]
+ dropout: float = 0.0
+ identity_skip: bool = False
+ prenorm: Literal["rms", "none"] = "none"
+
+
[email protected](frozen=True)
+class TransformerConfig:
+ """Framework-agnostic config for a transformer."""
+
+ model_dims: int
+ hidden_dims: int
+ num_heads: int
+ attention_norm: Literal["rms"]
+ feedforward_norm: Literal["rms"]
+ qk_norm: Literal["rms", "none"]
+ use_bias: bool
+ use_rope_seq: bool
+ use_rope_var: bool
+ ff_activation: Literal["relu", "swish", "none", "swiglu"]
+ deterministic: bool
+ v_norm: Literal["rms", "none"] = "none"
+ causal_attention: bool = True
+ debug_no_masking: bool = False
+ training: bool = True
+ use_memory_efficient_attention: bool = True
+ paired_token_skip_second: bool = False
+ max_variates: int = 32
+ # PyTorch-only: when True uses F.scaled_dot_product_attention.
+ use_sdpa: bool = True
+
+
[email protected](frozen=True)
+class StackedTransformersConfig:
+ """Framework-agnostic config for a stacked transformers."""
+
+ num_layers: int
+ transformer: TransformerConfig
+ use_remat: bool = True
diff --git a/src/timesfm3/cpm_revin_refine.py b/src/timesfm3/cpm_revin_refine.py
new file mode 100644
index 0000000..753225f
--- /dev/null
+++ b/src/timesfm3/cpm_revin_refine.py
@@ -0,0 +1,137 @@
+"""Standalone iterative RevIN refinement for CPM-masked patches in PyTorch.
+
+Extracted so it can be tested independently of the TimesFM3 model.
+"""
+
+from __future__ import annotations
+
+import torch
+
+from . import util
+
+
+def cpm_iterative_revin_refine(
+ raw_logits: torch.Tensor,
+ revin_n: torch.Tensor,
+ revin_mu: torch.Tensor,
+ revin_sigma: torch.Tensor,
+ patch_cpm_mask: torch.Tensor,
+ median_q_idx: int,
+ rolls: int,
+ patch_len: int,
+ num_quantiles: int,
+ value_clip: float = 1e9,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Refines RevIN stats at CPM-masked patches via iterative estimation.
+
+ For each CPM-masked position p the currently frozen stats (from the last
+ observed patch before the CPM region) are replaced with stats that also
+ incorporate model-estimated values for all CPM patches that precede p.
+
+ Args:
+ raw_logits: Output of the output head, shape (b, v, n, output_patch_len *
+ num_quantiles). In RevIN-normalised space, before reverse RevIN.
+ revin_n: Count of valid (unmasked) values accumulated at each patch
+ position, shape (b, v, n).
+ revin_mu: Running mean per position, (b, v, n).
+ revin_sigma: Running std per position, (b, v, n).
+ patch_cpm_mask: Boolean mask, True = CPM-masked patch, shape (b, n).
+ median_q_idx: Index into quantiles selecting the median quantile used as
+ point estimate (typically num_quantiles // 2).
+ rolls: Number of output patches per input patch (output_patch_len //
+ patch_len).
+ patch_len: Length of each input patch.
+ num_quantiles: Total number of quantile heads.
+ value_clip: Absolute bound for clamping estimated values after reverse
+ RevIN.
+
+ Returns:
+ Tuple (refined_mu, refined_sigma), each shape (b, v, n).
+ Non-CPM positions are identical to revin_mu / revin_sigma.
+ CPM positions incorporate estimates of all preceding CPM patches in
+ the same block (and all estimates from earlier blocks in the segment).
+ """
+ b, v, n_patches, _ = raw_logits.shape
+ device = raw_logits.device
+
+ # Reshape and slice raw_logits to keep only the median quantile.
+ # (b, v, n, oq) -> (b, v, n, rolls, patch_len, num_quantiles)
+ # -> (b, v, n, rolls, patch_len)
+ median_logits = raw_logits.reshape(
+ b, v, n_patches, rolls, patch_len, num_quantiles
+ )[:, :, :, :, :, median_q_idx]
+
+ # Initialise carry with zeros.
+ carry_n = torch.zeros((b, v), dtype=torch.float32, device=device)
+ carry_mu = torch.zeros((b, v), dtype=torch.float32, device=device)
+ carry_sigma = torch.zeros((b, v), dtype=torch.float32, device=device)
+ anchor_predicted_values = torch.zeros(
+ (b, v, rolls, patch_len), dtype=torch.float32, device=device
+ )
+ block_offset = torch.zeros((b,), dtype=torch.long, device=device)
+
+ refined_mu_list = []
+ refined_sigma_list = []
+
+ step_masks = torch.zeros((b, v, patch_len), dtype=torch.bool, device=device)
+
+ for i in range(n_patches):
+ actual_n = revin_n[:, :, i]
+ actual_mu = revin_mu[:, :, i]
+ actual_sigma = revin_sigma[:, :, i]
+ current_step_logits = median_logits[:, :, i]
+ is_cpm = patch_cpm_mask[:, i : i + 1] # (b, 1)
+
+ # Select the block_offset[b]-th patch for each batch element
+ offset_onehot = torch.eq(
+ torch.arange(rolls, device=device).unsqueeze(0),
+ block_offset.unsqueeze(1),
+ ).float()
+ predicted_values_step = torch.einsum(
+ "br,bvrp->bvp", offset_onehot, anchor_predicted_values
+ )
+
+ # Update running stats with the estimated patch.
+ new_n, new_mu, new_sigma = util.update_running_stats(
+ carry_n, carry_mu, carry_sigma, predicted_values_step, step_masks
+ )
+
+ out_n = torch.where(is_cpm, new_n, actual_n)
+ out_mu = torch.where(is_cpm, new_mu, actual_mu)
+ out_sigma = torch.where(is_cpm, new_sigma, actual_sigma)
+
+ # Advance block_offset: +1 (mod rolls) for CPM, reset to 0 for non-CPM.
+ new_block_offset = torch.where(
+ is_cpm.squeeze(-1),
+ (block_offset + 1) % rolls,
+ torch.zeros_like(block_offset),
+ )
+
+ should_update_anchor = torch.eq(new_block_offset, 0)
+
+ # Pre-calculate predicted values for the new anchor.
+ step_predicted_values = util.revin(
+ current_step_logits, out_mu, out_sigma, reverse=True
+ )
+ step_predicted_values = torch.clamp(
+ step_predicted_values, -value_clip, value_clip
+ )
+
+ new_anchor_predicted_values = torch.where(
+ should_update_anchor.view(b, 1, 1, 1),
+ step_predicted_values,
+ anchor_predicted_values,
+ )
+
+ carry_n = out_n
+ carry_mu = out_mu
+ carry_sigma = out_sigma
+ anchor_predicted_values = new_anchor_predicted_values
+ block_offset = new_block_offset
+
+ refined_mu_list.append(out_mu)
+ refined_sigma_list.append(out_sigma)
+
+ refined_mu = torch.stack(refined_mu_list, dim=2)
+ refined_sigma = torch.stack(refined_sigma_list, dim=2)
+ return refined_mu, refined_sigma
diff --git a/src/timesfm3/cpm_revin_refine_test.py b/src/timesfm3/cpm_revin_refine_test.py
new file mode 100644
index 0000000..4b68719
--- /dev/null
+++ b/src/timesfm3/cpm_revin_refine_test.py
@@ -0,0 +1,122 @@
+# Copyright 2025 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 PyTorch cpm_iterative_revin_refine."""
+
+import unittest
+import numpy as np
+import torch
+
+from . import cpm_revin_refine as torch_lib
+
+
+class CpmRevinRefineTest(unittest.TestCase):
+
+ def test_shape(self):
+ b, v, n = 2, 3, 8
+ rolls, patch_len, num_q = 2, 2, 3
+ oq = rolls * patch_len * num_q
+ raw_logits = torch.zeros((b, v, n, oq))
+ revin_n = torch.ones((b, v, n))
+ revin_mu = torch.zeros((b, v, n))
+ revin_sigma = torch.ones((b, v, n))
+ patch_cpm_mask = torch.zeros((b, n), dtype=torch.bool)
+
+ refined_mu, refined_sigma = torch_lib.cpm_iterative_revin_refine(
+ raw_logits=raw_logits,
+ revin_n=revin_n,
+ revin_mu=revin_mu,
+ revin_sigma=revin_sigma,
+ patch_cpm_mask=patch_cpm_mask,
+ median_q_idx=num_q // 2,
+ rolls=rolls,
+ patch_len=patch_len,
+ num_quantiles=num_q,
+ )
+ self.assertEqual(refined_mu.shape, (b, v, n))
+ self.assertEqual(refined_sigma.shape, (b, v, n))
+
+ def test_no_cpm_mask_identity(self):
+ b, v, n = 1, 2, 6
+ rolls, patch_len, num_q = 2, 4, 3
+ oq = rolls * patch_len * num_q
+
+ raw_logits = torch.randn(b, v, n, oq)
+ revin_n = torch.full((b, v, n), 4.0)
+ revin_mu = torch.randn(b, v, n)
+ revin_sigma = torch.abs(torch.randn(b, v, n)) + 0.1
+ patch_cpm_mask = torch.zeros((b, n), dtype=torch.bool)
+
+ refined_mu, refined_sigma = torch_lib.cpm_iterative_revin_refine(
+ raw_logits=raw_logits,
+ revin_n=revin_n,
+ revin_mu=revin_mu,
+ revin_sigma=revin_sigma,
+ patch_cpm_mask=patch_cpm_mask,
+ median_q_idx=num_q // 2,
+ rolls=rolls,
+ patch_len=patch_len,
+ num_quantiles=num_q,
+ )
+ np.testing.assert_allclose(refined_mu.numpy(), revin_mu.numpy())
+ np.testing.assert_allclose(refined_sigma.numpy(), revin_sigma.numpy())
+
+ def test_cpm_mask_modifies_cpm_positions_only(self):
+ for b, v, n, rolls, patch_len, num_q in [
+ (1, 1, 8, 2, 4, 3),
+ (2, 3, 16, 2, 32, 9),
+ (2, 2, 12, 4, 8, 5),
+ ]:
+ torch.manual_seed(42)
+ oq = rolls * patch_len * num_q
+
+ raw_logits = torch.randn(b, v, n, oq)
+ revin_n = torch.full((b, v, n), 10.0)
+ revin_mu = torch.randn(b, v, n)
+ revin_sigma = torch.abs(torch.randn(b, v, n)) + 0.5
+
+ # First 4 patches non-CPM, remaining CPM
+ patch_cpm_mask = torch.zeros((b, n), dtype=torch.bool)
+ patch_cpm_mask[:, 4:] = True
+
+ median_q_idx = num_q // 2
+
+ refined_mu, refined_sigma = torch_lib.cpm_iterative_revin_refine(
+ raw_logits=raw_logits,
+ revin_n=revin_n,
+ revin_mu=revin_mu,
+ revin_sigma=revin_sigma,
+ patch_cpm_mask=patch_cpm_mask,
+ median_q_idx=median_q_idx,
+ rolls=rolls,
+ patch_len=patch_len,
+ num_quantiles=num_q,
+ )
+
+ # Non-CPM positions should be identical to inputs
+ np.testing.assert_allclose(
+ refined_mu[:, :, :4].numpy(), revin_mu[:, :, :4].numpy()
+ )
+ np.testing.assert_allclose(
+ refined_sigma[:, :, :4].numpy(), revin_sigma[:, :, :4].numpy()
+ )
+
+ # Refined outputs should be finite
+ self.assertTrue(torch.isfinite(refined_mu).all().item())
+ self.assertTrue(torch.isfinite(refined_sigma).all().item())
+ self.assertTrue((refined_sigma > 0).all().item())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src/timesfm3/dense.py b/src/timesfm3/dense.py
new file mode 100644
index 0000000..f8b1c9d
--- /dev/null
+++ b/src/timesfm3/dense.py
@@ -0,0 +1,100 @@
+"""Dense layers for TimesFM3 PyTorch (inference only)."""
+
+from __future__ import annotations
+
+import torch
+from torch import nn
+
+from . import configs
+from . import util
+
+
+class ResidualBlock(nn.Module):
+ """Residual block with two linear layers and a linear residual connection.
+
+ Architecture:
+ if prenorm == "rms": x_norm = RMSNorm(x) else: x_norm = x
+ hidden = activation(hidden_layer(x_norm))
+ output = output_layer(hidden) + residual_layer(x) [or + x if identity_skip]
+ """
+
+ def __init__(self, config: configs.ResidualBlockConfig):
+ super().__init__()
+ self.config = config
+
+ # Defining placeholder layers in __init__ ensures PyTorch registers them as
+ # submodules. This is required for standard parameter tracking, printing/
+ # debugging, and correctly propagating device/dtype moves applied to the
+ # parent module (e.g. `model.to(device)`) before any forward handles them.
+ # They are safely re-initialized/overwritten with correct dimensions during
+ # the first forward pass (using `set_input_dims()`) before the matrix
+ # multiplication is evaluated, avoiding shape mismatch errors.
+ self.hidden_layer = nn.Linear(
+ in_features=config.hidden_dims, # placeholder, set in first forward
+ out_features=config.hidden_dims,
+ bias=config.use_bias,
+ )
+ self.output_layer = nn.Linear(
+ in_features=config.hidden_dims,
+ out_features=config.output_dims,
+ bias=config.use_bias,
+ )
+
+ if config.identity_skip:
+ self.residual_layer = None
+ else:
+ self.residual_layer = nn.Linear(
+ in_features=config.hidden_dims, # placeholder
+ out_features=config.output_dims,
+ bias=config.use_bias,
+ )
+
+ self.activation = util.get_activation_fn(config.activation)
+
+ if config.prenorm == "rms":
+ self.pre_norm = nn.RMSNorm(config.hidden_dims)
+ else:
+ self.pre_norm = None
+
+ # Mark layers as lazy so input dim gets set on first use
+ self._input_dim_set = False
+
+ def set_input_dims(self, input_dim: int) -> None:
+ """Reinitialize linear layers with the correct input dimension."""
+ if self._input_dim_set:
+ return
+ device = self.hidden_layer.weight.device
+ dtype = self.hidden_layer.weight.dtype
+
+ self.hidden_layer = nn.Linear(
+ input_dim, self.config.hidden_dims, bias=self.config.use_bias
+ ).to(device=device, dtype=dtype)
+ self.output_layer = nn.Linear(
+ self.config.hidden_dims,
+ self.config.output_dims,
+ bias=self.config.use_bias,
+ ).to(device=device, dtype=dtype)
+ if self.residual_layer is not None:
+ self.residual_layer = nn.Linear(
+ input_dim, self.config.output_dims, bias=self.config.use_bias
+ ).to(device=device, dtype=dtype)
+ if self.pre_norm is not None:
+ self.pre_norm = nn.RMSNorm(input_dim).to(device=device, dtype=dtype)
+ self._input_dim_set = True
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass. x shape: (b, ..., input_dim)."""
+ if not self._input_dim_set:
+ self.set_input_dims(x.shape[-1])
+
+ if self.pre_norm is not None:
+ hidden_input = self.pre_norm(x)
+ else:
+ hidden_input = x
+
+ hidden_output = self.activation(self.hidden_layer(hidden_input))
+
+ if self.residual_layer is not None:
+ return self.output_layer(hidden_output) + self.residual_layer(x)
+ else:
+ return self.output_layer(hidden_output) + x
diff --git a/src/timesfm3/model.py b/src/timesfm3/model.py
new file mode 100644
index 0000000..102a2fe
--- /dev/null
+++ b/src/timesfm3/model.py
@@ -0,0 +1,642 @@
+"""TimesFM3 PyTorch model (inference only).
+
+Supports:
+ - forward(): equivalent to Flax __call__, full-sequence forward pass.
+ - decode(): non-autoregressive and cached decoding with frozen stats and
+ configurable output_patch_len.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Any
+
+import torch
+from torch import nn
+
+from . import configs
+from . import cpm_revin_refine as cpm_revin_refine_lib
+from . import dense
+from . import transformations
+from . import transformer
+from . import util
+
+
+class TimesFM3Torch(nn.Module):
+ """PyTorch inference-only implementation of TimesFM3.
+
+ Attributes:
+ input_patch_len: The length of each input patch.
+ output_patch_len: The length of the output forecast for each patch.
+ quantiles: A list of quantiles to predict.
+ residual_block_config: Configuration for the pre-transformer residual block.
+ transformer_config: Configuration for the stacked transformers.
+ use_variate_attention: Whether to use variate attention.
+ value_clip: Absolute value to clip input values to.
+ use_stitching: Whether to use stitching for predictions.
+ use_linear_detrending: Whether to apply linear detrending on context.
+ linear_detrending_threshold: Ratio threshold for applying linear detrending.
+ use_iterative_cpm_revin: Whether to use iterative RevIN refinement.
+ use_frozen_running_stats: Whether running stats freeze at context boundary.
+ """
+
+ def __init__(
+ self,
+ input_patch_len: int = 32,
+ output_patch_len: int = 64,
+ quantiles: list[float] | None = None,
+ residual_block_config: configs.ResidualBlockConfig | None = None,
+ transformer_config: configs.StackedTransformersConfig | None = None,
+ use_variate_attention: bool = True,
+ value_clip: float = 1e20,
+ use_stitching: bool = True,
+ use_linear_detrending: bool = True,
+ linear_detrending_threshold: float = 0.5,
+ use_iterative_cpm_revin: bool = True,
+ use_frozen_running_stats: bool = False,
+ input_transform: str = "identity",
+ ):
+ super().__init__()
+ if quantiles is None:
+ quantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
+ if residual_block_config is None:
+ residual_block_config = configs.ResidualBlockConfig(
+ hidden_dims=1280,
+ output_dims=1280,
+ use_bias=False,
+ activation="relu",
+ )
+ if transformer_config is None:
+ transformer_config = configs.StackedTransformersConfig(
+ num_layers=20,
+ transformer=configs.TransformerConfig(
+ model_dims=1280,
+ hidden_dims=1280,
+ num_heads=16,
+ 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,
+ ),
+ )
+ if output_patch_len % input_patch_len != 0:
+ raise ValueError(
+ f"Output patch len {output_patch_len} must be a multiple of"
+ f" input patch len {input_patch_len}."
+ )
+ if (
+ residual_block_config.output_dims
+ != transformer_config.transformer.model_dims
+ ):
+ raise ValueError(
+ "ResidualBlock output_dims must match Transformer model_dims."
+ )
+
+ self.input_patch_len = input_patch_len
+ self.output_patch_len = output_patch_len
+ self.quantiles = quantiles
+ self.num_quantiles = len(quantiles)
+ self.rolls = output_patch_len // input_patch_len
+ self.residual_block_config = residual_block_config
+ self.transformer_config = transformer_config
+ self.use_variate_attention = use_variate_attention
+ self.value_clip = value_clip
+ self.use_stitching = use_stitching
+ self.use_linear_detrending = use_linear_detrending
+ self.linear_detrending_threshold = linear_detrending_threshold
+ self.use_iterative_cpm_revin = use_iterative_cpm_revin
+ self.use_frozen_running_stats = use_frozen_running_stats
+ self.input_transform = input_transform
+
+ if self.use_stitching:
+ if self.output_patch_len <= self.input_patch_len:
+ raise ValueError(
+ "use_stitching requires output_patch_len > input_patch_len"
+ )
+ self._stitching_extract_len = min(
+ 2 * self.input_patch_len, self.output_patch_len
+ )
+
+ self.pre_transformer_resblock = dense.ResidualBlock(
+ config=residual_block_config
+ )
+ self.transformer_stack = transformer.StackedMixingTransformer(
+ config=transformer_config,
+ use_variate_attention=use_variate_attention,
+ )
+
+ self.output_head = nn.Linear(
+ transformer_config.transformer.model_dims,
+ output_patch_len * self.num_quantiles,
+ bias=True,
+ )
+
+ def _preprocess(
+ self,
+ values: torch.Tensor,
+ masks: torch.Tensor,
+ patch_is_target: torch.Tensor,
+ freeze_after: int | None = None,
+ patch_cpm_mask: torch.Tensor | None = None,
+ ) -> tuple[
+ torch.Tensor,
+ torch.Tensor,
+ torch.Tensor,
+ tuple[torch.Tensor, torch.Tensor],
+ torch.Tensor,
+ ]:
+ """Applies preprocessing: RevIN, masking, future covariates, ResBlock.
+
+ Args:
+ values: (b, v, n, p).
+ masks: (b, v, n, p) bool. True=masked.
+ patch_is_target: (b, v, n) bool.
+ freeze_after: Optional patch index after which running stats freeze.
+ patch_cpm_mask: (b, n) bool or None. If given, target variates at True
+ positions are additionally masked (used for horizon CPM masking).
+
+ Returns:
+ (resblock_input, resblock_output, patch_mask, (running_mean, running_std),
+ running_n)
+ """
+ running_n, running_mean, running_std = util.get_running_stats(
+ values, masks
+ )
+ if freeze_after is not None:
+ _, _, n, _ = values.shape
+ if 0 <= freeze_after < n - 1:
+ running_mean[:, :, freeze_after + 1 :] = running_mean[
+ :, :, freeze_after : freeze_after + 1
+ ]
+ running_std[:, :, freeze_after + 1 :] = running_std[
+ :, :, freeze_after : freeze_after + 1
+ ]
+
+ # Apply CPM mask: mask target variates at CPM positions.
+ if patch_cpm_mask is not None:
+ cpm_bvnp = patch_cpm_mask[:, None, :, None] # (b, 1, n, 1)
+ cpm_target_only = cpm_bvnp & patch_is_target.unsqueeze(-1)
+ masks = masks | cpm_target_only
+
+ values_bvnp = util.revin(values, running_mean, running_std, reverse=False)
+ values_bvnp = torch.where(masks, 0.0, values_bvnp)
+
+ # Roll values to get future covariate patches
+ values_fcov, wrap_mask = util.get_output_patch_via_roll(values, self.rolls)
+ values_fcov = util.revin(
+ values_fcov, running_mean, running_std, reverse=False
+ )
+
+ # Roll the (CPM-modified) masks for future covariate masking.
+ masks_fcov_raw, _ = util.get_output_patch_via_roll(masks, self.rolls)
+ masks_fcov = masks_fcov_raw | patch_is_target.unsqueeze(-1) | wrap_mask
+ values_fcov = torch.where(masks_fcov, 0.0, values_fcov)
+
+ values_cat = torch.cat([values_bvnp, values_fcov], dim=-1)
+ masks_cat = torch.cat([masks, masks_fcov], dim=-1)
+
+ resblock_input = torch.cat([values_cat, masks_cat.float()], dim=-1)
+ resblock_output = self.pre_transformer_resblock(resblock_input)
+
+ # Patch mask: a patch is fully masked if ALL points are masked
+ patch_mask_bvn = masks_cat.all(dim=3)
+
+ return (
+ resblock_input,
+ resblock_output,
+ patch_mask_bvn,
+ (running_mean, running_std),
+ running_n,
+ )
+
+ def forward(
+ self,
+ inputs: dict[str, Any],
+ freeze_after: int | None = None,
+ patch_cpm_mask: torch.Tensor | None = None,
+ return_aux_outputs: bool = False,
+ ) -> dict[str, Any]:
+ """Full-sequence forward pass (equivalent to Flax __call__).
+
+ Args:
+ inputs: Dictionary with keys: - "values": (b, v, n, p) float - "masks":
+ (b, v, n, p) bool - "patch_is_target": (b, v, n) bool
+ freeze_after: Optional patch index after which running stats freeze.
+ patch_cpm_mask: (b, n) bool or None. Horizon CPM mask.
+ return_aux_outputs: Whether to return auxiliary outputs.
+
+ Returns:
+ Dictionary with "logits" of shape (b, v, n, output_patch_len,
+ num_quantiles).
+ """
+ values = inputs["values"]
+ values = torch.nan_to_num(values, nan=0.0)
+ values = torch.clamp(values, -self.value_clip, self.value_clip)
+ masks = inputs["masks"].bool()
+ patch_is_target = inputs["patch_is_target"]
+
+ _, _, _, p = values.shape
+ if p != self.input_patch_len:
+ raise ValueError(
+ f"Input patch_len {p} != model input_patch_len {self.input_patch_len}"
+ )
+
+ # Preprocessing & ResBlock
+ (
+ resblock_input,
+ transformer_input,
+ transformer_patch_mask,
+ revin_stats,
+ running_n,
+ ) = self._preprocess(
+ values,
+ masks,
+ patch_is_target,
+ freeze_after=freeze_after,
+ patch_cpm_mask=patch_cpm_mask,
+ )
+
+ # Transformer
+ # At inference, only mask *leading* fully-masked patches (left-padding).
+ # Flax __call__ does: effective_patch_mask = cumprod(mask, axis=2) when
+ # not training. This keeps horizon patches (which are fully masked but
+ # come after valid context) visible to attention.
+ effective_patch_mask = torch.cumprod(
+ transformer_patch_mask.int(), dim=2
+ ).bool()
+ transformer_output, _, seq_attn_mask = self.transformer_stack(
+ transformer_input,
+ effective_patch_mask,
+ )
+
+ # Output head
+ raw_logits = self.output_head(transformer_output)
+ revin_mean, revin_std = revin_stats
+
+ if self.use_iterative_cpm_revin and patch_cpm_mask is not None:
+ refined_mu, refined_sigma = (
+ cpm_revin_refine_lib.cpm_iterative_revin_refine(
+ raw_logits,
+ revin_n=running_n,
+ revin_mu=revin_mean,
+ revin_sigma=revin_std,
+ patch_cpm_mask=patch_cpm_mask,
+ median_q_idx=self.num_quantiles // 2,
+ rolls=self.rolls,
+ patch_len=self.input_patch_len,
+ num_quantiles=self.num_quantiles,
+ value_clip=self.value_clip,
+ )
+ )
+ cpm_bvn = patch_cpm_mask.unsqueeze(1) # (b, 1, n)
+ revin_mean = torch.where(cpm_bvn, refined_mu, revin_mean)
+ revin_std = torch.where(cpm_bvn, refined_sigma, revin_std)
+
+ revin_logits = util.revin(raw_logits, revin_mean, revin_std, reverse=True)
+ clipped_logits = torch.clamp(
+ revin_logits, -self.value_clip, self.value_clip
+ )
+
+ # Reshape: (b, v, n, o*q) -> (b, v, n, o, q)
+ b, v, n_patches = clipped_logits.shape[:3]
+ final_logits = clipped_logits.view(
+ b, v, n_patches, self.output_patch_len, self.num_quantiles
+ )
+
+ outputs = {"logits": final_logits, "revin_stats": revin_stats}
+
+ if return_aux_outputs:
+ outputs["__call__:resblock_input"] = resblock_input
+ outputs["__call__:transformer_input"] = transformer_input
+ outputs["__call__:seq_attn_mask"] = seq_attn_mask
+ outputs["__call__:transformer_output"] = transformer_output
+
+ return outputs
+
+ @torch.no_grad()
+ def decode(
+ self,
+ target: torch.Tensor,
+ horizon: int = 0,
+ past_only_covariates: torch.Tensor | None = None,
+ past_future_covariates: torch.Tensor | None = None,
+ target_mask: torch.Tensor | None = None,
+ past_only_mask: torch.Tensor | None = None,
+ past_future_mask: torch.Tensor | None = None,
+ mask: torch.Tensor | None = None,
+ return_aux_outputs: bool = False,
+ ) -> Any:
+ """Non-autoregressive single-pass decoding for TimesFM3.
+
+ Args:
+ target: (b, u, context_len).
+ horizon: Forecast horizon. Inferred if past_future_covariates given.
+ past_only_covariates: (b, v_po, context_len) or None.
+ past_future_covariates: (b, w, context_len+horizon) or None.
+ target_mask: (b, u, context_len) bool or None.
+ past_only_mask: (b, v_po, context_len) bool or None.
+ past_future_mask: (b, w, context_len+horizon) bool or None.
+ mask: (b, context_len) global bool mask or None.
+ return_aux_outputs: If True, return (logits, aux_dict).
+
+ Returns:
+ Logits of shape (b, num_variates, horizon, num_quantiles).
+ """
+ device = target.device
+ batch_size, 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 function requires horizon > 0.")
+
+ # 1. Pad context to multiple of input_patch_len
+ ctx_padding = (
+ self.input_patch_len - (context % self.input_patch_len)
+ ) % self.input_patch_len
+ if ctx_padding > 0:
+ target = torch.nn.functional.pad(target, (ctx_padding, 0))
+ if mask is not None:
+ mask = torch.nn.functional.pad(mask, (ctx_padding, 0), value=True)
+ if past_only_covariates is not None:
+ past_only_covariates = torch.nn.functional.pad(
+ past_only_covariates, (ctx_padding, 0)
+ )
+ if past_future_covariates is not None:
+ past_future_covariates = torch.nn.functional.pad(
+ past_future_covariates, (ctx_padding, 0)
+ )
+ if target_mask is not None:
+ target_mask = torch.nn.functional.pad(
+ target_mask, (ctx_padding, 0), value=True
+ )
+ if past_only_mask is not None:
+ past_only_mask = torch.nn.functional.pad(
+ past_only_mask, (ctx_padding, 0), value=True
+ )
+ if past_future_mask is not None:
+ past_future_mask = torch.nn.functional.pad(
+ past_future_mask, (ctx_padding, 0), value=True
+ )
+ context = context + ctx_padding
+
+ if mask is None:
+ mask = torch.zeros(batch_size, context, dtype=torch.bool, device=device)
+ if ctx_padding > 0:
+ mask[:, :ctx_padding] = True
+
+ # 2. Pad horizon
+ if self.use_stitching:
+ extract_len = self._stitching_extract_len
+ overlap = extract_len - self.input_patch_len
+ num_forecast_patches = max(
+ math.ceil((horizon - overlap) / self.input_patch_len), 1
+ )
+ num_horizon_patches = num_forecast_patches + self.rolls - 1
+ padded_horizon = num_horizon_patches * self.input_patch_len
+ hor_padding = padded_horizon - horizon
+ else:
+ hor_padding = (-horizon) % self.output_patch_len
+ padded_horizon = horizon + hor_padding
+ num_horizon_patches = padded_horizon // self.input_patch_len
+ num_context_patches = context // self.input_patch_len
+
+ # 3. Build context & horizon inputs
+ if target_mask is None:
+ target_mask = torch.zeros_like(target, dtype=torch.bool)
+ target_mask = target_mask | mask.unsqueeze(1)
+
+ all_ctx_vals = [target]
+ all_ctx_masks = [target_mask]
+ 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 = torch.zeros_like(
+ past_only_covariates, dtype=torch.bool
+ )
+ all_ctx_vals.append(past_only_covariates)
+ all_ctx_masks.append(past_only_mask | mask.unsqueeze(1))
+ if past_future_covariates is not None:
+ if past_future_mask is None:
+ past_future_mask = torch.zeros_like(
+ past_future_covariates, dtype=torch.bool
+ )
+ all_ctx_vals.append(past_future_covariates[..., :context])
+ all_ctx_masks.append(past_future_mask[..., :context] | mask.unsqueeze(1))
+
+ ctx_vals = torch.cat(all_ctx_vals, dim=1)
+ ctx_masks = torch.cat(all_ctx_masks, dim=1)
+
+ if self.use_linear_detrending:
+ t_ctx = torch.arange(
+ -(context - 1), 1, dtype=torch.float32, device=device
+ )
+ t_ctx_bvc = t_ctx[None, None, :]
+ t_ctx_bvc_normalized = t_ctx_bvc / context
+
+ valid = ~ctx_masks
+ n_v = valid.float().sum(dim=-1, keepdim=True)
+ sum_t = torch.where(valid, t_ctx_bvc_normalized, 0.0).sum(
+ dim=-1, keepdim=True
+ )
+ sum_t2 = torch.where(valid, t_ctx_bvc_normalized**2, 0.0).sum(
+ dim=-1, keepdim=True
+ )
+ sum_y = torch.where(valid, ctx_vals, 0.0).sum(dim=-1, keepdim=True)
+ sum_ty = torch.where(valid, t_ctx_bvc_normalized * ctx_vals, 0.0).sum(
+ dim=-1, keepdim=True
+ )
+
+ det = n_v * sum_t2 - sum_t**2
+ safe_det = torch.where(det == 0.0, 1.0, det)
+ m_trend = torch.where(
+ det == 0.0, 0.0, (n_v * sum_ty - sum_t * sum_y) / safe_det
+ )
+ c_trend = torch.where(
+ det == 0.0,
+ torch.where(n_v > 0, sum_y / torch.clamp_min(n_v, 1.0), 0.0),
+ (sum_y - m_trend * sum_t) / torch.clamp_min(n_v, 1.0),
+ )
+
+ ctx_vals_detrended = ctx_vals - (
+ m_trend * t_ctx_bvc_normalized + c_trend
+ )
+
+ mean_y = sum_y / torch.clamp_min(n_v, 1.0)
+ sum_y2 = torch.where(valid, ctx_vals**2, 0.0).sum(dim=-1, keepdim=True)
+ var_orig = torch.clamp_min(
+ sum_y2 / torch.clamp_min(n_v, 1.0) - mean_y**2, 0.0
+ )
+ std_orig = torch.sqrt(var_orig)
+
+ sum_yd = torch.where(valid, ctx_vals_detrended, 0.0).sum(
+ dim=-1, keepdim=True
+ )
+ mean_yd = sum_yd / torch.clamp_min(n_v, 1.0)
+ sum_yd2 = torch.where(valid, ctx_vals_detrended**2, 0.0).sum(
+ dim=-1, keepdim=True
+ )
+ var_det = torch.clamp_min(
+ sum_yd2 / torch.clamp_min(n_v, 1.0) - mean_yd**2, 0.0
+ )
+ std_det = torch.sqrt(var_det)
+
+ apply_detrend = std_det < self.linear_detrending_threshold * std_orig
+ ctx_vals = torch.where(apply_detrend, ctx_vals_detrended, ctx_vals)
+ else:
+ num_variates = ctx_vals.shape[1]
+ m_trend = torch.zeros(
+ (batch_size, num_variates, 1), dtype=torch.float32, device=device
+ )
+ c_trend = torch.zeros(
+ (batch_size, num_variates, 1), dtype=torch.float32, device=device
+ )
+ apply_detrend = torch.zeros(
+ (batch_size, num_variates, 1), dtype=torch.bool, device=device
+ )
+
+ ctx_vals = torch.where(ctx_masks, 0.0, ctx_vals)
+
+ all_hor_vals = [
+ torch.zeros(batch_size, num_target, padded_horizon, device=device),
+ torch.zeros(batch_size, num_past_only, padded_horizon, device=device),
+ ]
+ all_hor_masks = [
+ torch.ones(
+ batch_size,
+ num_target,
+ padded_horizon,
+ dtype=torch.bool,
+ device=device,
+ ),
+ torch.ones(
+ batch_size,
+ num_past_only,
+ padded_horizon,
+ dtype=torch.bool,
+ device=device,
+ ),
+ ]
+
+ if past_future_covariates is not None:
+ if past_future_mask is None:
+ past_future_mask = torch.zeros_like(
+ past_future_covariates, dtype=torch.bool
+ )
+ pf_future_vals = past_future_covariates[..., context : context + horizon]
+ pf_future_masks = past_future_mask[..., context : context + horizon]
+ if self.use_linear_detrending:
+ m_pf = m_trend[:, num_target + num_past_only :, :]
+ c_pf = c_trend[:, num_target + num_past_only :, :]
+ apply_detrend_pf = apply_detrend[:, num_target + num_past_only :, :]
+ t_hor_pf = torch.arange(
+ 1, horizon + 1, dtype=torch.float32, device=device
+ )[None, None, :]
+ t_hor_pf_normalized = t_hor_pf / context
+ pf_trend_hor = m_pf * t_hor_pf_normalized + c_pf
+ pf_future_vals = torch.where(
+ apply_detrend_pf, pf_future_vals - pf_trend_hor, pf_future_vals
+ )
+ pf_future_vals = torch.where(pf_future_masks, 0.0, pf_future_vals)
+ if hor_padding > 0:
+ pf_future_vals = torch.nn.functional.pad(
+ pf_future_vals, (0, hor_padding)
+ )
+ pf_future_masks = torch.nn.functional.pad(
+ pf_future_masks, (0, hor_padding), value=True
+ )
+ all_hor_vals.append(pf_future_vals)
+ all_hor_masks.append(pf_future_masks)
+
+ hor_vals = torch.cat(all_hor_vals, dim=1)
+ hor_masks = torch.cat(all_hor_masks, dim=1)
+
+ all_vals = torch.cat([ctx_vals, hor_vals], dim=-1)
+ all_masks = torch.cat([ctx_masks, hor_masks], dim=-1)
+
+ num_variates = all_vals.shape[1]
+ patch_is_target = torch.zeros(
+ (batch_size, num_variates, num_context_patches + num_horizon_patches),
+ dtype=torch.bool,
+ device=device,
+ )
+ patch_is_target[:, : num_target + num_past_only, :] = True
+
+ # Reshape values & masks to patched shape (b, v, n, p)
+ values_bvnp = all_vals.reshape(
+ batch_size, num_variates, -1, self.input_patch_len
+ )
+ masks_bvnp = all_masks.reshape(
+ batch_size, num_variates, -1, self.input_patch_len
+ )
+
+ inputs = {
+ "values": values_bvnp,
+ "masks": masks_bvnp,
+ "patch_is_target": patch_is_target,
+ }
+
+ # Build horizon CPM mask: context=False, horizon=True.
+ num_total_patches = num_context_patches + num_horizon_patches
+ horizon_cpm_mask = torch.zeros(
+ batch_size, num_total_patches, dtype=torch.bool, device=device
+ )
+ horizon_cpm_mask[:, num_context_patches:] = True
+
+ freeze_after = (
+ num_context_patches - 1 if self.use_frozen_running_stats else None
+ )
+ forward_out = self.forward(
+ inputs,
+ freeze_after=freeze_after,
+ patch_cpm_mask=horizon_cpm_mask,
+ return_aux_outputs=return_aux_outputs,
+ )
+ logits = forward_out["logits"] # (b, v, n, output_patch_len, num_quantiles)
+
+ if self.use_stitching:
+ extract_len = self._stitching_extract_len
+ overlap = extract_len - self.input_patch_len
+ num_forecast_patches = max(
+ math.ceil((horizon - overlap) / self.input_patch_len), 1
+ )
+ forecast_indices = torch.arange(
+ num_forecast_patches, device=device
+ ) + (num_context_patches - 1)
+ patch_preds = logits[:, :, forecast_indices, :extract_len, :]
+ horizon_logits = util.stitch_patches(
+ patch_preds,
+ self.input_patch_len,
+ )[:, :, :horizon, :]
+ else:
+ num_forecast_chunks = padded_horizon // self.output_patch_len
+ forecast_indices = torch.arange(
+ num_forecast_chunks, device=device
+ ) * self.rolls + (num_context_patches - 1)
+ forecast_logits = logits[:, :, forecast_indices, :, :]
+ horizon_logits = forecast_logits.reshape(
+ batch_size, num_variates, -1, self.num_quantiles
+ )[:, :, :horizon, :]
+
+ if self.use_linear_detrending:
+ t_forecast = torch.arange(
+ 1, horizon + 1, dtype=torch.float32, device=device
+ )
+ t_forecast_normalized = t_forecast / context
+ trend_forecast = (
+ m_trend[:, :, 0, None] * t_forecast_normalized[None, None, :]
+ + c_trend[:, :, 0, None]
+ )
+ trend_forecast = torch.where(
+ apply_detrend[:, :, 0, None], trend_forecast, 0.0
+ )
+ horizon_logits = horizon_logits + trend_forecast[:, :, :, None]
+
+ if return_aux_outputs:
+ return horizon_logits, forward_out
+ return horizon_logits
diff --git a/src/timesfm3/model_test.py b/src/timesfm3/model_test.py
new file mode 100644
index 0000000..ffefd46
--- /dev/null
+++ b/src/timesfm3/model_test.py
@@ -0,0 +1,116 @@
+# Copyright 2025 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 PyTorch TimesFM3Torch model."""
+
+import unittest
+import numpy as np
+import torch
+
+from . import configs
+from . import model as torch_model_lib
+
+
+class TimesFM3TorchTest(unittest.TestCase):
+
+ def setUp(self):
+ super().setUp()
+ self.resblock_config = configs.ResidualBlockConfig(
+ hidden_dims=32,
+ output_dims=32,
+ use_bias=False,
+ activation="relu",
+ dropout=0.0,
+ )
+ self.transformer_config = configs.StackedTransformersConfig(
+ num_layers=2,
+ use_remat=False,
+ transformer=configs.TransformerConfig(
+ model_dims=32,
+ hidden_dims=32,
+ num_heads=4,
+ attention_norm="rms",
+ feedforward_norm="rms",
+ qk_norm="rms",
+ use_rope_seq=True,
+ use_rope_var=True,
+ use_bias=False,
+ ff_activation="relu",
+ deterministic=True,
+ use_sdpa=True,
+ ),
+ )
+ self.model = torch_model_lib.TimesFM3Torch(
+ input_patch_len=8,
+ output_patch_len=16,
+ quantiles=[0.1, 0.5, 0.9],
+ residual_block_config=self.resblock_config,
+ transformer_config=self.transformer_config,
+ use_stitching=True,
+ use_linear_detrending=True,
+ use_iterative_cpm_revin=True,
+ use_frozen_running_stats=False,
+ )
+ self.model.eval()
+
+ def test_forward_pass_training_dict(self):
+ b, v, n, p = 2, 3, 4, 8
+ inputs = {
+ "values": torch.randn(b, v, n, p),
+ "masks": torch.zeros(b, v, n, p, dtype=torch.bool),
+ "patch_segment_ids": torch.zeros(b, n, dtype=torch.long),
+ "patch_positions": torch.arange(n).unsqueeze(0).repeat(b, 1),
+ "patch_is_target": torch.ones(b, v, n, dtype=torch.bool),
+ "patch_is_past_only": torch.zeros(b, v, n, dtype=torch.bool),
+ "patch_is_past_future_covariate": torch.zeros(b, v, n, dtype=torch.bool),
+ }
+ with torch.no_grad():
+ out = self.model(inputs)
+ self.assertIn("logits", out)
+ # Shape: (b, v, n, output_patch_len, num_quantiles) = (2, 3, 4, 16, 3)
+ self.assertEqual(out["logits"].shape, (b, v, n, 16, 3))
+
+ def test_decode_univariate(self):
+ b, v, context_len = 2, 1, 32
+ target = torch.randn(b, v, context_len)
+ horizon = 32
+ with torch.no_grad():
+ out = self.model.decode(target=target, horizon=horizon)
+ # Output shape: (b, v, horizon, num_quantiles) = (2, 1, 32, 3)
+ self.assertEqual(out.shape, (b, v, horizon, 3))
+ self.assertTrue(torch.isfinite(out).all().item())
+
+ def test_decode_multivariate_with_covariates(self):
+ b, v, context_len = 2, 3, 32
+ target = torch.randn(b, v, context_len)
+ po_cov = torch.randn(b, v, context_len)
+ horizon = 32
+ pf_cov = torch.randn(b, v, context_len + horizon)
+ mask = torch.zeros(b, context_len, dtype=torch.bool)
+
+ with torch.no_grad():
+ out = self.model.decode(
+ target=target,
+ horizon=horizon,
+ past_only_covariates=po_cov,
+ past_future_covariates=pf_cov,
+ mask=mask,
+ )
+ # Total variates: 3 targets + 3 past_only + 3 past_future = 9
+ self.assertEqual(out.shape, (b, 9, horizon, 3))
+ self.assertTrue(torch.isfinite(out).all().item())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src/timesfm3/normalization.py b/src/timesfm3/normalization.py
new file mode 100644
index 0000000..25fcf91
--- /dev/null
+++ b/src/timesfm3/normalization.py
@@ -0,0 +1,35 @@
+"""Normalization layers for TimesFM3 PyTorch."""
+
+from __future__ import annotations
+
+import math
+
+import torch
+from torch import nn
+
+_RECIPROCAL_OF_SOFTPLUS_0 = 1.442695041
+
+
+class PerDimScale(nn.Module):
+ """Per-dimension 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)
+
+ The per_dim_scale parameter is initialized to zeros, so at init time
+ softplus(0) ≈ 0.693..., and the net scale is close to 1/sqrt(d).
+ """
+
+ def __init__(self, num_dims: int):
+ super().__init__()
+ self.num_dims = num_dims
+ self.per_dim_scale = nn.Parameter(torch.zeros(num_dims))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Applies per-dim scaling to the last dimension of x."""
+ return (
+ x
+ * _RECIPROCAL_OF_SOFTPLUS_0
+ / math.sqrt(self.num_dims)
+ * torch.nn.functional.softplus(self.per_dim_scale)
+ )
diff --git a/src/timesfm3/primitives_test.py b/src/timesfm3/primitives_test.py
new file mode 100644
index 0000000..6f76493
--- /dev/null
+++ b/src/timesfm3/primitives_test.py
@@ -0,0 +1,357 @@
+# Copyright 2025 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 TimesFM3 PyTorch primitives."""
+
+import math
+import unittest
+import numpy as np
+import torch
+
+from . import configs
+from . import dense as torch_dense
+from . import normalization as torch_norm
+from . import transformations as torch_trans
+from . import util as torch_util
+
+
+class TransformationsTest(unittest.TestCase):
+ """Tests reversible transformations."""
+
+ def test_signed_log(self):
+ x = torch.tensor([-10.0, -1.0, 0.0, 1.0, 10.0], dtype=torch.float32)
+ y = torch_trans.signed_log(x)
+ expected_y = torch.sign(x) * torch.log1p(torch.abs(x))
+ np.testing.assert_allclose(y.numpy(), expected_y.numpy(), atol=1e-6)
+
+ # Reverse round-trip
+ z = torch_trans.signed_log(y, reverse=True)
+ np.testing.assert_allclose(z.numpy(), x.numpy(), atol=1e-5)
+
+ def test_signed_sqrt(self):
+ x = torch.tensor([-9.0, -1.0, 0.0, 1.0, 16.0], dtype=torch.float32)
+ y = torch_trans.signed_sqrt(x)
+ expected_y = torch.sign(x) * torch.sqrt(torch.abs(x))
+ np.testing.assert_allclose(y.numpy(), expected_y.numpy(), atol=1e-6)
+
+ # Reverse round-trip
+ z = torch_trans.signed_sqrt(y, reverse=True)
+ np.testing.assert_allclose(z.numpy(), x.numpy(), atol=1e-5)
+
+ def test_identity(self):
+ x = torch.randn(2, 3, 4)
+ y = torch_trans.identity(x)
+ np.testing.assert_allclose(y.numpy(), x.numpy())
+ z = torch_trans.identity(y, reverse=True)
+ np.testing.assert_allclose(z.numpy(), x.numpy())
+
+ def test_max_output(self):
+ value_clip = 10.0
+ self.assertAlmostEqual(
+ torch_trans.max_output("signed_log", value_clip).item(),
+ math.log1p(value_clip),
+ places=5,
+ )
+ self.assertAlmostEqual(
+ torch_trans.max_output("signed_sqrt", value_clip).item(),
+ math.sqrt(value_clip),
+ places=5,
+ )
+ self.assertAlmostEqual(
+ torch_trans.max_output("identity", value_clip).item(),
+ value_clip,
+ places=5,
+ )
+
+
+class NormalizationTest(unittest.TestCase):
+ """Tests PerDimScale."""
+
+ def test_per_dim_scale(self):
+ num_dims = 8
+ mod = torch_norm.PerDimScale(num_dims=num_dims)
+ x = torch.randn(2, 3, num_dims)
+ y = mod(x)
+ self.assertEqual(y.shape, x.shape)
+ # PerDimScale scales by RECIPROCAL_OF_SOFTPLUS_0 / sqrt(num_dims) * softplus(0)
+ # Since softplus(0) = ln(2) = 0.693147, and RECIPROCAL_OF_SOFTPLUS_0 = 1 / ln(2),
+ # at init it approximately scales by 1 / sqrt(num_dims).
+ expected_scale = 1.0 / math.sqrt(num_dims)
+ np.testing.assert_allclose(
+ y.detach().numpy(), (x * expected_scale).numpy(), atol=1e-4
+ )
+
+
+class ResidualBlockTest(unittest.TestCase):
+ """Tests ResidualBlock."""
+
+ def test_residual_block_identity_skip(self):
+ input_dim = 8
+ hidden_dims = 16
+ config = configs.ResidualBlockConfig(
+ hidden_dims=hidden_dims,
+ output_dims=input_dim,
+ use_bias=True,
+ activation="relu",
+ identity_skip=True,
+ prenorm="none",
+ )
+ mod = torch_dense.ResidualBlock(config=config)
+ x = torch.randn(2, input_dim)
+ out = mod(x)
+ self.assertEqual(out.shape, (2, input_dim))
+
+ def test_residual_block_projection_skip(self):
+ input_dim = 8
+ hidden_dims = 16
+ output_dims = 12
+ config = configs.ResidualBlockConfig(
+ hidden_dims=hidden_dims,
+ output_dims=output_dims,
+ use_bias=True,
+ activation="relu",
+ identity_skip=False,
+ prenorm="none",
+ )
+ mod = torch_dense.ResidualBlock(config=config)
+ x = torch.randn(2, input_dim)
+ out = mod(x)
+ self.assertEqual(out.shape, (2, output_dims))
+
+ def test_residual_block_with_prenorm(self):
+ input_dim = 8
+ hidden_dims = 16
+ config = configs.ResidualBlockConfig(
+ hidden_dims=hidden_dims,
+ output_dims=input_dim,
+ use_bias=False,
+ activation="relu",
+ identity_skip=True,
+ prenorm="rms",
+ )
+ mod = torch_dense.ResidualBlock(config=config)
+ x = torch.randn(2, input_dim)
+ out = mod(x)
+ self.assertEqual(out.shape, (2, input_dim))
+
+
+class UtilTest(unittest.TestCase):
+ """Tests utility functions."""
+
+ def test_activation_fns(self):
+ x = torch.tensor([-1.0, 0.0, 1.0])
+
+ relu = torch_util.get_activation_fn("relu")
+ np.testing.assert_allclose(relu(x).numpy(), [0.0, 0.0, 1.0])
+
+ silu = torch_util.get_activation_fn("silu")
+ expected_silu = x * torch.sigmoid(x)
+ np.testing.assert_allclose(silu(x).numpy(), expected_silu.numpy())
+
+ swish = torch_util.get_activation_fn("swish")
+ np.testing.assert_allclose(swish(x).numpy(), expected_silu.numpy())
+
+ swiglu = torch_util.get_activation_fn("swiglu")
+ np.testing.assert_allclose(swiglu(x).numpy(), expected_silu.numpy())
+
+ def test_decode_cache(self):
+ num_layers = 2
+ batch_size = 2
+ num_variates = 3
+ num_total_input_patches = 10
+ num_heads = 4
+ head_dim = 8
+
+ caches = torch_util.DecodeCache.init_decode_cache(
+ num_layers=num_layers,
+ batch_size=batch_size,
+ num_variates=num_variates,
+ num_total_input_patches=num_total_input_patches,
+ num_heads=num_heads,
+ head_dim=head_dim,
+ )
+
+ self.assertEqual(len(caches), num_layers)
+ leading_size = batch_size * num_variates
+
+ for cache in caches:
+ self.assertEqual(cache.next_index.shape, (leading_size,))
+ self.assertEqual(cache.num_front_masked.shape, (leading_size,))
+ self.assertEqual(
+ cache.key.shape,
+ (leading_size, num_total_input_patches, num_heads, head_dim),
+ )
+ self.assertEqual(
+ cache.value.shape,
+ (leading_size, num_total_input_patches, num_heads, head_dim),
+ )
+ np.testing.assert_allclose(cache.next_index.numpy(), 0)
+ np.testing.assert_allclose(cache.num_front_masked.numpy(), 0)
+ np.testing.assert_allclose(cache.key.numpy(), 0.0)
+ np.testing.assert_allclose(cache.value.numpy(), 0.0)
+
+ def test_update_running_stats_single_batch_no_mask(self):
+ n, mu, sigma = 0.0, 0.0, 0.0
+ x = torch.tensor([[[1.0, 2.0, 3.0]]])
+ mask = torch.zeros_like(x, dtype=torch.bool)
+ new_n, new_mu, new_sigma = torch_util.update_running_stats(
+ torch.tensor([[n]]),
+ torch.tensor([[mu]]),
+ torch.tensor([[sigma]]),
+ x,
+ mask,
+ )
+ self.assertAlmostEqual(new_n[0, 0].item(), 3.0)
+ self.assertAlmostEqual(new_mu[0, 0].item(), 2.0)
+ self.assertAlmostEqual(
+ new_sigma[0, 0].item(), torch.std(x, unbiased=False).item(), places=6
+ )
+
+ def test_update_running_stats_multiple_batches_no_mask(self):
+ x1 = torch.tensor([[[1.0, 2.0, 3.0]]])
+ mask1 = torch.zeros_like(x1, dtype=torch.bool)
+ x2 = torch.tensor([[[4.0, 5.0, 6.0]]])
+ mask2 = torch.zeros_like(x2, dtype=torch.bool)
+
+ n1, mu1, sigma1 = torch_util.update_running_stats(
+ torch.tensor([[0.0]]),
+ torch.tensor([[0.0]]),
+ torch.tensor([[0.0]]),
+ x1,
+ mask1,
+ )
+ n2, mu2, sigma2 = torch_util.update_running_stats(
+ n1, mu1, sigma1, x2, mask2
+ )
+
+ self.assertAlmostEqual(n2[0, 0].item(), 6.0)
+ self.assertAlmostEqual(mu2[0, 0].item(), 3.5)
+ concat_x = torch.cat([x1, x2], dim=-1)
+ self.assertAlmostEqual(
+ sigma2[0, 0].item(),
+ torch.std(concat_x, unbiased=False).item(),
+ places=6,
+ )
+
+ def test_update_running_stats_with_mask(self):
+ n, mu, sigma = 0.0, 0.0, 0.0
+ x = torch.tensor([[[1.0, 100.0, 2.0, 3.0]]])
+ mask = torch.tensor([[[False, True, False, False]]])
+ new_n, new_mu, new_sigma = torch_util.update_running_stats(
+ torch.tensor([[n]]),
+ torch.tensor([[mu]]),
+ torch.tensor([[sigma]]),
+ x,
+ mask,
+ )
+ self.assertAlmostEqual(new_n[0, 0].item(), 3.0)
+ self.assertAlmostEqual(new_mu[0, 0].item(), 2.0)
+ valid_x = torch.tensor([1.0, 2.0, 3.0])
+ self.assertAlmostEqual(
+ new_sigma[0, 0].item(),
+ torch.std(valid_x, unbiased=False).item(),
+ places=6,
+ )
+
+ def test_revin_no_reverse(self):
+ x = torch.tensor([[[1.0, 2.0, 3.0]]])
+ mu = torch.tensor([[2.0]])
+ sigma = torch.tensor([[1.0]])
+ normalized_x = torch_util.revin(x, mu, sigma, reverse=False)
+ expected = torch.tensor([[[-1.0, 0.0, 1.0]]])
+ np.testing.assert_allclose(
+ normalized_x.numpy(), expected.numpy(), atol=1e-6
+ )
+
+ def test_revin_reverse(self):
+ x_normalized = torch.tensor([[[-1.0, 0.0, 1.0]]])
+ mu = torch.tensor([[2.0]])
+ sigma = torch.tensor([[1.0]])
+ denormalized_x = torch_util.revin(x_normalized, mu, sigma, reverse=True)
+ expected = torch.tensor([[[1.0, 2.0, 3.0]]])
+ np.testing.assert_allclose(
+ denormalized_x.numpy(), expected.numpy(), atol=1e-6
+ )
+
+ def test_revin_near_zero_sigma(self):
+ x = torch.tensor([[[2.0, 2.0, 2.0]]])
+ mu = torch.tensor([[2.0]])
+ sigma = torch.tensor([[1e-7]])
+ normalized_x = torch_util.revin(x, mu, sigma, reverse=False)
+ expected = torch.tensor([[[0.0, 0.0, 0.0]]])
+ np.testing.assert_allclose(
+ normalized_x.numpy(), expected.numpy(), atol=1e-6
+ )
+
+ def test_get_output_patch_via_roll(self):
+ x = torch.tensor([[[[1, 2], [3, 4], [5, 6], [7, 8]]]], dtype=torch.float32)
+ rolls = 2
+ expected_output = torch.tensor(
+ [[[[3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 1, 2], [1, 2, 3, 4]]]],
+ dtype=torch.float32,
+ )
+ output, _ = torch_util.get_output_patch_via_roll(x, rolls)
+ np.testing.assert_allclose(
+ output.numpy(), expected_output.numpy(), atol=1e-6
+ )
+
+ def test_get_running_stats_single_segment(self):
+ values = torch.tensor([[[[1, 3], [5, 7]]]], dtype=torch.float32)
+ masks = torch.zeros_like(values, dtype=torch.bool)
+ segment_ids = torch.tensor([[0, 0]], dtype=torch.int32)
+ _, mu, sigma = torch_util.get_running_stats(
+ values, masks, segment_ids=segment_ids
+ )
+
+ expected_mu = torch.tensor([[[2.0, 4.0]]])
+ expected_sigma = torch.tensor([[[1.0, 2.236068]]])
+ np.testing.assert_allclose(mu.numpy(), expected_mu.numpy(), atol=1e-6)
+ np.testing.assert_allclose(sigma.numpy(), expected_sigma.numpy(), atol=1e-6)
+
+ def test_get_running_stats_multiple_segments(self):
+ values = torch.tensor(
+ [[[[1, 3], [10, 10], [5, 7], [4, 6]]]], dtype=torch.float32
+ )
+ masks = torch.zeros_like(values, dtype=torch.bool)
+ segment_ids = torch.tensor([[0, 0, 1, 1]], dtype=torch.int32)
+ _, mu, sigma = torch_util.get_running_stats(
+ values, masks, segment_ids=segment_ids
+ )
+
+ expected_mu = torch.tensor([[[2.0, 6.0, 6.0, 5.5]]])
+ expected_sigma = torch.tensor([[[1.0, 4.062019, 1.0, 1.118034]]])
+ np.testing.assert_allclose(mu.numpy(), expected_mu.numpy(), atol=1e-6)
+ np.testing.assert_allclose(sigma.numpy(), expected_sigma.numpy(), atol=1e-6)
+
+ def test_get_running_stats_with_masks(self):
+ values = torch.tensor(
+ [[[[1, 10, 3, 0], [100, 5, 200, 7]]]], dtype=torch.float32
+ )
+ masks = torch.tensor(
+ [[[[False, True, False, True], [True, False, True, False]]]],
+ dtype=torch.bool,
+ )
+ segment_ids = torch.tensor([[0, 0]], dtype=torch.int32)
+ _, mu, sigma = torch_util.get_running_stats(
+ values, masks, segment_ids=segment_ids
+ )
+
+ expected_mu = torch.tensor([[[2.0, 4.0]]])
+ expected_sigma = torch.tensor([[[1.0, 2.236068]]])
+ np.testing.assert_allclose(mu.numpy(), expected_mu.numpy(), atol=1e-6)
+ np.testing.assert_allclose(sigma.numpy(), expected_sigma.numpy(), atol=1e-6)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src/timesfm3/timesfm3_forecaster.py b/src/timesfm3/timesfm3_forecaster.py
new file mode 100644
index 0000000..61c0e37
--- /dev/null
+++ b/src/timesfm3/timesfm3_forecaster.py
@@ -0,0 +1,671 @@
+"""Forecaster API wrapping a pretrained TimesFM3 PyTorch model."""
+
+from __future__ import annotations
+
+import dataclasses
+import gc
+import logging
+import math
+import os
+from typing import Any, Iterator
+
+import numpy as np
+import torch
+
+from . import configs
+from . import model as torch_model_lib
+from . import util
+
+_MAX_CONTEXT_LENGTH = 16384
+_SIGMA_THRESHOLD: float = 1e-7
+_GC_MEMORY_THRESHOLD: float = 0.9
+
+
+class _ModelConfig:
+ """Configuration for a PyTorch TimesFM3 forecaster."""
+
+ # Path to checkpoint file (.pth or .safetensors).
+ checkpoint_path: str = "~/models/tfm3/timesfm3_torch_1944000.safetensors"
+
+ # Batch size to use for inference.
+ per_core_batch_size: int = 4
+
+ # Input (context) patch length used by the model.
+ input_patch_length: int = 32
+
+ # Output (horizon) patch length used by the model.
+ output_patch_length: int = 64
+
+ # Quantiles to predict.
+ quantiles: list[float] = dataclasses.field(
+ default_factory=lambda: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
+ )
+
+ # Median quantile index for the forecast.
+ median_quantile_index: int = 4
+
+ # Whether to use stitching.
+ use_stitching: bool = True
+
+ # Whether to use linear detrending.
+ use_linear_detrending: bool = True
+
+ # Linear detrending threshold.
+ linear_detrending_threshold: float = 0.5
+
+ # Whether to use iterative CPM RevIN refinement.
+ use_iterative_cpm_revin: bool = True
+
+ # Whether running stats freeze at context boundary.
+ use_frozen_running_stats: bool = False
+
+ # Whether to use variate attention.
+ use_variate_attention: bool = True
+
+ # Value clipping bound.
+ value_clip: float = 1e20
+
+ # Input transformation.
+ input_transform: str = "identity"
+
+ # Whether to use scaled_dot_product_attention.
+ use_sdpa: bool = True
+
+ # Optional PyTorch device string ('cuda', 'cpu', etc.).
+ device: str | None = None
+
+ # Optional configuration objects
+ residual_block_config: configs.ResidualBlockConfig | None = None
+ transformer_config: configs.StackedTransformersConfig | None = None
+
+
+# Public alias
+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
+
+
+def try_gc(
+ device: torch.device | str | None = None,
+ gc_memory_threshold: float = _GC_MEMORY_THRESHOLD,
+) -> None:
+ """Trigger Python GC and empty CUDA cache if memory exceeds threshold."""
+ if device is not None and torch.cuda.is_available():
+ d = torch.device(device) if isinstance(device, str) else device
+ if d.type == "cuda":
+ allocated = torch.cuda.memory_allocated(d)
+ total = torch.cuda.get_device_properties(d).total_memory
+ if total > 0 and (allocated / total) > gc_memory_threshold:
+ gc.collect()
+ torch.cuda.empty_cache()
+ return
+ gc.collect()
+
+
+def strip_leading_nans(arr: np.ndarray) -> np.ndarray:
+ """Removes contiguous NaN values from the beginning of a NumPy array."""
+ if arr.size == 0:
+ return arr
+
+ was_1d = arr.ndim == 1
+ arr2d = np.atleast_2d(arr)
+
+ isnan = np.atleast_1d(np.isnan(arr2d).all(axis=0))
+ first_valid_index = int(np.argmax(~isnan))
+
+ if first_valid_index == 0 and isnan[0]:
+ if was_1d:
+ return np.array([], dtype=arr.dtype)
+ return np.empty((arr2d.shape[0], 0), dtype=arr.dtype)
+
+ result = arr2d[:, first_valid_index:]
+ return result[0] if was_1d else result
+
+
+def linear_interpolation(arr: np.ndarray) -> np.ndarray:
+ """Performs linear interpolation to fill NaN values in a NumPy array."""
+ was_1d = arr.ndim == 1
+ arr2d = np.atleast_2d(arr)
+
+ nan_mask = np.isnan(arr2d)
+ if not np.any(nan_mask):
+ return arr
+
+ result = arr2d.copy()
+ for r in range(result.shape[0]):
+ if np.any(nan_mask[r]):
+ row = result[r]
+ valid_mask = ~nan_mask[r]
+ nan_indices = nan_mask[r].nonzero()[0]
+ valid_indices = valid_mask.nonzero()[0]
+ valid_values = row[valid_mask]
+ row[nan_mask[r]] = np.interp(nan_indices, valid_indices, valid_values)
+
+ return result[0] if was_1d else result
+
+
+def _znorm_stats(arr: np.ndarray) -> tuple[float, float]:
+ """Returns (mean, std) for z-normalization, ignoring NaNs."""
+ mu = float(np.nanmean(arr))
+ sigma = float(np.nanstd(arr))
+ if not np.isfinite(mu):
+ mu = 0.0
+ if not np.isfinite(sigma) or sigma < _SIGMA_THRESHOLD:
+ sigma = 1.0
+ return mu, sigma
+
+
+def _is_nonnegative(arr: np.ndarray) -> bool | np.ndarray:
+ """Returns True if `arr` has at least one finite value and all are >= 0."""
+ was_1d = arr.ndim == 1
+ arr2d = np.atleast_2d(arr)
+
+ result = np.zeros(arr2d.shape[0], dtype=bool)
+ for r in range(arr2d.shape[0]):
+ valid = arr2d[r][~np.isnan(arr2d[r])]
+ result[r] = valid.size > 0 and bool(np.all(valid >= 0))
+
+ return bool(result[0]) if was_1d else result
+
+
[email protected](frozen=True)
+class _Query:
+ """A single forecast query."""
+
+ horizon: int
+ targets: np.ndarray
+ past_only_covariates: np.ndarray | None = None
+ past_future_covariates: np.ndarray | None = None
+ padded: bool = False
+
+ @property
+ def context_length(self) -> int:
+ return self.targets.shape[-1]
+
+ def format(self, global_context: int) -> tuple[
+ int,
+ np.ndarray,
+ np.ndarray,
+ np.ndarray | None,
+ np.ndarray | None,
+ bool,
+ ]:
+ """Formats and left-pads/truncates the query to global_context length."""
+ targets = np.atleast_2d(self.targets)
+ masks = np.zeros((self.context_length,), dtype=bool)
+ past_only_covariates = (
+ np.atleast_2d(self.past_only_covariates)
+ if self.past_only_covariates is not None
+ else None
+ )
+ past_future_covariates = (
+ np.atleast_2d(self.past_future_covariates)
+ if self.past_future_covariates is not None
+ else None
+ )
+
+ if self.context_length > global_context:
+ targets = targets[:, -global_context:]
+ masks = masks[-global_context:]
+ if past_only_covariates is not None:
+ past_only_covariates = past_only_covariates[:, -global_context:]
+ if past_future_covariates is not None:
+ past_future_covariates = past_future_covariates[
+ :, -(global_context + self.horizon) :
+ ]
+ elif self.context_length < global_context:
+ pad_len = global_context - self.context_length
+ targets = np.pad(
+ targets,
+ [(0, 0), (pad_len, 0)],
+ mode="constant",
+ constant_values=0.0,
+ )
+ masks = np.pad(
+ masks,
+ [(pad_len, 0)],
+ mode="constant",
+ constant_values=True,
+ )
+ if self.padded:
+ masks = np.ones_like(masks, dtype=bool)
+ if past_only_covariates is not None:
+ past_only_covariates = np.pad(
+ past_only_covariates,
+ [(0, 0), (pad_len, 0)],
+ mode="constant",
+ constant_values=0.0,
+ )
+ if past_future_covariates is not None:
+ past_future_covariates = np.pad(
+ past_future_covariates,
+ [(0, 0), (pad_len, 0)],
+ mode="constant",
+ constant_values=0.0,
+ )
+
+ return (
+ self.horizon,
+ targets,
+ masks,
+ past_only_covariates,
+ past_future_covariates,
+ self.padded,
+ )
+
+
+def _make_torch_model(
+ config: _ModelConfig,
+) -> torch_model_lib.TimesFM3Torch:
+ """Builds a PyTorch model using ModelConfig."""
+ resblock_config = (
+ config.residual_block_config
+ if config.residual_block_config is not None
+ else configs.ResidualBlockConfig(
+ hidden_dims=1280,
+ output_dims=1280,
+ use_bias=False,
+ activation="relu",
+ )
+ )
+
+ transformer_config = (
+ config.transformer_config
+ if config.transformer_config is not None
+ else configs.StackedTransformersConfig(
+ num_layers=20,
+ transformer=configs.TransformerConfig(
+ model_dims=1280,
+ hidden_dims=1280,
+ num_heads=16,
+ attention_norm="rms",
+ feedforward_norm="rms",
+ qk_norm="rms",
+ use_rope_seq=True,
+ use_rope_var=True,
+ use_bias=False,
+ ff_activation="relu",
+ deterministic=True,
+ ),
+ )
+ )
+
+ t_model = torch_model_lib.TimesFM3Torch(
+ input_patch_len=config.input_patch_length,
+ output_patch_len=config.output_patch_length,
+ quantiles=config.quantiles,
+ use_variate_attention=config.use_variate_attention,
+ value_clip=config.value_clip,
+ input_transform=config.input_transform,
+ use_stitching=config.use_stitching,
+ use_linear_detrending=config.use_linear_detrending,
+ linear_detrending_threshold=config.linear_detrending_threshold,
+ use_iterative_cpm_revin=config.use_iterative_cpm_revin,
+ use_frozen_running_stats=config.use_frozen_running_stats,
+ residual_block_config=resblock_config,
+ transformer_config=transformer_config,
+ )
+ t_model.eval()
+ input_dim = 2 * (t_model.input_patch_len + t_model.output_patch_len)
+ t_model.pre_transformer_resblock.set_input_dims(input_dim)
+ return t_model
+
+
+class TimesFM3Forecaster:
+ """Forecaster wrapping a PyTorch TimesFM3 model for inference."""
+
+ def __init__(self, config: _ModelConfig | None = None, **kwargs):
+ if config is None:
+ self.config = _ModelConfig(**kwargs)
+ elif kwargs:
+ self.config = dataclasses.replace(config, **kwargs)
+ else:
+ self.config = config
+ self._init_model()
+
+ @property
+ def global_context(self) -> int:
+ """Max context length rounded up to the nearest input patch boundary."""
+ return (
+ math.ceil(_MAX_CONTEXT_LENGTH / self.config.input_patch_length)
+ * self.config.input_patch_length
+ )
+
+ def _init_model(self):
+ """Initializes the PyTorch model and loads weights."""
+ if self.config.device is not None:
+ self.device = torch.device(self.config.device)
+ else:
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+
+ self.model = _make_torch_model(self.config)
+
+ checkpoint_path = os.path.expanduser(self.config.checkpoint_path)
+ if os.path.exists(checkpoint_path):
+ if checkpoint_path.endswith(".safetensors"):
+ state_dict = util.load_safetensors(checkpoint_path, device=self.device)
+ self.model.load_state_dict(state_dict)
+ elif checkpoint_path.endswith(".pth") or checkpoint_path.endswith(".pt"):
+ state_dict = torch.load(checkpoint_path, map_location=self.device)
+ self.model.load_state_dict(state_dict)
+ else:
+ raise ValueError(
+ f"Unsupported checkpoint path format: {checkpoint_path}. "
+ "Expected .safetensors or .pth / .pt file."
+ )
+
+ self.model.to(self.device)
+ self.model.eval()
+
+ 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,
+ use_znorm: bool = False,
+ padding_mode: str = "none",
+ ) -> ForecastOutput:
+ """Convenience wrapper: runs inference on a single time series."""
+ 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,
+ 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,
+ use_znorm: bool = False,
+ padding_mode: str = "none",
+ ) -> Iterator[ForecastOutput]:
+ """Runs inference on a batch of time series with optional covariates."""
+ global_horizon = (
+ math.ceil(horizon / self.config.output_patch_length)
+ * self.config.output_patch_length
+ )
+ num_original_ts = len(contexts)
+ original_ts_ids = (
+ list(ts_ids) if ts_ids is not None else [None] * num_original_ts
+ )
+
+ po_cov_list = (
+ list(past_only_covariates)
+ if past_only_covariates is not None
+ else [None] * num_original_ts
+ )
+ pf_cov_list = (
+ list(past_future_covariates)
+ if past_future_covariates is not None
+ else [None] * num_original_ts
+ )
+
+ contexts_2d: list[np.ndarray] = []
+ po_2d: list[np.ndarray | None] = []
+ pf_2d: list[np.ndarray | None] = []
+
+ for idx, ctx in enumerate(contexts):
+ arr = np.atleast_2d(np.array(ctx, dtype=np.float64))
+ arr = strip_leading_nans(arr)
+ arr = linear_interpolation(arr)
+ contexts_2d.append(arr)
+
+ po = po_cov_list[idx]
+ if po is not None:
+ po_arr = np.atleast_2d(np.array(po, dtype=np.float64))
+ po_arr = strip_leading_nans(po_arr)
+ po_arr = linear_interpolation(po_arr)
+ po_2d.append(po_arr)
+ else:
+ po_2d.append(None)
+
+ pf = pf_cov_list[idx]
+ if pf is not None:
+ pf_arr = np.atleast_2d(np.array(pf, dtype=np.float64))
+ pf_arr = strip_leading_nans(pf_arr)
+ pf_arr = linear_interpolation(pf_arr)
+ pf_2d.append(pf_arr)
+ else:
+ pf_2d.append(None)
+
+ original_contexts = list(contexts_2d)
+ num_targets_in = contexts_2d[0].shape[0] if contexts_2d else 1
+
+ for idx, ctx in enumerate(contexts_2d):
+ if ctx.shape[0] != num_targets_in:
+ raise ValueError(
+ "All contexts must have the same number of target variates, but"
+ f" contexts[0] has {num_targets_in} and contexts[{idx}] has"
+ f" {ctx.shape[0]}."
+ )
+
+ is_univariate = num_targets_in == 1
+
+ znorm_per_example: list[list[tuple[float, float]]] = []
+ if use_znorm:
+ normed_contexts: list[np.ndarray] = []
+ normed_po: list[np.ndarray | None] = []
+ normed_pf: list[np.ndarray | None] = []
+
+ for idx, ctx in enumerate(contexts_2d):
+ stats_for_ex: list[tuple[float, float]] = []
+ normed = ctx.copy()
+ for r, row in enumerate(ctx):
+ mu, sigma = _znorm_stats(row)
+ stats_for_ex.append((mu, sigma))
+ normed[r] = (row - mu) / sigma
+ znorm_per_example.append(stats_for_ex)
+ normed_contexts.append(normed)
+
+ po = po_2d[idx]
+ if po is not None:
+ po_norm = po.copy()
+ for r, row in enumerate(po):
+ mu, sigma = _znorm_stats(row)
+ po_norm[r] = (row - mu) / sigma
+ normed_po.append(po_norm)
+ else:
+ normed_po.append(None)
+
+ pf = pf_2d[idx]
+ if pf is not None:
+ pf_norm = pf.copy()
+ for r, row in enumerate(pf):
+ mu, sigma = _znorm_stats(row)
+ pf_norm[r] = (row - mu) / sigma
+ normed_pf.append(pf_norm)
+ else:
+ normed_pf.append(None)
+
+ contexts_2d = normed_contexts
+ po_2d = normed_po
+ pf_2d = normed_pf
+ else:
+ for ctx in contexts_2d:
+ znorm_per_example.append([(0.0, 1.0) for _ in range(ctx.shape[0])])
+
+ if use_symmetric_averaging:
+ sym_contexts: list[np.ndarray] = []
+ sym_po: list[np.ndarray | None] = []
+ sym_pf: list[np.ndarray | None] = []
+ for idx, ctx in enumerate(contexts_2d):
+ sym_contexts.append(ctx)
+ sym_contexts.append(-ctx)
+ po_val = po_2d[idx]
+ sym_po.append(po_val)
+ sym_po.append(None if po_val is None else -po_val)
+ pf_val = pf_2d[idx]
+ sym_pf.append(pf_val)
+ sym_pf.append(None if pf_val is None else -pf_val)
+ contexts_2d = sym_contexts
+ po_2d = sym_po
+ pf_2d = sym_pf
+
+ if padding_mode == "edge":
+ pad_len = global_horizon - horizon
+ if pad_len > 0:
+ for i, pf in enumerate(pf_2d):
+ if pf is not None:
+ pad_width = [(0, 0)] * (pf.ndim - 1) + [(0, pad_len)]
+ pf_2d[i] = np.pad(pf, pad_width, mode="edge")
+ elif padding_mode != "none":
+ raise ValueError(f"Unknown padding_mode: '{padding_mode}'")
+
+ queries: list[_Query] = []
+ for idx, ctx in enumerate(contexts_2d):
+ queries.append(
+ _Query(
+ horizon=global_horizon,
+ targets=ctx,
+ past_only_covariates=po_2d[idx],
+ past_future_covariates=pf_2d[idx],
+ )
+ )
+
+ if not queries:
+ for i in range(num_original_ts):
+ yield ForecastOutput(ts_id=original_ts_ids[i], forecast=None)
+ return
+
+ # Yield batches of size per_core_batch_size
+ batch_size = self.config.per_core_batch_size
+ ys = []
+ num_queries = len(queries)
+ num_batches = math.ceil(num_queries / batch_size)
+
+ for i in range(num_batches):
+ query_batch = queries[i * batch_size : (i + 1) * batch_size]
+ while len(query_batch) < batch_size:
+ query_batch.append(dataclasses.replace(query_batch[0], padded=True))
+ formatted_batch = [q.format(self.global_context) for q in query_batch]
+
+ (
+ batched_hor,
+ batched_tgt,
+ batched_mask,
+ batched_po,
+ batched_pf,
+ _,
+ ) = tuple(list(w) for w in zip(*formatted_batch))
+
+ tgt_torch = torch.from_numpy(np.stack(batched_tgt, axis=0)).to(
+ self.device, dtype=torch.float32
+ )
+ mask_torch = torch.from_numpy(np.stack(batched_mask, axis=0)).to(
+ self.device, dtype=torch.bool
+ )
+
+ po_torch = None
+ if any(po is not None for po in batched_po):
+ po_arrs = [
+ po if po is not None else np.zeros_like(batched_tgt[j])
+ for j, po in enumerate(batched_po)
+ ]
+ po_torch = torch.from_numpy(np.stack(po_arrs, axis=0)).to(
+ self.device, dtype=torch.float32
+ )
+
+ pf_torch = None
+ if any(pf is not None for pf in batched_pf):
+ pf_arrs = [
+ pf if pf is not None else np.zeros_like(batched_tgt[j])
+ for j, pf in enumerate(batched_pf)
+ ]
+ pf_torch = torch.from_numpy(np.stack(pf_arrs, axis=0)).to(
+ self.device, dtype=torch.float32
+ )
+
+ with torch.no_grad():
+ out_logits = self.model.decode(
+ target=tgt_torch,
+ horizon=batched_hor[0],
+ past_only_covariates=po_torch,
+ past_future_covariates=pf_torch,
+ mask=mask_torch,
+ )
+ ys.append(out_logits.cpu().numpy())
+ try_gc(self.device)
+
+ all_raw_outputs = np.concatenate(ys, axis=0)
+
+ num_relevant_outputs = (
+ 2 * num_original_ts if use_symmetric_averaging else num_original_ts
+ )
+ all_raw_outputs = all_raw_outputs[
+ :num_relevant_outputs, :num_targets_in, :, :
+ ]
+
+ if use_symmetric_averaging:
+ ys_pos = all_raw_outputs[0::2]
+ ys_neg = all_raw_outputs[1::2]
+ if ys_pos.ndim >= 3 and ys_pos.shape[-1] > 1:
+ all_raw_outputs = (ys_pos - ys_neg[..., ::-1]) / 2
+ else:
+ all_raw_outputs = (ys_pos - ys_neg) / 2
+
+ if use_znorm:
+ for i in range(all_raw_outputs.shape[0]):
+ stats = znorm_per_example[i]
+ for r in range(num_targets_in):
+ mu, sigma = stats[r]
+ all_raw_outputs[i, r] = all_raw_outputs[i, r] * sigma + mu
+
+ if make_positive:
+ for i in range(num_original_ts):
+ if is_univariate:
+ if _is_nonnegative(original_contexts[i]):
+ all_raw_outputs[i] = np.maximum(all_raw_outputs[i], 0.0)
+ else:
+ nonneg = _is_nonnegative(original_contexts[i])
+ assert isinstance(nonneg, np.ndarray)
+ for r in range(num_targets_in):
+ if nonneg[r]:
+ all_raw_outputs[i, r] = np.maximum(all_raw_outputs[i, r], 0.0)
+
+ for i in range(num_original_ts):
+ raw = all_raw_outputs[i]
+ if is_univariate:
+ raw = raw[0]
+ yield ForecastOutput(
+ ts_id=original_ts_ids[i],
+ forecast=raw[:horizon, self.config.median_quantile_index],
+ quantiles=raw[:horizon, :] if return_quantiles else None,
+ )
+ else:
+ yield ForecastOutput(
+ ts_id=original_ts_ids[i],
+ forecast=raw[:, :horizon, self.config.median_quantile_index],
+ quantiles=raw[:, :horizon, :] if return_quantiles else None,
+ )
diff --git a/src/timesfm3/timesfm3_forecaster_test.py b/src/timesfm3/timesfm3_forecaster_test.py
new file mode 100644
index 0000000..aa1d8bb
--- /dev/null
+++ b/src/timesfm3/timesfm3_forecaster_test.py
@@ -0,0 +1,135 @@
+# Copyright 2025 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 PyTorch TimesFM3Forecaster."""
+
+import unittest
+from unittest import mock
+import numpy as np
+import torch
+
+from . import timesfm3_forecaster
+
+
+class FakeModel(torch.nn.Module):
+ """A tiny fake model for testing."""
+
+ def __init__(self, input_patch_len=8, output_patch_len=8, quantiles=3):
+ super().__init__()
+ self.input_patch_len = input_patch_len
+ self.output_patch_len = output_patch_len
+ self.quantiles = quantiles
+
+ def decode(
+ self,
+ target,
+ autoregressive_index=0,
+ horizon=8,
+ past_only_covariates=None,
+ past_future_covariates=None,
+ mask=None,
+ ):
+ del autoregressive_index, past_only_covariates, past_future_covariates, mask
+ b, v, _ = target.shape
+ shape = (b, v, horizon, self.quantiles)
+ return torch.ones(shape, dtype=torch.float32) * 2.0
+
+
+class TimesFM3ForecasterTest(unittest.TestCase):
+
+ def setUp(self):
+ super().setUp()
+ self.config = timesfm3_forecaster._ModelConfig(
+ checkpoint_path="/fake/path",
+ per_core_batch_size=2,
+ input_patch_length=8,
+ output_patch_length=8,
+ median_quantile_index=1,
+ )
+
+ def test_strip_leading_nans_1d(self):
+ arr = np.array([np.nan, np.nan, 1.0, 2.0, np.nan])
+ res = timesfm3_forecaster.strip_leading_nans(arr)
+ np.testing.assert_array_equal(res, np.array([1.0, 2.0, np.nan]))
+
+ def test_strip_leading_nans_2d(self):
+ arr = np.array([
+ [np.nan, 1.0, 2.0],
+ [np.nan, np.nan, 3.0],
+ ])
+ res = timesfm3_forecaster.strip_leading_nans(arr)
+ expected = np.array([
+ [1.0, 2.0],
+ [np.nan, 3.0],
+ ])
+ np.testing.assert_array_equal(res, expected)
+
+ def test_linear_interpolation(self):
+ arr = np.array([1.0, np.nan, 3.0])
+ res = timesfm3_forecaster.linear_interpolation(arr)
+ np.testing.assert_array_equal(res, np.array([1.0, 2.0, 3.0]))
+
+ def test_znorm_stats(self):
+ arr = np.array([1.0, 2.0, 3.0])
+ mu, sigma = timesfm3_forecaster._znorm_stats(arr)
+ self.assertAlmostEqual(mu, 2.0)
+ self.assertAlmostEqual(sigma, np.std([1.0, 2.0, 3.0]))
+
+ def test_is_nonnegative(self):
+ arr_pos = np.array([0.0, 1.0, 2.0])
+ arr_neg = np.array([-1.0, 1.0, 2.0])
+ self.assertTrue(timesfm3_forecaster._is_nonnegative(arr_pos))
+ self.assertFalse(timesfm3_forecaster._is_nonnegative(arr_neg))
+
+ @mock.patch.object(
+ timesfm3_forecaster.TimesFM3Forecaster, "_init_model", autospec=True
+ )
+ def test_univariate_predict(self, _):
+ forecaster = timesfm3_forecaster.TimesFM3Forecaster(self.config)
+ forecaster.model = FakeModel()
+ forecaster.device = torch.device("cpu")
+
+ ctx = np.array([1.0, 2.0, 3.0, 4.0])
+ out = forecaster.predict(ctx, horizon=4)
+ self.assertEqual(out.forecast.shape, (4,))
+ np.testing.assert_array_equal(out.forecast, np.full((4,), 2.0))
+
+ @mock.patch.object(
+ timesfm3_forecaster.TimesFM3Forecaster, "_init_model", autospec=True
+ )
+ def test_multivariate_predict_with_covariates(self, _):
+ forecaster = timesfm3_forecaster.TimesFM3Forecaster(self.config)
+ forecaster.model = FakeModel()
+ forecaster.device = torch.device("cpu")
+
+ ctx = np.array([
+ [1.0, 2.0, 3.0, 4.0],
+ [5.0, 6.0, 7.0, 8.0],
+ ])
+ po_cov = np.array([1.0, 1.0, 1.0, 1.0])
+ pf_cov = np.array([2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0])
+
+ out = forecaster.predict(
+ ctx,
+ horizon=4,
+ past_only_covariates=po_cov,
+ past_future_covariates=pf_cov,
+ return_quantiles=True,
+ )
+ self.assertEqual(out.forecast.shape, (2, 4))
+ self.assertEqual(out.quantiles.shape, (2, 4, 3))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src/timesfm3/transformations.py b/src/timesfm3/transformations.py
new file mode 100644
index 0000000..6167dc8
--- /dev/null
+++ b/src/timesfm3/transformations.py
@@ -0,0 +1,74 @@
+"""Reversible transformations for time-series models (PyTorch).
+
+Direct port of the Flax transformations.py: signed_log, signed_sqrt, identity.
+Each transformation is a callable with signature (x, reverse=False) -> x'.
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Protocol
+
+import torch
+
+
+class TransformFn(Protocol):
+ """Protocol for a reversible transformation function."""
+
+ def __call__(self, x: torch.Tensor, *, reverse: bool = False) -> torch.Tensor:
+ ...
+
+
+def signed_log(x: torch.Tensor, *, reverse: bool = False) -> torch.Tensor:
+ """Signed-log transform: sign(x) * log(1 + |x|)."""
+ if reverse:
+ return torch.sign(x) * torch.expm1(torch.abs(x))
+ return torch.sign(x) * torch.log1p(torch.abs(x))
+
+
+def _max_output_signed_log(value_clip: float) -> torch.Tensor:
+ return torch.log1p(torch.tensor(value_clip))
+
+
+def signed_sqrt(x: torch.Tensor, *, reverse: bool = False) -> torch.Tensor:
+ """Signed-sqrt transform: sign(x) * sqrt(|x|)."""
+ if reverse:
+ return torch.sign(x) * torch.square(x)
+ return torch.sign(x) * torch.sqrt(torch.abs(x))
+
+
+def _max_output_signed_sqrt(value_clip: float) -> torch.Tensor:
+ return torch.sqrt(torch.tensor(value_clip))
+
+
+def identity(x: torch.Tensor, *, reverse: bool = False) -> torch.Tensor:
+ """Identity (no-op) transform."""
+ del reverse
+ return x
+
+
+def _max_output_identity(value_clip: float) -> torch.Tensor:
+ return torch.tensor(value_clip, dtype=torch.float32)
+
+
+_REGISTRY: dict[
+ str,
+ tuple[TransformFn, Callable[[float], torch.Tensor]],
+] = {
+ "signed_log": (signed_log, _max_output_signed_log),
+ "signed_sqrt": (signed_sqrt, _max_output_signed_sqrt),
+ "identity": (identity, _max_output_identity),
+}
+
+
+def get_transform(name: str) -> TransformFn:
+ """Looks up a reversible transformation by name."""
+ if name not in _REGISTRY:
+ raise ValueError(f"Unknown transform name: {name}")
+ return _REGISTRY[name][0]
+
+
+def max_output(name: str, value_clip: float) -> torch.Tensor:
+ """Returns the maximum output magnitude for a transform given a value clip."""
+ if name not in _REGISTRY:
+ raise ValueError(f"Unknown transform name: {name}")
+ return _REGISTRY[name][1](value_clip)
diff --git a/src/timesfm3/transformer.py b/src/timesfm3/transformer.py
new file mode 100644
index 0000000..db8e57e
--- /dev/null
+++ b/src/timesfm3/transformer.py
@@ -0,0 +1,599 @@
+"""Transformer layers for TimesFM3 PyTorch (inference only).
+
+Port of the Flax MixingTransformer architecture:
+ - RotaryPositionalEmbedding
+ - MultiHeadAttention (with KV-cache support)
+ - MixingTransformer (sequential seq + variate attention + FFN)
+ - StackedMixingTransformer (nn.ModuleList of MixingTransformer)
+"""
+
+from __future__ import annotations
+
+import math
+
+import torch
+from torch import nn
+import torch.nn.functional as F
+
+from . import configs
+from . import normalization
+from . import util
+
+
+def make_attn_mask(
+ query_length: int,
+ num_all_masked_kv: torch.Tensor,
+ query_index_offset: torch.Tensor | None = None,
+ kv_length: int = 0,
+ causal: bool = True,
+) -> torch.Tensor:
+ """Makes attention mask. True = attend, False = mask.
+
+ Args:
+ query_length: Number of query positions.
+ num_all_masked_kv: Shape (b,). Number of leading masked KV positions.
+ query_index_offset: Shape (b,). Offset for query indices (decode mode).
+ kv_length: Length of KV sequence. Defaults to query_length.
+ causal: Whether to apply causal masking.
+
+ Returns:
+ Boolean mask of shape (b, 1, query_length, kv_length). True = attend.
+ """
+ if kv_length == 0:
+ kv_length = query_length
+
+ device = num_all_masked_kv.device
+ q_index = torch.arange(query_length, device=device).view(1, 1, -1, 1)
+ if query_index_offset is not None:
+ q_index = q_index + query_index_offset.view(-1, 1, 1, 1)
+ kv_index = torch.arange(kv_length, device=device).view(1, 1, 1, -1)
+ mask = kv_index >= num_all_masked_kv.view(-1, 1, 1, 1)
+ if causal:
+ return (q_index >= kv_index) & mask
+ return mask
+
+
+def make_segment_mask(
+ segment_ids: torch.Tensor,
+) -> torch.Tensor:
+ """Makes a segment mask from segment ids.
+
+ Args:
+ segment_ids: Shape (b, seq_length).
+
+ Returns:
+ Boolean mask of shape (b, 1, seq_length, seq_length).
+ """
+ return (segment_ids.unsqueeze(2) == segment_ids.unsqueeze(1)).unsqueeze(1)
+
+
+class RotaryPositionalEmbedding(nn.Module):
+ """Rotary positional embedding (RoPE).
+
+ Stateless module — no learnable parameters.
+ Supports 3D (b, n, d) and 4D (b, n, h, hd) inputs.
+ """
+
+ def __init__(
+ self,
+ embedding_dims: int,
+ min_timescale: int = 1,
+ max_timescale: int = 10000,
+ ):
+ super().__init__()
+ self.embedding_dims = embedding_dims
+ self.min_timescale = min_timescale
+ self.max_timescale = max_timescale
+
+ half_dim = embedding_dims // 2
+ fraction = (
+ 2.0
+ * torch.arange(half_dim, dtype=torch.float32)
+ / embedding_dims
+ )
+ timescale = (
+ min_timescale
+ * (max_timescale / min_timescale) ** fraction
+ )
+ self.register_buffer("timescale", timescale, persistent=False)
+
+ def forward(
+ self,
+ inputs: torch.Tensor,
+ position: torch.Tensor | None = None,
+ ) -> torch.Tensor:
+ """Applies rotary positional embeddings.
+
+ Args:
+ inputs: Shape (b, n, d) or (b, n, h, hd).
+ position: Shape (b, n). If None, uses arange(n).
+
+ Returns:
+ Tensor with same shape as inputs, with RoPE applied.
+ """
+ if self.embedding_dims != inputs.shape[-1]:
+ raise ValueError(
+ "The embedding dims of the rotary position embedding "
+ "must match the hidden dimension of the inputs."
+ )
+ timescale = self.timescale.to(inputs.device)
+
+ if position is None:
+ seq_length = inputs.shape[1]
+ position = torch.arange(
+ seq_length, device=inputs.device, dtype=torch.float32
+ ).unsqueeze(0)
+
+ if inputs.dim() == 4:
+ # (b, n) -> (b, n, 1, 1) for broadcasting with (b, n, h, hd)
+ pos = position.unsqueeze(-1).unsqueeze(-1)
+ ts = timescale.view(1, 1, 1, -1)
+ elif inputs.dim() == 3:
+ pos = position.unsqueeze(-1)
+ ts = timescale.view(1, 1, -1)
+ else:
+ raise ValueError("Inputs must be of rank 3 or 4.")
+
+ sinusoid_inp = pos.float() / ts
+ sin_val = torch.sin(sinusoid_inp)
+ cos_val = torch.cos(sinusoid_inp)
+ first_half, second_half = inputs.chunk(2, dim=-1)
+ first_part = first_half * cos_val - second_half * sin_val
+ second_part = second_half * cos_val + first_half * sin_val
+ return torch.cat([first_part, second_part], dim=-1)
+
+
+class MultiHeadAttention(nn.Module):
+ """Multi-head attention with RoPE, QK-norm, PerDimScale, and KV-cache.
+
+ This matches the Flax MultiHeadAttention exactly, including the
+ pre-multiplication of query by sqrt(head_dim) which cancels with the
+ standard 1/sqrt(d) scaling in dot-product attention.
+ """
+
+ def __init__(
+ self,
+ num_heads: int,
+ in_features: int,
+ use_per_dim_scale: bool = True,
+ use_rotary_position_embeddings: bool = True,
+ causal_attention: bool = True,
+ use_bias: bool = False,
+ qk_norm: str = "rms",
+ v_norm: str = "none",
+ use_sdpa: bool = False,
+ rescale_logits: bool = False,
+ ):
+ super().__init__()
+ self.num_heads = num_heads
+ self.in_features = in_features
+ self.causal_attention = causal_attention
+ self.head_dim = in_features // num_heads
+ self.use_sdpa = use_sdpa
+ # rescale_logits=False → MEA=True behaviour: Q is pre-multiplied by √d,
+ # no internal division. Matches Flax
+ # memory_efficient_attention(rescale_logits=False).
+ # rescale_logits=True → MEA=False behaviour: Q*√d is passed but divided
+ # by √d internally, so they cancel (net scale = 1.0). Matches Flax
+ # nn.dot_product_attention.
+ self.rescale_logits = rescale_logits
+
+ # Q, K, V projections: Linear(in, heads*hd)
+ # We'll reshape the output to (b, n, heads, hd)
+ self.query_proj = nn.Linear(in_features, in_features, bias=use_bias)
+ self.key_proj = nn.Linear(in_features, in_features, bias=use_bias)
+ self.value_proj = nn.Linear(in_features, in_features, bias=use_bias)
+
+ # Output projection
+ self.out_proj = nn.Linear(in_features, in_features, bias=use_bias)
+
+ # QK normalization
+ if qk_norm == "rms":
+ self.query_ln = nn.RMSNorm(self.head_dim)
+ self.key_ln = nn.RMSNorm(self.head_dim)
+ else:
+ self.query_ln = None
+ self.key_ln = None
+
+ # V normalization
+ if v_norm == "rms":
+ self.value_ln = nn.RMSNorm(self.head_dim, elementwise_affine=False)
+ else:
+ self.value_ln = None
+
+ # RoPE
+ if use_rotary_position_embeddings:
+ self.rotary_position_embedding = RotaryPositionalEmbedding(
+ embedding_dims=self.head_dim
+ )
+ else:
+ self.rotary_position_embedding = None
+
+ # PerDimScale
+ if use_per_dim_scale:
+ self.per_dim_scale = normalization.PerDimScale(num_dims=self.head_dim)
+ else:
+ self.per_dim_scale = None
+
+ def forward(
+ self,
+ inputs_q: torch.Tensor,
+ *,
+ segment_ids: torch.Tensor | None = None,
+ segment_pos: torch.Tensor | None = None,
+ decode_cache: util.DecodeCache | None = None,
+ patch_mask: torch.Tensor | None = None,
+ ) -> tuple[torch.Tensor, util.DecodeCache | None, torch.Tensor]:
+ """Applies multi-head attention.
+
+ Args:
+ inputs_q: Shape (b, n, d).
+ segment_ids: Shape (b, n). Optional segment IDs for masking.
+ segment_pos: Shape (b, n). Optional positions for RoPE.
+ decode_cache: Optional KV cache for autoregressive decoding.
+ patch_mask: Shape (b, n). True = masked patch.
+
+ Returns:
+ Tuple of (output, updated_cache, attn_mask).
+ - output: Shape (b, n, d).
+ - updated_cache: Updated DecodeCache or None.
+ - attn_mask: The attention mask used.
+ """
+ batch_size, n_patches, _ = inputs_q.shape
+ device = inputs_q.device
+
+ if patch_mask is None:
+ patch_mask = torch.zeros(
+ batch_size, n_patches, dtype=torch.bool, device=device
+ )
+
+ # Project Q, K, V and reshape to (b, n, h, hd)
+ query = self.query_proj(inputs_q).view(
+ batch_size, n_patches, self.num_heads, self.head_dim
+ )
+ key = self.key_proj(inputs_q).view(
+ batch_size, n_patches, self.num_heads, self.head_dim
+ )
+ value = self.value_proj(inputs_q).view(
+ batch_size, n_patches, self.num_heads, self.head_dim
+ )
+
+ if decode_cache is None:
+ num_front_masked = torch.sum(
+ torch.cumprod(patch_mask.int(), dim=-1), dim=-1
+ )
+ next_index = torch.zeros_like(num_front_masked, dtype=torch.int32)
+ else:
+ num_front_masked = decode_cache.num_front_masked
+ next_index = decode_cache.next_index
+
+ # Apply RoPE
+ if self.rotary_position_embedding is not None:
+ if segment_pos is None:
+ position = torch.arange(
+ n_patches, device=device, dtype=torch.int32
+ ).unsqueeze(0) + next_index.unsqueeze(-1)
+ else:
+ position = segment_pos
+ query = self.rotary_position_embedding(query, position)
+ key = self.rotary_position_embedding(key, position)
+
+ # QK normalization
+ if self.query_ln is not None:
+ query = self.query_ln(query)
+ if self.key_ln is not None:
+ key = self.key_ln(key)
+
+ # PerDimScale
+ if self.per_dim_scale is not None:
+ query = self.per_dim_scale(query)
+
+ # V normalization
+ if self.value_ln is not None:
+ value = self.value_ln(value)
+
+ if decode_cache is not None:
+ # Cached decoding: update cache with new K, V
+ cache_size = decode_cache.key.shape[1]
+ idx = next_index[0].item() # assumes uniform batch
+ decode_cache.key[:, idx : idx + n_patches, :, :] = key
+ decode_cache.value[:, idx : idx + n_patches, :, :] = value
+ key = decode_cache.key
+ value = decode_cache.value
+
+ decode_cache = util.DecodeCache(
+ next_index=next_index + n_patches,
+ num_front_masked=num_front_masked,
+ key=key,
+ value=value,
+ )
+
+ attn_mask = make_attn_mask(
+ query_length=n_patches,
+ num_all_masked_kv=num_front_masked,
+ query_index_offset=next_index,
+ kv_length=cache_size,
+ causal=self.causal_attention,
+ )
+ else:
+ # Training / full-sequence mode
+ attn_mask = make_attn_mask(
+ query_length=n_patches,
+ num_all_masked_kv=torch.zeros_like(num_front_masked),
+ causal=self.causal_attention,
+ )
+ # Apply patch_mask to K/V positions
+ attn_mask = attn_mask & (~patch_mask[:, None, None, :])
+ if segment_ids is not None:
+ segment_mask = make_segment_mask(segment_ids)
+ attn_mask = attn_mask & segment_mask
+
+ # Transpose for attention: (b, n, h, d) -> (b, h, n, d)
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ if self.use_sdpa:
+ # --- F.scaled_dot_product_attention path (PyTorch >= 2.1) ---
+ # SDPA computes: softmax(Q @ K^T * scale) @ V.
+ if self.rescale_logits:
+ # MEA=False equivalent: Flax passes Q*√d to nn.dot_product_attention
+ # which divides by √d internally → net scale = 1.0.
+ attn_scale = 1.0
+ else:
+ # MEA=True equivalent: Flax passes Q*√d with rescale_logits=False
+ # → no internal division → net scale = √d.
+ attn_scale = math.sqrt(self.head_dim)
+ x = F.scaled_dot_product_attention(
+ query,
+ key,
+ value,
+ attn_mask=attn_mask.expand(-1, self.num_heads, -1, -1),
+ scale=attn_scale,
+ )
+ else:
+ # --- Manual attention path ---
+ # Convert mask: True=attend -> 0.0, False=mask -> -1e9 (matching Flax
+ # MEA bias).
+ float_mask = torch.where(
+ attn_mask.expand(-1, self.num_heads, -1, -1),
+ torch.tensor(0.0, device=device),
+ torch.tensor(-1e9, device=device),
+ )
+ if self.rescale_logits:
+ # MEA=False equivalent: Q*√d then divide by √d → net scale = 1.0.
+ # Flax nn.dot_product_attention receives Q*√d and divides by √d
+ # internally, so the pre-multiplication and rescaling cancel out.
+ query = query * math.sqrt(self.head_dim)
+ attn_logits = (
+ torch.matmul(query, key.transpose(-2, -1))
+ / math.sqrt(self.head_dim)
+ + float_mask
+ )
+ else:
+ # MEA=True equivalent: Q*√d, no internal division → net scale = √d.
+ # Matches Flax memory_efficient_attention(rescale_logits=False).
+ query = query * math.sqrt(self.head_dim)
+ attn_logits = torch.matmul(query, key.transpose(-2, -1)) + float_mask
+ attn_weights = F.softmax(attn_logits, dim=-1)
+ x = torch.matmul(attn_weights, value)
+
+ # Transpose back: (b, h, n, d) -> (b, n, h, d)
+ x = x.transpose(1, 2).contiguous()
+
+ # Reshape and project: (b, n, h, d) -> (b, n, h*d)
+ x = x.view(batch_size, n_patches, self.in_features)
+
+ out = self.out_proj(x)
+ return out, decode_cache, attn_mask
+
+
+class MixingTransformer(nn.Module):
+ """Transformer with sequential sequence and variate attention.
+
+ Attention is applied first across the sequence dimension 'n', then
+ across the variate dimension 'v' for inputs of shape 'b v n d'.
+
+ Architecture per layer:
+ 1. Sequence attention: pre_ln -> reshape(bv,n,d) -> MHA -> post_ln +
+ residual
+ 2. Variate attention: pre_ln -> reshape(bn,v,d) -> MHA -> post_ln + residual
+ 3. FFN: pre_ln -> ff0 -> activation -> ff1 -> post_ln + residual
+ """
+
+ def __init__(
+ self,
+ config: configs.TransformerConfig,
+ use_variate_attention: bool = True,
+ ):
+ super().__init__()
+ self.config = config
+ self.use_variate_attention = use_variate_attention
+
+ # Sequence attention norms + module
+ self.pre_seq_attn_ln = nn.RMSNorm(config.model_dims)
+ self.post_seq_attn_ln = nn.RMSNorm(config.model_dims)
+ # rescale_logits mirrors Flax: use_memory_efficient_attention=True →
+ # MEA=True (rescale_logits=False, scale=√d);
+ # use_memory_efficient_attention=False → MEA=False (rescale_logits=True,
+ # net scale=1.0).
+ rescale_logits = not getattr(config, "use_memory_efficient_attention", False)
+ self.seq_attn = MultiHeadAttention(
+ num_heads=config.num_heads,
+ in_features=config.model_dims,
+ use_per_dim_scale=True,
+ use_rotary_position_embeddings=config.use_rope_seq,
+ qk_norm=config.qk_norm,
+ v_norm=getattr(config, "v_norm", "none"),
+ causal_attention=getattr(config, "causal_attention", True),
+ use_bias=config.use_bias,
+ use_sdpa=config.use_sdpa,
+ rescale_logits=rescale_logits,
+ )
+
+ # Variate attention norms + module
+ if use_variate_attention:
+ self.pre_var_attn_ln = nn.RMSNorm(config.model_dims)
+ self.post_var_attn_ln = nn.RMSNorm(config.model_dims)
+ self.var_attn = MultiHeadAttention(
+ num_heads=config.num_heads,
+ in_features=config.model_dims,
+ use_per_dim_scale=True,
+ use_rotary_position_embeddings=config.use_rope_var,
+ qk_norm=config.qk_norm,
+ v_norm=getattr(config, "v_norm", "none"),
+ causal_attention=False,
+ use_bias=config.use_bias,
+ use_sdpa=config.use_sdpa,
+ rescale_logits=rescale_logits,
+ )
+
+ # FFN norms + layers
+ self.pre_ff_ln = nn.RMSNorm(config.model_dims)
+ self.post_ff_ln = nn.RMSNorm(config.model_dims)
+ self.ff0 = nn.Linear(
+ config.model_dims, config.hidden_dims, bias=config.use_bias
+ )
+ self.ff1 = nn.Linear(
+ config.hidden_dims, config.model_dims, bias=config.use_bias
+ )
+ self.activation = util.get_activation_fn(config.ff_activation)
+
+ def forward(
+ self,
+ input_embeddings: torch.Tensor,
+ patch_mask: torch.Tensor,
+ segment_ids: torch.Tensor | None = None,
+ segment_pos: torch.Tensor | None = None,
+ decode_cache: util.DecodeCache | None = None,
+ var_segment_pos: torch.Tensor | None = None,
+ ) -> tuple[torch.Tensor, util.DecodeCache | None, torch.Tensor]:
+ """Forward pass.
+
+ Args:
+ input_embeddings: Shape (b, v, n, d).
+ patch_mask: Shape (b, v, n). True = masked.
+ segment_ids: Shape (b, n). Optional.
+ segment_pos: Shape (b, n). Optional.
+ decode_cache: Optional KV cache.
+ var_segment_pos: Shape (b*n, v). Optional variate positions.
+
+ Returns:
+ (output_embeddings, updated_cache, seq_attn_mask).
+ """
+ b, v, n, d = input_embeddings.shape
+
+ # --- Sequence Attention ---
+ seq_attn_in = self.pre_seq_attn_ln(input_embeddings)
+ # (b, v, n, d) -> (b*v, n, d)
+ seq_attn_in_flat = seq_attn_in.reshape(b * v, n, d)
+ patch_mask_flat = patch_mask.reshape(b * v, n)
+
+ # Broadcast segment_ids/pos across variates
+ seq_seg_ids_flat = None
+ if segment_ids is not None:
+ seg_ids_bvn = segment_ids.unsqueeze(1).expand(b, v, n)
+ seq_seg_ids_flat = seg_ids_bvn.reshape(b * v, n)
+
+ seq_seg_pos_flat = None
+ if segment_pos is not None:
+ seg_pos_bvn = segment_pos.unsqueeze(1).expand(b, v, n)
+ seq_seg_pos_flat = seg_pos_bvn.reshape(b * v, n)
+
+ seq_attn_out_flat, decode_cache, seq_attn_mask = self.seq_attn(
+ seq_attn_in_flat,
+ segment_ids=seq_seg_ids_flat,
+ segment_pos=seq_seg_pos_flat,
+ decode_cache=decode_cache,
+ patch_mask=patch_mask_flat,
+ )
+ seq_attn_out = seq_attn_out_flat.view(b, v, n, d)
+ h1 = self.post_seq_attn_ln(seq_attn_out) + input_embeddings
+
+ # --- Variate Attention ---
+ if self.use_variate_attention:
+ var_attn_in = self.pre_var_attn_ln(h1)
+ # (b, v, n, d) -> (b*n, v, d)
+ var_attn_in_flat = var_attn_in.permute(0, 2, 1, 3).reshape(b * n, v, d)
+ # Mask: (b, v, n) -> (b, n, v) -> (b*n, v)
+ var_patch_mask = patch_mask.permute(0, 2, 1).reshape(b * n, v)
+
+ var_attn_out_flat, _, _ = self.var_attn(
+ var_attn_in_flat,
+ segment_pos=var_segment_pos,
+ decode_cache=None,
+ patch_mask=var_patch_mask,
+ )
+ # (b*n, v, d) -> (b, n, v, d) -> (b, v, n, d)
+ var_attn_out = var_attn_out_flat.view(b, n, v, d).permute(0, 2, 1, 3)
+ h2 = self.post_var_attn_ln(var_attn_out) + h1
+ else:
+ h2 = h1
+
+ # --- FeedForward ---
+ ff_out = self.ff1(self.activation(self.ff0(self.pre_ff_ln(h2))))
+ output_embeddings = self.post_ff_ln(ff_out) + h2
+
+ return output_embeddings, decode_cache, seq_attn_mask
+
+
+class StackedMixingTransformer(nn.Module):
+ """Stacked MixingTransformer layers."""
+
+ def __init__(
+ self,
+ config: configs.StackedTransformersConfig,
+ use_variate_attention: bool = True,
+ ):
+ super().__init__()
+ self.config = config
+ self.layers = nn.ModuleList([
+ MixingTransformer(
+ config=config.transformer,
+ use_variate_attention=use_variate_attention,
+ )
+ for _ in range(config.num_layers)
+ ])
+
+ def forward(
+ self,
+ input_embeddings: torch.Tensor,
+ patch_mask: torch.Tensor,
+ segment_ids: torch.Tensor | None = None,
+ segment_pos: torch.Tensor | None = None,
+ decode_cache: list[util.DecodeCache] | None = None,
+ var_segment_pos: torch.Tensor | None = None,
+ ) -> tuple[torch.Tensor, list[util.DecodeCache] | None, list[torch.Tensor]]:
+ """Forward pass through all layers.
+
+ Args:
+ input_embeddings: Shape (b, v, n, d).
+ patch_mask: Shape (b, v, n).
+ segment_ids: Shape (b, n). Optional.
+ segment_pos: Shape (b, n). Optional.
+ decode_cache: List of DecodeCache (one per layer), or None.
+ var_segment_pos: Shape (b*n, v). Optional.
+
+ Returns:
+ (output_embeddings, updated_caches, attn_masks).
+ """
+ if decode_cache is None:
+ decode_cache = [None] * len(self.layers) # pyrefly: ignore[bad-assignment]
+
+ output = input_embeddings
+ new_caches = []
+ attn_masks = []
+
+ for i, layer in enumerate(self.layers):
+ output, layer_cache, layer_mask = layer(
+ output,
+ patch_mask,
+ segment_ids,
+ segment_pos,
+ decode_cache[i], # pyrefly: ignore[unsupported-operation]
+ var_segment_pos,
+ )
+ new_caches.append(layer_cache)
+ attn_masks.append(layer_mask)
+
+ return output, new_caches, attn_masks
diff --git a/src/timesfm3/transformer_test.py b/src/timesfm3/transformer_test.py
new file mode 100644
index 0000000..e482eb6
--- /dev/null
+++ b/src/timesfm3/transformer_test.py
@@ -0,0 +1,164 @@
+# Copyright 2025 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 TimesFM3 PyTorch transformer layers."""
+
+import unittest
+import numpy as np
+import torch
+
+from . import configs
+from . import transformer as torch_trans
+from . import util as torch_util
+
+
+class MaskTest(unittest.TestCase):
+
+ def test_make_attn_mask_causal(self):
+ query_len = 4
+ num_masked = torch.tensor([1])
+ mask = torch_trans.make_attn_mask(
+ query_length=query_len, num_all_masked_kv=num_masked, causal=True
+ )
+ # Shape: (1, 1, 4, 4)
+ self.assertEqual(mask.shape, (1, 1, 4, 4))
+ # Position 0 KV is masked (index 0 < 1)
+ self.assertFalse(mask[0, 0, 0, 0].item())
+ # Position (1, 1): query=1 >= kv=1 and kv=1 >= 1 => True
+ self.assertTrue(mask[0, 0, 1, 1].item())
+ # Position (1, 2): causal mask (1 < 2) => False
+ self.assertFalse(mask[0, 0, 1, 2].item())
+
+ def test_make_segment_mask(self):
+ segment_ids = torch.tensor([[0, 0, 1, 1]])
+ mask = torch_trans.make_segment_mask(segment_ids)
+ self.assertEqual(mask.shape, (1, 1, 4, 4))
+ self.assertTrue(mask[0, 0, 0, 1].item())
+ self.assertFalse(mask[0, 0, 0, 2].item())
+
+
+class RotaryEmbeddingTest(unittest.TestCase):
+
+ def test_rope_forward(self):
+ rope = torch_trans.RotaryPositionalEmbedding(embedding_dims=16)
+ x = torch.randn(2, 8, 16)
+ out = rope(x)
+ self.assertEqual(out.shape, (2, 8, 16))
+
+ def test_rope_with_position(self):
+ rope = torch_trans.RotaryPositionalEmbedding(embedding_dims=16)
+ x = torch.randn(2, 4, 16)
+ positions = torch.tensor([[0, 1, 2, 3], [2, 3, 4, 5]])
+ out = rope(x, position=positions)
+ self.assertEqual(out.shape, (2, 4, 16))
+
+
+class MultiHeadAttentionTest(unittest.TestCase):
+
+ def test_mha_forward_and_cache(self):
+ mha = torch_trans.MultiHeadAttention(
+ num_heads=4,
+ in_features=64,
+ qk_norm="rms",
+ use_bias=False,
+ use_sdpa=True,
+ )
+ b, n, d = 2, 8, 64
+ x = torch.randn(b, n, d)
+ patch_mask = torch.zeros(b, n, dtype=torch.bool)
+
+ # Full forward pass
+ out, cache, mask = mha(x, patch_mask=patch_mask)
+ self.assertEqual(out.shape, (b, n, d))
+ self.assertIsNone(cache)
+
+ # Decode mode with cache
+ decode_cache = torch_util.DecodeCache(
+ next_index=torch.zeros(b, dtype=torch.int32),
+ num_front_masked=torch.zeros(b, dtype=torch.int32),
+ key=torch.zeros(b, 16, 4, 16),
+ value=torch.zeros(b, 16, 4, 16),
+ )
+ q_x = torch.randn(b, 1, d)
+ q_mask = torch.zeros(b, 1, dtype=torch.bool)
+ out_step, updated_cache, _ = mha(
+ q_x, patch_mask=q_mask, decode_cache=decode_cache
+ )
+ self.assertEqual(out_step.shape, (b, 1, d))
+ self.assertIsNotNone(updated_cache)
+ self.assertEqual(updated_cache.next_index[0].item(), 1)
+
+
+class MixingTransformerTest(unittest.TestCase):
+
+ def test_mixing_transformer_forward(self):
+ cfg = configs.TransformerConfig(
+ model_dims=64,
+ hidden_dims=64,
+ num_heads=4,
+ attention_norm="rms",
+ feedforward_norm="rms",
+ qk_norm="rms",
+ use_rope_seq=True,
+ use_rope_var=True,
+ use_bias=False,
+ ff_activation="relu",
+ deterministic=True,
+ use_sdpa=True,
+ )
+ layer = torch_trans.MixingTransformer(config=cfg, use_variate_attention=True)
+ b, v, n, d = 2, 3, 8, 64
+ inputs = torch.randn(b, v, n, d)
+ patch_mask = torch.zeros(b, v, n, dtype=torch.bool)
+
+ out, cache, _ = layer(inputs, patch_mask=patch_mask)
+ self.assertEqual(out.shape, (b, v, n, d))
+ self.assertIsNone(cache)
+
+
+class StackedMixingTransformerTest(unittest.TestCase):
+
+ def test_stacked_transformer(self):
+ sub_cfg = configs.TransformerConfig(
+ model_dims=64,
+ hidden_dims=64,
+ num_heads=4,
+ attention_norm="rms",
+ feedforward_norm="rms",
+ qk_norm="rms",
+ use_rope_seq=True,
+ use_rope_var=True,
+ use_bias=False,
+ ff_activation="relu",
+ deterministic=True,
+ use_sdpa=True,
+ )
+ stack_cfg = configs.StackedTransformersConfig(
+ num_layers=2,
+ use_remat=False,
+ transformer=sub_cfg,
+ )
+ stack = torch_trans.StackedMixingTransformer(
+ config=stack_cfg, use_variate_attention=True
+ )
+ b, v, n, d = 2, 2, 4, 64
+ inputs = torch.randn(b, v, n, d)
+ patch_mask = torch.zeros(b, v, n, dtype=torch.bool)
+
+ out, caches, _ = stack(inputs, patch_mask=patch_mask)
+ self.assertEqual(out.shape, (b, v, n, d))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src/timesfm3/util.py b/src/timesfm3/util.py
new file mode 100644
index 0000000..ba6347b
--- /dev/null
+++ b/src/timesfm3/util.py
@@ -0,0 +1,383 @@
+"""Utility functions and classes for TimesFM3 PyTorch implementation."""
+
+from __future__ import annotations
+
+import dataclasses
+import os
+import tempfile
+from typing import Callable
+
+from safetensors import torch as safetensors_torch
+import torch
+import torch.nn.functional as F
+
+_TOLERANCE = 1e-6
+
+
+def _make_safe_for_division(values: torch.Tensor) -> torch.Tensor:
+ """Handles near zero values."""
+ return torch.where(values < _TOLERANCE, 1.0, values)
+
+
+class DecodeCache:
+ """Cache for autoregressive decoding.
+
+ Attributes:
+ next_index: The next index to decode for each batch element.
+ Shape: (batch_leading,).
+ num_front_masked: Number of front masked tokens for each batch element.
+ Shape: (batch_leading,).
+ key: The key cache. Shape: (batch_leading, cache_len, num_heads, head_dim).
+ value: The value cache. Same shape as key.
+ """
+
+ next_index: torch.Tensor
+ num_front_masked: torch.Tensor
+ key: torch.Tensor
+ value: torch.Tensor
+
+ @classmethod
+ def init_decode_cache(
+ cls,
+ num_layers: int,
+ batch_size: int,
+ num_variates: int,
+ num_total_input_patches: int,
+ num_heads: int,
+ head_dim: int,
+ device: torch.device | None = None,
+ ) -> list["DecodeCache"]:
+ """Initializes a list of decode caches for stacked layers.
+
+ Args:
+ num_layers: The number of transformer layers.
+ batch_size: The batch size.
+ num_variates: The number of variates.
+ num_total_input_patches: Total number of patches the cache should hold.
+ num_heads: The number of attention heads.
+ head_dim: The head dimension.
+ device: The device to create tensors on.
+
+ Returns:
+ A list of DecodeCache, one per layer.
+ """
+ leading_size = batch_size * num_variates
+ return [
+ cls(
+ next_index=torch.zeros(
+ leading_size, dtype=torch.int32, device=device
+ ),
+ num_front_masked=torch.zeros(
+ leading_size, dtype=torch.int32, device=device
+ ),
+ key=torch.zeros(
+ leading_size,
+ num_total_input_patches,
+ num_heads,
+ head_dim,
+ device=device,
+ ),
+ value=torch.zeros(
+ leading_size,
+ num_total_input_patches,
+ num_heads,
+ head_dim,
+ device=device,
+ ),
+ )
+ for _ in range(num_layers)
+ ]
+
+
+def update_running_stats(
+ n: torch.Tensor,
+ mu: torch.Tensor,
+ sigma: torch.Tensor,
+ x: torch.Tensor,
+ mask: torch.Tensor,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Updates running stats with a new patch of data.
+
+ Args:
+ n: Count of seen non-masked elements. Shape: (b, v).
+ mu: Running mean. Shape: (b, v).
+ sigma: Running std. Shape: (b, v).
+ x: New data patch. Shape: (b, v, p).
+ mask: Boolean mask where True = masked/invalid. Shape: (b, v, p).
+
+ Returns:
+ Tuple of (new_n, new_mu, new_sigma), each of shape (b, v).
+ """
+ is_legit = ~mask
+ is_legit_f = is_legit.float()
+ inc_n = is_legit_f.sum(dim=-1)
+
+ # mean of valid elements in patch
+ x_masked = torch.where(is_legit, x, torch.zeros_like(x))
+ inc_sum = x_masked.sum(dim=-1)
+ inc_mu = torch.where(inc_n == 0, torch.zeros_like(inc_sum), inc_sum / inc_n)
+
+ # std of valid elements in patch
+ x_diff_sq = torch.where(
+ is_legit, (x - inc_mu.unsqueeze(-1)) ** 2, torch.zeros_like(x)
+ )
+ inc_var = torch.where(
+ inc_n == 0,
+ torch.zeros_like(inc_sum),
+ x_diff_sq.sum(dim=-1) / inc_n,
+ )
+ inc_sigma = torch.sqrt(inc_var)
+
+ new_n = n + inc_n
+ new_mu = torch.where(
+ new_n == 0,
+ torch.zeros_like(mu),
+ (n * mu + inc_mu * inc_n) / new_n,
+ )
+ new_sigma = torch.sqrt(
+ torch.where(
+ new_n == 0,
+ torch.zeros_like(sigma),
+ (
+ n * sigma * sigma
+ + inc_n * inc_sigma * inc_sigma
+ + n * (mu - new_mu) * (mu - new_mu)
+ + inc_n * (inc_mu - new_mu) * (inc_mu - new_mu)
+ )
+ / new_n,
+ )
+ )
+ return new_n, new_mu, new_sigma
+
+
+def get_running_stats(
+ values: torch.Tensor,
+ masks: torch.Tensor,
+ *,
+ segment_ids: torch.Tensor | None = None,
+ initial_stats: (
+ tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None
+ ) = None,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Computes cumulative running statistics patch-by-patch.
+
+ For each variate, patch `i` gets stats computed from all unmasked values
+ in patches 0 through i (inclusive). Statistics reset at segment boundaries.
+
+ Args:
+ values: Input values. Shape: (b, v, n, p).
+ masks: Boolean mask (True=masked). Shape: (b, v, n, p).
+ segment_ids: Segment IDs. Shape: (b, n). If None, no segment resets.
+ initial_stats: Optional initial (n, mu, sigma), each shape (b, v).
+
+ Returns:
+ Tuple of (running_n, running_mu, running_sigma), each shape (b, v, n).
+ """
+ b, v, n, _ = values.shape
+ device = values.device
+
+ if initial_stats is None:
+ init_n = torch.zeros((b, v), dtype=torch.float32, device=device)
+ init_mu = torch.zeros((b, v), dtype=torch.float32, device=device)
+ init_sigma = torch.zeros((b, v), dtype=torch.float32, device=device)
+ else:
+ init_n, init_mu, init_sigma = initial_stats
+
+ # Determine segment reset points
+ if segment_ids is None:
+ is_new_segment = torch.zeros((b, n), dtype=torch.bool, device=device)
+ else:
+ shifted = F.pad(segment_ids[:, :-1], (1, 0), value=-1)
+ is_new_segment = segment_ids != shifted
+
+ all_n = []
+ all_mu = []
+ all_sigma = []
+ cur_n, cur_mu, cur_sigma = init_n, init_mu, init_sigma
+
+ for i in range(n):
+ # Reset stats at new segments
+ reset = is_new_segment[:, i].unsqueeze(-1) # (b, 1) # pyrefly: ignore[bad-index]
+ cur_n = torch.where(reset, init_n, cur_n)
+ cur_mu = torch.where(reset, init_mu, cur_mu)
+ cur_sigma = torch.where(reset, init_sigma, cur_sigma)
+
+ cur_n, cur_mu, cur_sigma = update_running_stats(
+ cur_n, cur_mu, cur_sigma, values[:, :, i, :], masks[:, :, i, :]
+ )
+ all_n.append(cur_n)
+ all_mu.append(cur_mu)
+ all_sigma.append(cur_sigma)
+
+ return (
+ torch.stack(all_n, dim=2),
+ torch.stack(all_mu, dim=2),
+ torch.stack(all_sigma, dim=2),
+ )
+
+
+def revin(
+ x: torch.Tensor,
+ mu: torch.Tensor,
+ sigma: torch.Tensor,
+ reverse: bool = False,
+) -> torch.Tensor:
+ """Reversible per-instance normalization.
+
+ Automatically expands mu/sigma dims to match x.
+
+ Args:
+ x: Input tensor. Shape: (b, ..., d).
+ mu: Mean tensor. Shape: (b, ...) with 1 or 2 fewer dims than x.
+ sigma: Std tensor. Same shape as mu.
+ reverse: If True, applies reverse normalization (denormalize).
+
+ Returns:
+ Normalized or denormalized tensor, same shape as x.
+ """
+ if mu.dim() == x.dim() - 1:
+ mu = mu.unsqueeze(-1)
+ sigma = sigma.unsqueeze(-1)
+ elif mu.dim() == x.dim() - 2:
+ mu = mu.unsqueeze(-1).unsqueeze(-1)
+ sigma = sigma.unsqueeze(-1).unsqueeze(-1)
+ else:
+ raise ValueError(f"Unsupported shapes for x and mu: {x.shape}, {mu.shape}.")
+ if reverse:
+ return x * sigma + mu
+ else:
+ return (x - mu) / _make_safe_for_division(sigma)
+
+
+def get_output_patch_via_roll(
+ x: torch.Tensor, rolls: int
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Creates labels of output_patch length by rolling the patched inputs.
+
+ Takes patched input (b, v, n, p) and creates output patches of length
+ p*rolls by concatenating shifted views of the patches.
+
+ Args:
+ x: Patched inputs. Shape: (b, v, n, p).
+ rolls: Number of rolls (= output_patch_len / patch_len).
+
+ Returns:
+ Tuple of:
+ - Rolled output. Shape: (b, v, n, p * rolls).
+ - Wrap-around mask. Shape: (1, 1, n, p * rolls) bool.
+ """
+ b, v, n, p = x.shape
+ device = x.device
+ rolling_mat = torch.zeros(b, v, n, rolls + 1, p, device=device, dtype=x.dtype)
+ rolling_mat[:, :, :, 0, :] = x
+
+ for i in range(rolls):
+ rolling_mat[:, :, :, i + 1, :] = torch.roll(
+ rolling_mat[:, :, :, i, :], shifts=-1, dims=2
+ )
+
+ # Take [1:] along the roll axis and flatten
+ result = rolling_mat[:, :, :, 1:, :].reshape(b, v, n, rolls * p)
+
+ # Build wrap-around mask
+ patch_idx = torch.arange(n, device=device)
+ point_idx = torch.arange(rolls * p, device=device)
+ source_patch = patch_idx[:, None] + 1 + point_idx[None, :] // p
+ wrap_mask = (source_patch >= n).unsqueeze(0).unsqueeze(0)
+
+ return result, wrap_mask
+
+
+_ACTIVATIONS: dict[str, Callable[[torch.Tensor], torch.Tensor]] = {
+ "relu": F.relu,
+ "swish": F.silu,
+ "silu": F.silu,
+ "swiglu": F.silu,
+ "none": lambda x: x,
+}
+
+
+def get_activation_fn(
+ activation_name: str,
+) -> Callable[[torch.Tensor], torch.Tensor]:
+ """Returns the activation function for the given name."""
+ try:
+ return _ACTIVATIONS[activation_name]
+ except KeyError:
+ raise ValueError(
+ f"Activation: {activation_name} not supported. Supported "
+ f"activations: {list(_ACTIVATIONS.keys())}"
+ ) from None
+
+
+def load_safetensors(
+ pytorch_safetensors_path: str,
+ device: str | torch.device = "cpu",
+) -> dict[str, torch.Tensor]:
+ """Loads a PyTorch state dict from a safetensors file.
+
+ Args:
+ pytorch_safetensors_path: Path to the safetensors file.
+ device: The device to load the tensors onto.
+
+ Returns:
+ A dictionary of PyTorch state dict weights.
+ """
+ expanded_path = os.path.expanduser(pytorch_safetensors_path)
+ return safetensors_torch.load_file(expanded_path, device=str(device))
+
+
+def stitch_patches(
+ patch_preds: torch.Tensor,
+ patch_len: int,
+) -> torch.Tensor:
+ """Stitches overlapping patch predictions.
+
+ Each patch predicts patch_len + overlap timepoints, where
+ overlap = patch_preds.shape[3] - patch_len is inferred from the input.
+ Consecutive patches share overlap timepoints, which are linearly stitched.
+
+ Args:
+ patch_preds: Predictions of shape (batch, variates, num_patches, patch_len
+ + overlap, num_quantiles).
+ patch_len: The patch length.
+
+ Returns:
+ Stitched predictions of shape
+ (batch, variates, num_patches * patch_len + overlap, num_quantiles).
+ """
+ b, v, num_patches, total_len, q = patch_preds.shape
+ overlap = total_len - patch_len
+
+ if num_patches == 1:
+ return patch_preds[:, :, 0, :, :]
+
+ stitch_weights = torch.linspace(
+ 1.0, 0.0, overlap, device=patch_preds.device, dtype=patch_preds.dtype
+ )
+ stitch_weights = stitch_weights[None, None, None, :, None]
+
+ first_chunk = patch_preds[:, :, 0, :patch_len, :]
+
+ prev_patches = patch_preds[:, :, :-1, :, :]
+ next_patches = patch_preds[:, :, 1:, :, :]
+
+ prev_overlaps = prev_patches[:, :, :, patch_len:, :]
+ next_overlaps = next_patches[:, :, :, :overlap, :]
+
+ stitched_overlaps = (
+ stitch_weights * prev_overlaps
+ + (1.0 - stitch_weights) * next_overlaps
+ )
+
+ middles = next_patches[:, :, :, overlap:patch_len, :]
+
+ output_chunks = torch.cat([stitched_overlaps, middles], dim=3)
+
+ mid = output_chunks.reshape(b, v, (num_patches - 1) * patch_len, q)
+
+ tail = patch_preds[:, :, -1, patch_len:, :]
+
+ return torch.cat([first_chunk, mid, tail], dim=2)
+
diff --git a/timesfm-forecasting/notebooks/promotion_and_synthetic_parity_demo.ipynb b/timesfm-forecasting/notebooks/promotion_and_synthetic_parity_demo.ipynb
new file mode 100644
index 0000000..7fb5851
--- /dev/null
+++ b/timesfm-forecasting/notebooks/promotion_and_synthetic_parity_demo.ipynb
@@ -0,0 +1,273 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# TimesFM 3.0 PyTorch Inference Demo\n",
+ "\n",
+ "This interactive notebook demonstrates zero-shot time series forecasting using **TimesFM 3.0** (PyTorch).\n",
+ "\n",
+ "### Key Features Highlighted:\n",
+ "1. **Promotion Example with Dynamic Covariates**: Context length = 2048, Forecast Horizon = 512 with dynamic past-future promotion indicator.\n",
+ "2. **Synthetic Curves (Horizon > 64)**: Evaluating long horizons across sine waves and linear trend extrapolation.\n",
+ "3. **GPU Acceleration**: Automatic CUDA inference with quantile uncertainty intervals."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. Setup and Imports"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "import torch\n",
+ "\n",
+ "from timesfm3 import TimesFM3Forecaster, ModelConfig\n",
+ "\n",
+ "# Set random seeds for reproducibility\n",
+ "np.random.seed(42)\n",
+ "torch.manual_seed(42)\n",
+ "\n",
+ "print(f\"PyTorch version: {torch.__version__}\")\n",
+ "print(f\"CUDA available: {torch.cuda.is_available()}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Initialize TimesFM 3.0 Forecaster\n",
+ "\n",
+ "We instantiate `TimesFM3Forecaster` with the default 1280-dim, 20-layer, 16-head checkpoint."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "config = ModelConfig(\n",
+ " checkpoint_path=\"~/models/tfm3/timesfm3_torch_1944000.safetensors\",\n",
+ " input_patch_length=32,\n",
+ " output_patch_length=64,\n",
+ " per_core_batch_size=2,\n",
+ " use_sdpa=True,\n",
+ ")\n",
+ "\n",
+ "forecaster = TimesFM3Forecaster(config)\n",
+ "print(f\"TimesFM3 forecaster loaded successfully on device: {forecaster.device}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Scenario 1: Promotion Example with Dynamic Covariates\n",
+ "\n",
+ "- **Context Length**: 2048\n",
+ "- **Forecast Horizon**: 512\n",
+ "- **Past-Future Covariates**: Binary promotion covariate (0 or 1) spanning the full length (2560 steps).\n",
+ "- **Target Multiplier**: Target value is boosted by 5x during active promotions."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "context_len = 2048\n",
+ "horizon_len = 512\n",
+ "total_len = context_len + horizon_len\n",
+ "time = np.arange(total_len)\n",
+ "\n",
+ "# Generate promotion indicator\n",
+ "promotions = np.zeros(total_len, dtype=np.float32)\n",
+ "# Promotion in context\n",
+ "promotions[1130:1180] = 1.0\n",
+ "# Promotions in forecast horizon\n",
+ "promotions[2250:2290] = 1.0\n",
+ "promotions[2320:2355] = 1.0\n",
+ "\n",
+ "pfc_np = np.array([promotions], dtype=np.float32)\n",
+ "\n",
+ "# Generate base target: periodic sine + noise\n",
+ "base_target = 2.0 + np.sin(time / 20.0) + np.random.randn(total_len) * 0.15\n",
+ "# Apply 5x promo boost\n",
+ "target_full = (base_target * np.where(promotions == 1.0, 5.0, 1.0)).astype(np.float32)\n",
+ "\n",
+ "context = target_full[:context_len]\n",
+ "actual_horizon = target_full[context_len:]\n",
+ "\n",
+ "print(f\"Context shape: {context.shape}\")\n",
+ "print(f\"Horizon length: {horizon_len}\")\n",
+ "print(f\"Past-Future Covariates shape: {pfc_np.shape}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Run zero-shot forecast with dynamic past-future covariates\n",
+ "torch_out = forecaster.predict(\n",
+ " context=context,\n",
+ " horizon=horizon_len,\n",
+ " past_future_covariates=pfc_np,\n",
+ " return_quantiles=True,\n",
+ ")\n",
+ "\n",
+ "print(\"Forecast generated successfully!\")\n",
+ "print(f\"Point forecast shape: {torch_out.forecast.shape}\")\n",
+ "print(f\"Quantiles shape: {torch_out.quantiles.shape}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Plot Promotion Example\n",
+ "time_context = np.arange(context_len)\n",
+ "time_horizon = np.arange(context_len, total_len)\n",
+ "\n",
+ "fig, axes = plt.subplots(2, 1, figsize=(16, 8), sharex=True)\n",
+ "\n",
+ "# Subplot 0: Target, Actual Horizon, and PyTorch Forecast\n",
+ "axes[0].plot(time_context, context, label=\"Context (Input)\", color=\"black\", alpha=0.7, linewidth=1.2)\n",
+ "axes[0].plot(time_horizon, actual_horizon, label=\"Actual Horizon (Ground Truth)\", linestyle=\"--\", color=\"gray\", alpha=0.8)\n",
+ "axes[0].plot(time_horizon, torch_out.forecast, label=\"TimesFM3 Median Forecast (p50)\", color=\"#ff7f0e\", linewidth=2.5)\n",
+ "if torch_out.quantiles is not None:\n",
+ " axes[0].fill_between(\n",
+ " time_horizon,\n",
+ " torch_out.quantiles[:, 0],\n",
+ " torch_out.quantiles[:, -1],\n",
+ " color=\"salmon\",\n",
+ " alpha=0.3,\n",
+ " label=\"p10-p90 Prediction Interval\",\n",
+ " )\n",
+ "axes[0].set_title(\"TimesFM 3.0 Promotion Example Forecast (Context 2048, Horizon 512)\", fontsize=14)\n",
+ "axes[0].set_ylabel(\"Target Value\", fontsize=12)\n",
+ "axes[0].legend(loc=\"upper left\")\n",
+ "axes[0].grid(True, alpha=0.3)\n",
+ "\n",
+ "# Subplot 1: Past-Future Promotion Covariate\n",
+ "axes[1].plot(time, promotions, label=\"Promotion Indicator (0 or 1)\", color=\"green\", drawstyle=\"steps-mid\", linewidth=1.5)\n",
+ "axes[1].fill_between(time, 0, promotions, color=\"green\", alpha=0.2)\n",
+ "axes[1].set_title(\"Past-Future Covariate: Promotions Timeline\", fontsize=12)\n",
+ "axes[1].set_ylabel(\"Promotion Active\", fontsize=12)\n",
+ "axes[1].set_xlabel(\"Time Step (t)\", fontsize=12)\n",
+ "axes[1].set_yticks([0, 1])\n",
+ "axes[1].legend(loc=\"upper left\")\n",
+ "axes[1].grid(True, alpha=0.3)\n",
+ "\n",
+ "plt.tight_layout()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Scenario 2: Long Horizon Synthetic Curves (Horizon 128 > 64)\n",
+ "\n",
+ "Evaluates rolling patch autoregressive decoding across:\n",
+ "1. **Sine Curve** (periodic continuation)\n",
+ "2. **Linear Trend** (linear detrending extrapolation)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "synth_context_len = 256\n",
+ "synth_horizon_len = 128\n",
+ "synth_total_len = synth_context_len + synth_horizon_len\n",
+ "t_synth = np.linspace(0, 8 * np.pi, synth_total_len, dtype=np.float32)\n",
+ "\n",
+ "# Series 0: Sine wave\n",
+ "s_sine = np.sin(t_synth)\n",
+ "# Series 1: Linear trend line\n",
+ "s_line = np.arange(synth_total_len, dtype=np.float32) * 0.05 + 2.0\n",
+ "\n",
+ "contexts = [s_sine[:synth_context_len], s_line[:synth_context_len]]\n",
+ "ground_truths = [s_sine[synth_context_len:], s_line[synth_context_len:]]\n",
+ "\n",
+ "# Batch predict\n",
+ "synth_outputs = list(forecaster.predict_batch(contexts, horizon=synth_horizon_len))\n",
+ "\n",
+ "# Compute metrics\n",
+ "sine_mae = np.mean(np.abs(synth_outputs[0].forecast - ground_truths[0]))\n",
+ "line_mae = np.mean(np.abs(synth_outputs[1].forecast - ground_truths[1]))\n",
+ "\n",
+ "print(f\"Sine Curve Mean Absolute Error: {sine_mae:.6f}\")\n",
+ "print(f\"Linear Trend Mean Absolute Error: {line_mae:.6f}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Plot Synthetic Curves\n",
+ "fig, axes = plt.subplots(2, 1, figsize=(14, 8), sharex=True)\n",
+ "t_ctx = np.arange(synth_context_len)\n",
+ "t_hor = np.arange(synth_context_len, synth_total_len)\n",
+ "titles = [\n",
+ " f\"Sine Curve Forecast (MAE: {sine_mae:.6f})\",\n",
+ " f\"Linear Trend Forecast (MAE: {line_mae:.6f})\",\n",
+ "]\n",
+ "\n",
+ "for i, ax in enumerate(axes):\n",
+ " ax.plot(t_ctx, contexts[i], label=\"Context (Input)\", color=\"black\", linewidth=1.5)\n",
+ " ax.plot(t_hor, ground_truths[i], label=\"Ground Truth\", color=\"gray\", linestyle=\"--\", alpha=0.7)\n",
+ " ax.plot(t_hor, synth_outputs[i].forecast, label=\"TimesFM3 Forecast\", color=\"#ff7f0e\", linewidth=2.5)\n",
+ " ax.set_title(titles[i], fontsize=13)\n",
+ " ax.set_ylabel(\"Value\", fontsize=11)\n",
+ " ax.legend(loc=\"upper left\")\n",
+ " ax.grid(True, alpha=0.3)\n",
+ "\n",
+ "axes[1].set_xlabel(\"Time Step\", fontsize=12)\n",
+ "plt.tight_layout()\n",
+ "plt.show()"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": ".venv",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.3"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}