patchfm 3.0.0__tar.gz → 3.1.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {patchfm-3.0.0/src/patchfm.egg-info → patchfm-3.1.1}/PKG-INFO +105 -16
- patchfm-3.1.1/README.md +225 -0
- {patchfm-3.0.0 → patchfm-3.1.1}/pyproject.toml +1 -1
- {patchfm-3.0.0 → patchfm-3.1.1}/src/patchfm/configs/model_config.py +1 -0
- {patchfm-3.0.0 → patchfm-3.1.1}/src/patchfm/inference/forecaster.py +9 -4
- {patchfm-3.0.0 → patchfm-3.1.1}/src/patchfm/inference/modules.py +3 -3
- {patchfm-3.0.0 → patchfm-3.1.1/src/patchfm.egg-info}/PKG-INFO +105 -16
- patchfm-3.0.0/README.md +0 -136
- {patchfm-3.0.0 → patchfm-3.1.1}/LICENSE +0 -0
- {patchfm-3.0.0 → patchfm-3.1.1}/setup.cfg +0 -0
- {patchfm-3.0.0 → patchfm-3.1.1}/src/patchfm/__init__.py +0 -0
- {patchfm-3.0.0 → patchfm-3.1.1}/src/patchfm.egg-info/SOURCES.txt +0 -0
- {patchfm-3.0.0 → patchfm-3.1.1}/src/patchfm.egg-info/dependency_links.txt +0 -0
- {patchfm-3.0.0 → patchfm-3.1.1}/src/patchfm.egg-info/requires.txt +0 -0
- {patchfm-3.0.0 → patchfm-3.1.1}/src/patchfm.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: patchfm
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.1.1
|
|
4
4
|
Summary: a Foundation Model for Univariate Time Series Forecasting
|
|
5
5
|
Author-email: Samy-Melwan Vilhes <samy-melwan.vilhes@insa-rouen.fr>
|
|
6
6
|
License: MIT License
|
|
@@ -42,20 +42,41 @@ Dynamic: license-file
|
|
|
42
42
|
|
|
43
43
|
# A tutorial on how to build a Foundation Model for Univariate Time Series Forecasting
|
|
44
44
|
|
|
45
|
-
[Huggingface Model Card](https://huggingface.co/vilhess/PatchFM)
|
|
46
|
-
[Paper Model Card](https://github.com/vilhess/PatchFM/blob/main/main.pdf)
|
|
47
|
-
|
|
48
45
|
A concise, reproducible recipe for training a transformer-based, patch-to-patch forecasting model for univariate time series. The approach mirrors Large Language Model (LLM) practices (next-token → next-patch) while remaining lightweight compared to a classic LLM and practical.
|
|
49
46
|
|
|
47
|
+
Our model is deployed on the [TS-Arena benchmark](https://ts-arena.live) and achieves competitive performance against state-of-the-art methods under the name `LITIS/PatchFM-Large`.
|
|
48
|
+
|
|
49
|
+
## Resuls on the FEV benchmark:
|
|
50
|
+
|
|
51
|
+
**Our model is competitive with the state-of-the-art notably compared to [MOIRAI2.0](https://arxiv.org/pdf/2511.11698)**
|
|
52
|
+
|
|
53
|
+
| Model Name | Win Rate | Skill Score |
|
|
54
|
+
|----------------------|----------|-------------|
|
|
55
|
+
| (🥇) Chronos-2 | 0.9008 | 0.4728 |
|
|
56
|
+
| (🥈) TiRex | 0.8092 | 0.4268 |
|
|
57
|
+
| (🥉) TimesFM-2.5 | 0.8085 | 0.4668 |
|
|
58
|
+
| (4) Toto-1.0 | 0.7069 | 0.4110 |
|
|
59
|
+
| (5) **PatchFM (us)** | 0.6677 | 0.3983 |
|
|
60
|
+
| (6) Moirai-2.0 | 0.6546 | 0.4026 |
|
|
61
|
+
| (7) Chronos-Bolt | 0.6277 | 0.3889 |
|
|
62
|
+
| (8) Sundial-Base | 0.4446 | 0.3387 |
|
|
63
|
+
| (9) CatBoost (Recursive)| 0.3362 | 0.2301 |
|
|
64
|
+
| (10) LightGBM (Recursive)| 0.3123 | 0.2168 |
|
|
65
|
+
| (11) AutoTheta | 0.2938 | 0.0546 |
|
|
66
|
+
| (12) Seasonal Naive | 0.2058 | 0.0000 |
|
|
67
|
+
| (13) Naive | 0.1404 | -0.4540 |
|
|
68
|
+
| (14) Drift | 0.0915 | -0.4578 |
|
|
69
|
+
|
|
70
|
+
|
|
50
71
|
## Highlights
|
|
51
72
|
- Next-patch prediction objective (autoregressive, causal)
|
|
52
73
|
- Patch-based representation of time series (tokens ↔ patches)
|
|
53
74
|
- Causal masking self-attention with RoPE (relative positions)
|
|
54
|
-
- RevIN
|
|
75
|
+
- Causal RevIN with $\sinh^{-1}$ transform for normalization
|
|
55
76
|
- SwiGLU feed-forward networks
|
|
56
|
-
-
|
|
77
|
+
- Autoregressive multi-quantile decoding [MOIRAI2.0](https://arxiv.org/pdf/2511.11698)
|
|
57
78
|
- KV-cache for efficient long-horizon inference
|
|
58
|
-
-
|
|
79
|
+
- flips equivariance during inference (optional) [Reverso](https://arxiv.org/pdf/2602.17634v1)
|
|
59
80
|
|
|
60
81
|
## Quick Start
|
|
61
82
|
|
|
@@ -71,21 +92,22 @@ pip install -r requirements.txt
|
|
|
71
92
|
|
|
72
93
|
```python
|
|
73
94
|
import torch
|
|
74
|
-
|
|
95
|
+
|
|
75
96
|
from configs import PatchFMConfig
|
|
97
|
+
from model import Forecaster
|
|
76
98
|
|
|
77
99
|
# --- Instantiate model ---
|
|
78
|
-
config = PatchFMConfig(load_from_hub=True)
|
|
100
|
+
config = PatchFMConfig(load_from_hub=True)
|
|
79
101
|
model = Forecaster(config)
|
|
80
102
|
|
|
81
103
|
# --- Inference ---
|
|
82
104
|
forecast_horizon = 64
|
|
83
105
|
seq = torch.randn(1, 1024) # (batch, time)
|
|
84
|
-
pred_median, pred_quantiles = model(seq, forecast_horizon=forecast_horizon, quantiles=[0.1, 0.5, 0.9],
|
|
106
|
+
pred_median, pred_quantiles = model(seq, forecast_horizon=forecast_horizon, quantiles=[0.1, 0.5, 0.9], flip_equivariance=True) # (batch, time), (batch, time, quantiles)
|
|
85
107
|
```
|
|
86
108
|
|
|
87
|
-
### from pip package
|
|
88
109
|
|
|
110
|
+
### from pip package
|
|
89
111
|
1. Install the package from PyPI
|
|
90
112
|
```bash
|
|
91
113
|
pip install patchfm
|
|
@@ -94,9 +116,11 @@ pip install patchfm
|
|
|
94
116
|
|
|
95
117
|
```python
|
|
96
118
|
import torch
|
|
97
|
-
|
|
119
|
+
|
|
120
|
+
from patchfm import Forecaster, PatchFMConfig
|
|
98
121
|
|
|
99
122
|
# same as above
|
|
123
|
+
pred_median, pred_quantiles = model(seq, forecast_horizon=forecast_horizon, quantiles=[0.1, 0.5, 0.9], flip_equivariance=True) # (batch, time), (batch, time, quantiles)
|
|
100
124
|
```
|
|
101
125
|
|
|
102
126
|
We provide an extended quick start example in [notebooks/tutorial.ipynb](./notebooks/tutorial.ipynb).
|
|
@@ -114,6 +138,7 @@ If you dont have suitable hardware you can run the the extended quick start exam
|
|
|
114
138
|
- Training: Multi-quantile (pinball) loss across positions, elements, and quantiles $\mathcal{Q}$.
|
|
115
139
|
- Inference: Predict next patch; roll out autoregressively for long horizons.
|
|
116
140
|
- KV-cache: during inference, cache keys/values to avoid redundant computations.
|
|
141
|
+
- Flip-equivariance: during inference, flip input sequence and average predictions to improve robustness (at cost of doubling batch size).
|
|
117
142
|
|
|
118
143
|
## Problem Formulation
|
|
119
144
|
Given context patches $x_{p_1}, \ldots, x_{p_n}$, predict the next patch $x_{p_{i+1}}$ for each position $i$ using only past patches (causality). The model outputs quantiles $\{\hat{x}_{p_{i+1}}^{(q)}: q \in \mathcal{Q}\}$ with median (q=0.5) as the point forecast.
|
|
@@ -135,18 +160,83 @@ Aggregate over positions, patch elements, and quantiles.
|
|
|
135
160
|
- Forecast horizon: 32 steps per forward pass
|
|
136
161
|
- Quantiles $\mathcal{Q}$: {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
|
|
137
162
|
- Layers: 6
|
|
138
|
-
- Attention heads:
|
|
163
|
+
- Attention heads: 32 (head dim 64)
|
|
139
164
|
- Model dim: 2048
|
|
140
165
|
- Parameters: ~300M
|
|
141
166
|
|
|
142
167
|
## Inference
|
|
143
168
|
- Single step: predict next patch ($P_{len}$ values)
|
|
144
169
|
- Long-horizon: append prediction to context and repeat (optionally drop oldest patch to keep window fixed)
|
|
170
|
+
- Flip-equivariance [Reverso](https://arxiv.org/pdf/2602.17634v1): optionally flip input sequence and average predictions to improve robustness (at cost of doubling batch size):
|
|
171
|
+
$$y = \frac{1}{2} \left( f(x) - f(-x) \right)$$
|
|
172
|
+
|
|
173
|
+
- ### Autoregressive Inference with Quantile Forecasting ([Moirai 2.0](https://arxiv.org/pdf/2511.11698v1))
|
|
174
|
+
During autoregressive inference, the model generates forecasted values patch by patch. At each time step, the predicted patch is fed back into the model as input for the next step. This iterative process continues until the desired forecast horizon is reached.
|
|
175
|
+
|
|
176
|
+
When performing quantile forecasting, the situation becomes more complex. Instead of producing a single patch per step, the model outputs multiple patches corresponding to different quantiles (e.g., 0.1, 0.5, 0.9). Since the model expects a single patch for the next time step, it is not straightforward to feed all quantile predictions back into the model simultaneously.
|
|
177
|
+
|
|
178
|
+
A common workaround is to feed only the median prediction (the 0.5 quantile) back into the model at each step. While this approach preserves the autoregressive structure, it discards the uncertainty information captured by the other quantiles.
|
|
179
|
+
|
|
180
|
+
An alternative approach is **autoregressive multi-quantile decoding**, as proposed in [Moirai 2.0](https://arxiv.org/pdf/2511.11698v1). This method enables consistent autoregressive generation while preserving the full predictive distribution across quantiles. However, it is computationally more expensive than the median-only approach as it requires duplicating the context for each quantile.
|
|
181
|
+
|
|
182
|
+
<div style="display: flex; gap: 10px; align-items: flex-start;">
|
|
183
|
+
<div>
|
|
184
|
+
<img src="assets/classic_forecast_animation.gif" alt="Classic Autoregressive Inference" width="450">
|
|
185
|
+
<p style="text-align:center;">Classic Autoregressive Inference</p>
|
|
186
|
+
</div>
|
|
187
|
+
<div>
|
|
188
|
+
<img src="assets/quantile_forecast_animation.gif" alt="Autoregressive Multi-Quantile Decoding" width="450">
|
|
189
|
+
<p style="text-align:center;">Autoregressive Multi-Quantile Decoding</p>
|
|
190
|
+
</div>
|
|
191
|
+
</div>
|
|
192
|
+
|
|
193
|
+
The algorithm proceeds as follows:
|
|
194
|
+
|
|
195
|
+
1. **Initialization**
|
|
196
|
+
Start with the initial context window of observed data
|
|
197
|
+
**Shape:** `(BS × L)`
|
|
198
|
+
- `BS`: batch size
|
|
199
|
+
- `L`: context length
|
|
200
|
+
- `P`: patch size
|
|
201
|
+
- `Q`: number of quantiles
|
|
202
|
+
- `H`: forecast horizon
|
|
203
|
+
- `i=1`: current algorithm step
|
|
204
|
+
|
|
205
|
+
2. **First Quantile Prediction (Forward Pass)**
|
|
206
|
+
Predict the quantiles for the next patch using the current context.
|
|
207
|
+
**Output shape:** `(BS × P × Q)`
|
|
208
|
+
|
|
209
|
+
3. **Context Duplication**
|
|
210
|
+
For each predicted quantile, create a separate context by appending the corresponding predicted patch to the current context.
|
|
211
|
+
This increases the number of contexts by a factor of `Q` at each step.
|
|
212
|
+
**New context shape:** `(BS × Q × i(L + P))`
|
|
213
|
+
|
|
214
|
+
4. **Next Forward Pass**
|
|
215
|
+
For each duplicated context, predict the quantiles of the next patch.
|
|
216
|
+
**Output shape:** `(BS × Q × P × Q)`
|
|
217
|
+
|
|
218
|
+
5. **Quantile Collapse**
|
|
219
|
+
- Permute and reshape the predictions to aggregate all possible quantile paths:
|
|
220
|
+
**Intermediate shape:** `(BS × P × Q²)`
|
|
221
|
+
- Compute the quantiles across the `Q²` predictions to obtain the final quantile estimates for the next patch.
|
|
222
|
+
**Final shape:** `(BS × P × Q)`
|
|
223
|
+
- Increment the step counter `i ← i + 1`.
|
|
224
|
+
|
|
225
|
+
6. **Iteration**
|
|
226
|
+
Repeat Steps 3–5 until the forecast horizon `H` is reached, i.e., until the total number of predicted time steps satisfies
|
|
227
|
+
`i × P ≥ H`.
|
|
228
|
+
|
|
229
|
+
This procedure preserves predictive uncertainty across quantiles while maintaining the autoregressive structure of the model. Although it is computationally more expensive than feeding only the median prediction (0.5 quantile) back into the model, it remains tractable in practice and enables consistent multi-quantile forecasting.
|
|
230
|
+
|
|
231
|
+
⚠️ **Warning**
|
|
232
|
+
With this strategy, the median prediction (0.5 quantile) does **not necessarily** match the prediction obtained by autoregressively feeding only the median patch back into the model at each step.
|
|
233
|
+
|
|
234
|
+
This discrepancy arises because the *quantile collapse* step aggregates predictions across all possible quantile paths. As a result, the median is computed from the combined multi-path distribution rather than from a single deterministic trajectory, which can lead to different estimates compared to the single-path (median-only) autoregressive approach.
|
|
145
235
|
|
|
146
236
|
## Datasets
|
|
147
|
-
- UTSD (Unified Time Series Dataset) [UTSD]: seven domains (Energy, IoT, Nature, Web, Health, Transport, Environment). We work with UTSD-12G (~18M series after preprocessing).
|
|
148
237
|
- GIFT-Eval pretraining dataset [GIFT]: aligned with the GIFT-Eval dataset but without data leakage issue with the benchmark. The dataset contains approximately 71 univariate and 17 multivariate time series datasets from various
|
|
149
238
|
domains and various frequencies. After preprocessing, this yields approximately 600K univariate series.
|
|
239
|
+
- Chronos synthetic datasets [Chronos]: two large synthetic datasets generated with Chronos, one with TSMixup and one with KernelSynth. Each contains approximately 10 million univariate series and 1 million respectively, each signal of length 1024.
|
|
150
240
|
- Artificial: ~1M synthetic series (sinusoidal, linear, polynomial, logarithmic) plus mixtures via TSMixup [Chronos]; Gaussian Process samples via KernelSynth (mixtures of RBF/periodic/linear kernels with swept hyperparameters).
|
|
151
241
|
|
|
152
242
|
## Repository Layout
|
|
@@ -164,10 +254,9 @@ domains and various frequencies. After preprocessing, this yields approximately
|
|
|
164
254
|
|
|
165
255
|
- `dataset/` — data loading and preprocessing
|
|
166
256
|
- `artificial.py` — synthetic dataset : artificial signals + TSMixup + KernelSynth
|
|
167
|
-
- `utsd.py` — Unified Time Series Dataset (UTSD) loading and preprocessing
|
|
168
257
|
- `gift.py` — GIFT-Eval pretraining dataset loading and preprocessing
|
|
169
258
|
- `get_data.py` — utility to fetch and preprocess datasets
|
|
170
|
-
- `
|
|
259
|
+
- `chronosdata.py` — loading of the synthetic datasets generated with Chronos (TSMixup and KernelSynth) with download functions integrated
|
|
171
260
|
|
|
172
261
|
- `configs/` — model and training configurations
|
|
173
262
|
- `notebooks/inference` — how to load a trained model and generate forecasts
|
patchfm-3.1.1/README.md
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
# A tutorial on how to build a Foundation Model for Univariate Time Series Forecasting
|
|
2
|
+
|
|
3
|
+
A concise, reproducible recipe for training a transformer-based, patch-to-patch forecasting model for univariate time series. The approach mirrors Large Language Model (LLM) practices (next-token → next-patch) while remaining lightweight compared to a classic LLM and practical.
|
|
4
|
+
|
|
5
|
+
Our model is deployed on the [TS-Arena benchmark](https://ts-arena.live) and achieves competitive performance against state-of-the-art methods under the name `LITIS/PatchFM-Large`.
|
|
6
|
+
|
|
7
|
+
## Resuls on the FEV benchmark:
|
|
8
|
+
|
|
9
|
+
**Our model is competitive with the state-of-the-art notably compared to [MOIRAI2.0](https://arxiv.org/pdf/2511.11698)**
|
|
10
|
+
|
|
11
|
+
| Model Name | Win Rate | Skill Score |
|
|
12
|
+
|----------------------|----------|-------------|
|
|
13
|
+
| (🥇) Chronos-2 | 0.9008 | 0.4728 |
|
|
14
|
+
| (🥈) TiRex | 0.8092 | 0.4268 |
|
|
15
|
+
| (🥉) TimesFM-2.5 | 0.8085 | 0.4668 |
|
|
16
|
+
| (4) Toto-1.0 | 0.7069 | 0.4110 |
|
|
17
|
+
| (5) **PatchFM (us)** | 0.6677 | 0.3983 |
|
|
18
|
+
| (6) Moirai-2.0 | 0.6546 | 0.4026 |
|
|
19
|
+
| (7) Chronos-Bolt | 0.6277 | 0.3889 |
|
|
20
|
+
| (8) Sundial-Base | 0.4446 | 0.3387 |
|
|
21
|
+
| (9) CatBoost (Recursive)| 0.3362 | 0.2301 |
|
|
22
|
+
| (10) LightGBM (Recursive)| 0.3123 | 0.2168 |
|
|
23
|
+
| (11) AutoTheta | 0.2938 | 0.0546 |
|
|
24
|
+
| (12) Seasonal Naive | 0.2058 | 0.0000 |
|
|
25
|
+
| (13) Naive | 0.1404 | -0.4540 |
|
|
26
|
+
| (14) Drift | 0.0915 | -0.4578 |
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
## Highlights
|
|
30
|
+
- Next-patch prediction objective (autoregressive, causal)
|
|
31
|
+
- Patch-based representation of time series (tokens ↔ patches)
|
|
32
|
+
- Causal masking self-attention with RoPE (relative positions)
|
|
33
|
+
- Causal RevIN with $\sinh^{-1}$ transform for normalization
|
|
34
|
+
- SwiGLU feed-forward networks
|
|
35
|
+
- Autoregressive multi-quantile decoding [MOIRAI2.0](https://arxiv.org/pdf/2511.11698)
|
|
36
|
+
- KV-cache for efficient long-horizon inference
|
|
37
|
+
- flips equivariance during inference (optional) [Reverso](https://arxiv.org/pdf/2602.17634v1)
|
|
38
|
+
|
|
39
|
+
## Quick Start
|
|
40
|
+
|
|
41
|
+
### from source code
|
|
42
|
+
|
|
43
|
+
1. Clone the repository and install dependencies
|
|
44
|
+
```bash
|
|
45
|
+
git clone https://github.com/vilhess/PatchFM
|
|
46
|
+
cd PatchFM
|
|
47
|
+
pip install -r requirements.txt
|
|
48
|
+
```
|
|
49
|
+
2. Run inference with a pretrained model from Huggingface Hub
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import torch
|
|
53
|
+
|
|
54
|
+
from configs import PatchFMConfig
|
|
55
|
+
from model import Forecaster
|
|
56
|
+
|
|
57
|
+
# --- Instantiate model ---
|
|
58
|
+
config = PatchFMConfig(load_from_hub=True)
|
|
59
|
+
model = Forecaster(config)
|
|
60
|
+
|
|
61
|
+
# --- Inference ---
|
|
62
|
+
forecast_horizon = 64
|
|
63
|
+
seq = torch.randn(1, 1024) # (batch, time)
|
|
64
|
+
pred_median, pred_quantiles = model(seq, forecast_horizon=forecast_horizon, quantiles=[0.1, 0.5, 0.9], flip_equivariance=True) # (batch, time), (batch, time, quantiles)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
### from pip package
|
|
69
|
+
1. Install the package from PyPI
|
|
70
|
+
```bash
|
|
71
|
+
pip install patchfm
|
|
72
|
+
```
|
|
73
|
+
2. Run inference with a pretrained model from Huggingface Hub
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
import torch
|
|
77
|
+
|
|
78
|
+
from patchfm import Forecaster, PatchFMConfig
|
|
79
|
+
|
|
80
|
+
# same as above
|
|
81
|
+
pred_median, pred_quantiles = model(seq, forecast_horizon=forecast_horizon, quantiles=[0.1, 0.5, 0.9], flip_equivariance=True) # (batch, time), (batch, time, quantiles)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
We provide an extended quick start example in [notebooks/tutorial.ipynb](./notebooks/tutorial.ipynb).
|
|
85
|
+
If you dont have suitable hardware you can run the the extended quick start example example also in Google Colab:
|
|
86
|
+
|
|
87
|
+
<a target="_blank" href="https://colab.research.google.com/drive/17sdf-7luCkv5TaeLj3Z6kIaTDkwkz3VR?usp=share_link">
|
|
88
|
+
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open Quick Start In Colab"/>
|
|
89
|
+
</a>
|
|
90
|
+
|
|
91
|
+
## Method (TL;DR)
|
|
92
|
+
- Patching: Split a context signal of length $w$ into $P_{num} = w / P_{len}$ patches of length $P_{len}$.
|
|
93
|
+
- Causal RevIN: Normalize input signal and denormalize outputs to the original scale without statistics leakage.
|
|
94
|
+
- Architecture: Input residual MLP → stacked Transformer blocks (MHA + SwiGLU FFN, pre-norm, residual) → $|\mathcal{Q}|$ output heads mapping back to patch space.
|
|
95
|
+
- Positional encoding: Rotary Position Embeddings (RoPE) applied to queries/keys.
|
|
96
|
+
- Training: Multi-quantile (pinball) loss across positions, elements, and quantiles $\mathcal{Q}$.
|
|
97
|
+
- Inference: Predict next patch; roll out autoregressively for long horizons.
|
|
98
|
+
- KV-cache: during inference, cache keys/values to avoid redundant computations.
|
|
99
|
+
- Flip-equivariance: during inference, flip input sequence and average predictions to improve robustness (at cost of doubling batch size).
|
|
100
|
+
|
|
101
|
+
## Problem Formulation
|
|
102
|
+
Given context patches $x_{p_1}, \ldots, x_{p_n}$, predict the next patch $x_{p_{i+1}}$ for each position $i$ using only past patches (causality). The model outputs quantiles $\{\hat{x}_{p_{i+1}}^{(q)}: q \in \mathcal{Q}\}$ with median (q=0.5) as the point forecast.
|
|
103
|
+
|
|
104
|
+
## Loss: Multi-Quantile (Pinball)
|
|
105
|
+
For residual $u = x - \hat{x}^{(q)}$:
|
|
106
|
+
$$\rho_q(u) = \begin{cases} q\,u, & u \ge 0,\\ (q-1)\,u, & u < 0. \end{cases}$$
|
|
107
|
+
Aggregate over positions, patch elements, and quantiles.
|
|
108
|
+
|
|
109
|
+
## Architecture
|
|
110
|
+
- Input MLP: $\mathbb{R}^{P_{len}} \to \mathbb{R}^{dim}$ residual 2-layer MLP (ReLU)
|
|
111
|
+
- Multi-Head Attention: causal mask, RoPE; queries/keys/values per head
|
|
112
|
+
- FFN: SwiGLU (SiLU-gated), pre-norm + residual
|
|
113
|
+
- Output heads: |Q| linear maps $\mathbb{R}^{dim} \to \mathbb{R}^{P_{len}}$ (one per quantile)
|
|
114
|
+
|
|
115
|
+
### Model Details
|
|
116
|
+
- Patch size: 32
|
|
117
|
+
- Max context: 32 patches (1024 steps)
|
|
118
|
+
- Forecast horizon: 32 steps per forward pass
|
|
119
|
+
- Quantiles $\mathcal{Q}$: {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
|
|
120
|
+
- Layers: 6
|
|
121
|
+
- Attention heads: 32 (head dim 64)
|
|
122
|
+
- Model dim: 2048
|
|
123
|
+
- Parameters: ~300M
|
|
124
|
+
|
|
125
|
+
## Inference
|
|
126
|
+
- Single step: predict next patch ($P_{len}$ values)
|
|
127
|
+
- Long-horizon: append prediction to context and repeat (optionally drop oldest patch to keep window fixed)
|
|
128
|
+
- Flip-equivariance [Reverso](https://arxiv.org/pdf/2602.17634v1): optionally flip input sequence and average predictions to improve robustness (at cost of doubling batch size):
|
|
129
|
+
$$y = \frac{1}{2} \left( f(x) - f(-x) \right)$$
|
|
130
|
+
|
|
131
|
+
- ### Autoregressive Inference with Quantile Forecasting ([Moirai 2.0](https://arxiv.org/pdf/2511.11698v1))
|
|
132
|
+
During autoregressive inference, the model generates forecasted values patch by patch. At each time step, the predicted patch is fed back into the model as input for the next step. This iterative process continues until the desired forecast horizon is reached.
|
|
133
|
+
|
|
134
|
+
When performing quantile forecasting, the situation becomes more complex. Instead of producing a single patch per step, the model outputs multiple patches corresponding to different quantiles (e.g., 0.1, 0.5, 0.9). Since the model expects a single patch for the next time step, it is not straightforward to feed all quantile predictions back into the model simultaneously.
|
|
135
|
+
|
|
136
|
+
A common workaround is to feed only the median prediction (the 0.5 quantile) back into the model at each step. While this approach preserves the autoregressive structure, it discards the uncertainty information captured by the other quantiles.
|
|
137
|
+
|
|
138
|
+
An alternative approach is **autoregressive multi-quantile decoding**, as proposed in [Moirai 2.0](https://arxiv.org/pdf/2511.11698v1). This method enables consistent autoregressive generation while preserving the full predictive distribution across quantiles. However, it is computationally more expensive than the median-only approach as it requires duplicating the context for each quantile.
|
|
139
|
+
|
|
140
|
+
<div style="display: flex; gap: 10px; align-items: flex-start;">
|
|
141
|
+
<div>
|
|
142
|
+
<img src="assets/classic_forecast_animation.gif" alt="Classic Autoregressive Inference" width="450">
|
|
143
|
+
<p style="text-align:center;">Classic Autoregressive Inference</p>
|
|
144
|
+
</div>
|
|
145
|
+
<div>
|
|
146
|
+
<img src="assets/quantile_forecast_animation.gif" alt="Autoregressive Multi-Quantile Decoding" width="450">
|
|
147
|
+
<p style="text-align:center;">Autoregressive Multi-Quantile Decoding</p>
|
|
148
|
+
</div>
|
|
149
|
+
</div>
|
|
150
|
+
|
|
151
|
+
The algorithm proceeds as follows:
|
|
152
|
+
|
|
153
|
+
1. **Initialization**
|
|
154
|
+
Start with the initial context window of observed data
|
|
155
|
+
**Shape:** `(BS × L)`
|
|
156
|
+
- `BS`: batch size
|
|
157
|
+
- `L`: context length
|
|
158
|
+
- `P`: patch size
|
|
159
|
+
- `Q`: number of quantiles
|
|
160
|
+
- `H`: forecast horizon
|
|
161
|
+
- `i=1`: current algorithm step
|
|
162
|
+
|
|
163
|
+
2. **First Quantile Prediction (Forward Pass)**
|
|
164
|
+
Predict the quantiles for the next patch using the current context.
|
|
165
|
+
**Output shape:** `(BS × P × Q)`
|
|
166
|
+
|
|
167
|
+
3. **Context Duplication**
|
|
168
|
+
For each predicted quantile, create a separate context by appending the corresponding predicted patch to the current context.
|
|
169
|
+
This increases the number of contexts by a factor of `Q` at each step.
|
|
170
|
+
**New context shape:** `(BS × Q × i(L + P))`
|
|
171
|
+
|
|
172
|
+
4. **Next Forward Pass**
|
|
173
|
+
For each duplicated context, predict the quantiles of the next patch.
|
|
174
|
+
**Output shape:** `(BS × Q × P × Q)`
|
|
175
|
+
|
|
176
|
+
5. **Quantile Collapse**
|
|
177
|
+
- Permute and reshape the predictions to aggregate all possible quantile paths:
|
|
178
|
+
**Intermediate shape:** `(BS × P × Q²)`
|
|
179
|
+
- Compute the quantiles across the `Q²` predictions to obtain the final quantile estimates for the next patch.
|
|
180
|
+
**Final shape:** `(BS × P × Q)`
|
|
181
|
+
- Increment the step counter `i ← i + 1`.
|
|
182
|
+
|
|
183
|
+
6. **Iteration**
|
|
184
|
+
Repeat Steps 3–5 until the forecast horizon `H` is reached, i.e., until the total number of predicted time steps satisfies
|
|
185
|
+
`i × P ≥ H`.
|
|
186
|
+
|
|
187
|
+
This procedure preserves predictive uncertainty across quantiles while maintaining the autoregressive structure of the model. Although it is computationally more expensive than feeding only the median prediction (0.5 quantile) back into the model, it remains tractable in practice and enables consistent multi-quantile forecasting.
|
|
188
|
+
|
|
189
|
+
⚠️ **Warning**
|
|
190
|
+
With this strategy, the median prediction (0.5 quantile) does **not necessarily** match the prediction obtained by autoregressively feeding only the median patch back into the model at each step.
|
|
191
|
+
|
|
192
|
+
This discrepancy arises because the *quantile collapse* step aggregates predictions across all possible quantile paths. As a result, the median is computed from the combined multi-path distribution rather than from a single deterministic trajectory, which can lead to different estimates compared to the single-path (median-only) autoregressive approach.
|
|
193
|
+
|
|
194
|
+
## Datasets
|
|
195
|
+
- GIFT-Eval pretraining dataset [GIFT]: aligned with the GIFT-Eval dataset but without data leakage issue with the benchmark. The dataset contains approximately 71 univariate and 17 multivariate time series datasets from various
|
|
196
|
+
domains and various frequencies. After preprocessing, this yields approximately 600K univariate series.
|
|
197
|
+
- Chronos synthetic datasets [Chronos]: two large synthetic datasets generated with Chronos, one with TSMixup and one with KernelSynth. Each contains approximately 10 million univariate series and 1 million respectively, each signal of length 1024.
|
|
198
|
+
- Artificial: ~1M synthetic series (sinusoidal, linear, polynomial, logarithmic) plus mixtures via TSMixup [Chronos]; Gaussian Process samples via KernelSynth (mixtures of RBF/periodic/linear kernels with swept hyperparameters).
|
|
199
|
+
|
|
200
|
+
## Repository Layout
|
|
201
|
+
|
|
202
|
+
- `model/training/` — main PatchFM model class
|
|
203
|
+
|
|
204
|
+
- `modules.py` - core modules (Residual Layers, MHA, SwiGLU, RoPE, Transformer Encoder, ...)
|
|
205
|
+
- `revin.py` — causal RevIN
|
|
206
|
+
- `loss.py` — multi-quantile (pinball) loss
|
|
207
|
+
- `trainer.py` — PyTorch Lightning trainer class
|
|
208
|
+
|
|
209
|
+
- `model/inference/` — main PatchFM model class for inference
|
|
210
|
+
- `modules.py` — core modules with caching support
|
|
211
|
+
- `forecaster.py` — Forecasting model and rollout logic
|
|
212
|
+
|
|
213
|
+
- `dataset/` — data loading and preprocessing
|
|
214
|
+
- `artificial.py` — synthetic dataset : artificial signals + TSMixup + KernelSynth
|
|
215
|
+
- `gift.py` — GIFT-Eval pretraining dataset loading and preprocessing
|
|
216
|
+
- `get_data.py` — utility to fetch and preprocess datasets
|
|
217
|
+
- `chronosdata.py` — loading of the synthetic datasets generated with Chronos (TSMixup and KernelSynth) with download functions integrated
|
|
218
|
+
|
|
219
|
+
- `configs/` — model and training configurations
|
|
220
|
+
- `notebooks/inference` — how to load a trained model and generate forecasts
|
|
221
|
+
- `training.py` — training script using PyTorch Lightning
|
|
222
|
+
|
|
223
|
+
## Acknowledgements
|
|
224
|
+
We thank the authors of the following repositories for inspiration and code snippets:
|
|
225
|
+
- [TiRex](https://github.com/NX-AI/tirex)
|
|
@@ -22,8 +22,13 @@ class Forecaster(nn.Module):
|
|
|
22
22
|
self.n_quantiles = len(self.quantiles)
|
|
23
23
|
self.max_patches = self.max_seq_len // self.patch_len
|
|
24
24
|
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
if config["full_leakage"]:
|
|
26
|
+
print("Loading full leakage model from HuggingFace Hub...")
|
|
27
|
+
model_name = "vilhess/PatchFM-Leakage"
|
|
28
|
+
else:
|
|
29
|
+
print("Loading base model from HuggingFace Hub...")
|
|
30
|
+
model_name = "vilhess/PatchFM"
|
|
31
|
+
base_model = PatchFM.from_pretrained(model_name)
|
|
27
32
|
|
|
28
33
|
self._init_from_base(base_model)
|
|
29
34
|
|
|
@@ -41,7 +46,7 @@ class Forecaster(nn.Module):
|
|
|
41
46
|
self.revin = CausalRevIN()
|
|
42
47
|
self.proj_embedding = ResidualBlock(
|
|
43
48
|
in_dim=self.patch_len,
|
|
44
|
-
hid_dim=
|
|
49
|
+
hid_dim=4 * self.d_model,
|
|
45
50
|
out_dim=self.d_model
|
|
46
51
|
)
|
|
47
52
|
self.transformer_encoder = TransformerEncoder(
|
|
@@ -51,7 +56,7 @@ class Forecaster(nn.Module):
|
|
|
51
56
|
)
|
|
52
57
|
self.proj_output = ResidualBlock(
|
|
53
58
|
in_dim=self.d_model,
|
|
54
|
-
hid_dim=
|
|
59
|
+
hid_dim=4 * self.d_model,
|
|
55
60
|
out_dim=self.patch_len * self.n_quantiles
|
|
56
61
|
)
|
|
57
62
|
|
|
@@ -175,7 +175,7 @@ class ResidualBlock(nn.Module):
|
|
|
175
175
|
self.hidden_layer = nn.Linear(in_dim, hid_dim)
|
|
176
176
|
self.output_layer = nn.Linear(hid_dim, out_dim)
|
|
177
177
|
self.residual_layer = nn.Linear(in_dim, out_dim)
|
|
178
|
-
self.act = nn.
|
|
178
|
+
self.act = nn.SiLU()
|
|
179
179
|
|
|
180
180
|
def forward(self, x):
|
|
181
181
|
hid = self.act(self.hidden_layer(x))
|
|
@@ -313,7 +313,7 @@ class PatchFM(nn.Module, PyTorchModelHubMixin):
|
|
|
313
313
|
self.revin = CausalRevIN()
|
|
314
314
|
self.proj_embedding = ResidualBlock(
|
|
315
315
|
in_dim=self.patch_len,
|
|
316
|
-
hid_dim=
|
|
316
|
+
hid_dim=4 * self.d_model,
|
|
317
317
|
out_dim=self.d_model
|
|
318
318
|
)
|
|
319
319
|
self.transformer_encoder = TransformerEncoder(
|
|
@@ -323,6 +323,6 @@ class PatchFM(nn.Module, PyTorchModelHubMixin):
|
|
|
323
323
|
)
|
|
324
324
|
self.proj_output = ResidualBlock(
|
|
325
325
|
in_dim=self.d_model,
|
|
326
|
-
hid_dim=
|
|
326
|
+
hid_dim=4 * self.d_model,
|
|
327
327
|
out_dim=self.patch_len * self.n_quantiles
|
|
328
328
|
)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: patchfm
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.1.1
|
|
4
4
|
Summary: a Foundation Model for Univariate Time Series Forecasting
|
|
5
5
|
Author-email: Samy-Melwan Vilhes <samy-melwan.vilhes@insa-rouen.fr>
|
|
6
6
|
License: MIT License
|
|
@@ -42,20 +42,41 @@ Dynamic: license-file
|
|
|
42
42
|
|
|
43
43
|
# A tutorial on how to build a Foundation Model for Univariate Time Series Forecasting
|
|
44
44
|
|
|
45
|
-
[Huggingface Model Card](https://huggingface.co/vilhess/PatchFM)
|
|
46
|
-
[Paper Model Card](https://github.com/vilhess/PatchFM/blob/main/main.pdf)
|
|
47
|
-
|
|
48
45
|
A concise, reproducible recipe for training a transformer-based, patch-to-patch forecasting model for univariate time series. The approach mirrors Large Language Model (LLM) practices (next-token → next-patch) while remaining lightweight compared to a classic LLM and practical.
|
|
49
46
|
|
|
47
|
+
Our model is deployed on the [TS-Arena benchmark](https://ts-arena.live) and achieves competitive performance against state-of-the-art methods under the name `LITIS/PatchFM-Large`.
|
|
48
|
+
|
|
49
|
+
## Resuls on the FEV benchmark:
|
|
50
|
+
|
|
51
|
+
**Our model is competitive with the state-of-the-art notably compared to [MOIRAI2.0](https://arxiv.org/pdf/2511.11698)**
|
|
52
|
+
|
|
53
|
+
| Model Name | Win Rate | Skill Score |
|
|
54
|
+
|----------------------|----------|-------------|
|
|
55
|
+
| (🥇) Chronos-2 | 0.9008 | 0.4728 |
|
|
56
|
+
| (🥈) TiRex | 0.8092 | 0.4268 |
|
|
57
|
+
| (🥉) TimesFM-2.5 | 0.8085 | 0.4668 |
|
|
58
|
+
| (4) Toto-1.0 | 0.7069 | 0.4110 |
|
|
59
|
+
| (5) **PatchFM (us)** | 0.6677 | 0.3983 |
|
|
60
|
+
| (6) Moirai-2.0 | 0.6546 | 0.4026 |
|
|
61
|
+
| (7) Chronos-Bolt | 0.6277 | 0.3889 |
|
|
62
|
+
| (8) Sundial-Base | 0.4446 | 0.3387 |
|
|
63
|
+
| (9) CatBoost (Recursive)| 0.3362 | 0.2301 |
|
|
64
|
+
| (10) LightGBM (Recursive)| 0.3123 | 0.2168 |
|
|
65
|
+
| (11) AutoTheta | 0.2938 | 0.0546 |
|
|
66
|
+
| (12) Seasonal Naive | 0.2058 | 0.0000 |
|
|
67
|
+
| (13) Naive | 0.1404 | -0.4540 |
|
|
68
|
+
| (14) Drift | 0.0915 | -0.4578 |
|
|
69
|
+
|
|
70
|
+
|
|
50
71
|
## Highlights
|
|
51
72
|
- Next-patch prediction objective (autoregressive, causal)
|
|
52
73
|
- Patch-based representation of time series (tokens ↔ patches)
|
|
53
74
|
- Causal masking self-attention with RoPE (relative positions)
|
|
54
|
-
- RevIN
|
|
75
|
+
- Causal RevIN with $\sinh^{-1}$ transform for normalization
|
|
55
76
|
- SwiGLU feed-forward networks
|
|
56
|
-
-
|
|
77
|
+
- Autoregressive multi-quantile decoding [MOIRAI2.0](https://arxiv.org/pdf/2511.11698)
|
|
57
78
|
- KV-cache for efficient long-horizon inference
|
|
58
|
-
-
|
|
79
|
+
- flips equivariance during inference (optional) [Reverso](https://arxiv.org/pdf/2602.17634v1)
|
|
59
80
|
|
|
60
81
|
## Quick Start
|
|
61
82
|
|
|
@@ -71,21 +92,22 @@ pip install -r requirements.txt
|
|
|
71
92
|
|
|
72
93
|
```python
|
|
73
94
|
import torch
|
|
74
|
-
|
|
95
|
+
|
|
75
96
|
from configs import PatchFMConfig
|
|
97
|
+
from model import Forecaster
|
|
76
98
|
|
|
77
99
|
# --- Instantiate model ---
|
|
78
|
-
config = PatchFMConfig(load_from_hub=True)
|
|
100
|
+
config = PatchFMConfig(load_from_hub=True)
|
|
79
101
|
model = Forecaster(config)
|
|
80
102
|
|
|
81
103
|
# --- Inference ---
|
|
82
104
|
forecast_horizon = 64
|
|
83
105
|
seq = torch.randn(1, 1024) # (batch, time)
|
|
84
|
-
pred_median, pred_quantiles = model(seq, forecast_horizon=forecast_horizon, quantiles=[0.1, 0.5, 0.9],
|
|
106
|
+
pred_median, pred_quantiles = model(seq, forecast_horizon=forecast_horizon, quantiles=[0.1, 0.5, 0.9], flip_equivariance=True) # (batch, time), (batch, time, quantiles)
|
|
85
107
|
```
|
|
86
108
|
|
|
87
|
-
### from pip package
|
|
88
109
|
|
|
110
|
+
### from pip package
|
|
89
111
|
1. Install the package from PyPI
|
|
90
112
|
```bash
|
|
91
113
|
pip install patchfm
|
|
@@ -94,9 +116,11 @@ pip install patchfm
|
|
|
94
116
|
|
|
95
117
|
```python
|
|
96
118
|
import torch
|
|
97
|
-
|
|
119
|
+
|
|
120
|
+
from patchfm import Forecaster, PatchFMConfig
|
|
98
121
|
|
|
99
122
|
# same as above
|
|
123
|
+
pred_median, pred_quantiles = model(seq, forecast_horizon=forecast_horizon, quantiles=[0.1, 0.5, 0.9], flip_equivariance=True) # (batch, time), (batch, time, quantiles)
|
|
100
124
|
```
|
|
101
125
|
|
|
102
126
|
We provide an extended quick start example in [notebooks/tutorial.ipynb](./notebooks/tutorial.ipynb).
|
|
@@ -114,6 +138,7 @@ If you dont have suitable hardware you can run the the extended quick start exam
|
|
|
114
138
|
- Training: Multi-quantile (pinball) loss across positions, elements, and quantiles $\mathcal{Q}$.
|
|
115
139
|
- Inference: Predict next patch; roll out autoregressively for long horizons.
|
|
116
140
|
- KV-cache: during inference, cache keys/values to avoid redundant computations.
|
|
141
|
+
- Flip-equivariance: during inference, flip input sequence and average predictions to improve robustness (at cost of doubling batch size).
|
|
117
142
|
|
|
118
143
|
## Problem Formulation
|
|
119
144
|
Given context patches $x_{p_1}, \ldots, x_{p_n}$, predict the next patch $x_{p_{i+1}}$ for each position $i$ using only past patches (causality). The model outputs quantiles $\{\hat{x}_{p_{i+1}}^{(q)}: q \in \mathcal{Q}\}$ with median (q=0.5) as the point forecast.
|
|
@@ -135,18 +160,83 @@ Aggregate over positions, patch elements, and quantiles.
|
|
|
135
160
|
- Forecast horizon: 32 steps per forward pass
|
|
136
161
|
- Quantiles $\mathcal{Q}$: {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
|
|
137
162
|
- Layers: 6
|
|
138
|
-
- Attention heads:
|
|
163
|
+
- Attention heads: 32 (head dim 64)
|
|
139
164
|
- Model dim: 2048
|
|
140
165
|
- Parameters: ~300M
|
|
141
166
|
|
|
142
167
|
## Inference
|
|
143
168
|
- Single step: predict next patch ($P_{len}$ values)
|
|
144
169
|
- Long-horizon: append prediction to context and repeat (optionally drop oldest patch to keep window fixed)
|
|
170
|
+
- Flip-equivariance [Reverso](https://arxiv.org/pdf/2602.17634v1): optionally flip input sequence and average predictions to improve robustness (at cost of doubling batch size):
|
|
171
|
+
$$y = \frac{1}{2} \left( f(x) - f(-x) \right)$$
|
|
172
|
+
|
|
173
|
+
- ### Autoregressive Inference with Quantile Forecasting ([Moirai 2.0](https://arxiv.org/pdf/2511.11698v1))
|
|
174
|
+
During autoregressive inference, the model generates forecasted values patch by patch. At each time step, the predicted patch is fed back into the model as input for the next step. This iterative process continues until the desired forecast horizon is reached.
|
|
175
|
+
|
|
176
|
+
When performing quantile forecasting, the situation becomes more complex. Instead of producing a single patch per step, the model outputs multiple patches corresponding to different quantiles (e.g., 0.1, 0.5, 0.9). Since the model expects a single patch for the next time step, it is not straightforward to feed all quantile predictions back into the model simultaneously.
|
|
177
|
+
|
|
178
|
+
A common workaround is to feed only the median prediction (the 0.5 quantile) back into the model at each step. While this approach preserves the autoregressive structure, it discards the uncertainty information captured by the other quantiles.
|
|
179
|
+
|
|
180
|
+
An alternative approach is **autoregressive multi-quantile decoding**, as proposed in [Moirai 2.0](https://arxiv.org/pdf/2511.11698v1). This method enables consistent autoregressive generation while preserving the full predictive distribution across quantiles. However, it is computationally more expensive than the median-only approach as it requires duplicating the context for each quantile.
|
|
181
|
+
|
|
182
|
+
<div style="display: flex; gap: 10px; align-items: flex-start;">
|
|
183
|
+
<div>
|
|
184
|
+
<img src="assets/classic_forecast_animation.gif" alt="Classic Autoregressive Inference" width="450">
|
|
185
|
+
<p style="text-align:center;">Classic Autoregressive Inference</p>
|
|
186
|
+
</div>
|
|
187
|
+
<div>
|
|
188
|
+
<img src="assets/quantile_forecast_animation.gif" alt="Autoregressive Multi-Quantile Decoding" width="450">
|
|
189
|
+
<p style="text-align:center;">Autoregressive Multi-Quantile Decoding</p>
|
|
190
|
+
</div>
|
|
191
|
+
</div>
|
|
192
|
+
|
|
193
|
+
The algorithm proceeds as follows:
|
|
194
|
+
|
|
195
|
+
1. **Initialization**
|
|
196
|
+
Start with the initial context window of observed data
|
|
197
|
+
**Shape:** `(BS × L)`
|
|
198
|
+
- `BS`: batch size
|
|
199
|
+
- `L`: context length
|
|
200
|
+
- `P`: patch size
|
|
201
|
+
- `Q`: number of quantiles
|
|
202
|
+
- `H`: forecast horizon
|
|
203
|
+
- `i=1`: current algorithm step
|
|
204
|
+
|
|
205
|
+
2. **First Quantile Prediction (Forward Pass)**
|
|
206
|
+
Predict the quantiles for the next patch using the current context.
|
|
207
|
+
**Output shape:** `(BS × P × Q)`
|
|
208
|
+
|
|
209
|
+
3. **Context Duplication**
|
|
210
|
+
For each predicted quantile, create a separate context by appending the corresponding predicted patch to the current context.
|
|
211
|
+
This increases the number of contexts by a factor of `Q` at each step.
|
|
212
|
+
**New context shape:** `(BS × Q × i(L + P))`
|
|
213
|
+
|
|
214
|
+
4. **Next Forward Pass**
|
|
215
|
+
For each duplicated context, predict the quantiles of the next patch.
|
|
216
|
+
**Output shape:** `(BS × Q × P × Q)`
|
|
217
|
+
|
|
218
|
+
5. **Quantile Collapse**
|
|
219
|
+
- Permute and reshape the predictions to aggregate all possible quantile paths:
|
|
220
|
+
**Intermediate shape:** `(BS × P × Q²)`
|
|
221
|
+
- Compute the quantiles across the `Q²` predictions to obtain the final quantile estimates for the next patch.
|
|
222
|
+
**Final shape:** `(BS × P × Q)`
|
|
223
|
+
- Increment the step counter `i ← i + 1`.
|
|
224
|
+
|
|
225
|
+
6. **Iteration**
|
|
226
|
+
Repeat Steps 3–5 until the forecast horizon `H` is reached, i.e., until the total number of predicted time steps satisfies
|
|
227
|
+
`i × P ≥ H`.
|
|
228
|
+
|
|
229
|
+
This procedure preserves predictive uncertainty across quantiles while maintaining the autoregressive structure of the model. Although it is computationally more expensive than feeding only the median prediction (0.5 quantile) back into the model, it remains tractable in practice and enables consistent multi-quantile forecasting.
|
|
230
|
+
|
|
231
|
+
⚠️ **Warning**
|
|
232
|
+
With this strategy, the median prediction (0.5 quantile) does **not necessarily** match the prediction obtained by autoregressively feeding only the median patch back into the model at each step.
|
|
233
|
+
|
|
234
|
+
This discrepancy arises because the *quantile collapse* step aggregates predictions across all possible quantile paths. As a result, the median is computed from the combined multi-path distribution rather than from a single deterministic trajectory, which can lead to different estimates compared to the single-path (median-only) autoregressive approach.
|
|
145
235
|
|
|
146
236
|
## Datasets
|
|
147
|
-
- UTSD (Unified Time Series Dataset) [UTSD]: seven domains (Energy, IoT, Nature, Web, Health, Transport, Environment). We work with UTSD-12G (~18M series after preprocessing).
|
|
148
237
|
- GIFT-Eval pretraining dataset [GIFT]: aligned with the GIFT-Eval dataset but without data leakage issue with the benchmark. The dataset contains approximately 71 univariate and 17 multivariate time series datasets from various
|
|
149
238
|
domains and various frequencies. After preprocessing, this yields approximately 600K univariate series.
|
|
239
|
+
- Chronos synthetic datasets [Chronos]: two large synthetic datasets generated with Chronos, one with TSMixup and one with KernelSynth. Each contains approximately 10 million univariate series and 1 million respectively, each signal of length 1024.
|
|
150
240
|
- Artificial: ~1M synthetic series (sinusoidal, linear, polynomial, logarithmic) plus mixtures via TSMixup [Chronos]; Gaussian Process samples via KernelSynth (mixtures of RBF/periodic/linear kernels with swept hyperparameters).
|
|
151
241
|
|
|
152
242
|
## Repository Layout
|
|
@@ -164,10 +254,9 @@ domains and various frequencies. After preprocessing, this yields approximately
|
|
|
164
254
|
|
|
165
255
|
- `dataset/` — data loading and preprocessing
|
|
166
256
|
- `artificial.py` — synthetic dataset : artificial signals + TSMixup + KernelSynth
|
|
167
|
-
- `utsd.py` — Unified Time Series Dataset (UTSD) loading and preprocessing
|
|
168
257
|
- `gift.py` — GIFT-Eval pretraining dataset loading and preprocessing
|
|
169
258
|
- `get_data.py` — utility to fetch and preprocess datasets
|
|
170
|
-
- `
|
|
259
|
+
- `chronosdata.py` — loading of the synthetic datasets generated with Chronos (TSMixup and KernelSynth) with download functions integrated
|
|
171
260
|
|
|
172
261
|
- `configs/` — model and training configurations
|
|
173
262
|
- `notebooks/inference` — how to load a trained model and generate forecasts
|
patchfm-3.0.0/README.md
DELETED
|
@@ -1,136 +0,0 @@
|
|
|
1
|
-
# A tutorial on how to build a Foundation Model for Univariate Time Series Forecasting
|
|
2
|
-
|
|
3
|
-
[Huggingface Model Card](https://huggingface.co/vilhess/PatchFM)
|
|
4
|
-
[Paper Model Card](https://github.com/vilhess/PatchFM/blob/main/main.pdf)
|
|
5
|
-
|
|
6
|
-
A concise, reproducible recipe for training a transformer-based, patch-to-patch forecasting model for univariate time series. The approach mirrors Large Language Model (LLM) practices (next-token → next-patch) while remaining lightweight compared to a classic LLM and practical.
|
|
7
|
-
|
|
8
|
-
## Highlights
|
|
9
|
-
- Next-patch prediction objective (autoregressive, causal)
|
|
10
|
-
- Patch-based representation of time series (tokens ↔ patches)
|
|
11
|
-
- Causal masking self-attention with RoPE (relative positions)
|
|
12
|
-
- RevIN (Reversible Instance Normalization)
|
|
13
|
-
- SwiGLU feed-forward networks
|
|
14
|
-
- Multi-quantile outputs (median + uncertainty bands)
|
|
15
|
-
- KV-cache for efficient long-horizon inference
|
|
16
|
-
- Autoregressive multi-quantile decoding [MOIRAI2.0](https://arxiv.org/pdf/2511.11698) (currently without KV-cache)
|
|
17
|
-
|
|
18
|
-
## Quick Start
|
|
19
|
-
|
|
20
|
-
### from source code
|
|
21
|
-
|
|
22
|
-
1. Clone the repository and install dependencies
|
|
23
|
-
```bash
|
|
24
|
-
git clone https://github.com/vilhess/PatchFM
|
|
25
|
-
cd PatchFM
|
|
26
|
-
pip install -r requirements.txt
|
|
27
|
-
```
|
|
28
|
-
2. Run inference with a pretrained model from Huggingface Hub
|
|
29
|
-
|
|
30
|
-
```python
|
|
31
|
-
import torch
|
|
32
|
-
from model import Forecaster
|
|
33
|
-
from configs import PatchFMConfig
|
|
34
|
-
|
|
35
|
-
# --- Instantiate model ---
|
|
36
|
-
config = PatchFMConfig(load_from_hub=True)
|
|
37
|
-
model = Forecaster(config)
|
|
38
|
-
|
|
39
|
-
# --- Inference ---
|
|
40
|
-
forecast_horizon = 64
|
|
41
|
-
seq = torch.randn(1, 1024) # (batch, time)
|
|
42
|
-
pred_median, pred_quantiles = model(seq, forecast_horizon=forecast_horizon, quantiles=[0.1, 0.5, 0.9], quantile_decoding=True) # (batch, time), (batch, time, quantiles)
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
### from pip package
|
|
46
|
-
|
|
47
|
-
1. Install the package from PyPI
|
|
48
|
-
```bash
|
|
49
|
-
pip install patchfm
|
|
50
|
-
```
|
|
51
|
-
2. Run inference with a pretrained model from Huggingface Hub
|
|
52
|
-
|
|
53
|
-
```python
|
|
54
|
-
import torch
|
|
55
|
-
from patchfm import PatchFMConfig, Forecaster
|
|
56
|
-
|
|
57
|
-
# same as above
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
We provide an extended quick start example in [notebooks/tutorial.ipynb](./notebooks/tutorial.ipynb).
|
|
61
|
-
If you dont have suitable hardware you can run the the extended quick start example example also in Google Colab:
|
|
62
|
-
|
|
63
|
-
<a target="_blank" href="https://colab.research.google.com/drive/17sdf-7luCkv5TaeLj3Z6kIaTDkwkz3VR?usp=share_link">
|
|
64
|
-
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open Quick Start In Colab"/>
|
|
65
|
-
</a>
|
|
66
|
-
|
|
67
|
-
## Method (TL;DR)
|
|
68
|
-
- Patching: Split a context signal of length $w$ into $P_{num} = w / P_{len}$ patches of length $P_{len}$.
|
|
69
|
-
- Causal RevIN: Normalize input signal and denormalize outputs to the original scale without statistics leakage.
|
|
70
|
-
- Architecture: Input residual MLP → stacked Transformer blocks (MHA + SwiGLU FFN, pre-norm, residual) → $|\mathcal{Q}|$ output heads mapping back to patch space.
|
|
71
|
-
- Positional encoding: Rotary Position Embeddings (RoPE) applied to queries/keys.
|
|
72
|
-
- Training: Multi-quantile (pinball) loss across positions, elements, and quantiles $\mathcal{Q}$.
|
|
73
|
-
- Inference: Predict next patch; roll out autoregressively for long horizons.
|
|
74
|
-
- KV-cache: during inference, cache keys/values to avoid redundant computations.
|
|
75
|
-
|
|
76
|
-
## Problem Formulation
|
|
77
|
-
Given context patches $x_{p_1}, \ldots, x_{p_n}$, predict the next patch $x_{p_{i+1}}$ for each position $i$ using only past patches (causality). The model outputs quantiles $\{\hat{x}_{p_{i+1}}^{(q)}: q \in \mathcal{Q}\}$ with median (q=0.5) as the point forecast.
|
|
78
|
-
|
|
79
|
-
## Loss: Multi-Quantile (Pinball)
|
|
80
|
-
For residual $u = x - \hat{x}^{(q)}$:
|
|
81
|
-
$$\rho_q(u) = \begin{cases} q\,u, & u \ge 0,\\ (q-1)\,u, & u < 0. \end{cases}$$
|
|
82
|
-
Aggregate over positions, patch elements, and quantiles.
|
|
83
|
-
|
|
84
|
-
## Architecture
|
|
85
|
-
- Input MLP: $\mathbb{R}^{P_{len}} \to \mathbb{R}^{dim}$ residual 2-layer MLP (ReLU)
|
|
86
|
-
- Multi-Head Attention: causal mask, RoPE; queries/keys/values per head
|
|
87
|
-
- FFN: SwiGLU (SiLU-gated), pre-norm + residual
|
|
88
|
-
- Output heads: |Q| linear maps $\mathbb{R}^{dim} \to \mathbb{R}^{P_{len}}$ (one per quantile)
|
|
89
|
-
|
|
90
|
-
### Model Details
|
|
91
|
-
- Patch size: 32
|
|
92
|
-
- Max context: 32 patches (1024 steps)
|
|
93
|
-
- Forecast horizon: 32 steps per forward pass
|
|
94
|
-
- Quantiles $\mathcal{Q}$: {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
|
|
95
|
-
- Layers: 6
|
|
96
|
-
- Attention heads: 64 (head dim 32)
|
|
97
|
-
- Model dim: 2048
|
|
98
|
-
- Parameters: ~300M
|
|
99
|
-
|
|
100
|
-
## Inference
|
|
101
|
-
- Single step: predict next patch ($P_{len}$ values)
|
|
102
|
-
- Long-horizon: append prediction to context and repeat (optionally drop oldest patch to keep window fixed)
|
|
103
|
-
|
|
104
|
-
## Datasets
|
|
105
|
-
- UTSD (Unified Time Series Dataset) [UTSD]: seven domains (Energy, IoT, Nature, Web, Health, Transport, Environment). We work with UTSD-12G (~18M series after preprocessing).
|
|
106
|
-
- GIFT-Eval pretraining dataset [GIFT]: aligned with the GIFT-Eval dataset but without data leakage issue with the benchmark. The dataset contains approximately 71 univariate and 17 multivariate time series datasets from various
|
|
107
|
-
domains and various frequencies. After preprocessing, this yields approximately 600K univariate series.
|
|
108
|
-
- Artificial: ~1M synthetic series (sinusoidal, linear, polynomial, logarithmic) plus mixtures via TSMixup [Chronos]; Gaussian Process samples via KernelSynth (mixtures of RBF/periodic/linear kernels with swept hyperparameters).
|
|
109
|
-
|
|
110
|
-
## Repository Layout
|
|
111
|
-
|
|
112
|
-
- `model/training/` — main PatchFM model class
|
|
113
|
-
|
|
114
|
-
- `modules.py` - core modules (Residual Layers, MHA, SwiGLU, RoPE, Transformer Encoder, ...)
|
|
115
|
-
- `revin.py` — causal RevIN
|
|
116
|
-
- `loss.py` — multi-quantile (pinball) loss
|
|
117
|
-
- `trainer.py` — PyTorch Lightning trainer class
|
|
118
|
-
|
|
119
|
-
- `model/inference/` — main PatchFM model class for inference
|
|
120
|
-
- `modules.py` — core modules with caching support
|
|
121
|
-
- `forecaster.py` — Forecasting model and rollout logic
|
|
122
|
-
|
|
123
|
-
- `dataset/` — data loading and preprocessing
|
|
124
|
-
- `artificial.py` — synthetic dataset : artificial signals + TSMixup + KernelSynth
|
|
125
|
-
- `utsd.py` — Unified Time Series Dataset (UTSD) loading and preprocessing
|
|
126
|
-
- `gift.py` — GIFT-Eval pretraining dataset loading and preprocessing
|
|
127
|
-
- `get_data.py` — utility to fetch and preprocess datasets
|
|
128
|
-
- `generate_data.py` — utility to generate and save the KernelSynth dataset (long to generate)
|
|
129
|
-
|
|
130
|
-
- `configs/` — model and training configurations
|
|
131
|
-
- `notebooks/inference` — how to load a trained model and generate forecasts
|
|
132
|
-
- `training.py` — training script using PyTorch Lightning
|
|
133
|
-
|
|
134
|
-
## Acknowledgements
|
|
135
|
-
We thank the authors of the following repositories for inspiration and code snippets:
|
|
136
|
-
- [TiRex](https://github.com/NX-AI/tirex)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|