AI Logic

Architectures

TSMixer (IBM)

Updated:

Architecture of TSMixer (IBM). Left: the overall flow from a multivariate time series to the forecast. Right: inside an MLP mixer layer (the three mixers, inter-patch, intra-patch, and inter-channel, and the internals shared by each mixer).

Background and Overview

TSMixer (IBM) is an all-MLP model that splits a time series into patches (short segments) and forecasts future values by alternately applying an MLP that mixes across patches and an MLP that mixes features within each patch. It was presented in 2023 by Ekambaram, Jati, Nguyen, Sinthong, and Kalagnanam of IBM Research in "TSMixer: Lightweight MLP-Mixer Model for Multivariate Time Series Forecasting" and accepted at KDD 2023. An implementation is available in Hugging Face transformers under the name PatchTSMixer.

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

At the time, PatchTST, which splits a time series into patches and feeds them to a Transformer, was a strong baseline for time series forecasting. However, PatchTST internally uses computationally heavy multi-head self-attention. Meanwhile, in vision, MLP-Mixer had achieved accuracy close to Transformers without self-attention.

The paper shows that applying MLP-Mixer to time series as is does not yield a strong model, and then adds the following design choices.

  • Patching and channel independence: As in PatchTST, the series is split into patches, and the same weights are used for every variable (a "channel" in the paper's terms).
  • Gated attention: A simple gate that amplifies important features and suppresses unneeded ones is attached after the MLP of each mixer.
  • Heads that reconcile the forecast: Two kinds of heads (online reconciliation heads) can be attached that correct the forecast during training using relations between variables and relations among values aggregated per patch.

With this design, it achieved 1–2% better accuracy than PatchTST with one-half to one-third of the training time and memory. The same team later presented TTM, a small pretrained model built from TSMixer components.

Architecture

The input is a time series of length slsl with cc variables (channels). The output is the forecast for the next flfl steps. The left of the figure at the top of the article shows the overall flow, and the right shows the inside of one MLP mixer layer (Figures 1 and 2 of the paper).

The flow of information is as follows.

  1. Normalize: Reversible instance normalization (RevIN), which subtracts the mean and divides by the standard deviation per input window and per variable, is applied. This addresses distribution shift over time.
  2. Split into patches: For each variable, patches of length plpl are extracted with stride ss. The number of patches is n=⌊(slβˆ’pl)/sβŒ‹+1n = \lfloor (sl - pl)/s \rfloor + 1.
    • The input length becomes roughly 1/s1/s, which lightens computation.
  3. Embed patches: Each patch is mapped to an hfhf-dimensional vector by a fully connected layer. The shape is [cΓ—nΓ—hf][c \times n \times hf].
  4. Stack mixer layers: nlnl MLP mixer layers are stacked. Weights are shared across all variables (channel independence). Within one layer, mixing proceeds in the following order.
    • Inter-patch mixer: An MLP is applied along the patch axis (length nn), mixing relations between patches.
    • Intra-patch mixer: An MLP is applied along the feature axis (length hfhf), mixing features within a single patch.
    • Inter-channel mixer (optional): An MLP is applied along the variable axis (length cc), mixing relations between variables. The version with this layer is called IC-TSMixer.
  5. Forecast: The features of all patches are flattened and concatenated, and dropout and a fully connected layer produce a forecast of length flfl. Finally, the normalization is reversed.

Inside each mixer

The three mixers differ only in the axis they mix; their internals are shared (bottom right of the figure at the top).

  1. Apply layer normalization to the input.
  2. Rearrange so that the axis to be mixed comes last, and apply a two-layer MLP (fully connected layer β†’ GELU and dropout β†’ fully connected layer β†’ dropout). The hidden dimension is expanded to a multiple of the input dimension.
  3. Apply gated attention, restore the original arrangement, and add the input (residual connection).

Gated attention

Gated attention creates per-feature weights with a fully connected layer AA and softmax, and multiplies them element-wise with the features (Section 3.3.5 of the paper). XMX^M is the output of the MLP.

WA=softmax(A(XM)),XG=WAβ‹…XMW^A = \mathrm{softmax}\bigl(A(X^M)\bigr), \qquad X^G = W^A \cdot X^M

Unlike Transformer self-attention, it does not compute relations between tokens; it is a lightweight gate that only decides which features within a single vector to pass and which to suppress.

Two reconciliation heads (optional)

The following heads can be attached after the prediction head to correct the forecast (Section 3.3.7 of the paper).

  • Cross-channel reconciliation head: The forecast at a time step is flattened across all variables together with the forecasts at neighboring time steps (context length clcl), and corrected with gated attention and a fully connected layer. This is a "hybrid" design in which the backbone stays channel-independent and only the head handles relations between variables.
  • Hierarchical patch reconciliation head: It also forecasts the per-patch sums of the forecast and corrects the fine-grained forecast so that it does not contradict the patch-level forecast. The loss adds, to the error of the fine-grained forecast, the patch-level error and the discrepancy between the summed fine-grained forecast and the patch-level forecast.

Pretraining is also possible

By swapping only the head, the model can also be used for self-supervised learning. As in BERT's masked language modeling, part of the input patches is masked and the model is trained to reconstruct the masked patches (pretraining); then a forecasting head is attached and the model is fine-tuned.

Why It Works

From the paper's comparisons, the effective components can be summarized as follows.

  • Channel independence helps a lot: CI-TSMixer, which uses the same weights for each variable, had on average 9.5% lower MSE than V-TSMixer, which flattens and mixes all variables together as in MLP-Mixer (ETTh1, ETTm1, Weather; Table 4 of the paper). The paper explains that mixing variables together lets "noise" from weakly related variables mix in at the first layer, which cannot be untangled at the output.
  • Relations between variables are more stable when handled in the head: Keeping the backbone independent and attaching a cross-channel reconciliation head was more accurate than IC-TSMixer, which mixes variables inside the backbone (Table 5 of the paper). Because the backbone does not depend on the number of variables, there is also the advantage of being able to pretrain on multiple datasets with different numbers of variables.
  • Combining gating and hierarchical reconciliation gives stable gains: Adding both gated attention (G) and the hierarchical patch reconciliation head (H) to CI-TSMixer improved on V-TSMixer by 11.5% in total. Adding both was more stable than adding only one.
  • No self-attention makes it light: Patching shortens the input, and the absence of computationally heavy self-attention greatly reduces computation, parameters, and memory compared with PatchTST.

MLP-Mixer's two operations, "mixing across patches" and "mixing within a patch", correspond in time series to "relations between distant segments (periodicity and trends)" and "the shape within a short segment". The paper also notes that MLP-Mixer preserves the order of the input, so unlike self-attention it does not lose positional information, which makes it well suited to time series.

Experimental Results

Supervised long-term forecasting (input length 512, MSE, lower is better; excerpt from Table 2 of the paper)

Seven datasets were used for evaluation: ETT (ETTh1, ETTh2, ETTm1, ETTm2), Weather, Electricity, and Traffic. CI-TSMixer-Best is the better of CI-TSMixer(G,H) and CI-TSMixer(G,H,CC). The PatchTST values are quoted from the PatchTST paper, and the values of the other methods from the DLinear paper.

DataForecast lengthCI-TSMixer-BestPatchTSTDLinearFEDformerAutoformerInformer
ETTh1960.3680.3700.3750.3760.4490.865
ETTh17200.4440.4470.4720.5060.5141.181
ETTm2960.1640.1660.1670.2030.2550.365
Weather960.1460.1490.1760.2170.2660.300
Electricity960.1290.1290.1400.1930.2010.274
Traffic960.3560.3600.4100.5870.6130.719

Over the whole table, the MSE improvement was 8% over DLinear, 1% over PatchTST, 23% over FEDformer, 30% over Autoformer, and 64% over Informer.

Computational cost (forecast length 96, average over Electricity, Traffic, and Weather; Table 3 of the paper)

MetricCI-TSMixer vs. PatchTSTCI-TSMixer(G,H) vs. PatchTST
Multiply-accumulate operationsAbout 1/4About 1/3.2
Number of parametersAbout 1/3.4About 1/2.9
Time per epochAbout 1/2About 1/1.6
Peak GPU memoryAbout 1/2.7About 1/2.1

Attaching the cross-channel reconciliation head increases parameters in proportion to the number of variables (9.33M for the 862 variables of Traffic). However, only the head grows, so computation and training time stayed at one-half to one-third of PatchTST.

Self-supervised pretraining (Tables 6 and 7 of the paper)

After pretraining by masking and reconstructing patches and then fine-tuning for forecasting, the MSE on ETTh1 and Weather was 54–76% lower than other self-supervised methods (BTSF, TNC, TS-TCC, CPC) and 2.3% lower than self-supervised PatchTST. Transfer learning, pretraining on other data and transferring, was also tried, but it is reported that the gains were not as large as in vision or language.

Practical Considerations

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

  • On small datasets, reduce layers and increase dropout: The paper's default settings are input length 512, patch length 16, stride 8, 8 mixer layers, hf=32hf = 32, and dropout 0.1. On the small ETT datasets, 3 layers and dropout 0.7 are used to avoid overfitting.
  • Do not overlap patches during pretraining: In pretraining that masks and reconstructs patches, the patch length and stride are set equal (8 and 8 in the paper) so that masked parts cannot be seen from neighboring patches.
  • The cross-channel reconciliation head's parameters grow with the number of variables: On data with hundreds of variables, the head's parameters become large. The context length clcl also needs to be chosen for the data (the paper chose from 1 to 5).
  • The input and forecast lengths are built into the model: The inter-patch mixer weights are nΓ—nn \times n and the prediction head weights are determined by the forecast length, so the model must be retrained when the lengths change.
  • A Hugging Face implementation is available: It can be used via PatchTSMixerForPrediction in transformers. When the config's mode is "common_channel" it is channel-independent, and when it is "mix_channel" it uses the inter-channel mixer.

TSMixer (IBM) is a model that takes the past values of the series to be forecast as input and predicts what comes next. It cannot be used as is for regression that estimates the target from other variables alone without using 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.

ModelInput unitTemporal mixingCross-variate relationsComputational cost
PatchTSTPatchSelf-attentionNot used (each variable independent)Heavy (quadratic in the number of patches)
TSMixer (IBM)PatchInter-patch and intra-patch MLPs + gated attentionCorrected by reconciliation heads (optionally also mixed in the backbone)Light
TSMixer (Google)Time step (no patches)MLP over time stepsMixed by a feature-wise MLPLight
DLinearTime stepLinear layer (decomposed into trend and seasonal)Not usedVery light
TTMPatch (multiple stages at different resolutions)TSMixer (IBM) blocksOptional exogenous mixerLight (pretrained)

Rough guidelines for choosing:

  • To match PatchTST's accuracy with less computation: TSMixer (IBM) is a good fit.
  • When relations between variables or auxiliary features such as promotions and stores matter strongly: The extended version of TSMixer (Google), which centers on feature-wise mixing and can also handle auxiliary features, is a candidate.
  • When training data is scarce: TTM, pretrained with TSMixer (IBM) as a building block, used zero-shot or fine-tuned on a small amount of data, is a candidate.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small implementation of CI-TSMixer(G) from TSMixer (IBM)
(following Figures 1 and 2, appendix Figure 6, and Section 3.3 of arXiv:2306.09364; reconciliation heads omitted)
Input x: [batch, input length sl, number of variables c] -> output: [batch, forecast length fl, number of variables c]
"""


class GatedAttention(nn.Module):
  """W_A = softmax(A(X)), output = W_A * X (per-feature gate)"""

  def __init__(self, dim):
    super().__init__()
    self.attn = nn.Linear(dim, dim)

  def forward(self, x):
    return x * torch.softmax(self.attn(x), dim=-1)


class MixerBlock(nn.Module):
  """Mix the last dimension dim: layer norm -> MLP -> gated attention -> residual"""

  def __init__(self, dim, norm_dim, expansion=2, dropout=0.1):
    super().__init__()
    self.norm = nn.LayerNorm(norm_dim)  # normalization is applied along the patch-feature (hf) axis
    self.mlp = nn.Sequential(
      nn.Linear(dim, dim * expansion), nn.GELU(), nn.Dropout(dropout),
      nn.Linear(dim * expansion, dim), nn.Dropout(dropout),
    )
    self.gate = GatedAttention(dim)

  def forward(self, x, transpose):            # x: [B, c, n, hf]
    y = self.norm(x)
    if transpose:                              # inter-patch mixer: move the patch axis (n) to the end
      y = y.transpose(2, 3)
    y = self.gate(self.mlp(y))
    if transpose:
      y = y.transpose(2, 3)
    return x + y


class MixerLayer(nn.Module):
  def __init__(self, n_patches, hf, expansion, dropout):
    super().__init__()
    self.inter_patch = MixerBlock(n_patches, hf, expansion, dropout)  # weights [n x n]
    self.intra_patch = MixerBlock(hf, hf, expansion, dropout)         # weights [hf x hf]

  def forward(self, x):
    x = self.inter_patch(x, transpose=True)
    x = self.intra_patch(x, transpose=False)
    return x


class TSMixerIBM(nn.Module):
  def __init__(self, sl=512, fl=96, pl=16, stride=8, hf=32, nl=8, expansion=2, dropout=0.1, head_dropout=0.2):
    super().__init__()
    self.pl, self.stride = pl, stride
    self.n = (sl - pl) // stride + 1           # number of patches
    self.embed = nn.Linear(pl, hf)             # patch embedding (shared across all variables)
    self.layers = nn.ModuleList([MixerLayer(self.n, hf, expansion, dropout) for _ in range(nl)])
    self.head = nn.Sequential(nn.Flatten(start_dim=2), nn.Dropout(head_dropout), nn.Linear(self.n * hf, fl))

  def forward(self, x):                        # x: [B, sl, c]
    # instance normalization (per window, per variable)
    mean = x.mean(dim=1, keepdim=True)
    std = x.std(dim=1, keepdim=True, unbiased=False) + 1e-5
    x = (x - mean) / std
    # patching: [B, c, n, pl]
    x = x.transpose(1, 2).unfold(dimension=-1, size=self.pl, step=self.stride)
    x = self.embed(x)                          # [B, c, n, hf]
    for layer in self.layers:
      x = layer(x)
    y = self.head(x).transpose(1, 2)           # [B, fl, c]
    return y * std + mean                      # denormalize


model = TSMixerIBM(sl=512, fl=96)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.MSELoss()                       # supervised training in the paper minimizes MSE

x = torch.randn(8, 512, 7)                     # 7 variables, as in ETTh1
y = torch.randn(8, 96, 7)

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

model.eval()                                   # inference: dropout off
with torch.no_grad():
  pred = model(x)                              # [8, 96, 7]

# Using the Hugging Face implementation (pip install transformers)
# from transformers import PatchTSMixerConfig, PatchTSMixerForPrediction
# config = PatchTSMixerConfig(context_length=512, prediction_length=96, patch_length=16, patch_stride=8,
#                             num_input_channels=7, d_model=32, num_layers=8, expansion_factor=2,
#                             dropout=0.1, mode="common_channel", gated_attn=True)
# hf_model = PatchTSMixerForPrediction(config)
# out = hf_model(past_values=x, future_values=y)   # out.loss and out.prediction_outputs

FAQ

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

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

Q. Are PatchTSMixer and TSMixer (IBM) the same?
A.

Yes, they are the same model. The paper's authors released the implementation in Hugging Face transformers under the name PatchTSMixer, which makes it easy to distinguish from Google's TSMixer.

Q. How is it related to TTM?
A.

TTM is a small pretrained forecasting model built by the same IBM team using TSMixer (IBM) blocks as components. It stacks TSMixer blocks over multiple stages with patches at different resolutions and is pretrained on many public datasets, so that it can be used for zero-shot forecasting or forecasting with little data.

References

  1. Ekambaram, V., Jati, A., Nguyen, N., Sinthong, P., & Kalagnanam, J. (2023). TSMixer: Lightweight MLP-Mixer Model for Multivariate Time Series Forecasting. KDD 2023.
  2. Hugging Face Transformers: PatchTSMixer (official implementation by the authors)
  3. 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).
  4. Tolstikhin, I., Houlsby, N., Kolesnikov, A., et al. (2021). MLP-Mixer: An all-MLP Architecture for Vision. NeurIPS 2021.
  5. Nie, Y., Nguyen, N. H., Sinthong, P., & Kalagnanam, J. (2023). A Time Series is Worth 64 Words: Long-term Forecasting with Transformers. ICLR 2023.
  6. Ekambaram, V., Jati, A., Dayama, P., et al. (2024). Tiny Time Mixers (TTMs): Fast Pre-trained Models for Enhanced Zero/Few-Shot Forecasting of Multivariate Time Series. NeurIPS 2024.