TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google Research for time-series forecasting.
Python
feat(timesfm3): add TimesFM3Evaluator, variate chunking, and inference precision enhancements
Ayush Jain0e57ebc47830
diff --git a/src/timesfm3/__init__.py b/src/timesfm3/__init__.pyindex 380acce..ff741bf 100644--- a/src/timesfm3/__init__.py+++ b/src/timesfm3/__init__.py@@ -15,6 +15,7 @@"""TimesFM3 PyTorch API."""from .configs import ResidualBlockConfig, StackedTransformersConfig, TransformerConfig+from .evaluator import TimesFM3Evaluatorfrom .model import TimesFM3Torchfrom .timesfm3_forecaster import (ForecastOutput,@@ -28,6 +29,7 @@ __all__ = ["ModelConfig","ResidualBlockConfig","StackedTransformersConfig",+ "TimesFM3Evaluator","TimesFM3Forecaster","TimesFM3Torch","TransformerConfig",diff --git a/src/timesfm3/evaluator.py b/src/timesfm3/evaluator.pynew file mode 100644index 0000000..aa29df8--- /dev/null+++ b/src/timesfm3/evaluator.py@@ -0,0 +1,246 @@+"""Evaluator subclass extending TimesFM3Forecaster for benchmark evaluation."""++from __future__ import annotations++import math+from collections.abc import Iterator++import numpy as np++from .timesfm3_forecaster import (+ ForecastOutput,+ ModelConfig,+ TimesFM3Forecaster,+ _ModelConfig,+)++_MAX_VARIATES_PER_FORWARD = 32+++class TimesFM3Evaluator(TimesFM3Forecaster):+ """Evaluator subclass extending TimesFM3Forecaster for benchmark evaluation.++ Specializes inference specifically for zero-shot benchmark evaluation:+ - Sets benchmark evaluation defaults (return_quantiles=True, use_symmetric_averaging=True,+ make_positive=True, sort_quantiles=True).+ - Enforces padding_mode="none" and use_znorm=False.+ - Implements automatic variate chunking (<= _MAX_VARIATES_PER_FORWARD variates per forward pass)+ for high-dimensional multivariate inputs.+ - Supports univariate mode (univariate=True) unrolling channels into independent series.+ - Delegates batch forecasting, cross-variate attention, quantile sorting, symmetric+ averaging, and non-negativity clamping directly to TimesFM3Forecaster.+ """++ 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 = True,+ use_symmetric_averaging: bool = True,+ make_positive: bool = True,+ sort_quantiles: bool = True,+ use_znorm: bool = False,+ padding_mode: str = "none",+ univariate: bool = False,+ ) -> Iterator[ForecastOutput]:+ """Runs inference on a batch of time series with official benchmark defaults & chunking."""+ num_original_ts = len(contexts)+ original_ts_ids = (+ list(ts_ids) if ts_ids is not None else [None] * num_original_ts+ )++ if not contexts:+ return++ if univariate:+ flat_contexts = []+ variate_counts = []+ was_1d_list = []++ for ctx in contexts:+ ctx_arr = np.asarray(ctx)+ was_1d = ctx_arr.ndim == 1+ was_1d_list.append(was_1d)++ ctx_2d = np.atleast_2d(ctx_arr)+ num_vars = ctx_2d.shape[0]+ variate_counts.append(num_vars)+ for v in range(num_vars):+ flat_contexts.append(ctx_2d[v, :])++ flat_outs = list(+ super().predict_batch(+ contexts=flat_contexts,+ horizon=horizon,+ past_only_covariates=None,+ past_future_covariates=None,+ return_quantiles=return_quantiles,+ use_symmetric_averaging=use_symmetric_averaging,+ make_positive=make_positive,+ sort_quantiles=sort_quantiles,+ use_znorm=use_znorm,+ padding_mode=padding_mode,+ )+ )++ curr_idx = 0+ for i in range(num_original_ts):+ n_vars = variate_counts[i]+ series_outs = flat_outs[curr_idx : curr_idx + n_vars]+ curr_idx += n_vars++ f_list = [out.forecast for out in series_outs if out.forecast is not None]+ q_list = [out.quantiles for out in series_outs if out.quantiles is not None]++ if was_1d_list[i]:+ combined_f = f_list[0] if f_list else None+ combined_q = q_list[0] if q_list else None+ else:+ combined_f = np.stack(f_list, axis=0) if f_list else None+ combined_q = np.stack(q_list, axis=0) if q_list else None++ yield ForecastOutput(+ ts_id=original_ts_ids[i],+ forecast=combined_f,+ quantiles=combined_q,+ )+ return++ contexts_2d = [np.atleast_2d(ctx) for ctx in contexts]+ po_2d = (+ [np.atleast_2d(cov) if cov is not None else None for cov in past_only_covariates]+ if past_only_covariates is not None+ else [None] * num_original_ts+ )+ pf_2d = (+ [np.atleast_2d(cov) if cov is not None else None for cov in past_future_covariates]+ if past_future_covariates is not None+ else [None] * num_original_ts+ )++ num_targets_in = contexts_2d[0].shape[0] if contexts_2d else 1+ num_pf = max((cov.shape[0] for cov in pf_2d if cov is not None), default=0)+ num_po = max((cov.shape[0] for cov in po_2d if cov is not None), default=0)+ total_variates = num_targets_in + num_pf + num_po++ if total_variates > _MAX_VARIATES_PER_FORWARD:+ rng = np.random.default_rng(42)+ # Step 1a: Subsample future covariates to at most 31 slots.+ max_pf = min(num_pf, _MAX_VARIATES_PER_FORWARD - 1)+ if num_pf > max_pf:+ pf_idx = np.sort(rng.choice(num_pf, max_pf, replace=False))+ pf_2d = [+ cov[pf_idx] if cov is not None else None+ for cov in pf_2d+ ]+ num_pf = max_pf+ # Step 1b: Subsample past-only covariates to at most (31 - pf) slots.+ max_po = min(num_po, _MAX_VARIATES_PER_FORWARD - 1 - num_pf)+ if num_po > max_po:+ po_idx = np.sort(rng.choice(num_po, max_po, replace=False))+ po_2d = [+ cov[po_idx] if cov is not None else None+ for cov in po_2d+ ]+ num_po = max_po+ # Step 2: Compute how many target slots fit per forward pass.+ targets_per_chunk = _MAX_VARIATES_PER_FORWARD - num_pf - num_po+ assert (+ targets_per_chunk >= 1+ ), f"Not enough variate slots for targets: pf={num_pf}, po={num_po}"+ num_chunks = math.ceil(num_targets_in / targets_per_chunk)++ # Step 3: Process each target chunk, concatenate along variate axis.+ chunk_results = []+ for c in range(num_chunks):+ v_start = c * targets_per_chunk+ v_end = min((c + 1) * targets_per_chunk, num_targets_in)+ actual_chunk_size = v_end - v_start+ chunk_inputs = [inp[v_start:v_end, :] for inp in contexts_2d]+ if actual_chunk_size < targets_per_chunk:+ pad_needed = targets_per_chunk - actual_chunk_size+ padded_inputs = []+ for inp, c_inp in zip(contexts_2d, chunk_inputs):+ reps = math.ceil(pad_needed / inp.shape[0])+ repeated = np.tile(inp, (reps, 1))[:pad_needed, :]+ padded_inputs.append(np.concatenate([c_inp, repeated], axis=0))+ chunk_inputs = padded_inputs+ chunk_outs = list(+ super().predict_batch(+ contexts=chunk_inputs,+ horizon=horizon,+ past_only_covariates=po_2d,+ past_future_covariates=pf_2d,+ ts_ids=ts_ids,+ return_quantiles=return_quantiles,+ use_symmetric_averaging=use_symmetric_averaging,+ make_positive=make_positive,+ sort_quantiles=sort_quantiles,+ use_znorm=use_znorm,+ padding_mode=padding_mode,+ )+ )+ trimmed_outs = []+ for out in chunk_outs:+ f_2d = (+ out.forecast[:actual_chunk_size, ...]+ if out.forecast is not None+ else None+ )+ q_3d = (+ out.quantiles[:actual_chunk_size, ...]+ if out.quantiles is not None+ else None+ )+ trimmed_outs.append(+ ForecastOutput(+ ts_id=out.ts_id,+ forecast=f_2d,+ quantiles=q_3d,+ )+ )+ chunk_results.append(trimmed_outs)++ was_1d_input = len(contexts) > 0 and np.ndim(contexts[0]) == 1++ for i in range(num_original_ts):+ combined_f = (+ np.concatenate(+ [chunk_results[c][i].forecast for c in range(num_chunks)], axis=0+ )+ if chunk_results[0][i].forecast is not None+ else None+ )+ combined_q = (+ np.concatenate(+ [chunk_results[c][i].quantiles for c in range(num_chunks)], axis=0+ )+ if chunk_results[0][i].quantiles is not None+ else None+ )+ if was_1d_input and combined_f is not None:+ combined_f = combined_f[0]+ if was_1d_input and combined_q is not None:+ combined_q = combined_q[0]++ yield ForecastOutput(+ ts_id=original_ts_ids[i], forecast=combined_f, quantiles=combined_q+ )+ return++ yield from super().predict_batch(+ contexts=contexts,+ horizon=horizon,+ past_only_covariates=past_only_covariates,+ past_future_covariates=past_future_covariates,+ ts_ids=ts_ids,+ return_quantiles=return_quantiles,+ use_symmetric_averaging=use_symmetric_averaging,+ make_positive=make_positive,+ sort_quantiles=sort_quantiles,+ use_znorm=use_znorm,+ padding_mode=padding_mode,+ )diff --git a/src/timesfm3/timesfm3_forecaster.py b/src/timesfm3/timesfm3_forecaster.pyindex 4b4c43b..58c5e7e 100644--- a/src/timesfm3/timesfm3_forecaster.py+++ b/src/timesfm3/timesfm3_forecaster.py@@ -15,7 +15,7 @@ import torchfrom . import configs, utilfrom . import model as torch_model_lib-_MAX_CONTEXT_LENGTH = 16384+_MAX_CONTEXT_LENGTH = 15360_SIGMA_THRESHOLD: float = 1e-7_GC_MEMORY_THRESHOLD: float = 0.9@@ -119,26 +119,6 @@ def try_gc(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@@ -154,9 +134,18 @@ def linear_interpolation(arr: np.ndarray) -> np.ndarray: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)+ non_nan_indices = valid_mask.nonzero()[0]+ non_nan_values = row[valid_mask]+ try:+ row[nan_mask[r]] = np.interp(+ nan_indices, non_nan_indices, non_nan_values+ )+ except ValueError:+ if non_nan_values.size > 0:+ mu = np.nanmean(row)+ else:+ mu = 0.0+ row[nan_mask[r]] = mureturn result[0] if was_1d else result@@ -187,29 +176,27 @@ def _is_nonnegative(arr: np.ndarray) -> bool | np.ndarray:@dataclasses.dataclass(frozen=True)class _Query:- """A single forecast query."""+ """Represents a single formatted forecast query."""horizon: inttargets: np.ndarraypast_only_covariates: np.ndarray | None = Nonepast_future_covariates: np.ndarray | None = None- padded: bool = False@propertydef context_length(self) -> int:return self.targets.shape[-1]def format(- self, global_context: int+ self, context_len: 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."""+ """Formats and left-pads/truncates the query to context_len length."""targets = np.atleast_2d(self.targets)masks = np.zeros((self.context_length,), dtype=bool)past_only_covariates = (@@ -223,17 +210,17 @@ class _Query:else None)- if self.context_length > global_context:- targets = targets[:, -global_context:]- masks = masks[-global_context:]+ if self.context_length > context_len:+ targets = targets[:, -context_len:]+ masks = masks[-context_len:]if past_only_covariates is not None:- past_only_covariates = past_only_covariates[:, -global_context:]+ past_only_covariates = past_only_covariates[:, -context_len:]if past_future_covariates is not None:past_future_covariates = past_future_covariates[- :, -(global_context + self.horizon) :+ :, -(context_len + self.horizon) :]- elif self.context_length < global_context:- pad_len = global_context - self.context_length+ elif self.context_length < context_len:+ pad_len = context_len - self.context_lengthtargets = np.pad(targets,[(0, 0), (pad_len, 0)],@@ -246,8 +233,6 @@ class _Query: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,@@ -269,7 +254,6 @@ class _Query:masks,past_only_covariates,past_future_covariates,- self.padded,)@@ -438,6 +422,7 @@ class TimesFM3Forecaster:return_quantiles: bool = False,use_symmetric_averaging: bool = False,make_positive: bool = False,+ sort_quantiles: bool = True,use_znorm: bool = False,padding_mode: str = "none",) -> ForecastOutput:@@ -452,6 +437,7 @@ class TimesFM3Forecaster:return_quantiles=return_quantiles,use_symmetric_averaging=use_symmetric_averaging,make_positive=make_positive,+ sort_quantiles=sort_quantiles,use_znorm=use_znorm,padding_mode=padding_mode,)@@ -468,6 +454,7 @@ class TimesFM3Forecaster:return_quantiles: bool = False,use_symmetric_averaging: bool = False,make_positive: bool = False,+ sort_quantiles: bool = True,use_znorm: bool = False,padding_mode: str = "none",) -> Iterator[ForecastOutput]:@@ -477,7 +464,12 @@ class TimesFM3Forecaster:* 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+ original_ts_ids = (+ list(ts_ids) if ts_ids is not None else [None] * num_original_ts+ )++ if not contexts:+ returnpo_cov_list = (list(past_only_covariates)@@ -495,30 +487,53 @@ class TimesFM3Forecaster: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)-+ target_clean = np.atleast_2d(np.array(ctx, dtype=np.float32))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 = (+ np.atleast_2d(np.array(po, dtype=np.float32))+ if po is not None+ else None+ )+ pf = pf_cov_list[idx]+ pf_arr = (+ np.atleast_2d(np.array(pf, dtype=np.float32))+ if pf is not None+ else None+ )++ isnan = np.isnan(target_clean).all(axis=0)+ if isnan.all():+ first_valid_index = target_clean.shape[-1]+ else:+ first_valid_index = int(np.argmax(~isnan))++ if first_valid_index > 0 and first_valid_index < target_clean.shape[-1]:+ target_clean = target_clean[:, first_valid_index:]+ if po_arr is not None:+ po_arr = po_arr[:, first_valid_index:]+ if pf_arr is not None:+ pf_arr = pf_arr[:, first_valid_index:]+ elif first_valid_index == target_clean.shape[-1]:+ if target_clean.shape[-1] == 0:+ pass+ else:+ target_clean = np.zeros_like(target_clean)++ target_clean = linear_interpolation(target_clean)+ contexts_2d.append(target_clean)++ if po_arr is not None: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)+ if pf_arr is not None: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 1for idx, ctx in enumerate(contexts_2d):@@ -529,7 +544,7 @@ class TimesFM3Forecaster:f" {ctx.shape[0]}.")- is_univariate = num_targets_in == 1+ was_1d_input = len(contexts) > 0 and np.ndim(contexts[0]) == 1znorm_per_example: list[list[tuple[float, float]]] = []if use_znorm:@@ -625,9 +640,19 @@ class TimesFM3Forecaster: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]+ if not query_batch:+ continue++ # Dynamic per-batch context length rounded up to patch length boundary+ max_ctx_in_batch = max(q.context_length for q in query_batch)+ batch_context = min(+ math.ceil(max_ctx_in_batch / self.config.input_patch_length)+ * self.config.input_patch_length,+ self.global_context,+ )+ batch_context = max(batch_context, self.config.input_patch_length)++ formatted_batch = [q.format(batch_context) for q in query_batch](batched_hor,@@ -635,7 +660,6 @@ class TimesFM3Forecaster: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(@@ -665,7 +689,7 @@ class TimesFM3Forecaster:self.device, dtype=torch.float32)- with torch.no_grad():+ with torch.inference_mode():out_logits = self.model.decode(target=tgt_torch,horizon=batched_hor[0],@@ -674,14 +698,13 @@ class TimesFM3Forecaster:mask=mask_torch,)ys.append(out_logits.cpu().numpy())- try_gc(self.device)+ try_gc(self.device)all_raw_outputs = np.concatenate(ys, axis=0)+ all_raw_outputs = all_raw_outputs[:, :num_targets_in, :, :]- 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 sort_quantiles:+ all_raw_outputs = np.sort(all_raw_outputs, axis=-1)if use_symmetric_averaging:ys_pos = all_raw_outputs[0::2]@@ -700,11 +723,11 @@ class TimesFM3Forecaster:if make_positive:for i in range(num_original_ts):- if is_univariate:- if _is_nonnegative(original_contexts[i]):+ if was_1d_input:+ if _is_nonnegative(contexts[i]):all_raw_outputs[i] = np.maximum(all_raw_outputs[i], 0.0)else:- nonneg = _is_nonnegative(original_contexts[i])+ nonneg = _is_nonnegative(contexts[i])assert isinstance(nonneg, np.ndarray)for r in range(num_targets_in):if nonneg[r]:@@ -712,7 +735,7 @@ class TimesFM3Forecaster:for i in range(num_original_ts):raw = all_raw_outputs[i]- if is_univariate:+ if was_1d_input:raw = raw[0]yield ForecastOutput(ts_id=original_ts_ids[i],diff --git a/src/timesfm3/timesfm3_forecaster_test.py b/src/timesfm3/timesfm3_forecaster_test.pyindex e9dc229..e08bf63 100644--- a/src/timesfm3/timesfm3_forecaster_test.py+++ b/src/timesfm3/timesfm3_forecaster_test.py@@ -14,12 +14,14 @@"""Tests for PyTorch TimesFM3Forecaster."""+import tempfileimport unittestfrom unittest import mock-import numpy as npimport torch+from . import configs+from . import model as torch_model_libfrom . import timesfm3_forecaster@@ -58,32 +60,16 @@ class TimesFM3ForecasterTest(unittest.TestCase):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_linear_interpolation_all_nan(self):+ arr = np.array([np.nan, np.nan, np.nan])+ res = timesfm3_forecaster.linear_interpolation(arr)+ np.testing.assert_array_equal(res, np.array([0.0, 0.0, 0.0]))+def test_znorm_stats(self):arr = np.array([1.0, 2.0, 3.0])mu, sigma = timesfm3_forecaster._znorm_stats(arr)@@ -136,12 +122,37 @@ class TimesFM3ForecasterTest(unittest.TestCase):self.assertEqual(out.forecast.shape, (2, 4))self.assertEqual(out.quantiles.shape, (2, 4, 3))- def test_from_pretrained_local_directory(self):- import tempfile-- from . import configs- from . import model as torch_model_lib+ def test_query_format_padding_and_truncation(self):+ # Test padding when context_length < context_len+ q_short = timesfm3_forecaster._Query(+ horizon=4,+ targets=np.array([[1.0, 2.0]]),+ past_only_covariates=np.array([[5.0, 6.0]]),+ past_future_covariates=np.array([[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]]),+ )+ hor, tgt, mask, po, pf = q_short.format(context_len=4)+ self.assertEqual(hor, 4)+ self.assertEqual(tgt.shape, (1, 4))+ np.testing.assert_array_equal(tgt, np.array([[0.0, 0.0, 1.0, 2.0]]))+ np.testing.assert_array_equal(mask, np.array([True, True, False, False]))+ np.testing.assert_array_equal(po, np.array([[0.0, 0.0, 5.0, 6.0]]))+ self.assertEqual(pf.shape, (1, 8)) # 4 ctx + 4 horizon++ # Test truncation when context_length > context_len+ q_long = timesfm3_forecaster._Query(+ horizon=2,+ targets=np.array([[1.0, 2.0, 3.0, 4.0]]),+ past_only_covariates=np.array([[10.0, 20.0, 30.0, 40.0]]),+ past_future_covariates=np.array([[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]]),+ )+ hor, tgt, mask, po, pf = q_long.format(context_len=2)+ self.assertEqual(hor, 2)+ self.assertEqual(tgt.shape, (1, 2))+ np.testing.assert_array_equal(tgt, np.array([[3.0, 4.0]]))+ np.testing.assert_array_equal(mask, np.array([False, False]))+ np.testing.assert_array_equal(po, np.array([[30.0, 40.0]]))+ def test_from_pretrained_local_directory(self):resblock_config = configs.ResidualBlockConfig(hidden_dims=16,output_dims=16,