Anomaly Transformer is a Transformer-based model for unsupervised time series anomaly detection that flags unusual time points by measuring an association discrepancy: the gap between how a point actually attends to the rest of the series and how it would attend if it only related to its close neighbors. Introduced in 2022 by Xu, Wu, Wang and Long, it became a widely cited reference architecture in anomaly detection for multivariate sensor and server data.
The model rests on one observation. Normal points tend to form broad associations with many points across the series, because they share periodic and trend patterns, while rare anomalies concentrate their attention on adjacent time points. The model turns this difference into a score that complements the familiar reconstruction error.
How Anomaly-Attention measures association discrepancy
The core building block is Anomaly-Attention, a modified self-attention layer with two branches computed over the same sliding window. The series-association branch is ordinary self-attention: each time point receives a learned distribution of attention weights over all other points in the window. The prior-association branch uses a learnable Gaussian kernel over relative temporal distance, so each point attends mainly to its neighbors, with a width controlled by a learned scale parameter sigma.
The association discrepancy for a point is the symmetric Kullback-Leibler divergence between its prior and series distributions, averaged over all layers. A normal point has a wide series-association that differs strongly from the narrow Gaussian prior, which gives a high discrepancy. An anomalous point attends mostly to its neighbors, so its series-association resembles the prior and its discrepancy is low.
| Branch | How it is computed | What it captures |
|---|---|---|
| Prior-association | Gaussian kernel over time distance, learned scale | Local adjacent-concentration bias |
| Series-association | Softmax of query-key products | Actual dependencies learned from the data |
| Association discrepancy | Symmetric KL divergence between both | How far a point looks beyond its neighbors |
Minimax training strategy
The model is trained without labels by reconstructing the input window, combined with a term that rewards a large association discrepancy. Maximizing the discrepancy naively would let the Gaussian prior collapse to an extremely small width, which would make the criterion meaningless. The authors therefore use a two-phase minimax strategy with stop-gradient operations.
- Minimize phase: the prior-association is pulled toward the series-association, with gradients blocked on the series branch, so the prior adapts to realistic temporal patterns.
- Maximize phase: the series-association is pushed away from the prior, with gradients blocked on the prior branch, so normal points learn to attend to non-adjacent parts of the series.
- Reconstruction loss is optimized in both phases to keep the representation informative.
The total objective subtracts the weighted discrepancy from the reconstruction loss, with a weight lambda of about 3 in the original configuration. Typical settings use a window of 100 time steps, three encoder layers and a model width of 512, although these values should be tuned for each dataset.
Anomaly score and thresholding
At inference, the anomaly score for each time point multiplies two signals. The first is the point-wise reconstruction error. The second is a softmax over the negative association discrepancy across the window, which gives higher weight to points with unusually low discrepancy. A point receives a high score when it is both poorly reconstructed and locally concentrated.
The score must still be converted into binary alerts. The original work selects a threshold so that a fixed proportion of validation points, often between 0.1 and 1 percent, is labeled anomalous. In production, teams usually replace this with dynamic thresholding or a threshold tied to an expected contamination rate and the cost of false alarms.
| Component | High value means | Weakness on its own |
|---|---|---|
| Reconstruction error | The point is hard to reproduce | Noisy segments also score high |
| Low association discrepancy | The point relates only to neighbors | Smooth flat regions can look local |
| Combined score | Both signals agree on an anomaly | Still needs a calibrated threshold |
Comparison with other time series detectors
Anomaly Transformer sits among several families of time series anomaly detection methods. Its distinctive contribution is the use of attention structure as a detection signal, rather than relying only on prediction or reconstruction residuals.
| Approach | Detection signal | Strengths | Limitations |
|---|---|---|---|
| Anomaly Transformer | Association discrepancy and reconstruction | Captures long-range temporal context | Heavy model; sensitive to evaluation protocol |
| Autoencoder anomaly detection | Reconstruction error | Simple and widely understood | May reconstruct anomalies too well |
| Forecasting-based detection | Prediction residual | Interpretable per-channel errors | Struggles with irregular signals |
| Matrix profile | Distance to nearest subsequence | No training, finds discords exactly | Mainly univariate, fixed subsequence length |
| Isolation forest on windows | Path length in random trees | Fast and strong baseline | Ignores temporal ordering |
Benchmarks, criticism and practical limits
The original paper reported state-of-the-art F1 scores on public benchmarks such as SMD, MSL, SMAP, SWaT and PSM. Those results used the point-adjustment protocol, which marks an entire anomalous segment as detected if any single point in it is flagged. Later studies showed that this protocol strongly inflates scores, to the point that random or trivial detectors can appear competitive.
Under stricter metrics such as range-based or affiliation-based F1, the advantage of Anomaly Transformer over simpler baselines shrinks considerably and sometimes disappears. Practitioners should therefore treat published figures with caution and evaluate against strong simple baselines on their own data.
- Compute cost: quadratic attention over each window makes training heavier than classical detectors.
- Window dependence: anomalies longer than the window are hard to capture as local concentration.
- Contamination: anomalies in the training data weaken the learned notion of normal behavior.
- Explainability: the score indicates when, but not which channel caused the anomaly.
A plain-language summary
Picture a long recording of readings from a machine. Normal moments look like many other moments, such as every morning or every cycle. Strange moments look like nothing except what came just before and after.
Anomaly Transformer checks how widely each moment connects to the rest of the recording. Moments with only narrow, local connections are suspicious. The model also checks how hard each moment is to rebuild. When both signs point the same way, it raises the score.
An example from practice
An operations team at a cloud hosting provider monitors 38 metrics per server, including CPU load, memory, disk latency and network traffic, sampled every minute. They train an Anomaly Transformer on four weeks of data from a pool of servers with windows of 100 minutes, after removing periods with known incidents.
Before deployment, the team compares it with an isolation forest baseline using range-based F1 on six months of labeled incidents. The transformer detects slow memory leaks and unusual load patterns earlier than the baseline, but the gain is modest on sudden spikes, which both methods catch.
The team deploys it with a dynamic threshold set for roughly two alerts per day per server group. Engineers pair each alert with a per-metric reconstruction view to identify the responsible channel. The result is fewer missed gradual failures without a rise in alert fatigue.