Overview

6 Moirai: A universal forecasting transformer

This chapter introduces Moirai, an open-source foundation model designed as a universal forecaster that natively supports exogenous features and produces probabilistic predictions. Positioned alongside TimeGPT, Lag-Llama, and Chronos, Moirai stands out by handling multivariate inputs and external drivers, enabling zero-shot forecasting and anomaly detection without task-specific training. The chapter blends a conceptual tour of the model with hands-on guidance, showing how to install and use it in Python, and evaluating its behavior on sales forecasting and anomaly detection tasks.

Moirai adopts an encoder-only Transformer with non-overlapping patching that tokenizes time series at lengths tied to data frequency, then flattens multivariate inputs into a single sequence and uses a binary attention bias to distinguish within- and cross-variate relations—an “any-variate” attention scheme. Its output layer predicts parameters of a mixture distribution (Student’s t, log-normal, negative binomial, and a low-variance normal), enabling flexible, potentially asymmetric uncertainty. Pretraining leverages LOTSA, a 27-billion-point, multi-domain, multi-frequency archive; balanced subsampling and varied input lengths (2–512 steps) teach horizons up to 256 steps. The chapter also presents Moirai-MoE, a successor that switches to a decoder-only architecture with a sparse, 32-expert feedforward layer and a centroid-based gating mechanism derived from clustered token embeddings; it standardizes patching with a single input projection and achieves higher accuracy with faster inference due to sparse expert activation despite having more parameters.

Practically, Moirai is accessed via a Python package (uni2ts) and GluonTS formats: data are wrapped in a PandasDataset, a predictor generates samples, and point forecasts come from the median with configurable prediction intervals. In a weekly sales example, zero-shot cross-validation shows partial overlap with actuals but underestimates seasonal variation when using the small model; adding exogenous features (holiday as future-known, temperature/fuel/CPI/unemployment as past-only) improves accuracy modestly (MAE from 84,140 to 82,041; sMAPE from 2.64% to 2.57%). For anomaly detection on NYC taxi data, rolling forecasts with a 99% interval yield high recall and the best F1 among tested models (0.53), albeit with many false positives. The chapter closes with guidance on model size versus hardware trade-offs and highlights Moirai’s strengths when exogenous covariates are available and horizons are within its pretrained limit.

Architecture of Moirai. Here, the series is patched before entering the encoder-only Transformer. Then, a mixture of distributions generates a flexible output distribution of future values.
Illustrating the process of patching. Typically, each data point (circle) would be a token and sent to the embedding layer. With patching, we group data points together and each patch becomes a token that is sent to the embedding.
To handle an arbitrary number of variates, Moirai flattens the data into a single series.
Illustrating a mixture distribution made of a Student’s T-distribution and a log-normal distribution. For this plot, points have the same chance of being drawn from each distribution, and the result is a combination of both functions, as shown by the bars.
Architecture of Moirai-MoE. Unlike the first version of Moirai, it now uses a decoder-only transformer. Inside the decoder-only transformer, we notice the addition of a gating function and a layer of mixture of experts. The gating function learns which expert to activate depending on the data, with a maximum of two experts being activated at once. The activation of an expert is indicated by a solid arrow.
Zero-shot forecasts of the weekly sales of four stores eight weeks into the future. The shaded area represents the 95% prediction interval.
Predictions from running cross-validation with Moirai. The shaded area represents the 95% prediction interval. There is some overlap, but Moirai seems to not forecast the seasonal variations correctly.
Predictions obtained from running cross-validation with Moirai and using exogenous features. The shaded area represents the 95% prediction interval. Despite using features, the model still cannot predict the cyclical variations.
Both performance metrics improved when including exogenous features, indicating a boost in performance. Lower is better in this plot.
Anomalies detected by Moirai. Here, all anomalies were identified, but many points were mislabeled as anomalies. Therefore, its recall is high, but the precision is likely very low due to the high number of false positives.
F1 sore of foundation models used for anomaly detection. Here, Moirai achieves the best overall result. Higher is better.

Summary

  • Moirai is a large time model developed by Salesforce researchers. It leverages patching and an encoder-only Transformer for probabilistic forecasting.
  • The model is open-source and can be installed as a Python library.
  • Using the largest model usually leads to better results, although it also requires better hardware to have reasonable inference times.
  • Researchers also released LOTSA which represents the largest collection of open-source time series data, with more than 27 billion data points. This is an important contribution for the future development of large time models.

References

FAQ

What is Moirai and why is it called a “universal” forecasting transformer?Moirai is a probabilistic, encoder-only Transformer for time series forecasting that aims to work across domains, frequencies, and variable types. It tokenizes series with patches, supports exogenous features out of the box, and outputs full predictive distributions (not just point forecasts), making it broadly applicable—hence “universal.”
How does Moirai handle exogenous features?Moirai flattens the target and all exogenous series into a single sequence and uses a binary attention bias so the model can distinguish “same-series” vs “cross-series” interactions. In practice, you pass exogenous features as: - past_feat_dynamic_real: known only in the past (e.g., temperature, CPI) - feat_dynamic_real: known in both past and future (e.g., holidays) These are embedded and used jointly with the target to inform forecasts.
What is “patching” and how are patch sizes chosen?Patching groups consecutive time steps into a single token, reducing sequence length and helping capture local patterns. In Moirai, patches are non-overlapping and their length is determined by data frequency (e.g., longer patches for high-frequency data like hourly/second, shorter for monthly/quarterly/yearly). This reduces computation and enables longer input windows. In Moirai-MoE, a fixed, non-overlapping patch size is used for all frequencies with a single input projection.
How can Moirai work with any number of variates?Moirai flattens all variates (target plus exogenous) into one long sequence, avoiding fixed input dimensionality limits. A binary attention bias adds one learnable bias when attention is within the same variate and another when it is across variates, enabling “any-variate” attention that scales to arbitrary feature counts.
Why does Moirai predict with a mixture of distributions, and which components are used?Different series can have asymmetric, heavy-tailed, or count-like behavior. Moirai maps hidden states to a mixture of four components to flexibly model these shapes: - Student’s t-distribution - Log-normal distribution - Negative binomial distribution - Low-variance normal distribution (variance fixed to 0.001) This allows asymmetric intervals and better fit across heterogeneous data.
What data and training protocol were used to pretrain Moirai?Moirai was pretrained on LOTSA (Large-scale Open Time Series Archive), a 27B-point, multi-domain corpus spanning yearly to second-level frequencies. To avoid overfitting to overrepresented frequencies (e.g., hourly), datasets exceeding 0.1% of LOTSA were downsampled to 0.1% probability. Input lengths ranged from 2 to 512 steps; forecast horizons were 15–50% of the context (up to 256 steps).
Which Moirai sizes are available and how do I choose?Original Moirai: small (14M params, 100k steps), base (91M, 1M steps), large (311M, 1M steps). Larger models generally yield better accuracy but need more memory and may be slower on limited hardware. If you only have CPU, small/base are practical; with strong GPU, prefer large. Moirai-MoE releases (small≈117M, base≈935M) use a sparse mixture-of-experts and can be faster at inference despite higher total parameters.
What’s new in Moirai-MoE compared to the original model?Moirai-MoE: - Switches to a decoder-only Transformer that generates forecasts autoregressively at the patch level. - Replaces the feedforward sublayer with a sparse mixture-of-experts (32 experts), activating at most two experts per token. - Uses a gating function based on token clusters (k-means centroids) to route tokens. - Adopts a fixed non-overlapping patch size and a single input projection. These changes simplify the design and improve performance and speed.
How do I run zero-shot forecasting or cross-validation with Moirai in Python?Install the package (pip install uni2ts). Wrap your data as a GluonTS PandasDataset. Initialize a pretrained model via MoiraiForecast + MoiraiModule.from_pretrained (e.g., "Salesforce/moirai-1.0-R-small"), set prediction_length, context_length, patch_size="auto", num_samples, and feature dimensions. Create a predictor and call predict. For cross-validation, use GluonTS split and generate_instances to define windows, then evaluate metrics (e.g., MAE, sMAPE) from the forecast samples (median and quantiles).
Can Moirai be used for anomaly detection? How?Yes. Run rolling forecasts over consecutive windows and label a point as an anomaly if the actual value falls outside a chosen prediction interval (e.g., 99%). In the NYC taxi example, Moirai detected almost all true anomalies but produced many false positives (high recall, lower precision), yielding an F1 score of about 0.53 on that dataset.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Time Series Forecasting Using Foundation Models ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Time Series Forecasting Using Foundation Models ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Time Series Forecasting Using Foundation Models ebook for free