# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import contextlib import logging import math import time import warnings from pathlib import Path from typing import TYPE_CHECKING, Callable, Literal, Mapping, Sequence import numpy as np import pandas as pd import torch from einops import rearrange, repeat from transformers import AutoConfig from chronos.base import BaseChronosPipeline, ForecastType from chronos.chronos2.dataset import Chronos2Dataset, DatasetMode, PreparedInput, TensorOrArray from chronos.chronos2.preprocess import from_data_frame, prepare_inputs from chronos.df_utils import get_series_lengths, infer_freq_from_df, make_future_df, validate_and_normalize_df from chronos.utils import interpolate_quantiles, weighted_quantile from . import trend from .aggregation import AGGREGATIONS from .model import Chronos3Model from .text import Chronos3TextEncoder, Chronos3TextInputs, ForecastTexts from .text.encoding import _append_known_covariates, _build_item_text, _ItemText if TYPE_CHECKING: import datasets import fev logger = logging.getLogger(__name__) Inputs = ( TensorOrArray | Sequence[TensorOrArray] | Sequence[Mapping[str, TensorOrArray | Mapping[str, TensorOrArray]]] | Sequence[PreparedInput] ) class Chronos3Pipeline(BaseChronosPipeline): """Forecasting with ``Chronos3Model``. The inputs are those of ``Chronos2Pipeline``; fine-tuning is not supported.""" forecast_type: ForecastType = ForecastType.QUANTILES #: ``trend_differencing``: a target trends if its context's least-squares line explains at least this share of #: its variance (or it is a running total) ... trend_min_r2: float = 0.7 #: ... over at least this many observations, each directly after another (so its first difference is observed) trend_min_observations: int = 8 #: ``context_upsampling``: the factor a short context is upsampled by ... upsampling_factor: int = 4 #: ... where its history is at most this many steps: longer histories gain little and cost the most upsampling_max_history: int = 1024 def __init__(self, model: Chronos3Model): super().__init__(inner_model=model) self.model = model self._compiled = False tc = model.text_config #: embeds the text of a text checkpoint (its embedding model loads on first use); assign one to choose its #: device, dtype or a local copy of the embedding model self.text_encoder = None if tc is None else Chronos3TextEncoder(tc, device=model.device) def compile(self, **torch_compile_kwargs) -> "Chronos3Pipeline": """Compile the encoder in place with ``torch.compile`` (``dynamic=True`` by default) and return ``self``. A few compiled versions serve any number of series, context length and horizon: one for most inputs, one more each for a horizon of one output patch, a context of one patch and ``embed``; each pays its compile on first use. Batches whose series are each their own group and grouped batches compile separately. Batches of one series run eager. Call after moving the model to its device. Forecasts differ from eager by rounding. Compiled versions of all models in a process share one dynamo cache, so this raises the process-wide ``torch._dynamo.config.recompile_limit`` to at least 64. Compiled forecasts are not thread-safe; forecast eager from several threads. """ torch._dynamo.config.recompile_limit = max(torch._dynamo.config.recompile_limit, 64) self.model.encoder.compile(**{"dynamic": True, **torch_compile_kwargs}) self._compiled = True return self @property def model_context_length(self) -> int: return self.model.chronos_config.context_length @property def model_output_patch_size(self) -> int: return self.model.chronos_config.output_patch_size @property def model_prediction_length(self) -> int: return self.max_output_patches * self.model_output_patch_size @property def quantiles(self) -> list[float]: return self.model.chronos_config.quantiles @property def max_output_patches(self) -> int: return self.model.chronos_config.max_output_patches def fit(self, *args, **kwargs): raise NotImplementedError("Fine-tuning Chronos-3 is not supported") @torch.no_grad() def predict( self, inputs: Inputs, prediction_length: int | None = None, *, batch_size: int = 128, context_length: int | None = None, aggregation: Literal["sum", "max", "min"] | None = None, aggregation_indices: Sequence[int] | None = None, cross_learning: bool = True, limit_prediction_length: bool = False, symmetric_averaging: bool = True, trend_differencing: bool = False, context_upsampling: bool = True, clip_nonnegative: bool = True, snap_integers: bool = True, nan_context_fallback: Literal["zero"] | None = "zero", **kwargs, ) -> list[torch.Tensor]: """ Generate forecasts for the given time series. Parameters ---------- inputs The time series to forecast, in any of the formats of ``Chronos2Pipeline.predict``: a 3-d tensor or array (batch, n_variates, history_length), a list of 1-d or 2-d tensors or arrays, or a list of dicts with ``target``, ``past_covariates`` and ``future_covariates``. prediction_length The number of time steps to predict, by default the model's prediction length. Longer horizons are forecast autoregressively, which may degrade quality. batch_size The number of series per forward pass, targets and covariates included, by default 128 context_length The maximum context length, by default (and at most) the model's context length aggregation "sum", "max" or "min": forecast the quantiles of this aggregate of each target over the steps ``aggregation_indices`` instead of each step. ``prediction_length`` must be at most ``model_prediction_length``. Not supported with text. aggregation_indices The 0-based steps of the forecast horizon to aggregate, by default ``range(prediction_length)``. Requires ``aggregation``. cross_learning If True (default), all the tasks in a batch are forecast jointly and share information, so a task's forecast depends on the other tasks in its batch (and on ``batch_size``). False forecasts each task (its targets and covariates together) on its own, which sacrifices some accuracy but makes inference faster: the inputs are batched by context length, and batches of univariate tasks skip the model's attention across series. Not used with text limit_prediction_length If True, raise when ``prediction_length`` is greater than the model's prediction length, by default False symmetric_averaging Average each forecast with the mirrored forecast of the negated series, except where the context minimum is exactly 0. Doubles the compute of a batch, unless every target in it has a context minimum of exactly 0. Not used with text or ``aggregation``. By default True trend_differencing If True, targets with a clear trend (a near-linear context, see ``trend_min_r2``, or a running total) are also forecast from their first differences, and the two forecasts are averaged. Costs extra forward passes for the series with a trend. Not used with text or ``aggregation``. By default False; ``predict_df`` turns it on for daily or coarser data. context_upsampling Forecast a series whose history is at most ``upsampling_max_history`` steps from its context upsampled ``upsampling_factor`` times (every step repeated, so the model reads finer patches), and average the forecast back over every ``upsampling_factor`` steps. Needs ``upsampling_factor`` x ``prediction_length`` to fit one forward pass; with ``cross_learning``, the longest history of the batch decides. More accurate on short histories, at up to ``upsampling_factor`` times their compute. Not used with text or ``aggregation``. By default True clip_nonnegative Clip forecasts at 0 where the context is non-negative, by default True snap_integers Round forecasts where the context is integer-valued, by default True. Rounds the model's quantiles: levels that ``predict_quantiles`` interpolates between them may not be integers nan_context_fallback "zero" (default): forecast 0 for series whose context is entirely missing; None: the model's output Returns ------- A list of tensors, one per target (univariate or multivariate) in ``inputs``, of shape (n_variates, n_quantiles, prediction_length), or (n_variates, n_quantiles, 1) with ``aggregation``. """ model_prediction_length = self.model_prediction_length if prediction_length is None: prediction_length = model_prediction_length # the maximum number of output patches of one forward pass, before the long-horizon heuristic kicks in max_output_patches = kwargs.pop("max_output_patches", self.max_output_patches) # the quantiles appended to the context to forecast long horizons; a subset of the model's quantiles unrolled_quantiles = kwargs.pop("unrolled_quantiles", [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) after_batch_callback: Callable = kwargs.pop("after_batch", lambda: None) # from predict_df: per input, the text of each of its rows (position rows included in ``inputs``) text: Sequence[_ItemText] | None = kwargs.pop("text", None) if len(kwargs) > 0: raise TypeError(f"Unexpected keyword arguments: {list(kwargs.keys())}.") if text is not None: if self.text_encoder is None: raise ValueError("text: this checkpoint was not trained with text") # a longer forecast unrolls, and the unrolled steps would not read the text limit = min(max_output_patches, self.max_output_patches) * self.model_output_patch_size if prediction_length > limit: raise ValueError(f"with text, prediction_length is at most {limit}") # cross-learning would mix the text of different items cross_learning = False # the text describes the series as given, not negated, differenced or upsampled symmetric_averaging = trend_differencing = context_upsampling = False aggregation_mask = None if aggregation is not None or aggregation_indices is not None: aggregation_mask = self._aggregation_mask( aggregation, aggregation_indices, prediction_length, max_output_patches, text ) # the aggregation head was trained and evaluated on raw forecasts symmetric_averaging = trend_differencing = context_upsampling = False if not set(unrolled_quantiles).issubset(self.quantiles): raise ValueError( f"Unrolled quantiles must be a subset of the model's quantiles. " f"Found: {unrolled_quantiles=}, model_quantiles={self.quantiles}" ) if nan_context_fallback not in (None, "zero"): raise ValueError(f"nan_context_fallback must be None or 'zero', found {nan_context_fallback!r}") levels = torch.tensor(self.quantiles, dtype=torch.float64) if symmetric_averaging and not torch.allclose(levels, 1 - levels.flip(0)): raise ValueError("symmetric_averaging needs symmetric quantile levels; pass symmetric_averaging=False") if prediction_length > model_prediction_length: msg = ( f"We recommend keeping prediction length <= {model_prediction_length}. " "The quality of longer predictions may degrade since the model is not optimized for it. " ) if limit_prediction_length: msg += "You can turn off this check by setting `limit_prediction_length=False`." raise ValueError(msg) warnings.warn(msg) if context_length is None: context_length = self.model_context_length if context_length < 1: raise ValueError(f"context_length must be at least 1, found {context_length}") if context_length > self.model_context_length: warnings.warn( f"The specified context_length {context_length} is greater than the model's default context length " f"{self.model_context_length}. Resetting context_length to {self.model_context_length}." ) context_length = self.model_context_length prepared = [_truncated(x, context_length) for x in prepare_inputs(inputs, prediction_length)] order = None if not cross_learning and text is None and sum(len(x["context"]) for x in prepared) > batch_size: # each input's forecast does not depend on its batch: batch by context length (less left padding) order = sorted(range(len(prepared)), key=lambda i: -prepared[i]["context"].shape[-1]) prepared = [prepared[i] for i in order] predictions = self._forecast( prepared, batch_size=batch_size, cross_learning=cross_learning, symmetric_averaging=symmetric_averaging, trend_differencing=trend_differencing, context_upsampling=context_upsampling, clip_nonnegative=clip_nonnegative, snap_integers=snap_integers, nan_context_fallback=nan_context_fallback, text=text, after_batch=after_batch_callback, unrolled_quantiles=torch.tensor(unrolled_quantiles), prediction_length=prediction_length, max_output_patches=max_output_patches, aggregation=aggregation, aggregation_mask=aggregation_mask, ) if order is not None: unsorted: list[torch.Tensor] = [torch.empty(0)] * len(order) for position, i in enumerate(order): unsorted[i] = predictions[position] predictions = unsorted return predictions def _aggregation_mask( self, aggregation: str | None, indices: Sequence[int] | None, prediction_length: int, max_output_patches: int, text: Sequence[_ItemText] | None, ) -> torch.Tensor: """The (prediction_length,) mask of the steps ``indices``, after checking the aggregation arguments.""" if aggregation is None: raise ValueError("aggregation_indices requires aggregation") if aggregation not in AGGREGATIONS: raise ValueError(f"aggregation must be one of {AGGREGATIONS}, found {aggregation!r}") if text is not None: raise ValueError("aggregation is not supported with text") limit = min(max_output_patches, self.max_output_patches) * self.model_output_patch_size if prediction_length > limit: raise ValueError(f"with aggregation, prediction_length must be at most {limit}") steps = np.arange(prediction_length) if indices is None else np.asarray(indices) # bools are ints in Python: a 0/1 mask would silently read as the steps 0 and 1 if steps.ndim != 1 or steps.size == 0 or not np.issubdtype(steps.dtype, np.integer): raise ValueError("aggregation_indices must be a non-empty sequence of integer steps") if len(np.unique(steps)) != len(steps) or steps.min() < 0 or steps.max() >= prediction_length: raise ValueError(f"aggregation_indices must be unique steps in [0, {prediction_length})") mask = torch.zeros(prediction_length, dtype=torch.bool) mask[torch.from_numpy(steps)] = True return mask def _forecast( self, inputs: Sequence[PreparedInput], batch_size: int, cross_learning: bool, symmetric_averaging: bool, trend_differencing: bool, context_upsampling: bool, clip_nonnegative: bool, snap_integers: bool, nan_context_fallback: Literal["zero"] | None, text: Sequence[_ItemText] | None, after_batch: Callable, **predict_kwargs, ) -> list[torch.Tensor]: """The forecast of each input's targets (n_targets, n_quantiles, prediction_length, or 1 with an aggregation), batch by batch, with the adjustments of ``predict`` applied per batch.""" dataset = Chronos2Dataset( inputs, context_length=self.model_context_length, # the inputs are truncated already prediction_length=predict_kwargs["prediction_length"], batch_size=batch_size, output_patch_size=self.model_output_patch_size, mode=DatasetMode.TEST, ) median_index = self.quantiles.index(0.5) predictions: list[torch.Tensor] = [] for batch in dataset: context, group_ids, future_covariates = batch["context"], batch["group_ids"], batch["future_covariates"] if cross_learning: group_ids = torch.zeros_like(group_ids) text_inputs = None if text is not None: assert self.text_encoder is not None item_texts = text[len(predictions) : len(predictions) + len(batch["target_idx_ranges"])] rows_per_item = torch.bincount(batch["group_ids"]).tolist() if [len(t.tags) for t in item_texts] != rows_per_item: raise ValueError( f"text rows per input {[len(t.tags) for t in item_texts]} != input rows {rows_per_item}" ) text_inputs = self.text_encoder(item_texts) is_target = torch.zeros(len(context), dtype=torch.bool) for start, end in batch["target_idx_ranges"]: is_target[start:end] = True # decided once per batch, so all the passes over a row upsample it alike upsampled = self._upsampled_rows(context, group_ids, **predict_kwargs) & context_upsampling def forecast( context: torch.Tensor, group_ids: torch.Tensor, future_covariates: torch.Tensor, upsampled: torch.Tensor, used: torch.Tensor, ) -> torch.Tensor: """``used``: the rows whose forecast is read.""" def predict(sign: int) -> torch.Tensor: return sign * self._predict_upsampled( context=sign * context, group_ids=group_ids, future_covariates=sign * future_covariates, upsampled=upsampled, text=text_inputs, # noqa: B023 (called in this iteration only) **predict_kwargs, ) prediction = predict(1) if symmetric_averaging: # negation swaps q and 1 - q: with symmetric levels, flipping the quantile axis mirrors them floored_at_zero = context.nan_to_num(nan=torch.inf).amin(dim=-1) == 0 if not floored_at_zero[used].all(): # else no forecast that is read uses the mirrored one average = (prediction + predict(-1).flip(1)) / 2 prediction = torch.where(floored_at_zero[:, None, None], prediction, average) return prediction prediction = forecast(context, group_ids, future_covariates, upsampled, is_target) if trend_differencing: # the inputs with a trending target are forecast again with all their targets differenced (so related # targets stay on one scale); only the trending targets average the two forecasts trending = is_target & trend.is_trending(context, self.trend_min_r2, self.trend_min_observations) # cumulating from before a trailing gap would lag the forecast by the gap's increments trending &= torch.isfinite(context[:, -1]) if trending.any(): # with cross_learning, the differenced pass learns across these inputs only (on purpose) rows = torch.isin(batch["group_ids"], batch["group_ids"][trending]) differenced = forecast( trend.difference(context[rows], is_target[rows]), group_ids[rows], future_covariates[rows], upsampled[rows], trending[rows], ) average = (prediction[rows] + trend.cumulate(differenced, context[rows], median_index)) / 2 prediction[rows] = torch.where(trending[rows, None, None], average, prediction[rows]) observed = context.nan_to_num(nan=0.0) if clip_nonnegative: nonnegative = (observed >= 0).all(dim=-1) prediction[nonnegative] = prediction[nonnegative].clamp(min=0) if snap_integers: integer = (observed == observed.round()).all(dim=-1) prediction[integer] = prediction[integer].round() if nan_context_fallback == "zero": prediction[~torch.isfinite(context).any(dim=-1)] = 0.0 predictions.extend(prediction[start:end] for start, end in batch["target_idx_ranges"]) after_batch() return predictions def _upsampled_rows( self, context: torch.Tensor, group_ids: torch.Tensor, prediction_length: int, max_output_patches: int, **_ ) -> torch.Tensor: """Per row, whether the longest history of its group is at most ``upsampling_max_history`` steps (and fits the context upsampled) and ``upsampling_factor`` x ``prediction_length`` fits one forward pass.""" r = self.upsampling_factor if r * prediction_length > min(max_output_patches, self.max_output_patches) * self.model_output_patch_size: return torch.zeros(len(context), dtype=torch.bool) observed = torch.isfinite(context) length = torch.where(observed.any(-1), context.shape[-1] - observed.int().argmax(-1), 0) _, group = torch.unique(group_ids, return_inverse=True) length = torch.zeros(int(group.max()) + 1, dtype=length.dtype).scatter_reduce(0, group, length, "amax")[group] return length <= min(self.upsampling_max_history, self.model_context_length // r) def _predict_upsampled( self, context: torch.Tensor, group_ids: torch.Tensor, future_covariates: torch.Tensor, upsampled: torch.Tensor, prediction_length: int, **predict_kwargs, ) -> torch.Tensor: """``_predict_batch``, with the context and future covariates of the ``upsampled`` rows (a bool per row) upsampled ``upsampling_factor`` times (every step repeated) and their forecast averaged back over every ``upsampling_factor`` steps.""" if not upsampled.any(): # e.g. with text or aggregation return self._predict_batch( context=context, group_ids=group_ids, future_covariates=future_covariates, prediction_length=prediction_length, **predict_kwargs, ) r = self.upsampling_factor prediction = torch.empty(len(context), len(self.quantiles), prediction_length) # an upsampled row keeps only the steps an upsampled history can have, not the batch's left padding keep_up = min(self.upsampling_max_history, self.model_context_length // r) for rows, factor, keep in ((~upsampled, 1, self.model_context_length), (upsampled, r, keep_up)): if rows.any(): forecast = self._predict_batch( context=context[rows][..., -keep:].repeat_interleave(factor, -1), group_ids=group_ids[rows], future_covariates=future_covariates[rows].repeat_interleave(factor, dim=-1), prediction_length=factor * prediction_length, **predict_kwargs, ) prediction[rows] = forecast.unflatten(-1, (prediction_length, factor)).mean(-1) return prediction def _predict_batch( self, context: torch.Tensor, group_ids: torch.Tensor, future_covariates: torch.Tensor, unrolled_quantiles: torch.Tensor, prediction_length: int, max_output_patches: int, text: Chronos3TextInputs | None = None, aggregation: str | None = None, aggregation_mask: torch.Tensor | None = None, ) -> torch.Tensor: """(batch, n_quantiles, prediction_length) forecasts on the CPU; beyond ``max_output_patches``, by unrolling ``unrolled_quantiles`` of the forecast into the context (never with ``text`` or ``aggregation``). With ``aggregation`` over the steps of ``aggregation_mask`` (prediction_length,), (batch, n_quantiles, 1).""" # every row its own group (singleton groups): the model is told so by group_ids=None, which spares its group # attention singleton_groups = text is None and len(torch.unique(group_ids)) == len(group_ids) context = context.to(device=self.model.device, dtype=torch.float32) group_ids = group_ids.to(device=self.model.device) if text is not None: text = Chronos3TextInputs(*(None if t is None else t.to(self.model.device) for t in text)) future_covariates = future_covariates.to(device=self.model.device, dtype=torch.float32) def num_output_patches(remaining: int) -> int: return min(math.ceil(remaining / self.model_output_patch_size), max_output_patches) prediction = self._predict_step( context, None if singleton_groups else group_ids, future_covariates, num_output_patches(prediction_length), text=text, aggregation=aggregation, aggregation_mask=aggregation_mask, ) if aggregation is not None: # one forward pass, a horizon of 1: nothing to unroll return prediction.cpu() predictions = [prediction] remaining = prediction_length - prediction.shape[-1] if remaining > 0: # one path per unrolled quantile, each its own group n_paths = len(unrolled_quantiles) context = repeat(context, "b t -> b n t", n=n_paths) future_covariates = repeat(future_covariates, "b t -> b n t", n=n_paths) group_ids = repeat(group_ids, "b -> b n", n=n_paths) * n_paths + torch.arange( n_paths, device=self.model.device ) # the probability mass covered by each of the n_paths * n_quantiles samples sample_weights = torch.outer( _prob_mass_per_quantile_level(unrolled_quantiles), _prob_mass_per_quantile_level(torch.tensor(self.quantiles)), ) while remaining > 0: unrolled = interpolate_quantiles( query_quantile_levels=unrolled_quantiles, original_quantile_levels=self.quantiles, original_values=rearrange(prediction, "b q h -> b h q"), ) context = torch.cat([context, rearrange(unrolled, "b h n -> b n h")], dim=-1) context = context[..., -self.model_context_length :] # known future covariates replace their forecasts in the context step = prediction.shape[-1] known = future_covariates[..., :step] context[..., -step:] = torch.where(torch.isnan(known), context[..., -step:], known) future_covariates = future_covariates[..., step:] prediction = self._predict_step( rearrange(context, "b n t -> (b n) t"), None if singleton_groups else rearrange(group_ids, "b n -> (b n)"), rearrange(future_covariates, "b n t -> (b n) t"), num_output_patches(remaining), ) prediction = weighted_quantile( query_quantile_levels=self.quantiles, sample_weights=rearrange(sample_weights, "n q -> (n q)"), samples=rearrange(prediction, "(b n) q h -> b h (n q)", n=n_paths), ) prediction = rearrange(prediction, "b h q -> b q h") predictions.append(prediction) remaining -= prediction.shape[-1] return torch.cat(predictions, dim=-1)[..., :prediction_length].to(dtype=torch.float32, device="cpu") @contextlib.contextmanager def _compile_scope(self, num_rows: int): """The scope of an encoder call. A 1-row batch runs eager: dynamo specializes size 1 and would compile a version of its own. Other batches trace without duck sizing, so a first batch whose row count happens to equal another size (e.g. its number of context patches) doesn't bake that equality in and recompile on the next batch.""" if not self._compiled: yield elif num_rows == 1: with torch.compiler.set_stance("force_eager"): yield else: # private, so imported here: if it moves, only compiled pipelines fail import torch.fx.experimental._config as fx_config with fx_config.patch(use_duck_shape=False): # type: ignore[attr-defined] yield def _predict_step( self, context: torch.Tensor, group_ids: torch.Tensor | None, future_covariates: torch.Tensor, num_output_patches: int, text: Chronos3TextInputs | None = None, aggregation: str | None = None, aggregation_mask: torch.Tensor | None = None, ) -> torch.Tensor: output_size = num_output_patches * self.model_output_patch_size future_covariates = future_covariates[..., :output_size] future_covariates = torch.nn.functional.pad( future_covariates, (0, output_size - future_covariates.shape[-1]), value=torch.nan ) if aggregation_mask is not None: aggregation_mask = aggregation_mask.to(context.device).expand(len(context), 1, -1) with self._compile_scope(len(context)): output = self.model( context=context, group_ids=group_ids, future_covariates=future_covariates, num_output_patches=num_output_patches, aggregation_mask=aggregation_mask, text=text, ) if aggregation is not None: # (batch, 1 mask, 3 aggregations, n_quantiles) return output.aggregate_preds[:, 0, AGGREGATIONS.index(aggregation), :, None].to(context) return output.quantile_preds.to(context) def predict_quantiles( # type: ignore[override] self, inputs: Inputs, prediction_length: int | None = None, quantile_levels: list[float] = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], *, aggregation: Literal["sum", "max", "min"] | None = None, aggregation_indices: Sequence[int] | None = None, **predict_kwargs, ) -> tuple[list[torch.Tensor], list[torch.Tensor]]: """ Refer to ``Chronos3Pipeline.predict`` for shared parameters. Additional parameters --------------------- quantile_levels Quantile levels to compute, by default [0.1, 0.2, ..., 0.9] Returns ------- quantiles A list of tensors, one per target in ``inputs``, of shape (n_variates, prediction_length, len(quantile_levels)). mean A list of tensors, one per target in ``inputs``, of shape (n_variates, prediction_length): the median. """ predictions = self.predict( inputs, prediction_length=prediction_length, aggregation=aggregation, aggregation_indices=aggregation_indices, **predict_kwargs, ) predictions = [pred.transpose(-1, -2) for pred in predictions] # (..., horizon, levels) if set(quantile_levels).issubset(self.quantiles): indices = [self.quantiles.index(q) for q in quantile_levels] quantiles = [pred[..., indices] for pred in predictions] else: if min(quantile_levels) < min(self.quantiles) or max(quantile_levels) > max(self.quantiles): logger.warning( f"\tQuantiles to be predicted ({quantile_levels}) are not within the range of " f"quantiles that Chronos-3 was trained on ({self.quantiles}). " "Quantile predictions will be set to the minimum/maximum levels at which Chronos-3 " "was trained on. This may significantly affect the quality of the predictions." ) quantiles = [interpolate_quantiles(quantile_levels, self.quantiles, pred) for pred in predictions] mean = [pred[..., self.quantiles.index(0.5)] for pred in predictions] return quantiles, mean def predict_df( self, df: pd.DataFrame, future_df: pd.DataFrame | None = None, *, id_column: str = "item_id", timestamp_column: str = "timestamp", target: str | list[str] = "target", prediction_length: int | None = None, quantile_levels: list[float] = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], batch_size: int = 128, context_length: int | None = None, aggregation: Literal["sum", "max", "min"] | None = None, aggregation_indices: Sequence[int] | None = None, cross_learning: bool = True, validate_inputs: bool = True, freq: str | None = None, text: ForecastTexts | None = None, trend_differencing: bool | None = None, **predict_kwargs, ) -> pd.DataFrame: """ Forecast the time series of a long-format DataFrame, optionally conditioned on text. The other arguments are those of ``Chronos2Pipeline.predict_df``; ``predict_kwargs`` go to ``Chronos3Pipeline.predict``. Parameters ---------- aggregation, aggregation_indices See ``predict``. cross_learning See ``predict``: True by default (unlike ``Chronos2Pipeline.predict_df``); False is faster but somewhat less accurate. text From ``Translator.translate_df`` on the same df, ``future_df`` and ``prediction_length``. Items without text get the no-text tokens. A bound's floor or ceiling clips its target's forecast. The text is embedded by ``self.text_encoder``, created on the model's device; after moving the model, or for another device or dtype, assign a new ``Chronos3TextEncoder``. trend_differencing See ``predict``. If None (default), it is turned on for daily or coarser data, based on ``freq`` (inferred from ``df`` if not given). Returns ------- The forecasts, with the columns ``id_column``, ``timestamp_column``, "target_name", "predictions" (the median) and one per quantile level. With ``aggregation`` (see ``predict``), one row per item and target, at the first timestamp of the forecast horizon. """ if prediction_length is None: prediction_length = self.model_prediction_length if not isinstance(target, list): target = [target] if validate_inputs: df, future_df = validate_and_normalize_df( df=df, future_df=future_df, target_columns=target, prediction_length=prediction_length, id_column=id_column, timestamp_column=timestamp_column, ) freq = freq or infer_freq_from_df(df, id_column=id_column, timestamp_column=timestamp_column) if trend_differencing is None: trend_differencing = _is_daily_or_coarser(freq) item_texts = None if text is not None: tc = self.model.text_config if tc is None: raise ValueError("text: this checkpoint was not trained with text") if text.text_version != tc.text_version: raise ValueError( f"text is in text_version {text.text_version}, the model reads {tc.text_version}; " "translate with Translator(text_version=...)" ) last = np.cumsum(get_series_lengths(df, id_column=id_column)) - 1 # df is sorted by (item, timestamp) item_ids = df[id_column].iloc[last].to_numpy() text.check_window( freq=freq, prediction_length=prediction_length, item_ids=item_ids, cutoffs=df[timestamp_column].iloc[last].to_numpy(), ) prepared = from_data_frame( df, target_columns=target, prediction_length=prediction_length, future_df=future_df, id_column=id_column, timestamp_column=timestamp_column, validate_inputs=False, ) if text is not None: columns = _stacked_columns(df, future_df, target, id_column, timestamp_column) item_texts = [ _build_item_text( text.items.get(str(item_id)), columns=columns, n_targets=len(target), context_length=p["context"].shape[-1], prediction_length=prediction_length, ) for item_id, p in zip(item_ids, prepared) ] prepared = [_append_known_covariates(p, t.position_rows) for p, t in zip(prepared, item_texts)] future = make_future_df( df, prediction_length, freq=freq, id_column=id_column, timestamp_column=timestamp_column ) if validate_inputs and future_df is not None: if (pd.DatetimeIndex(future_df[timestamp_column]) != pd.DatetimeIndex(future[timestamp_column])).any(): raise ValueError( "future_df timestamps do not match the expected prediction timestamps. " "You can disable this check by setting `validate_inputs=False`" ) quantiles, mean = self.predict_quantiles( inputs=prepared, prediction_length=prediction_length, quantile_levels=quantile_levels, batch_size=batch_size, context_length=context_length, aggregation=aggregation, aggregation_indices=aggregation_indices, cross_learning=cross_learning, trend_differencing=trend_differencing, text=item_texts, **predict_kwargs, ) quantiles_np = torch.stack(quantiles).numpy() # (n_items, n_variates, horizon, n_quantiles) mean_np = torch.stack(mean).numpy() # (n_items, n_variates, horizon) if item_texts is not None: # the bounds the text states floor = np.stack([t.floor for t in item_texts]).astype(mean_np.dtype) ceiling = np.stack([t.ceiling for t in item_texts]).astype(mean_np.dtype) quantiles_np = np.clip(quantiles_np, floor[..., None], ceiling[..., None]) mean_np = np.clip(mean_np, floor, ceiling) # predictions are ordered (item, target, step); `future` has prediction_length rows per item n_items, n_variates, horizon = len(prepared), len(target), mean_np.shape[-1] # horizon 1 with aggregation item_rows = np.arange(len(future)).reshape(n_items, prediction_length)[:, :horizon] result = future.iloc[np.repeat(item_rows, n_variates, axis=0).ravel()].reset_index(drop=True) result["target_name"] = np.tile(np.repeat(target, horizon), n_items) result["predictions"] = mean_np.ravel() quantiles_flat = quantiles_np.reshape(len(result), len(quantile_levels)) for i, level in enumerate(quantile_levels): result[str(level)] = quantiles_flat[:, i] return result def predict_fev( self, task: "fev.Task", batch_size: int = 128, *, as_univariate: bool = False, texts: Sequence[ForecastTexts | None] | None = None, **kwargs, ) -> tuple[list["datasets.DatasetDict"], float]: """ Make predictions for evaluation on a fev.Task. Parameters ---------- task Benchmark task on which the evaluation should be done. batch_size Batch size used during evaluation. as_univariate If True, each target is its own univariate series and covariates, if any, are ignored. The series are still forecast jointly unless ``cross_learning=False`` is passed. texts The ``ForecastTexts`` of each window (in the order of ``task.iter_windows()``), passed to ``predict_df`` as ``text``; ``None`` for a window forecasts it without text. **kwargs Additional keyword arguments for ``predict_df``. Returns ------- predictions Predictions for each window, each stored as a DatasetDict inference_time_s Total time that it took to make predictions for all windows (in seconds) """ try: import fev except ImportError: raise ImportError("fev is required for predict_fev. Please install it with `pip install fev`.") num_variates = ( 1 if as_univariate else len(task.target_columns) + len(task.past_dynamic_columns) + len(task.known_dynamic_columns) ) if batch_size < num_variates: warnings.warn( f"batch_size ({batch_size}) is smaller than num_variates ({num_variates}) in the task. " f"Setting batch_size = num_variates = num_targets + num_covariates", category=UserWarning, stacklevel=2, ) batch_size = num_variates if texts is not None and len(texts) != task.num_windows: raise ValueError(f"texts has {len(texts)} entries, but the task has {task.num_windows} windows") predictions_per_window = [] inference_time_s = 0.0 for i, window in enumerate(task.iter_windows()): past_df, future_df, target_columns = self._fev_window_to_df(window, as_univariate=as_univariate) start_time = time.monotonic() forecast_df = self.predict_df( past_df, future_df=future_df, id_column=window.id_column, timestamp_column=window.timestamp_column, target=target_columns, prediction_length=window.horizon, quantile_levels=task.quantile_levels, batch_size=batch_size, text=None if texts is None else texts[i], **kwargs, ) inference_time_s += time.monotonic() - start_time predictions_per_window.append( fev.utils.convert_forecast_df_to_predictions( forecast_df, horizon=window.horizon, quantile_levels=task.quantile_levels, target_columns=window.target_columns, ) ) return predictions_per_window, inference_time_s @torch.no_grad() def embed( self, inputs: TensorOrArray | Sequence[TensorOrArray], *, batch_size: int = 128, context_length: int | None = None, ) -> tuple[list[torch.Tensor], list[tuple[torch.Tensor, torch.Tensor]]]: """ Get encoder embeddings for the given time series. Parameters ---------- inputs A 3-d tensor or array (batch, n_variates, history_length), or a list of 1-d or 2-d tensors or arrays; the variates of an input share information. batch_size The number of series per forward pass, by default 128 context_length The maximum context length, by default (and at most) the model's context length Returns ------- embeddings A list of tensors, one per input, of shape (n_variates, num_patches + 2, d_model): the context patches, the [REG] token and one forecast patch. loc_scale A list of (loc, scale) tuples of the instance norm of each input's series. """ if context_length is None or context_length > self.model_context_length: context_length = self.model_context_length dataset = Chronos2Dataset( inputs, context_length=context_length, prediction_length=0, batch_size=batch_size, output_patch_size=self.model_output_patch_size, mode=DatasetMode.TEST, ) all_embeds: list[torch.Tensor] = [] all_loc_scales: list[tuple[torch.Tensor, torch.Tensor]] = [] for batch in dataset: with self._compile_scope(len(batch["context"])): hidden_states, embedding = self.model.encode( context=batch["context"].to(device=self.model.device, dtype=torch.float32), group_ids=batch["group_ids"].to(self.model.device), ) # embedding.inputs_embeds excludes the text tokens that encode puts first: this keeps patches, [REG], future hidden_states = hidden_states[:, -embedding.inputs_embeds.shape[1] :].cpu() loc, scale = (x.squeeze(-1).cpu() for x in embedding.loc_scale[:2]) for start, end in batch["target_idx_ranges"]: all_embeds.append(hidden_states[start:end]) all_loc_scales.append((loc[start:end], scale[start:end])) return all_embeds, all_loc_scales @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs): """ Load the model, either from a local path, S3 prefix or from the HuggingFace Hub. Supports the same arguments as ``AutoConfig`` and ``AutoModel`` from ``transformers``. Without a ``dtype``, the model loads in the checkpoint's dtype on a CUDA ``device_map`` and in float32 otherwise. """ if str(pretrained_model_name_or_path).startswith("s3://"): return BaseChronosPipeline.from_pretrained(pretrained_model_name_or_path, *args, **kwargs) if "dtype" not in kwargs and "torch_dtype" not in kwargs: device_map = kwargs.get("device_map") if device_map == "auto": device_map = "cuda" if torch.cuda.is_available() else "cpu" if not (isinstance(device_map, int) or str(device_map).startswith("cuda")): kwargs["dtype"] = torch.float32 # float16 is slow on CPU config = AutoConfig.from_pretrained(pretrained_model_name_or_path, *args, **kwargs) architecture = (config.architectures or ["Chronos3Model"])[0] if architecture != "Chronos3Model": logger.warning(f"Unknown architecture: {architecture}, defaulting to Chronos3Model") return cls(model=Chronos3Model.from_pretrained(pretrained_model_name_or_path, *args, **kwargs)) def save_pretrained(self, save_directory: str | Path, *args, **kwargs): """Save the underlying model to a local directory or to HuggingFace Hub.""" self.model.save_pretrained(save_directory, *args, **kwargs) def _is_daily_or_coarser(freq: str) -> bool: """Whether a step of ``freq`` spans at least a day (calendar-aware: business days, months, ...).""" monday = pd.Timestamp("2001-01-01") return monday + pd.tseries.frequencies.to_offset(freq) >= pd.Timestamp("2001-01-02") def _truncated(prepared: PreparedInput, context_length: int) -> PreparedInput: return {**prepared, "context": prepared["context"][:, -context_length:]} def _prob_mass_per_quantile_level(quantile_levels: torch.Tensor) -> torch.Tensor: """The probability mass of each quantile level, (q_{i+1} - q_{i-1}) / 2 with q_0 = 0 and q_{n+1} = 1, normalized.""" boundaries = torch.cat([quantile_levels.new_zeros(1), quantile_levels, quantile_levels.new_ones(1)]) prob_mass = (boundaries[2:] - boundaries[:-2]) / 2 return prob_mass / prob_mass.sum() def _stacked_columns( df: pd.DataFrame, future_df: pd.DataFrame | None, target: list[str], id_column: str, timestamp_column: str ) -> list[str]: """The series ``from_data_frame`` stacks per item, in order: the targets, the past-only covariates, the known future ones.""" covariates = [c for c in df.columns if c not in {id_column, timestamp_column, *target}] known = set(future_df.columns) if future_df is not None else set() return [*target, *(c for c in covariates if c not in known), *(c for c in covariates if c in known)]