TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google Research for time-series forecasting.
Python
fix(timesfm3): shape covariate placeholders like the batch's real covariates, not the target
LngelKyo93d2c64f63d0
diff --git a/src/timesfm3/timesfm3_forecaster.py b/src/timesfm3/timesfm3_forecaster.pyindex 078b3dc..5b4ca91 100644--- a/src/timesfm3/timesfm3_forecaster.py+++ b/src/timesfm3/timesfm3_forecaster.py@@ -151,9 +151,7 @@ def linear_interpolation(arr: np.ndarray) -> np.ndarray: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- )+ 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)@@ -484,9 +482,7 @@ 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_tsif len(contexts) == 0:return@@ -509,17 +505,9 @@ class TimesFM3Forecaster:for idx, ctx in enumerate(contexts):target_clean = np.atleast_2d(np.array(ctx, dtype=np.float32))po = po_cov_list[idx]- po_arr = (- np.atleast_2d(np.array(po, dtype=np.float32))- if po is not None- else None- )+ po_arr = np.atleast_2d(np.array(po, dtype=np.float32)) if po is not None else Nonepf = pf_cov_list[idx]- pf_arr = (- np.atleast_2d(np.array(pf, dtype=np.float32))- if pf is not None- else None- )+ pf_arr = np.atleast_2d(np.array(pf, dtype=np.float32)) if pf is not None else Noneisnan = np.isnan(target_clean).all(axis=0)if isnan.all():@@ -691,20 +679,27 @@ class TimesFM3Forecaster:po_torch = Noneif 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)- ]+ # A query without covariates in a batch where others have them gets+ # a zero placeholder shaped like the real covariate arrays (channel+ # count and width), not like the target: the covariate channel count+ # need not equal the number of target variates, and np.stack needs+ # every entry to have the same shape.+ po_ref = next(po for po in batched_po if po is not None)+ po_arrs = [po if po is not None else np.zeros_like(po_ref) for po in batched_po]po_torch = torch.from_numpy(np.stack(po_arrs, axis=0)).to(self.device, dtype=torch.float32)pf_torch = Noneif 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)- ]+ # Same for past-future covariates. decode infers the horizon from+ # the covariate width (pf.shape[-1] - context) and slices the future+ # part, so the placeholder must match the real arrays' width as well+ # as their channel count. Real arrays in one batch already share both:+ # their context is the batch context and their future part is the+ # requested horizon.+ pf_ref = next(pf for pf in batched_pf if pf is not None)+ pf_arrs = [pf if pf is not None else np.zeros_like(pf_ref) for pf in batched_pf]pf_torch = torch.from_numpy(np.stack(pf_arrs, axis=0)).to(self.device, dtype=torch.float32)diff --git a/src/timesfm3/timesfm3_forecaster_test.py b/src/timesfm3/timesfm3_forecaster_test.pyindex c8f436e..9214c23 100644--- a/src/timesfm3/timesfm3_forecaster_test.py+++ b/src/timesfm3/timesfm3_forecaster_test.py@@ -218,6 +218,9 @@ class _RecordingFakeModel(FakeModel):past_future_covariates=(None if past_future_covariates is None else past_future_covariates.clone()),+ past_only_covariates=(+ None if past_only_covariates is None else past_only_covariates.clone()+ ),horizon=horizon,))@@ -289,6 +292,83 @@ class TimesFM3ForecasterCovariateWindowTest(unittest.TestCase):)self.assertEqual([o.forecast.shape for o in outputs], [(5,), (5,)])+ def test_mixed_none_and_pf_covariates(self):+ # A query without past-future covariates batched with one that has+ # them: the placeholder must have the decode-expected width (matching+ # the real PF arrays in the batch), or np.stack fails on lengths.+ forecaster = self._forecaster()+ long_ctx = np.arange(40, dtype=np.float32)+ short_ctx = np.arange(100, 112, dtype=np.float32)+ outputs = list(+ forecaster.predict_batch(+ contexts=[long_ctx, short_ctx],+ horizon=5,+ past_future_covariates=[np.arange(45, dtype=np.float32), None],+ )+ )+ self.assertEqual([o.forecast.shape for o in outputs], [(5,), (5,)])+ call = forecaster.model.calls[-1]+ pf = call["past_future_covariates"]+ # decode must see a uniform PF width across the batch. The batch+ # context is capped by _MAX_CONTEXT_LENGTH(16, set in setUp), so the+ # real PF is context(16) + requested horizon(5) = 21; the placeholder+ # matches that width.+ self.assertEqual(pf.shape[0], 2)+ self.assertEqual(pf.shape[-1], 21)+ pf_real = pf[0, 0]+ pf_placeholder = pf[1, 0]+ self.assertEqual(pf_real.shape[-1], pf_placeholder.shape[-1])+ # The placeholder's future part (the requested horizon, 5) is zeros;+ # decode infers horizon 5 from the width.+ np.testing.assert_array_equal(pf_placeholder[-5:], np.zeros((5,), dtype=np.float32))+ self.assertEqual(call["horizon"], 5)++ def test_mixed_none_and_multichannel_covariates(self):+ # Covariate channel count need not equal the number of target variates:+ # a 2-channel past-future covariate and a 2-channel past-only covariate+ # batched with a query that has neither must still stack.+ forecaster = self._forecaster()+ ctx_a = np.arange(12, dtype=np.float32)+ ctx_b = np.arange(100, 112, dtype=np.float32)+ pf_a = np.stack([np.arange(17, dtype=np.float32)] * 2)+ po_a = np.stack([np.arange(12, dtype=np.float32)] * 2)+ outputs = list(+ forecaster.predict_batch(+ contexts=[ctx_a, ctx_b],+ horizon=5,+ past_only_covariates=[po_a, None],+ past_future_covariates=[pf_a, None],+ )+ )+ self.assertEqual([o.forecast.shape for o in outputs], [(5,), (5,)])+ call = forecaster.model.calls[-1]+ # batch context 16 (12 rounded up to the patch), 2 channels, future 5.+ self.assertEqual(tuple(call["past_future_covariates"].shape), (2, 2, 21))+ self.assertEqual(tuple(call["past_only_covariates"].shape), (2, 2, 16))+ np.testing.assert_array_equal(+ call["past_future_covariates"][1].numpy(), np.zeros((2, 21), np.float32)+ )+ np.testing.assert_array_equal(+ call["past_only_covariates"][1].numpy(), np.zeros((2, 16), np.float32)+ )++ def test_mixed_none_covariates_multivariate_target(self):+ # Three target variates with a 2-channel past-future covariate on one+ # query and none on the other.+ forecaster = self._forecaster()+ ctx_a = np.stack([np.arange(12, dtype=np.float32)] * 3)+ ctx_b = np.stack([np.arange(100, 112, dtype=np.float32)] * 3)+ pf_a = np.stack([np.arange(17, dtype=np.float32)] * 2)+ outputs = list(+ forecaster.predict_batch(+ contexts=[ctx_a, ctx_b], horizon=5, past_future_covariates=[pf_a, None]+ )+ )+ self.assertEqual([o.forecast.shape for o in outputs], [(3, 5), (3, 5)])+ call = forecaster.model.calls[-1]+ self.assertEqual(tuple(call["target"].shape), (2, 3, 16))+ self.assertEqual(tuple(call["past_future_covariates"].shape), (2, 2, 21))+def test_predict_batch_accepts_2d_array(self):forecaster = self._forecaster()outputs = list(