timestral README

README проекта с github.com/mistralai/timestral. Одним файлом markdown: README.md.

Timestral

Timestral

Blog post · Hugging Face collection · License

Timestral is a family of time series foundation models for multivariate probabilistic forecasting, with support for past-only and known-future covariates. This repository provides standalone inference for Timestral models. It needs only PyTorch, NumPy, safetensors and huggingface_hub, and runs on CPU or GPU.

License: the code in this repository is licensed under Apache 2.0. The Timestral model weights are released separately on the Hugging Face Hub under a Modified MIT license. See License.

Highlights

At launch, Timestral-209M ranked first among pretrained and zero-shot models on the three main public forecasting benchmarks:

All four sizes (5M, 28M, 123M, 209M) sit on the Pareto front of accuracy versus model size. Full results are in the blog post and the model cards on Hugging Face.

Install

pip install git+https://github.com/mistralai/timestral.git   # Python >= 3.10, torch >= 2.4

Or from a clone with uv, using the versions pinned in uv.lock:

git clone https://github.com/mistralai/timestral.git && cd timestral
uv sync --frozen
source .venv/bin/activate

Models

The weights are on the Hugging Face Hub, in the Mistral AI organization:

model Hub repo weights (fp32)
Timestral-5M mistralai/Timestral-5M 21 MB
Timestral-28M mistralai/Timestral-28M 111 MB
Timestral-123M mistralai/Timestral-123M 490 MB
Timestral-209M mistralai/Timestral-209M 837 MB

from_pretrained downloads config.json and model.safetensors once to the Hub cache.

Forecast

import numpy as np
from timestral import TimestralForecaster

forecaster = TimestralForecaster.from_pretrained("mistralai/Timestral-209M")  # device="cuda" for a GPU

context = np.random.randn(2, 1, 2000).cumsum(-1)        # (series, variates, time); NaN = missing
forecast = forecaster.forecast(context, prediction_length=96)

forecast.quantiles.shape   # (2, 1, 96, 21): series, variates, horizon, quantile levels
forecast.quantile_levels   # (0.01, 0.05, 0.1, ..., 0.9, 0.95, 0.99)
forecast.median            # (2, 1, 96)
forecast.quantile(0.9)     # (2, 1, 96)

Loading options

from_pretrained takes a Hub repo id or a local directory with config.json and model.safetensors.

Covariates

forecast = forecaster.forecast(
    context,                          # (B, V, T)
    prediction_length=96,
    past_covariates=past,             # (B, C_past, T): known over the context only
    known_covariates=known,           # (B, C_known, T + 96): known over context and horizon
)

Covariates are conditioning rows: they are not forecast, and covariate rows never read the targets. Known-future covariate rows whose values are all 0 or 1 are treated as indicators. NaN marks a missing covariate value.

Categorical covariates

forecast = forecaster.forecast(
    context,
    prediction_length=96,
    categorical_past_covariates=codes_past,     # (B, C, T) numeric category codes, NaN = missing
    categorical_known_covariates=codes_known,   # (B, C, T + 96)
)

Pass categories as numeric codes (for example pandas.factorize), with NaN for missing values and for any padding. For a univariate target each categorical row is target-encoded per series: category c becomes (mean + sum_c) / (1 + count_c) over the forward-filled context, missing values form their own category, and a category absent from the context maps to the series mean. Multivariate targets receive the raw codes. Encoded rows are appended after the numeric covariates. timestral.covariate_encoding.target_encode exposes the encoding.

Architecture

Timestral is a causal patch-based transformer trained with Decoupled Horizon Forecasting (DHF), where forecasts are generated from separate prediction tokens that read the causally encoded context. Each variate is a target, a past-only covariate or a known-future covariate: covariates pass information to targets but never read them, and only known-future covariates see the forecast horizon. A quantile head outputs 21 non-crossing quantiles per time step, and each forecast patch is denormalized with the statistics of the context and the block's earlier predicted medians.

Benchmarks

Timestral is evaluated zero-shot on three benchmarks, with the forecaster defaults and the full history up to 32768 steps as context:

benchmark inputs beyond the target
GIFT-Eval (97 configs) past_feat_dynamic_real as past covariates
fev-bench (100 tasks) past and known covariates; categorical columns target-encoded
TIME (98 tasks) none (TIME has no covariates)

Contributing

We do not accept pull requests. Bug reports and questions are welcome as GitHub issues.

timestral is maintained by the team at Mistral AI. We answer issues on a best-effort basis and fix security vulnerabilities and major bugs. See CONTRIBUTING.md for how to report an issue.

License

The code in this repository (the timestral package and tests) is licensed under the Apache License 2.0. See the LICENSE file.

The Timestral model weights are not covered by the Apache License 2.0. They are distributed separately on the Hugging Face Hub under a Modified MIT license, available in each model repository (Timestral-5M, Timestral-28M, Timestral-123M, Timestral-209M). When using the model weights, you must not use them in a manner that infringes, misappropriates, or otherwise violates any third party's rights, including intellectual property rights.

timestral (mistralai/timestral)

Ищем в базе…

Что это такое?Timestral — семейство фундаментальных моделей для временных рядов от Mistral AI, предназначенных для многомерного вероятностного прогнозирования. Они поддерживают ковариаты, известные только по прошлым данным, и ковариаты, известные заранее на будущие периоды. Этот репозиторий содержит автономный код для запуска моделей в режиме инференса.
Это полноценный фреймворк для обучения или просто библиотека для инференса?Это автономная библиотека для инференса: вы загружаете предобученные веса из Hugging Face Hub и вызываете forecast() для своих данных, а не обучаете модель самостоятельно.
Как мне запустить прогноз с Timestral?Установите пакет (например, из клона репозитория с помощью uv, используя зафиксированный uv.lock), затем загрузите модель через Timestral.from_pretrained(), указав идентификатор репозитория Hub, например mistralai/Timestral-209M, и передайте свой массив временного ряда в forecast().
Что нужно установить, чтобы этим пользоваться?Нужны только PyTorch, NumPy, safetensors и huggingface_hub. Веса модели автоматически загружаются из Hugging Face Hub при первом запуске.
Для кого это предназначено?Для всех, кто строит конвейеры прогнозирования и нуждается в предобученной модели временных рядов, которая работает без дообучения (zero-shot), а не в обучении модели с нуля. Например, для специалистов по данным и ML-инженеров.
Код и веса модели распространяются под одной лицензией?Нет. Код инференса в этом репозитории распространяется по лицензии Apache 2.0, а веса модели публикуются отдельно на Hugging Face под модифицированной лицензией MIT с дополнительными ограничениями, направленными против нарушения прав третьих сторон.
Насколько точны прогнозы Timestral по сравнению с другими моделями?На момент запуска Timestral-209M занял первое место среди предобученных моделей и моделей, работающих без дообучения (zero-shot), на бенчмарках GIFT-Eval, TIME и fev-bench. Все четыре размера находятся на фронте Парето по соотношению точности и размера модели.
Какие размеры модели доступны?На Hugging Face опубликованы четыре размера: Timestral-5M, 28M, 123M и 209M. Веса в формате fp32 весят от 21 МБ до 837 МБ.
Что такое Decoupled Horizon Forecasting?Это подход к обучению, лежащий в основе Timestral: каузальный трансформер на основе патчей генерирует прогнозы с помощью отдельных токенов предсказания, которые считывают закодированный каузально контекст. Прогноз не декодируется авторегрессионно, шаг за шагом.
Могу ли я использовать ковариаты, помимо целевого ряда?Да, можно передавать ковариаты, известные только по прошлым данным, известные заранее на будущее и категориальные. Ковариаты влияют на прогноз, но сами не прогнозируются. Категориальные ковариаты кодируются по целевой переменной отдельно для каждого ряда.
Автор
mistralai
Размер
0.3 MB
Звёзды
1.2K
Обновлён
КоммитOct 15
Возраст
1 мес
Коммиты · 90 дней