AI Logic

Architectures

TimesFM

Updated:

TimesFM architecture. Left: the overall flow, which splits the context window into 32-point input patches, turns them into tokens with a residual block and positional encoding, passes them through a causal-attention Transformer, and outputs a 128-point output patch with a residual block. Right: during training, the next 128 points are predicted at every position; during forecasting, output patches are appended to the input to extend the horizon autoregressively

Background and overview

TimesFM (Time-series Foundation Model) is a forecasting foundation model based on a decoder-only Transformer, pretrained on a large amount of time-series data. It splits a series into short segments (patches) used as tokens and learns to predict "the next segment," just as a language model predicts the next word. On data it was never trained on, it forecasts without additional training (zero-shot) with accuracy close to models trained specifically for that data. Das, Kong, Sen, and Zhou of Google Research introduced it in 2023 in "A decoder-only foundation model for time-series forecasting," published at ICML 2024.

Earlier deep learning forecasting models (DeepAR, N-BEATS, PatchTST, and others) were typically trained per dataset. The paper asks whether, as with language models, "a single large pretrained model can be applied directly to new series," and achieves this through two ingredients:

  1. Large, diverse training data: Hundreds of billions of time points combining Google Trends search interest, Wikipedia page views, synthetic series, and more (about 380 billion points in total in Table 1 of the paper). It covers a range of granularities, including hourly, daily, weekly, and monthly.
  2. A decoder-only Transformer with patches as input: It has the same form as a language model and can be pretrained efficiently.

The model has 200 million parameters, far smaller than large language models. Even so, it was more accurate than using language models such as GPT-3 directly for forecasting (llmtime).

In this article, the past span used as the basis for forecasting is called the context window (length LL in the paper's notation; also called the context), and the span to be forecast is called the horizon (length HH). TimesFM produces the horizon in units of output patches (length 128), repeating until the required length is reached.

Architecture

TimesFM forecasts the horizon y^L+1:L+H\hat{y}_{L+1:L+H} from the context window y1:Ly_{1:L} of a single (univariate) series. The left of the figure at the top of the article shows the overall flow, and the right shows how outputs are produced during training and forecasting.

Model components

  1. Normalize: The scale of the whole series is standardized using the mean and standard deviation of the first patch of the context window (only the normalization part of RevIN is used).
  2. Split into input patches: The context window is split into non-overlapping input patches of length p=32p = 32, y~j=yp(j−1)+1:pj\tilde{y}_j = y_{p(j-1)+1:pj}. If the context length is not a multiple of 32, the beginning is padded with zeros and marked as "ignore" by a mask mm.
  3. Convert to tokens: Each patch is mapped to dmodel=1280d_{\mathrm{model}} = 1280 dimensions by a small MLP with one hidden layer and a residual connection (a residual block), and a sinusoidal positional encoding PEj\mathrm{PE}_j is added.
  4. Pass through a decoder-only Transformer: 20 layers are stacked. Each layer consists of causally masked multi-head attention (16 heads) and a feed-forward layer. Each token attends only to itself and earlier tokens.
  5. Produce output patches: The jj-th output token ojo_j is turned into an output patch of length h=128h = 128 by a separate residual block. This is the forecast of the 128 points immediately following the jj-th input patch.

The equations for the input, the Transformer, and the output (Eqs. 2–4 in the paper) are:

tj=InputResidualBlock(y~j⊙(1−m~j))+PEjt_j = \mathrm{InputResidualBlock}\bigl(\tilde{y}_j \odot (1 - \tilde{m}_j)\bigr) + \mathrm{PE}_j oj=StackedTransformer((t1,m˙1),…,(tj,m˙j)),y^pj+1:pj+h=OutputResidualBlock(oj)o_j = \mathrm{StackedTransformer}\bigl((t_1, \dot{m}_1), \dots, (t_j, \dot{m}_j)\bigr), \qquad \hat{y}_{pj+1:pj+h} = \mathrm{OutputResidualBlock}(o_j)

Training: predict "the next 128 points" at every position

As with a language model, forecasting is learned at every position of a series simultaneously. With input patches of 32 and output patches of 128, the model learns to predict the next 128 points from the first 32 points, points 65–192 from the first 64 points, points 97–224 from the first 96 points, and so on, all in a single pass. The loss is the average mean squared error:

TrainLoss=1N∑j=1NMSE(y^pj+1:pj+h, ypj+1:pj+h)\mathrm{TrainLoss} = \frac{1}{N} \sum_{j=1}^{N} \mathrm{MSE}\bigl(\hat{y}_{pj+1:pj+h},\ y_{pj+1:pj+h}\bigr)

During training, a random number rr between 00 and p−1p-1 is chosen for each series, and the first rr points are masked. This trains the model to forecast from every context length from 1 point up to the maximum (512), not only multiples of the patch length.

Forecasting: chain output patches autoregressively

  1. From the context window, output the next 128 points y^L+1:L+128\hat{y}_{L+1:L+128}.
  2. Append the 128 forecast points to the input and output the next 128 points.
  3. Repeat until the horizon length HH is reached.

For example, forecasting 256 points ahead from the past 256 points takes 2 autoregressive steps. If output patches were 32, the same as input patches, it would take 8.

Pretraining data and settings

DataGranularityNumber of seriesNumber of points
Wikipedia page viewsHourly, daily, weekly, monthlyAbout 200 millionAbout 375 billion
Google TrendsHourly, daily, weekly, monthly22,435 eachAbout 500 million
Synthetic series (combinations of ARMA, seasonal, trend, and step patterns)―3 millionAbout 6.1 billion
M4, Electricity, Traffic, Weather, Favorita, LibCity10 minutes to 1 yearAbout 220,000About 200 million

Training samples real data 80% and synthetic data 20% of the time, and gives equal weight to four groups of real data: "hourly or finer," "daily," "weekly," and "monthly." The maximum context window is 512 (256 for weekly data and 64 for monthly or coarser data). The 200M-parameter model was trained for 1.5 million steps in 2 days on TPUv5e (16 cores).

Why it works

The paper attributes the model's effectiveness to the following design choices.

Patches as tokens

As in PatchTST, each token is a 32-point patch rather than a single time step's value. Local shapes are captured in the tokens, and the number of tokens drops to 1/32, which also speeds up inference. In experiments varying the input patch length from 8 to 128 (a 70M-parameter model), 16 and 32 were best, and 32 trained almost twice as fast as 16.

A decoder-only form that handles any context length

PatchTST uses an encoder form that reads the whole context window and then outputs the entire horizon at once, so the context and horizon lengths must be fixed at training time. TimesFM, like a language model, "looks up to here and predicts what comes next," so from a single series it can learn forecasting from every context length simultaneously. For a foundation model used zero-shot, users may pass any context length, so this property is important.

Output patches longer than input patches

For long-horizon forecasting, it is known that outputting the entire horizon at once accumulates less error than autoregressive generation one step at a time. In the zero-shot setting, however, the horizon length is not known in advance, so the horizon cannot always be produced in one shot. TimesFM compromises by making output patches relatively long (128) to reduce the number of autoregressive steps. In an experiment forecasting 512 points ahead on ETT, the MAE decreased monotonically as the output patch length grew from 8 to 128.

Synthetic data fills in underrepresented granularities

Most real data consists of hourly or daily series, with relatively few quarterly, yearly, or 10-minute series. Training without synthetic data reduced accuracy on the Monash datasets, which contain many such granularities, and also on the 15-minute ETTm (accuracy was nearly unchanged on the hourly ETTh).

As an analogy, TimesFM is like "a forecaster who has seen a huge number of sales and page-view patterns across many stores, sites, and seasons." Even with data it has never seen, it can apply familiar patterns from experience (daily cycles, weekly cycles, steady growth, etc.) to make forecasts. However, it knows nothing about circumstances specific to that data (such as planned promotions) unless told.

Experimental results

The paper compared zero-shot TimesFM, with no additional training, against models trained on each dataset, using three groups of data not used in pretraining.

Monash (18 datasets) (Geometric mean of the MAE ratio relative to a forecast that repeats the last value; lower is better. Table 4 in the paper's appendix.)

ModelTrainingScaled MAE
TimesFMZero-shot0.6846
N-BEATSTrained per dataset0.7005
FFNN (fully connected network)Trained per dataset0.7044
DeepARTrained per dataset0.7477
CatBoostTrained per dataset0.7733
ETS (exponential smoothing)Trained per dataset0.8104
TransformerTrained per dataset0.8619
WaveNetTrained per dataset0.9384
llmtime (GPT-3)Zero-shot0.9715

TimesFM was the best, and its difference from N-BEATS was not statistically significant. It was more than 25% better than llmtime, which uses a language model directly.

Darts (8 univariate series) (Likewise, the geometric mean of scaled MAE. Table 3 in the paper's appendix.)

llmtime (GPT-3)ARIMATimesFMPatchTSTN-HiTSN-BEATSTCN
0.48820.52190.57670.64580.69360.73160.7946

With only 8 series, it is unclear which model is better. The paper states that TimesFM is not statistically significantly different from the best model, llmtime, or from ARIMA with manually configured seasonality. For llmtime, it cautions that because these datasets appear in many blog posts, they may have been included in the language model's training data.

ETT (4 datasets × horizons of 96 and 192) (Context window of 512. Mean MAE on the last test window. Table 5 in the paper's appendix.)

TimesFM (zero-shot)PatchTST (trained per dataset)FEDformerAutoformerInformerllmtime
0.360.370.530.530.990.45

Zero-shot TimesFM was nearly on par with PatchTST trained on ETT and far ahead of the other long-horizon forecasting models. In a comparison in the appendix, a 200M-parameter PatchTST pretrained on the same data (zero-shot) also scored about the same (0.35), but it was much worse on Monash (1.0557).

Fine-tuning with little data (Using 10% of the ETT training data. MAE. Table 2 in the paper's appendix.)

When only the input and output residual blocks were retrained on 10% of the data, the mean MAE on ETTh1 was 0.426, beating GPT4TS, which applies GPT-2 to time series (0.525), PatchTST (0.542), and DLinear (0.600).

Practical considerations

Keep the following in mind when using TimesFM:

  • It outputs point forecasts only: The paper's model produces point forecasts trained with MSE. If prediction intervals (quantiles) are needed, consider models that output probability distributions, such as Chronos or DeepAR. The paper notes that extending training to a quantile loss is easy but leaves it as future work.
  • Univariate, with no auxiliary features (covariates): Each series is forecast separately, and neither relationships between variables nor auxiliary features such as promotions or holidays are used in pretraining. The paper lists adding covariates to the residual blocks during fine-tuning, among other approaches, as future work.
  • The context window is at most 512 points: Longer histories cannot be used. For weekly and monthly data, the maximum training length is even shorter (256 and 64).
  • Check for overlap between training and evaluation data: Electricity, Traffic, Weather, M4, and others are included in pretraining, so evaluating on them does not give a fair comparison. The paper also excludes them from its zero-shot evaluation.

The paper's model (200M parameters, input patch 32, output patch 128, context window 512) differs in configuration from later public releases. The official repository publishes the weights, and newer versions such as 2.5 and 3.0 have been released; 3.0 is described as supporting multivariate forecasting and covariates. When using it, check which version's weights and settings you are using.

Comparison with other models

Pretrained models for time-series forecasting and models trained per dataset compare as follows from the same perspectives:

ModelInput representationHow the horizon is producedOutputTraining
TimesFM32-point patches embedded with a residual block128-point output patches chained autoregressivelyPoint forecastPretrained on hundreds of billions of points (decoder-only)
ChronosValues quantized into tokensAutoregressive, one token at a timeProbability distribution (sample paths)Pretrained in the form of a language model (T5)
TTMSplit into patches and mixed with MLPsAll at oncePoint forecastA small pretrained model
PatchTSTPatches embedded with a linear layer (per variable)All at once (flatten + linear layer)Point forecastTrained per dataset (self-supervised pretraining also possible)
DeepARValue at each time step plus auxiliary featuresAutoregressive, one step at a timeProbability distributionTrained per dataset
N-BEATSWhole context window read by fully connected layersAll at oncePoint forecastTrained per dataset

Rough guidelines for choosing:

  • No or little training data, or so many series that training each one is impractical: A zero-shot foundation model like TimesFM is a good fit.
  • Forecast uncertainty (intervals) is also needed: Chronos, which outputs probability distributions, is a candidate.
  • Compute must be kept low: Also compare small pretrained models like TTM and simple baselines like DLinear.
  • Enough data to train on, and auxiliary features to use: Per-dataset models such as DeepAR or extended versions of TSMixer (Google) are a good fit.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn

"""
A small implementation of the TimesFM architecture (following Section 4, Eqs. 2–5, and Appendix A.6 of arXiv:2310.10688)
Univariate series y: [batch B, context window L] (L is assumed to be a multiple of the input patch length p)
For real use, use the official implementation (google-research/timesfm) and the released weights
"""


class ResidualBlock(nn.Module):
  """MLP with one hidden layer + residual connection (used for both input and output; the activation is an example)"""

  def __init__(self, d_in, d_hidden, d_out):
    super().__init__()
    self.mlp = nn.Sequential(nn.Linear(d_in, d_hidden), nn.SiLU(), nn.Linear(d_hidden, d_out))
    self.skip = nn.Linear(d_in, d_out)

  def forward(self, x):
    return self.mlp(x) + self.skip(x)


def sinusoidal(n, d):
  pos = torch.arange(n).unsqueeze(1)
  div = torch.exp(torch.arange(0, d, 2) * (-math.log(10000.0) / d))
  pe = torch.zeros(n, d)
  pe[:, 0::2], pe[:, 1::2] = torch.sin(pos * div), torch.cos(pos * div)
  return pe


class TinyTimesFM(nn.Module):
  def __init__(self, p=32, h=128, d_model=256, n_heads=4, n_layers=4, dropout=0.2):
    super().__init__()
    self.p, self.h, self.d_model = p, h, d_model
    self.inp = ResidualBlock(2 * p, d_model, d_model)         # Patch (values + mask) → token
    layer = nn.TransformerEncoderLayer(d_model, n_heads, dim_feedforward=d_model, dropout=dropout,
                                       batch_first=True, norm_first=True)  # Layer details are an example
    self.stack = nn.TransformerEncoder(layer, n_layers)       # Add a causal mask to make it decoder-only
    self.out = ResidualBlock(d_model, d_model, h)             # Output token → next h points

  def forward(self, y, mask):                                 # y, mask: [B, L] (mask = 1 marks points to ignore)
    B, L = y.shape
    n = L // self.p
    yp = (y * (1 - mask)).reshape(B, n, self.p)
    mp = mask.reshape(B, n, self.p)
    t = self.inp(torch.cat([yp, mp], dim=-1)) + sinusoidal(n, self.d_model).to(y)
    causal = torch.triu(torch.ones(n, n, dtype=torch.bool, device=y.device), diagonal=1)
    o = self.stack(t, mask=causal)                            # Each token attends only to earlier tokens
    return self.out(o)                                        # [B, n, h]: forecast of the h points right after the j-th patch


def normalize(y, p):
  """Standardize the scale with the mean and std of the first input patch"""
  mu = y[:, :p].mean(dim=1, keepdim=True)
  sd = y[:, :p].std(dim=1, keepdim=True) + 1e-5
  return (y - mu) / sd, mu, sd


model = TinyTimesFM()
optimizer = torch.optim.AdamW(model.parameters(), lr=5e-4)

# Training: predict the next h points at every patch position (Eq. 5)
series = torch.randn(16, 512 + 128)                          # 512 past points + 128 points for targets
y, mu, sd = normalize(series, model.p)
ctx = y[:, :512]
mask = torch.zeros_like(ctx)
r = torch.randint(0, model.p, (16,))                          # Mask the first r points of each series
mask[torch.arange(512).unsqueeze(0) < r.unsqueeze(1)] = 1
model.train()
pred = model(ctx, mask)                                       # [16, 16, 128]
target = torch.stack([y[:, (j + 1) * 32:(j + 1) * 32 + 128] for j in range(16)], dim=1)
loss = ((pred - target) ** 2).mean()
optimizer.zero_grad()
loss.backward()
optimizer.step()

# Forecasting: use the last output patch as the horizon; if too short, append the forecast and repeat
model.eval()
with torch.no_grad():
  ctx_eval, mask_eval = ctx[:, -256:], torch.zeros(16, 256)
  outs = []
  for _ in range(2):                                          # 128 points × 2 steps = 256 points ahead
    step = model(ctx_eval, mask_eval)[:, -1]                  # [16, 128]
    outs.append(step)
    ctx_eval = torch.cat([ctx_eval, step], dim=1)[:, -512:]
    mask_eval = torch.zeros_like(ctx_eval)
  forecast = torch.cat(outs, dim=1) * sd + mu                 # Restore the original scale [16, 256]

FAQ

Q. How does it differ from Chronos?
A.

Both are zero-shot forecasting models pretrained on large amounts of time-series data, but they handle inputs and outputs differently. Chronos quantizes values into language-model tokens and samples one token at a time to produce probabilistic forecasts. TimesFM embeds 32-point patches as continuous values and is a point-forecast model that outputs 128-point output patches at once.

Q. Can it be used for multivariate time series?
A.

The paper's model is univariate; multivariate series are forecast one series at a time, and relationships between variables are not used. The official repository states that a later version (3.0) supports multivariate forecasting and covariates, so check the version if you want to use relationships between variables.

Q. What if zero-shot accuracy is not good enough?
A.

You can fine-tune it on your data. In the paper's appendix, retraining only the input and output residual blocks on just 10% of the ETT training data beat PatchTST, DLinear, GPT4TS, and others trained on the same 10%. Changing the context window length is another easy adjustment to try.

References

  1. Das, A., Kong, W., Sen, R., & Zhou, Y. (2024). A decoder-only foundation model for time-series forecasting. ICML 2024.
  2. google-research/timesfm (official implementation and released weights)
  3. Nie, Y., Nguyen, N. H., Sinthong, P., & Kalagnanam, J. (2023). A Time Series is Worth 64 Words: Long-term Forecasting with Transformers. ICLR 2023.
  4. Ansari, A. F., Stella, L., Turkmen, C., et al. (2024). Chronos: Learning the Language of Time Series. TMLR.