Skip to content

Forecasting API

tirex2.ForecastModel

High-level, batched forecasting interface around a :class:TiRex2 backbone.

The wrapper takes ownership of the model only as a delegate: it batches the :class:~tirex.model.types.TimeseriesType it is given (building them from a GluonTS dataset in :meth:forecast_gluon), feeds them to :meth:TiRex2.predict, and formats the per-series quantile forecasts into the requested output type. Attribute access falls through to the wrapped model, so the backbone's own methods (e.g. predict) remain reachable on the wrapper.

Parameters:

Name Type Description Default
model TiRex2

An instantiated, ready-for-inference backbone exposing predict(timeseries: list[TimeseriesType], prediction_length: int) -> list[Tensor] and a quantiles buffer holding the quantile levels it forecasts.

required
Source code in src/tirex2/api_adapter/forecast.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
class ForecastModel:
    """High-level, batched forecasting interface around a :class:`TiRex2` backbone.

    The wrapper takes ownership of the model only as a delegate: it batches the
    :class:`~tirex.model.types.TimeseriesType` it is given (building them from a GluonTS
    dataset in :meth:`forecast_gluon`), feeds them to :meth:`TiRex2.predict`, and formats the
    per-series quantile forecasts into the requested output type. Attribute access falls
    through to the wrapped model, so the backbone's own methods (e.g. ``predict``) remain
    reachable on the wrapper.

    Parameters
    ----------
    model : TiRex2
        An instantiated, ready-for-inference backbone exposing
        ``predict(timeseries: list[TimeseriesType], prediction_length: int) -> list[Tensor]``
        and a ``quantiles`` buffer holding the quantile levels it forecasts.
    """

    def __init__(self, model):
        self.model = model

    def _quantile_levels(self) -> list[float]:
        """Return the model's forecast quantile levels as clean Python floats (float32 noise rounded off)."""
        return [round(float(q), 6) for q in self.model.quantiles]

    def __getattr__(self, name):
        """Delegate unknown attribute lookups to the wrapped model."""
        try:
            model = object.__getattribute__(self, "model")
        except AttributeError:
            raise AttributeError(name)
        return getattr(model, name)

    def forecast(
        self,
        timeseries: list[TimeseriesType],
        prediction_length: int,
        output_type: ForecastOutputType = "torch",
        batch_size: int = 512,
        yield_per_batch: bool = False,
        **predict_kwargs,
    ):
        """Forecast a list of :class:`TimeseriesType`, each carrying a target and optional covariates.

        Extra ``predict_kwargs`` are forwarded verbatim to :meth:`TiRex2.predict`.
        In particular ``tta_sign_flip`` controls sign-flip test-time augmentation
        (roughly doubles inference cost), and ``tta_diff`` controls postprocessor
        differencing; when omitted, the checkpoint's configured defaults
        (``model-config.yaml``) are used. Pass ``True``/``False`` to override.

        Examples
        --------
        >>> import torch
        >>> from tirex2 import TimeseriesType, load_model
        >>> model = load_model("NX-AI/TiRex-2", device="cpu")
        >>> ts = TimeseriesType(target=torch.randn(1, 128), past_covariates=None, future_covariates=None)
        >>> forecasts = model.forecast([ts], prediction_length=32, output_type="numpy")
        >>> forecasts[0].shape
        (1, 9, 32)
        """
        assert batch_size >= 1, "Batch size must be >= 1"
        return _gen_forecast(
            self.model,
            list(timeseries),
            None,
            prediction_length,
            output_type,
            batch_size,
            yield_per_batch,
            self._quantile_levels(),
            **predict_kwargs,
        )

    def forecast_gluon(
        self,
        gluonDataset,
        prediction_length: int,
        output_type: ForecastOutputType = "torch",
        batch_size: int = 512,
        yield_per_batch: bool = False,
        multivariate: bool = False,
        data_kwargs: dict = {},
        **predict_kwargs,
    ):
        """Forecast every entry of a GluonTS dataset, carrying its covariates and metadata through.

        With ``multivariate=False`` (default) each target variate is rendered as its own
        univariate ``QuantileForecast``; with ``multivariate=True`` each series yields a single
        forecast retaining the variate axis, so a multivariate dataset is scored jointly rather
        than channel-by-channel. The flag only affects ``output_type="gluonts"`` formatting.

        Extra ``predict_kwargs`` are forwarded verbatim to :meth:`TiRex2.predict`.
        In particular ``tta_sign_flip`` controls sign-flip test-time augmentation
        (roughly doubles inference cost), and ``tta_diff`` controls postprocessor
        differencing; when omitted, the checkpoint's configured defaults
        (``model-config.yaml``) are used. Pass ``True``/``False`` to override.
        """
        assert batch_size >= 1, "Batch size must be >= 1"
        try:
            from .gluon import build_gluon_timeseries
        except ImportError:
            raise ValueError("forecast_gluon needs GluonTS but GluonTS is not available (not installed)!")

        timeseries, meta = build_gluon_timeseries(gluonDataset, multivariate=multivariate, **data_kwargs)
        return _gen_forecast(
            self.model,
            timeseries,
            meta,
            prediction_length,
            output_type,
            batch_size,
            yield_per_batch,
            self._quantile_levels(),
            **predict_kwargs,
        )

    def forecast_fev(
        self,
        window: "fev.EvaluationWindow",
        prediction_length: int,
        output_type: ForecastOutputType = "torch",
        batch_size: int = 512,
        yield_per_batch: bool = False,
        data_kwargs: dict | None = None,
        quantile_levels: list[float] | None = None,
        return_inference_time: bool = False,
        **predict_kwargs,
    ):
        """Forecast a single FEV evaluation window.

        The call mirrors :meth:`forecast_gluon`: convert the external dataset
        representation into :class:`TimeseriesType`, then delegate batching,
        prediction and output rendering to the common forecast path. Use
        ``output_type="fev"`` to return predictions in the format accepted by
        ``fev.Task.evaluation_summary``. Pass ``return_inference_time=True`` to
        also return the model-only prediction time, excluding FEV input
        conversion and final ``DatasetDict`` construction.
        """
        assert batch_size >= 1, "Batch size must be >= 1"
        try:
            import fev  # noqa: F401
        except ImportError:
            raise ValueError("forecast_fev needs fev but fev is not available (not installed)!")

        data_kwargs = data_kwargs or {}
        timeseries, meta = build_fev_timeseries(window, **data_kwargs)
        if output_type == "fev":
            requested_quantiles = quantile_levels if quantile_levels is not None else self._quantile_levels()
            for item in meta:
                item["quantile_levels"] = requested_quantiles

        return _gen_forecast(
            self.model,
            timeseries,
            meta,
            prediction_length,
            output_type,
            batch_size,
            yield_per_batch,
            self._quantile_levels(),
            return_inference_time=return_inference_time,
            **predict_kwargs,
        )

forecast

forecast(timeseries: list[TimeseriesType], prediction_length: int, output_type: ForecastOutputType = 'torch', batch_size: int = 512, yield_per_batch: bool = False, **predict_kwargs)

Forecast a list of :class:TimeseriesType, each carrying a target and optional covariates.

Extra predict_kwargs are forwarded verbatim to :meth:TiRex2.predict. In particular tta_sign_flip controls sign-flip test-time augmentation (roughly doubles inference cost), and tta_diff controls postprocessor differencing; when omitted, the checkpoint's configured defaults (model-config.yaml) are used. Pass True/False to override.

Examples:

>>> import torch
>>> from tirex2 import TimeseriesType, load_model
>>> model = load_model("NX-AI/TiRex-2", device="cpu")
>>> ts = TimeseriesType(target=torch.randn(1, 128), past_covariates=None, future_covariates=None)
>>> forecasts = model.forecast([ts], prediction_length=32, output_type="numpy")
>>> forecasts[0].shape
(1, 9, 32)
Source code in src/tirex2/api_adapter/forecast.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def forecast(
    self,
    timeseries: list[TimeseriesType],
    prediction_length: int,
    output_type: ForecastOutputType = "torch",
    batch_size: int = 512,
    yield_per_batch: bool = False,
    **predict_kwargs,
):
    """Forecast a list of :class:`TimeseriesType`, each carrying a target and optional covariates.

    Extra ``predict_kwargs`` are forwarded verbatim to :meth:`TiRex2.predict`.
    In particular ``tta_sign_flip`` controls sign-flip test-time augmentation
    (roughly doubles inference cost), and ``tta_diff`` controls postprocessor
    differencing; when omitted, the checkpoint's configured defaults
    (``model-config.yaml``) are used. Pass ``True``/``False`` to override.

    Examples
    --------
    >>> import torch
    >>> from tirex2 import TimeseriesType, load_model
    >>> model = load_model("NX-AI/TiRex-2", device="cpu")
    >>> ts = TimeseriesType(target=torch.randn(1, 128), past_covariates=None, future_covariates=None)
    >>> forecasts = model.forecast([ts], prediction_length=32, output_type="numpy")
    >>> forecasts[0].shape
    (1, 9, 32)
    """
    assert batch_size >= 1, "Batch size must be >= 1"
    return _gen_forecast(
        self.model,
        list(timeseries),
        None,
        prediction_length,
        output_type,
        batch_size,
        yield_per_batch,
        self._quantile_levels(),
        **predict_kwargs,
    )

forecast_gluon

forecast_gluon(gluonDataset, prediction_length: int, output_type: ForecastOutputType = 'torch', batch_size: int = 512, yield_per_batch: bool = False, multivariate: bool = False, data_kwargs: dict = {}, **predict_kwargs)

Forecast every entry of a GluonTS dataset, carrying its covariates and metadata through.

With multivariate=False (default) each target variate is rendered as its own univariate QuantileForecast; with multivariate=True each series yields a single forecast retaining the variate axis, so a multivariate dataset is scored jointly rather than channel-by-channel. The flag only affects output_type="gluonts" formatting.

Extra predict_kwargs are forwarded verbatim to :meth:TiRex2.predict. In particular tta_sign_flip controls sign-flip test-time augmentation (roughly doubles inference cost), and tta_diff controls postprocessor differencing; when omitted, the checkpoint's configured defaults (model-config.yaml) are used. Pass True/False to override.

Source code in src/tirex2/api_adapter/forecast.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
def forecast_gluon(
    self,
    gluonDataset,
    prediction_length: int,
    output_type: ForecastOutputType = "torch",
    batch_size: int = 512,
    yield_per_batch: bool = False,
    multivariate: bool = False,
    data_kwargs: dict = {},
    **predict_kwargs,
):
    """Forecast every entry of a GluonTS dataset, carrying its covariates and metadata through.

    With ``multivariate=False`` (default) each target variate is rendered as its own
    univariate ``QuantileForecast``; with ``multivariate=True`` each series yields a single
    forecast retaining the variate axis, so a multivariate dataset is scored jointly rather
    than channel-by-channel. The flag only affects ``output_type="gluonts"`` formatting.

    Extra ``predict_kwargs`` are forwarded verbatim to :meth:`TiRex2.predict`.
    In particular ``tta_sign_flip`` controls sign-flip test-time augmentation
    (roughly doubles inference cost), and ``tta_diff`` controls postprocessor
    differencing; when omitted, the checkpoint's configured defaults
    (``model-config.yaml``) are used. Pass ``True``/``False`` to override.
    """
    assert batch_size >= 1, "Batch size must be >= 1"
    try:
        from .gluon import build_gluon_timeseries
    except ImportError:
        raise ValueError("forecast_gluon needs GluonTS but GluonTS is not available (not installed)!")

    timeseries, meta = build_gluon_timeseries(gluonDataset, multivariate=multivariate, **data_kwargs)
    return _gen_forecast(
        self.model,
        timeseries,
        meta,
        prediction_length,
        output_type,
        batch_size,
        yield_per_batch,
        self._quantile_levels(),
        **predict_kwargs,
    )

forecast_fev

forecast_fev(window: EvaluationWindow, prediction_length: int, output_type: ForecastOutputType = 'torch', batch_size: int = 512, yield_per_batch: bool = False, data_kwargs: dict | None = None, quantile_levels: list[float] | None = None, return_inference_time: bool = False, **predict_kwargs)

Forecast a single FEV evaluation window.

The call mirrors :meth:forecast_gluon: convert the external dataset representation into :class:TimeseriesType, then delegate batching, prediction and output rendering to the common forecast path. Use output_type="fev" to return predictions in the format accepted by fev.Task.evaluation_summary. Pass return_inference_time=True to also return the model-only prediction time, excluding FEV input conversion and final DatasetDict construction.

Source code in src/tirex2/api_adapter/forecast.py
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
def forecast_fev(
    self,
    window: "fev.EvaluationWindow",
    prediction_length: int,
    output_type: ForecastOutputType = "torch",
    batch_size: int = 512,
    yield_per_batch: bool = False,
    data_kwargs: dict | None = None,
    quantile_levels: list[float] | None = None,
    return_inference_time: bool = False,
    **predict_kwargs,
):
    """Forecast a single FEV evaluation window.

    The call mirrors :meth:`forecast_gluon`: convert the external dataset
    representation into :class:`TimeseriesType`, then delegate batching,
    prediction and output rendering to the common forecast path. Use
    ``output_type="fev"`` to return predictions in the format accepted by
    ``fev.Task.evaluation_summary``. Pass ``return_inference_time=True`` to
    also return the model-only prediction time, excluding FEV input
    conversion and final ``DatasetDict`` construction.
    """
    assert batch_size >= 1, "Batch size must be >= 1"
    try:
        import fev  # noqa: F401
    except ImportError:
        raise ValueError("forecast_fev needs fev but fev is not available (not installed)!")

    data_kwargs = data_kwargs or {}
    timeseries, meta = build_fev_timeseries(window, **data_kwargs)
    if output_type == "fev":
        requested_quantiles = quantile_levels if quantile_levels is not None else self._quantile_levels()
        for item in meta:
            item["quantile_levels"] = requested_quantiles

    return _gen_forecast(
        self.model,
        timeseries,
        meta,
        prediction_length,
        output_type,
        batch_size,
        yield_per_batch,
        self._quantile_levels(),
        return_inference_time=return_inference_time,
        **predict_kwargs,
    )