# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Plain user text into the text a Chronos-3 text checkpoint was trained on. ``Translator.translate_df`` (an LLM) returns a ``ForecastTexts``, which can be inspected, edited and saved before ``Chronos3Pipeline.predict_df`` uses it. Translating needs no forecasting model, GPU or text encoder.""" import json import warnings from abc import ABC, abstractmethod from collections.abc import Mapping, Sequence from concurrent.futures import ThreadPoolExecutor, as_completed from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Any, Literal, get_args import numpy as np import pandas as pd from pandas.tseries.frequencies import to_offset from . import _prompt, _reply __all__ = [ "ForecastTexts", "ItemTranslation", "Statement", "StatementType", "TranslationError", "Translator", ] #: What a statement says happens. A position row's learned tag is its type's index here. StatementType = Literal[ "spike", "jump", "level_shift", "mean_trend", "volatility_regime", "volatility_burst", "periodic_volatility", "seasonality", "amplitude_trend", "censor", "waypoint", ] @dataclass(frozen=True) class Statement: """One thing the text says happens to a series.""" #: The sentence the model reads. sentence: str type: StatementType #: The column it is about; None: the item's targets. variate: str | None = None #: Where it happens: (first, last) steps, inclusive, counted from the forecast start (0: the first forecast step, #: -1: the last context step). Empty: not located; a bound (censor) without episodes holds throughout. episodes: tuple[tuple[int, int], ...] = () #: A seasonality's period, in steps. period_steps: int | None = None #: Steps where a seasonality is at a low: the episodes holding one (or a whole number of periods away) are its #: lows, the others its highs. lows: tuple[int, ...] = () #: Raw values the sentence says the series reaches (scale hints). value_hints: tuple[float, ...] = () #: A bound's level in the series' units: the forecast is clipped at it where the bound holds in the forecast #: window. None: not clipped. floor: float | None = None ceiling: float | None = None def __post_init__(self) -> None: if self.type not in get_args(StatementType): raise ValueError(f"unknown statement type {self.type!r}; one of {get_args(StatementType)}") if self.period_steps is not None and not self.period_steps > 0: raise ValueError(f"period_steps must be positive, found {self.period_steps}") if any(first > last for first, last in self.episodes): raise ValueError(f"an episode's first step is after its last: {self.episodes}") if self.floor is not None and self.ceiling is not None and self.floor > self.ceiling: raise ValueError(f"floor {self.floor} is above ceiling {self.ceiling}") @dataclass(frozen=True) class ItemTranslation: """The translated text of one item (a target, possibly with covariates), valid for one forecast window.""" #: Last context timestamp; statements count steps from the step after it. cutoff: pd.Timestamp statements: tuple[Statement, ...] = () @dataclass class ForecastTexts: """Translated text for the items of one forecast, keyed by ``str(item_id)``. Valid for one ``freq``, ``prediction_length`` and a cutoff per item; ``predict_df`` raises on a df that differs in any of them. Items absent from ``items`` are forecast without text. """ freq: str prediction_length: int #: the text version it is in (``Chronos3TextConfig.text_version``) text_version: int items: dict[str, ItemTranslation] = field(default_factory=dict) #: ``item_id`` -> why it failed to translate; these items are forecast without text failures: dict[str, str] = field(default_factory=dict) def check_window(self, *, freq: str, prediction_length: int, item_ids: np.ndarray, cutoffs: np.ndarray) -> None: """Raise ``ValueError`` unless this translation holds for the forecast window of ``predict_df``: the same frequency (compared as offsets, so "D" and "1D" match) and ``prediction_length``, and for each of its items, the cutoff in ``cutoffs`` (aligned with ``item_ids``).""" if to_offset(freq) != to_offset(self.freq) or prediction_length != self.prediction_length: raise ValueError( f"text was translated for freq={self.freq!r}, prediction_length={self.prediction_length}, but the " f"forecast has freq={freq!r}, prediction_length={prediction_length}; translate again" ) ids = [str(i) for i in item_ids] if unknown := sorted(set(self.items) - set(ids)): raise ValueError(f"text for {len(unknown)} item(s) not in the df, e.g. {unknown[0]!r}") moved = [ (i, c) for i, c in zip(ids, pd.DatetimeIndex(cutoffs)) if i in self.items and self.items[i].cutoff != c ] if moved: item_id, cutoff = moved[0] raise ValueError( f"{len(moved)} item(s) end at another timestamp than when their text was translated, e.g. {item_id!r}: " f"{self.items[item_id].cutoff} then, {cutoff} now; their statements would land on the wrong steps. " "Translate again." ) def save(self, path: str | Path) -> None: """Write as JSON.""" items = {item_id: {**asdict(item), "cutoff": item.cutoff.isoformat()} for item_id, item in self.items.items()} data = {**asdict(self), "items": items} Path(path).write_text(json.dumps(data, indent=1)) @classmethod def load(cls, path: str | Path) -> "ForecastTexts": """Read what ``save`` wrote.""" data = json.loads(Path(path).read_text()) def statement(d: dict[str, Any]) -> Statement: episodes = tuple((a, b) for a, b in d["episodes"]) return Statement( **{**d, "episodes": episodes, "lows": tuple(d["lows"]), "value_hints": tuple(d["value_hints"])} ) items = { item_id: ItemTranslation( cutoff=pd.Timestamp(d["cutoff"]), statements=tuple(statement(s) for s in d["statements"]), ) for item_id, d in data["items"].items() } return cls(**{**data, "items": items}) class TranslationError(Exception): """An item that could not be translated; ``translate_df`` records it in ``ForecastTexts.failures``.""" class Translator(ABC): """ Rewrites user text into the text a Chronos-3 text checkpoint was trained on, with one LLM call per item. Subclasses implement ``_complete``. Parameters ---------- max_workers Number of items translated in parallel. text_version The checkpoint's ``text_config.text_version``: which prompt set to translate with. context_length The context statistics the LLM gets are of each item's last ``context_length`` steps, the history the forecasting checkpoint reads: its ``chronos_config["context_length"]`` (``AutoConfig.from_pretrained`` reads it without loading the weights). max_attempts Times an item is asked: an item whose reply is unusable (``_complete`` or reading the reply raises ``TranslationError``) is asked again, and fails after the last attempt. """ def __init__( self, *, max_workers: int = 8, text_version: int = 1, context_length: int = 32768, max_attempts: int = 3 ): if max_attempts < 1: raise ValueError(f"max_attempts must be at least 1, got {max_attempts}") self.max_workers = max_workers self.max_attempts = max_attempts self.text_version = text_version self.context_length = context_length self.prompts = _prompt.load_prompts(text_version) def translate_df( self, df: pd.DataFrame, text: str | Mapping[str, str | Mapping[str, str]], prediction_length: int, future_df: pd.DataFrame | None = None, *, id_column: str = "item_id", timestamp_column: str = "timestamp", target: str | list[str] = "target", freq: str | None = None, strict: bool = False, ) -> ForecastTexts: """ Translate ``text`` for the forecast that ``Chronos3Pipeline.predict_df`` makes with the same arguments. Besides the text, the LLM gets each item's dates and statistics of its context, which it needs to place and size what the text states. Parameters ---------- text One text for every item, or a text per item id; items without one get no text. An item's text is a string or several named fields (e.g. {"background": ..., "scenario": ...}), the same for every item (a string is the field "text"); empty fields are left out. strict If True, raise when an item fails to translate instead of recording it in ``ForecastTexts.failures`` (which emits a warning). """ target = [target] if isinstance(target, str) else list(target) requests, columns, freq = _prompt.item_requests( df, text, prediction_length, future_df, id_column=id_column, timestamp_column=timestamp_column, target=target, freq=freq, context_length=self.context_length, ) items, failures = {}, {} if requests: system = _prompt.system_prompt(self.prompts, requests, columns) results: dict[str, ItemTranslation] = {} with ThreadPoolExecutor(self.max_workers) as pool: futures = {pool.submit(self._translate_item, r, system): r.item_id for r in requests} for future in as_completed(futures): try: results[futures[future]] = future.result() except TranslationError as e: if strict: # the calls not yet started are not made pool.shutdown(cancel_futures=True) raise failures[futures[future]] = str(e) items = {r.item_id: results[r.item_id] for r in requests if r.item_id in results} if failures: shown = "; ".join(f"{item_id!r}: {error}" for item_id, error in list(failures.items())[:3]) more = f" (and {len(failures) - 3} more)" if len(failures) > 3 else "" warnings.warn( f"{len(failures)} of {len(requests)} items failed to translate and get no text: {shown}{more}. " "See ForecastTexts.failures, or pass strict=True to raise instead." ) return ForecastTexts(freq, prediction_length, self.text_version, items, failures) def _translate_item(self, request: _prompt._TranslationRequest, system: list[str]) -> ItemTranslation: user = _prompt.user_message(self.prompts, request) for attempt in range(self.max_attempts): try: statements = self._read_reply(self._complete(system, user, self.prompts.tool), request) break except TranslationError: if attempt == self.max_attempts - 1: raise return ItemTranslation( cutoff=pd.Timestamp(request.timestamps[request.context_length - 1]), statements=statements ) def _read_reply(self, reply: dict[str, Any], request: _prompt._TranslationRequest) -> tuple[Statement, ...]: try: return _reply.read_reply(reply, request, self.prompts) except TranslationError: raise except Exception as e: # a reply of an unexpected shape fails its item, not the whole call raise TranslationError(f"The reply could not be read: {type(e).__name__}: {e}") from e @abstractmethod def _complete(self, system: Sequence[str], user: str, tool: Mapping[str, Any]) -> dict[str, Any]: """ Call the LLM with the system prompt's parts and the user message, and return the arguments of its call to ``tool`` (``name``, ``description`` and the JSON schema ``input_schema``). One call: raise ``TranslationError`` when the reply is unusable (e.g. no such call), so that the item is asked again. """