AI Logic

Architectures

TSMixer (Google)

Updated:

Architecture of TSMixer (Google). Left: the overall flow from a multivariate time series to the forecast. Right: inside a Mixer layer (time mixing and feature mixing) and the structure of the MLPs within it.

Background and Overview

TSMixer (Google) is an all-MLP model that takes a multivariate time series as a "time Γ— variable" table and forecasts future values by alternately applying an MLP that mixes along the time axis and an MLP that mixes along the variable (feature) axis. It was presented in 2023 by Chen, Li, Yoder, ArΔ±k, and Pfister of Google Cloud AI Research in "TSMixer: An All-MLP Architecture for Time Series Forecasting" and published in TMLR.

In the same year, 2023, Ekambaram et al. at IBM also presented a different model with the same name, TSMixer (IBM) (KDD 2023). The Google version mixes along two directions, "time" and "variable", without splitting the series into patches, whereas the IBM version splits the series into patches and then mixes "across patches" and "within patches" (and optionally "across variables"). When a paper or library says TSMixer, check which one it means.

The starting point of this paper is a reversal that had occurred in time series forecasting. Simple linear models that handle each variable separately (such as DLinear) had been shown to be more accurate on commonly used benchmarks than multivariate Transformers that can also model relations between variables, such as Informer, Autoformer, and FEDformer. The paper poses two questions: does cross-variate information really help, and can a multivariate model avoid losing to univariate models even when it does not?

TSMixer is the answer. The idea has two stages:

  1. Keep the strength of linear models: A fully connected layer along the time axis is exactly a linear model that multiplies each past time step by a fixed weight and sums. Nonlinear activation functions and residual connections are added, and the layers are stacked.
  2. Also make cross-variate information usable: MLPs along the variable axis are inserted between the MLPs along the time axis. When they do not help, the residual connections let the input pass through.

It replaces the alternating mixing of "patches" and "channels" in the image model MLP-Mixer with "time steps" and "variables".

Architecture

The input is a table X∈RLΓ—CX \in \mathbb{R}^{L \times C} of CC variables over the past LL steps (rows are time steps, columns are variables). The output is a table Y^∈RTΓ—C\hat{Y} \in \mathbb{R}^{T \times C} for the next TT steps. The left of the figure at the top of the article shows the overall flow, and the right shows the inside of one Mixer layer.

The flow of information is as follows.

  1. Normalize: On long-term forecasting benchmarks, reversible instance normalization (RevIN) is applied, subtracting the mean and dividing by the standard deviation per input window and per variable. The inverse transform is applied to the output to restore the original scale.
  2. Mix along time (Time Mixing): The whole table is normalized and transposed, and the same fully connected layer (L→LL \to L), ReLU, and dropout are applied to each variable's column of length LL. The result is transposed back and the input is added (residual connection).
    • The weights of the fully connected layer are shared across all variables. They learn relations between time steps (periodicity and trends).
  3. Mix along features (Feature Mixing): The whole table is normalized again, the same two-layer MLP (C→H→CC \to H \to C) is applied to each time step's row of length CC, and the input is added.
    • The weights of the MLP are shared across all time steps. They learn relations between variables.
  4. Repeat: NN Mixer layers, each combining steps 2–3, are stacked. The table keeps the shape [LΓ—C][L \times C].
  5. Change to the forecast length (Temporal Projection): Finally, a single fully connected layer along the time axis changes the length from LL to TT. This is the same computation as a simple linear model.

In the equations of Appendix B.3 of the paper, temporal projection and time mixing are written as follows (Xβˆ—,iX_{*,i} is the column of the ii-th variable, Οƒ\sigma is the activation function, Drop\mathrm{Drop} is dropout, and Norm\mathrm{Norm} is normalization over the whole table).

TPLβ†’T(X)βˆ—,i=W1Xβˆ—,i+b1,TM(X)βˆ—,i=Norm(Xβˆ—,i+Drop(Οƒ(TPLβ†’L(X)βˆ—,i)))\mathrm{TP}_{L \to T}(X)_{*,i} = W_1 X_{*,i} + b_1, \qquad \mathrm{TM}(X)_{*,i} = \mathrm{Norm}\bigl(X_{*,i} + \mathrm{Drop}(\sigma(\mathrm{TP}_{L \to L}(X)_{*,i}))\bigr)

Feature mixing is a two-layer residual MLP applied to each time step's row Xj,βˆ—X_{j,*}.

Uj,βˆ—=Drop(Οƒ(W2Xj,βˆ—+b2)),FM(X)j,βˆ—=Norm(Xj,βˆ—+Drop(W3Uj,βˆ—+b3))U_{j,*} = \mathrm{Drop}(\sigma(W_2 X_{j,*} + b_2)), \qquad \mathrm{FM}(X)_{j,*} = \mathrm{Norm}\bigl(X_{j,*} + \mathrm{Drop}(W_3 U_{j,*} + b_3)\bigr)

The equations above apply normalization after the residual (post-norm), but the paper states that for the long-term forecasting models it switched to applying normalization first (pre-norm) to preserve the scale of the input. The figure at the top and the official implementation use the pre-norm form.

Differences from MLP-Mixer

The structure closely resembles MLP-Mixer, but the paper lists the following differences (Section 4.3).

  • The two mixing directions: MLP-Mixer mixes "patches" and "features"; TSMixer mixes "time steps" and "variables".
  • Normalization axes: To preserve temporal information, batch normalization (or layer normalization) is applied across both time steps and variables (in 2D), not only along the variable axis.
  • Number of layers in the temporal MLP: Based on the analysis that linear models alone are strong, the temporal MLP has 1 layer, while the feature MLP has 2 layers, as in Transformers.

Variants for comparison and extensions

  • TMix-Only: A univariate model that removes feature mixing and stacks only time mixing. It is used to measure how much cross-variate information helps.
  • TSMixer-Ext: An extension that also takes static features such as store location and features known into the future such as planned promotions. Inputs of different lengths are aligned to the same shape [TΓ—H][T \times H] via temporal projection and feature mixing, concatenated, and mixed with Mixer layers. For M5, normalization is changed to post-norm layer normalization, and the model outputs the parameters of a negative binomial distribution.

Why It Works

The paper attributes the strength of linear models in time series forecasting to their weights being determined by time-step position (Chapter 3).

For each time step to forecast, a linear model multiplies each past time step by a fixed weight and sums (Y^=AXβŠ•b\hat{Y} = AX \oplus b, A∈RTΓ—LA \in \mathbb{R}^{T \times L}). For example, a series with period PP, x(t)=x(tβˆ’P)x(t) = x(t-P) (P<LP < L), can be forecast exactly with the following weights.

Aij={1(j=Lβˆ’P+(iβ€Šmodβ€ŠP))0(otherwise),bi=0A_{ij} = \begin{cases} 1 & (j = L - P + (i \bmod P)) \\ 0 & (\text{otherwise}) \end{cases}, \qquad b_i = 0

In other words, the weights "copy the value at the same position one period earlier". The paper further shows that for series expressible as the sum of periodic components and a smooth trend, there exists a linear model with a bounded error when the input length satisfies Lβ‰₯P+1L \geq P + 1 (Theorem 3.1).

In contrast, the gates of an LSTM and the attention of a Transformer are mechanisms whose weights change depending on the input values. They are highly expressive, but the paper explains that learning "weights determined only by position" from data is difficult for them, and they tend to overfit.

TSMixer exploits this property as follows.

  • The temporal direction keeps the form of a linear model: The fully connected layer along the time axis provides "position-determined weights" shared across all variables. The final temporal projection is also the same computation as a linear model.
  • It can pass through when extra mixing is unhelpful: Thanks to the residual connections, on data where feature mixing does not help, its output can be made small so the model behaves close to a linear model.
  • Parameters grow slowly: Because time steps and variables are mixed by separate MLPs, parameters grow as O(L+C)O(L + C). Handling the whole table with a single fully connected layer would be O(LC)O(LC). This makes the model less prone to overfitting even with long input windows.

As an analogy, the temporal MLP learns calendar rules such as "every Monday is close to last Monday", while the feature MLP learns relations between items such as "sales rise on days with a price cut". Applying the two alternately lets the model combine both kinds of rules.

Experimental Results

Long-term forecasting benchmarks (input length L=512L = 512, MSE, lower is better; excerpt from Table 3 of the paper)

Seven datasets were used for evaluation, ETT (ETTh1, ETTh2, ETTm1, ETTm2), Weather, Electricity, and Traffic, with the forecast length TT varied from 96 to 720. The values for FEDformer, Autoformer, Informer, and PatchTST are quoted from the PatchTST paper.

DataTTTSMixerTMix-OnlyLinear modelPatchTSTFEDformerAutoformerInformer
ETTh1960.3610.3590.3680.3700.3760.4350.941
ETTh17200.4630.4530.4810.4470.4690.5151.144
ETTm2960.1630.1620.1700.1660.1800.2050.355
ETTm27200.4200.3580.4350.3620.4100.4143.001
Weather960.1450.1450.1700.1490.2380.2490.354
Electricity960.1310.1320.1350.1290.1860.1960.304
Traffic960.3760.3700.3950.3600.5760.5970.733

Averaged over the whole table, TSMixer's MSE was 62.40% lower than Informer, 24.51% lower than Autoformer, 16.69% lower than FEDformer, and 6.77% lower than the linear model, and nearly the same as PatchTST (βˆ’1.53%) and TMix-Only (βˆ’0.66%). The paper states that while other multivariate models lost badly to univariate models, TSMixer was the only multivariate model that matched the best univariate models.

On the other hand, there is almost no difference between TSMixer and TMix-Only. From this, the paper concludes that on these benchmarks cross-variate information is not very helpful.

Retail demand forecasting M5 (sales of 30,490 Walmart series; WRMSSE, lower is better; mean over 5 random seeds; Tables 4 and 5 of the paper)

ModelMultivariateAuxiliary featuresTest WRMSSE
Linear model――0.983
PatchTST――0.976
TMix-Only――0.960
Autoformerβœ“β€•0.742
FEDformerβœ“β€•0.804
TSMixerβœ“β€•0.737
DeepARβœ“Static, future-known0.789
TFTβœ“Static, future-known0.670
TSMixer-Extβœ“Static, future-known0.640

On M5, multivariate models greatly outperformed univariate models. This shows that on data where relations between variables (such as prices) matter, TSMixer can take advantage of them. TSMixer-Ext, with auxiliary features added, outperformed DeepAR (Amazon SageMaker) and TFT (Google Cloud Vertex), which are widely used in industry.

Computational cost (M5, one V100; Table 6 of the paper)

TSMixer has 189K parameters, far fewer than FEDformer (1.7M) or TFT (2.9M), and its inference ran at 96 steps per second, close to the linear model (110).

Practical Considerations

Keep the following points in mind when using TSMixer (Google).

  • On data with weak cross-variate relations, it only matches univariate models: On long-term forecasting benchmarks such as ETT, its accuracy was almost the same as TMix-Only, which removes feature mixing. The benefit of being multivariate appears when, as in M5, the relations between variables or the auxiliary features carry predictive cues.
  • Choose the normalization to suit the data: The paper used 2D batch normalization on the long-term forecasting benchmarks, and post-norm layer normalization on M5, where batch statistics are unstable unless the batch is large. Pre-norm is reported to produce NaN when input values are very large.
  • Use a fairly long input window: In the paper's experiments, the linear model improved substantially when the input length was extended from 96 to 336, while TSMixer was best at 336 or 512 and stayed about the same at 720. Many Transformer-based models are said to overfit with windows longer than 192.
  • Small datasets need strong regularization: The dropout rates selected on the long-term forecasting benchmarks were often 0.7–0.9, and the number of blocks varied widely from 1 to 8 depending on the dataset (Table 8 of the paper). Per-dataset tuning is required.
  • The forecast length is built into the model: Because the final temporal projection has Lβ†’TL \to T weights, the model must be retrained when the input length LL or the forecast length TT changes.
  • No built-in PyTorch version: The official implementation is in TensorFlow (Keras). The structure is simple, so it can be written in a few dozen lines, as in the implementation example below.

TSMixer (Google) assumes that the past values of the series to be forecast are included in the input (Cy≀CxC_y \leq C_x in the paper's notation). It cannot be used as is for regression that estimates the target from other variables alone without its past values.

Comparison with Other Models

Lining up MLP-based and Transformer-based models commonly used for time series forecasting from the same viewpoints gives the following.

ModelTemporal handlingCross-variate relationsCore componentAuxiliary features
DLinearLinear weights per time step (decomposed into trend and seasonal)Not used (each variable independent)Linear layerNot used
PatchTSTSelf-attention over patchesNot used (each variable independent)TransformerNot used
TSMixer (Google)MLP over time steps (no patches)Mixed by a feature-wise MLPMLPUsed in the extended version (TSMixer-Ext)
TSMixer (IBM)Split into patches; inter-patch and intra-patch MLPsCorrected in the prediction head (optionally also mixed in the backbone)MLP + gated attentionNot used
TTMTSMixer (IBM) stacked at multiple resolutionsOptional exogenous mixerSmall pretrained MLPExogenous variables optional
MLP-Mixer(Image model; mixes across patches)(Mixes channels)MLP―

Rough guidelines for choosing:

  • To build a strong baseline quickly: A univariate model such as DLinear or TMix-Only is often sufficient.
  • When relations between variables or auxiliary features such as promotions and stores help forecasting: TSMixer (Google), especially TSMixer-Ext, is a good fit.
  • To handle long inputs with little computation: TSMixer (IBM) or PatchTST, which shorten the input by splitting it into patches, are a good fit.
  • When training data is scarce and a pretrained model is preferred: A small pretrained model such as TTM is a candidate.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small implementation of TSMixer (Google) (following Figure 1 and Appendix B.3 of arXiv:2303.06053, and
res_block in the official TensorFlow implementation tsmixer_basic/models/tsmixer.py)
Input x: [batch, input length L, number of variables C] -> output: [batch, forecast length T, number of variables C]
"""


class RevIN(nn.Module):
  """Per-window, per-variable normalization and its inverse (Kim et al. 2022, with learnable scale and shift)"""

  def __init__(self, n_vars, eps=1e-5):
    super().__init__()
    self.eps = eps
    self.weight = nn.Parameter(torch.ones(n_vars))
    self.bias = nn.Parameter(torch.zeros(n_vars))

  def normalize(self, x):                       # x: [B, L, C]
    self.mean = x.mean(dim=1, keepdim=True).detach()
    self.std = torch.sqrt(x.var(dim=1, keepdim=True, unbiased=False) + self.eps).detach()
    return (x - self.mean) / self.std * self.weight + self.bias

  def denormalize(self, y):                     # y: [B, T, C]
    y = (y - self.bias) / (self.weight + self.eps)
    return y * self.std + self.mean


class Norm2D(nn.Module):
  """2D normalization spanning both time steps and variables.
  'B': mean and variance over the batch for each (time step, variable) element (same as Keras BatchNormalization(axis=[-2, -1]))
  'L': mean and variance over the whole table [L x C] of one window"""

  def __init__(self, seq_len, n_vars, norm_type="B"):
    super().__init__()
    self.norm_type = norm_type
    if norm_type == "B":
      self.norm = nn.BatchNorm1d(seq_len * n_vars)
    else:
      self.norm = nn.LayerNorm([seq_len, n_vars])

  def forward(self, x):                         # x: [B, L, C]
    if self.norm_type == "B":
      b, l, c = x.shape
      return self.norm(x.reshape(b, l * c)).reshape(b, l, c)
    return self.norm(x)


class MixerLayer(nn.Module):
  def __init__(self, seq_len, n_vars, ff_dim, dropout, norm_type="B"):
    super().__init__()
    # Time mixing: FC layer (L -> L) -> ReLU -> dropout. Weights shared across all variables
    self.time_norm = Norm2D(seq_len, n_vars, norm_type)
    self.time_fc = nn.Linear(seq_len, seq_len)
    # Feature mixing: FC layer (C -> H) -> ReLU -> dropout -> FC layer (H -> C) -> dropout. Weights shared across all time steps
    self.feat_norm = Norm2D(seq_len, n_vars, norm_type)
    self.feat_fc1 = nn.Linear(n_vars, ff_dim)
    self.feat_fc2 = nn.Linear(ff_dim, n_vars)
    self.dropout = nn.Dropout(dropout)

  def forward(self, x):                         # x: [B, L, C]
    # Time mixing (pre-norm -> transpose -> MLP_time -> transpose -> residual)
    y = self.time_norm(x).transpose(1, 2)       # [B, C, L]
    y = torch.relu(self.time_fc(y)).transpose(1, 2)
    x = x + self.dropout(y)
    # Feature mixing (pre-norm -> MLP_feat -> residual)
    y = self.feat_norm(x)
    y = self.dropout(torch.relu(self.feat_fc1(y)))
    y = self.dropout(self.feat_fc2(y))
    return x + y


class TSMixer(nn.Module):
  def __init__(self, seq_len=512, pred_len=96, n_vars=7, n_block=2, ff_dim=64, dropout=0.7, norm_type="B"):
    super().__init__()
    self.revin = RevIN(n_vars)
    self.blocks = nn.ModuleList(
      [MixerLayer(seq_len, n_vars, ff_dim, dropout, norm_type) for _ in range(n_block)]
    )
    self.temporal_projection = nn.Linear(seq_len, pred_len)  # temporal projection (L -> T), shared across all variables

  def forward(self, x):                         # x: [B, L, C]
    x = self.revin.normalize(x)
    for block in self.blocks:
      x = block(x)
    y = self.temporal_projection(x.transpose(1, 2)).transpose(1, 2)  # [B, T, C]
    return self.revin.denormalize(y)


# Usage (7 variables as in ETTh1; forecast the next 96 steps from the past 512 steps)
model = TSMixer(seq_len=512, pred_len=96, n_vars=7)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
criterion = nn.MSELoss()                        # the paper minimizes MSE

x = torch.randn(32, 512, 7)                     # past window
y = torch.randn(32, 96, 7)                      # targets (future values)

model.train()                                   # training: dropout is active, batch norm uses batch statistics
optimizer.zero_grad()
loss = criterion(model(x), y)
loss.backward()
optimizer.step()

model.eval()                                    # inference: dropout off, batch norm uses statistics accumulated during training
with torch.no_grad():
  pred = model(x)                               # [32, 96, 7]

FAQ

Q. How do TSMixer (Google) and TSMixer (IBM) differ?
A.

They are different models with the same name, presented in the same year by different teams. The Google version (Chen et al., TMLR 2023) does not split the series into patches and alternately mixes with MLPs along two directions, time and variable. The IBM version (Ekambaram et al., KDD 2023) splits the series into patches, mixes across patches and within patches, and mainly corrects for relations between variables in the prediction head.

Q. Can it be used for a time series with only one variable?
A.

Yes. However, with C=1C = 1 feature mixing is meaningless, so it becomes almost the same as TMix-Only, which stacks only time mixing. On the paper's benchmarks, TMix-Only was also about as accurate as PatchTST.

Q. What advantages does it have over Transformer-based models?
A.

Fewer parameters and faster inference. On M5, TSMixer has 189K parameters, less than one-fifteenth of TFT (2.9M), and its inference speed was close to that of a simple linear model. It is also reported to be less prone to overfitting with long input windows and to maintain accuracy more easily when the input is extended.

References

  1. Chen, S.-A., Li, C.-L., Yoder, N. C., ArΔ±k, S. Γ–., & Pfister, T. (2023). TSMixer: An All-MLP Architecture for Time Series Forecasting. Transactions on Machine Learning Research (09/2023).
  2. google-research/tsmixer (official implementation, TensorFlow)
  3. Ekambaram, V., Jati, A., Nguyen, N., Sinthong, P., & Kalagnanam, J. (2023). TSMixer: Lightweight MLP-Mixer Model for Multivariate Time Series Forecasting. KDD 2023.
  4. Tolstikhin, I., Houlsby, N., Kolesnikov, A., et al. (2021). MLP-Mixer: An all-MLP Architecture for Vision. NeurIPS 2021.
  5. Zeng, A., Chen, M., Zhang, L., & Xu, Q. (2023). Are Transformers Effective for Time Series Forecasting? AAAI 2023.
  6. Nie, Y., Nguyen, N. H., Sinthong, P., & Kalagnanam, J. (2023). A Time Series is Worth 64 Words: Long-term Forecasting with Transformers. ICLR 2023.
  7. Kim, T., Kim, J., Tae, Y., Park, C., Choi, J.-H., & Choo, J. (2022). Reversible Instance Normalization for Accurate Time-Series Forecasting against Distribution Shift. ICLR 2022 (official implementation).