diff --git a/README.md b/README.md index da74ea8..a75587c 100644 --- a/README.md +++ b/README.md @@ -1,313 +1,3 @@ # TimesFM -TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google -Research for time-series forecasting. - -* Paper: [A decoder-only foundation model for time-series forecasting](https://arxiv.org/abs/2310.10688), to appear in ICML 2024. -* [Google Research blog](https://research.google/blog/a-decoder-only-foundation-model-for-time-series-forecasting/) -* [Hugging Face release](https://huggingface.co/collections/google/timesfm-release-66e4be5fdb56e960c1e482a6) - -This repo contains the code to load public TimesFM checkpoints and run model -inference. Please visit our -[Hugging Face release](https://huggingface.co/collections/google/timesfm-release-66e4be5fdb56e960c1e482a6) -to download model checkpoints. - -This is not an officially supported Google product. - -We recommend at least 32GB RAM to load TimesFM dependencies. - -**Need help?** See [TROUBLESHOOTING.md](TROUBLESHOOTING.md) for common installation and usage issues. - -## Update - Dec. 30, 2024 -- We are launching a 500m checkpoint as a part of TimesFM-2.0 release. This new checkpoint can be upto 25% better than v1.0 on leading benchmarks and also has a 4 times longer max. context length. -- Launched [finetuning support](https://github.com/google-research/timesfm/blob/master/notebooks/finetuning.ipynb) that lets you finetune the weights of the pretrained TimesFM model on your own data. -- Launched [~zero-shot covariate support](https://github.com/google-research/timesfm/blob/master/notebooks/covariates.ipynb) with external regressors. More details [here](https://github.com/google-research/timesfm?tab=readme-ov-file#covariates-support). - -## Update - Feb. 17, 2024 -- We are providing the option for [finetuning using Pytorch](https://github.com/google-research/timesfm/blob/master/notebooks/finetuning_torch.ipynb), which mimics the previously added functionality from [finetuning support](https://github.com/google-research/timesfm/blob/master/notebooks/finetuning.ipynb). -- We are also providing the Multi-GPU finetuining with Pytorch. We currently support DDP multi-gpu finetuning, other variants of multi-gpu training (pipeline parallelism/model parallelism) might be added later. In order to use it, follow the steps in [finetuning example](https://github.com/google-research/timesfm/blob/master/finetuning/finetuning_example.py) . - -## Checkpoint timesfm-1.0-200m (-pytorch) - -timesfm-1.0-200m is our first open model checkpoint: - -- It performs univariate time series forecasting for context lengths up to 512 timepoints and any horizon lengths, with an optional frequency indicator. -- It focuses on point forecasts, and does not support probabilistic forecasts. We experimentally offer quantile heads but they have not been calibrated after pretraining. - -## Checkpoint timesfm-2.0-500m (-jax/-pytorch) - -timesfm-2.0-500m is our second open model checkpoint: - -- It performs univariate time series forecasting for context lengths up to 2048 timepoints and any horizon lengths, with an optional frequency indicator. -- It focuses on point forecasts. We experimentally offer 10 quantile heads but they have not been calibrated after pretraining. -- This new checkpoint can be upto 25% better than v1.0 on leading benchmarks and also has a 4 times longer max. context length. - -## Benchmarking - -TimesFM 2.0 has been added to [GIFT-Eval](https://huggingface.co/spaces/Salesforce/GIFT-Eval) which is one of the most comprehensive time-series bechmarks available. It takes the top spot in terms of aggregated MASE and CRPS, where it is 6\% better than the next best model in terms of aggregated MASE. - -## Installation - -### Local installation using poetry - -We will be using `pyenv` and `poetry`. In order to set these things up please follow the instructions [here](https://substack.com/home/post/p-148747960?r=28a5lx&utm_campaign=post&utm_medium=web). Note that the PAX (or JAX) version needs to run on python 3.10.x and the PyTorch version can run on >=3.11.x. Therefore make sure you have two versions of python installed: - -``` -pyenv install 3.10 -pyenv install 3.11 -pyenv versions # to list the versions available (lets assume the versions are 3.10.15 and 3.11.10) -``` - -### For PAX version installation do the following. - -``` -pyenv local 3.10.15 -poetry env use 3.10.15 -poetry lock -poetry install -E pax -``` - -After than you can run the timesfm under `poetry shell` or do `poetry run python3 ...`. - -### For PyTorch version installation do the following. - -``` -pyenv local 3.11.10 -poetry env use 3.11.10 -poetry lock -poetry install -E torch -``` - -After than you can run the timesfm under `poetry shell` or do `poetry run python3 ...`. - -**Additional Note**: - -If you plan to use the **`forecast_with_covariates`** function (which requires external regressors), -you need to install **JAX** and **jaxlib**. If you installed the base version of TimesFM (`torch`), you must manually install the dependencies for **`forecast_with_covariates`** support: -``` -pip install jax jaxlib -``` - -**Why is this needed?** -The `forecast_with_covariates` method relies on the `xreg_lib` module, which depends on JAX and jaxlib. If these packages are not installed, -calling `forecast_with_covariates` will raise an error. However, due to a lazy import mechanism, `xreg_lib` (and hence JAX/jaxlib) is not needed for standard `forecast` calls. - -### Notes - -1. Running the provided benchmarks would require additional dependencies. Please see the `experiments` folder. - -2. The dependency `lingvo` does not support ARM architectures, and the code is not working for machines with Apple silicon. We are aware of this issue and are working on a solution. Stay tuned. - -### Install from PyPI (and publish) - -On python 3.11 you can install the torch version using: - -```pip install timesfm[torch]``` - -On python 3.10 you can install the pax version using: - -```pip install timesfm[pax]``` - - -## Usage - -### Initialize the model and load a checkpoint. -Then the base class can be loaded as, - -```python -import timesfm - -# Loading the timesfm-2.0 checkpoint: -# For PAX -tfm = timesfm.TimesFm( - hparams=timesfm.TimesFmHparams( - backend="gpu", - per_core_batch_size=32, - horizon_len=128, - num_layers=50, - context_len=2048, - - use_positional_embedding=False, - ), - checkpoint=timesfm.TimesFmCheckpoint( - huggingface_repo_id="google/timesfm-2.0-500m-jax"), - ) - -# For Torch -tfm = timesfm.TimesFm( - hparams=timesfm.TimesFmHparams( - backend="gpu", - per_core_batch_size=32, - horizon_len=128, - num_layers=50, - use_positional_embedding=False, - context_len=2048, - ), - checkpoint=timesfm.TimesFmCheckpoint( - huggingface_repo_id="google/timesfm-2.0-500m-pytorch"), - ) - -# Loading the timesfm-1.0 checkpoint: -# For PAX -tfm = timesfm.TimesFm( - hparams=timesfm.TimesFmHparams( - backend="gpu", - per_core_batch_size=32, - horizon_len=128, - ), - checkpoint=timesfm.TimesFmCheckpoint( - huggingface_repo_id="google/timesfm-1.0-200m"), - ) - -# For Torch -tfm = timesfm.TimesFm( - hparams=timesfm.TimesFmHparams( - backend="gpu", - per_core_batch_size=32, - horizon_len=128, - ), - checkpoint=timesfm.TimesFmCheckpoint( - huggingface_repo_id="google/timesfm-1.0-200m-pytorch"), - ) -``` - -Note some of the parameters are fixed to load the 200m and 500m models - -1. The `context_len` in `hparams` here can be set as the max context length **of the model** (a maximum of 2048 for 2.0 models and 512 for 1.0 models). **It needs to be a multiplier of `input_patch_len`, i.e. a multiplier of 32.** You can provide a shorter series to the `tfm.forecast()` function and the model will handle it. The input time series can have **any context length**. Padding / truncation will be handled by the inference code if needed. - -2. The horizon length can be set to anything. We recommend setting it to the largest horizon length you would need in the forecasting tasks for your application. We generally recommend horizon length <= context length but it is not a requirement in the function call. - -3. `backend` is one of "cpu", "gpu", case sensitive. - -### Perform inference - -We provide APIs to forecast from either array inputs or `pandas` dataframe. Both forecast methods expect (1) the input time series contexts, (2) along with their frequencies. Please look at the documentation of the functions `tfm.forecast()` and `tfm.forecast_on_df()` for detailed instructions. - -In particular regarding the frequency, TimesFM expects a categorical indicator valued in {0, 1, 2}: - -- **0** (default): high frequency, long horizon time series. We recommend using this for time series up to daily granularity. -- **1**: medium frequency time series. We recommend using this for weekly and monthly data. -- **2**: low frequency, short horizon time series. We recommend using this for anything beyond monthly, e.g. quarterly or yearly. - -This categorical value should be directly provided with the array inputs. For dataframe inputs, we convert the conventional letter coding of frequencies to our expected categories, that - -- **0**: T, MIN, H, D, B, U -- **1**: W, M -- **2**: Q, Y - -Notice you do **NOT** have to strictly follow our recommendation here. Although this is our setup during model training and we expect it to offer the best forecast result, you can also view the frequency input as a free parameter and modify it per your specific use case. - - -Examples: - -Array inputs, with the frequencies set to low, medium and high respectively. - -```python -import numpy as np -forecast_input = [ - np.sin(np.linspace(0, 20, 100)), - np.sin(np.linspace(0, 20, 200)), - np.sin(np.linspace(0, 20, 400)), -] -frequency_input = [0, 1, 2] - -point_forecast, experimental_quantile_forecast = tfm.forecast( - forecast_input, - freq=frequency_input, -) -``` - -`pandas` dataframe, with the frequency set to "M" monthly. - -```python -import pandas as pd - -# e.g. input_df is -# unique_id ds y -# 0 T1 1975-12-31 697458.0 -# 1 T1 1976-01-31 1187650.0 -# 2 T1 1976-02-29 1069690.0 -# 3 T1 1976-03-31 1078430.0 -# 4 T1 1976-04-30 1059910.0 -# ... ... ... ... -# 8175 T99 1986-01-31 602.0 -# 8176 T99 1986-02-28 684.0 -# 8177 T99 1986-03-31 818.0 -# 8178 T99 1986-04-30 836.0 -# 8179 T99 1986-05-31 878.0 - -forecast_df = tfm.forecast_on_df( - inputs=input_df, - freq="M", # monthly - value_name="y", - num_jobs=-1, -) -``` - -## Covariates Support - -We now have an external regressors library on top of TimesFM that can support static covariates as well as dynamic covariates available in the future. We have an usage example in [notebooks/covariates.ipynb](https://github.com/google-research/timesfm/blob/master/notebooks/covariates.ipynb). - -If you plan to use the **`forecast_with_covariates`** on timesfm `torch` version, you need to install **JAX** and **jaxlib**. -You must manually install the dependencies for **`forecast_with_covariates`** support: -``` -pip install jax jaxlib -``` - -Let's take a toy example of forecasting sales for a grocery store: - -**Task:** Given the observed the daily sales of this week (7 days), forecast the daily sales of next week (7 days). - -``` -Product: ice cream -Daily_sales: [30, 30, 4, 5, 7, 8, 10] -Category: food -Base_price: 1.99 -Weekday: [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6] -Has_promotion: [Yes, Yes, No, No, No, Yes, Yes, No, No, No, No, No, No, No] -Daily_temperature: [31.0, 24.3, 19.4, 26.2, 24.6, 30.0, 31.1, 32.4, 30.9, 26.0, 25.0, 27.8, 29.5, 31.2] -``` - -``` -Product: sunscreen -Daily_sales: [5, 7, 12, 13, 5, 6, 10] -Category: skin product -Base_price: 29.99 -Weekday: [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6] -Has_promotion: [No, No, Yes, Yes, No, No, No, Yes, Yes, Yes, Yes, Yes, Yes, Yes] -Daily_temperature: [31.0, 24.3, 19.4, 26.2, 24.6, 30.0, 31.1, 32.4, 30.9, 26.0, 25.0, 27.8, 29.5, 31.2] -``` - -In this example, besides the `Daily_sales`, we also have covariates `Category`, `Base_price`, `Weekday`, `Has_promotion`, `Daily_temperature`. Let's introduce some concepts: - -**Static covariates** are covariates for each time series. -- In our example, `Category` is a **static categorical covariate**, -- `Base_price` is a **static numerical covariates**. - -**Dynamic covariates** are covaraites for each time stamps. -- Date / time related features can be usually treated as dynamic covariates. -- In our example, `Weekday` and `Has_promotion` are **dynamic categorical covariates**. -- `Daily_temperate` is a **dynamic numerical covariate**. - -**Notice:** Here we make it mandatory that the dynamic covariates need to cover both the forecasting context and horizon. For example, all dynamic covariates in the example have 14 values: the first 7 correspond to the observed 7 days, and the last 7 correspond to the next 7 days. - -We can now provide the past data of the two products along with static and dynamic covariates as a batch input to TimesFM and produce forecasts that take into the account the covariates. To learn more, check out the example in [notebooks/covariates.ipynb](https://github.com/google-research/timesfm/blob/master/notebooks/covariates.ipynb). - -## Finetuning - -We have provided an example of finetuning the model on a new dataset in [notebooks/finetuning.ipynb](https://github.com/google-research/timesfm/blob/master/notebooks/finetuning.ipynb). - -## Contribution Style guide - -If you would like to submit a PR please make sure that you use our formatting style. We use [yapf](https://github.com/google/yapf) for formatting with the following options, - -``` -[style] -based_on_style = google -# Add your custom style rules here -indent_width = 2 -spaces_before_comment = 2 - -``` - -Please run `yapf --in-place --recursive ` on all affected files. +PLACEHOLDER diff --git a/pyproject.toml b/pyproject.toml index 6280f41..6055583 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,75 +1,27 @@ [tool.poetry] name = "timesfm" -packages = [ - { include = "timesfm", from = "src" }, - { include = "finetuning", from = "src" }, -] -description = "Open weights time-series foundation model from Google Research." -version = "1.3.0" +version = "2.0.0" +description = "A time series foundation model." authors = [ "Rajat Sen ", "Yichen Zhou ", "Abhimanyu Das ", "Petros Mol ", - "Justin Güse ", "Michael Chertushkin " ] +license = "Apache-2.0" readme = "README.md" -keywords = ["time series", "timesfm", "forecast", "time series model"] -homepage = "https://github.com/google-research/timesfm" -repository = "https://github.com/google-research/timesfm" -classifiers = [ - "Environment :: Console", - "Framework :: Flake8", - "Operating System :: OS Independent", - "Topic :: Software Development :: Documentation", - "Topic :: Software Development :: Libraries :: Python Modules", - "Topic :: Software Development :: Quality Assurance", -] -include = ["LICENSE"] +packages = [{include = "timesfm", from = "src"}] [tool.poetry.dependencies] -python = ">=3.10,<3.12" -einshape = ">=1.0.0" +python = ">=3.11" numpy = ">=1.26.4" -pandas = ">=2.0.0" -utilsforecast = ">=0.1.10" huggingface_hub = { version = ">=0.23.0", extras = ["cli"] } -scikit-learn = ">=1.2.2" -typer = ">=0.12.3" -wandb = ">=0.17.5" -absl-py = ">=1.4.0" -safetensors = "^0.5.3" +safetensors = ">=0.5.3" +torch = { version = ">=2.0.0", extras = ["cuda"] } -[tool.poetry.extras] -pax = ["paxml", "lingvo", "jax", "jaxlib"] -torch = ["torch"] - -[tool.poetry.dependencies.paxml] -version = ">=1.4.0" -python = ">=3.10,<3.11" - -[tool.poetry.dependencies.lingvo] -version = ">=0.12.7" -python = ">=3.10,<3.11" - -[tool.poetry.dependencies.jax] -version = ">=0.4.26" -extras = ["cuda12"] -python = ">=3.10,<3.12" # Support both python versions - -[tool.poetry.dependencies.jaxlib] -version = ">=0.4.26" -python = ">=3.10,<3.12" # Support both python versions - -[tool.poetry.dependencies.torch] -version = ">=2.0.0" -extras = ["cuda"] -python = ">=3.11,<3.12" - -[tool.poetry.group.dev.dependencies] -pytest = ">=8.3.2" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" + diff --git a/src/timesfm/__init__.py b/src/timesfm/__init__.py index 739807a..cf83c93 100644 --- a/src/timesfm/__init__.py +++ b/src/timesfm/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2024 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,25 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""TimesFM init file.""" -print( - " See https://github.com/google-research/timesfm/blob/master/README.md for updated APIs." -) -from timesfm.timesfm_base import ( - freq_map, - TimesFmCheckpoint, - TimesFmHparams, - TimesFmBase, -) -import sys +"""TimesFM API.""" -try: - from timesfm.timesfm_jax import TimesFmJax as TimesFm - from timesfm import data_loader +from .timesfm_2p5 import timesfm_2p5_torch - print(f"Loaded Jax TimesFM, likely because python version is {sys.version}.") -except Exception as _: - from timesfm.timesfm_torch import TimesFmTorch as TimesFm - - print(f"Loaded PyTorch TimesFM, likely because python version is {sys.version}.") +TimesFM_2p5_200M_torch = timesfm_2p5_torch.TimesFM_2p5_200M_torch diff --git a/src/timesfm/configs.py b/src/timesfm/configs.py new file mode 100644 index 0000000..34d3975 --- /dev/null +++ b/src/timesfm/configs.py @@ -0,0 +1,78 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Abstract configs for TimesFM layers.""" + +import dataclasses +from typing import Literal + + +@dataclasses.dataclass(frozen=False) +class ForecastConfig: + """Options for forecasting.""" + + max_context: int = 0 + max_horizon: int = 0 + normalize_inputs: bool = False + window_size: int = 0 + per_core_batch_size: int = 1 + use_continuous_quantile_head: bool = False + force_flip_invariance: bool = True + infer_is_positive: bool = True + fix_quantile_crossing: bool = False + return_backcast: bool = False + + +@dataclasses.dataclass(frozen=True) +class ResidualBlockConfig: + """Framework-agnostic config for a residual block.""" + + input_dims: int + hidden_dims: int + output_dims: int + use_bias: bool + activation: Literal["relu", "swish", "none"] + + +@dataclasses.dataclass(frozen=True) +class RandomFourierFeaturesConfig: + """Framework-agnostic config for random fourier features.""" + + input_dims: int + output_dims: int + projection_stddev: float + use_bias: bool + + +@dataclasses.dataclass(frozen=True) +class TransformerConfig: + """Framework-agnostic config for a transformer.""" + + model_dims: int + hidden_dims: int + num_heads: int + attention_norm: Literal["rms"] + feedforward_norm: Literal["rms"] + qk_norm: Literal["rms", "none"] + use_bias: bool + use_rotary_position_embeddings: bool + ff_activation: Literal["relu", "swish", "none"] + + +@dataclasses.dataclass(frozen=True) +class StackedTransformersConfig: + """Framework-agnostic config for a stacked transformers.""" + + num_layers: int + transformer: TransformerConfig diff --git a/src/timesfm/timesfm_2p5/timesfm_2p5_base.py b/src/timesfm/timesfm_2p5/timesfm_2p5_base.py new file mode 100644 index 0000000..dfcdb34 --- /dev/null +++ b/src/timesfm/timesfm_2p5/timesfm_2p5_base.py @@ -0,0 +1,186 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""TimesFM 2p5 base implementation.""" + +import dataclasses +from typing import Any, Callable +import numpy as np +from .. import configs + +ResidualBlockConfig = configs.ResidualBlockConfig +StackedTransformersConfig = configs.StackedTransformersConfig +TransformerConfig = configs.TransformerConfig +ForecastConfig = configs.ForecastConfig + + +def strip_leading_nans(arr): + """Removes contiguous NaN values from the beginning of a NumPy array. + + Args: + arr: The input NumPy array. + + Returns: + A new NumPy array with leading NaN values removed. + If the array is all NaNs or empty, returns an empty array. + """ + + isnan = np.isnan(arr) + first_valid_index = np.argmax(~isnan) + return arr[first_valid_index:] + + +def linear_interpolation(arr): + """Performs linear interpolation to fill NaN values in a 1D numpy array. + + Args: + arr: The 1D numpy array containing NaN values. + + Returns: + A new numpy array with NaN values filled using linear interpolation, + or the original array if no NaNs are present. + Returns None if the input is not a 1D array. + Returns the original array if there are no NaN values. + """ + + nans = np.isnan(arr) + if not np.any(nans): # Check if there are any NaNs + return arr + + def x(z): + return z.nonzero()[0] + + nans_indices = x(nans) + non_nans_indices = x(~nans) + non_nans_values = arr[~nans] + + try: + arr[nans] = np.interp(nans_indices, non_nans_indices, non_nans_values) + except ValueError: + if non_nans_values: + mu = np.nanmean(arr) + else: + mu = 0.0 + arr = np.where(np.isfinite(arr), arr, mu) + return arr + + +@dataclasses.dataclass(frozen=True) +class TimesFM_2p5_200M_Definition: + """Framework-agnostic config of TimesFM 2.5.""" + + context_limit = 16384 + input_patch_len: int = 32 + output_patch_len: int = 128 + output_quantile_len: int = 1024 + quantiles: list[float] = dataclasses.field( + default_factory=lambda: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] + ) + decode_index: int = 5 + tokenizer: ResidualBlockConfig = ResidualBlockConfig( + input_dims=64, + hidden_dims=1280, + output_dims=1280, + use_bias=True, + activation="swish", + ) + stacked_transformers: StackedTransformersConfig = StackedTransformersConfig( + num_layers=20, + transformer=TransformerConfig( + model_dims=1280, + hidden_dims=1280, + num_heads=16, + attention_norm="rms", + feedforward_norm="rms", + qk_norm="rms", + use_bias=False, + use_rotary_position_embeddings=True, + ff_activation="swish", + ), + ) + output_projection_point: ResidualBlockConfig = ResidualBlockConfig( + input_dims=1280, + hidden_dims=1280, + output_dims=1280, + use_bias=False, + activation="swish", + ) + output_projection_quantiles: ResidualBlockConfig = ResidualBlockConfig( + input_dims=1280, + hidden_dims=1280, + output_dims=10240, + use_bias=False, + activation="swish", + ) + + +class TimesFM_2p5: + """Abstract base class for TimesFM models.""" + + forecast_config: ForecastConfig | None = None + compiled_decode: Callable[..., Any] | None = None + global_batch_size: int = 0 + + def load_checkpoint(self, path: str): + """Loads a TimesFM model from a checkpoint.""" + raise NotImplementedError() + + def compile(self, forecast_config: ForecastConfig | None = None): + """Compiles the TimesFM model for fast decoding.""" + raise NotImplementedError() + + def forecast( + self, horizon: int, inputs: list[np.ndarray] + ) -> tuple[np.ndarray, np.ndarray]: + """Forecasts the time series.""" + if self.compiled_decode is None: + raise RuntimeError("Model is not compiled. Please call compile() first.") + + assert self.global_batch_size > 0 + assert self.forecast_config is not None + + context = self.forecast_config.max_context + num_inputs = len(inputs) + if (w := num_inputs % self.global_batch_size) != 0: + inputs += [np.array([0.0] * 3)] * (self.global_batch_size - w) + + output_points = [] + output_quantiles = [] + values = [] + masks = [] + idx = 0 + for each_input in inputs: + value = linear_interpolation(strip_leading_nans(np.array(each_input))) + if (w := len(value)) >= context: + value = value[-context:] + mask = np.zeros_like(value, dtype=bool) + else: + mask = np.array([True] * (context - w) + [False] * w) + value = np.pad(value, (context - w, 0), "constant", constant_values=0.0) + values.append(value) + masks.append(mask) + idx += 1 + if idx == self.global_batch_size: + idx = 0 + point_forecast, quantile_forecast = self.compiled_decode( + horizon, values, masks + ) + output_points.append(point_forecast) + output_quantiles.append(quantile_forecast) + values = [] + masks = [] + + output_points = np.concatenate(output_points, axis=0) + output_quantiles = np.concatenate(output_quantiles, axis=0) + return output_points[:num_inputs], output_quantiles[:num_inputs] diff --git a/src/timesfm/timesfm_2p5/timesfm_2p5_torch.py b/src/timesfm/timesfm_2p5/timesfm_2p5_torch.py new file mode 100644 index 0000000..c4acf05 --- /dev/null +++ b/src/timesfm/timesfm_2p5/timesfm_2p5_torch.py @@ -0,0 +1,418 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""TimesFM models.""" + +import logging +import math +import os +from typing import Sequence + +import huggingface_hub +import numpy as np +from safetensors.torch import load_file +import torch +from torch import nn + +from .. import configs +from ..torch import dense +from ..torch import transformer +from ..torch import util +from . import timesfm_2p5_base + +revin = util.revin + + +class TimesFM_2p5_200M_torch_module(nn.Module): + """TimesFM 2.5 with 200M parameters.""" + + config = timesfm_2p5_base.TimesFM_2p5_200M_Definition() + + def __init__(self): + super().__init__() + + # Names constants. + self.p = self.config.input_patch_len # 32 + self.o = self.config.output_patch_len # 128 + self.os = self.config.output_quantile_len # 1024 + self.m = self.o // self.p # 4 + self.x = self.config.stacked_transformers.num_layers # 20 + self.h = self.config.stacked_transformers.transformer.num_heads # 16 + self.md = self.config.stacked_transformers.transformer.model_dims # 1280 + self.hd = self.md // self.h # 80 + self.q = len(self.config.quantiles) + 1 # 10 + self.aridx = self.config.decode_index # 5 + + # Layers. + self.tokenizer = dense.ResidualBlock(self.config.tokenizer) + self.stacked_xf = nn.ModuleList( + [ + transformer.Transformer(self.config.stacked_transformers.transformer) + for _ in range(self.x) + ] + ) + self.output_projection_point = dense.ResidualBlock( + self.config.output_projection_point + ) + self.output_projection_quantiles = dense.ResidualBlock( + self.config.output_projection_quantiles + ) + + # Device. + if torch.cuda.is_available(): + self.device = torch.device("cuda:0") + self.device_count = torch.cuda.device_count() + else: + self.device = torch.device("cpu") + self.device_count = 1 + + def load_checkpoint(self, path: str): + """Loads a PyTorch TimesFM model from a checkpoint.""" + tensors = load_file(path) + self.load_state_dict(tensors) + self.to(self.device) + + def forward( + self, + inputs: torch.Tensor, + masks: torch.Tensor, + decode_caches: list[util.DecodeCache] | None = None, + ): + tokenizer_inputs = torch.cat([inputs, masks.to(inputs.dtype)], dim=-1) + input_embeddings = self.tokenizer(tokenizer_inputs) + + if decode_caches is None: + decode_caches = [None] * self.x + + output_embeddings = input_embeddings + new_decode_caches = [] + for i, layer in enumerate(self.stacked_xf): + output_embeddings, new_cache = layer( + output_embeddings, masks[..., -1], decode_caches[i] + ) + new_decode_caches.append(new_cache) + output_ts = self.output_projection_point(output_embeddings) + output_quantile_spread = self.output_projection_quantiles(output_embeddings) + + return ( + input_embeddings, + output_embeddings, + output_ts, + output_quantile_spread, + ), new_decode_caches + + def decode(self, horizon: int, inputs, masks): + """Decodes the time series.""" + + inputs = inputs.to(self.device) + masks = masks.to(self.device) + + with torch.no_grad(): + batch_size, context = inputs.shape[0], inputs.shape[1] + num_decode_steps = (horizon - 1) // self.o + num_input_patches = context // self.p + decode_cache_size = num_input_patches + num_decode_steps * self.m + + # Prefill + patched_inputs = torch.reshape(inputs, (batch_size, -1, self.p)) + patched_masks = torch.reshape(masks, (batch_size, -1, self.p)) + + # running stats + n = torch.zeros(batch_size, device=inputs.device) + mu = torch.zeros(batch_size, device=inputs.device) + sigma = torch.zeros(batch_size, device=inputs.device) + patch_mu = [] + patch_sigma = [] + for i in range(num_input_patches): + (n, mu, sigma), _ = util.update_running_stats( + n, mu, sigma, patched_inputs[:, i], patched_masks[:, i] + ) + patch_mu.append(mu) + patch_sigma.append(sigma) + last_n, last_mu, last_sigma = n, mu, sigma + context_mu = torch.stack(patch_mu, dim=1) + context_sigma = torch.stack(patch_sigma, dim=1) + + decode_caches = [ + util.DecodeCache( + next_index=torch.zeros( + batch_size, dtype=torch.int32, device=inputs.device + ), + num_masked=torch.zeros( + batch_size, dtype=torch.int32, device=inputs.device + ), + key=torch.zeros( + batch_size, + decode_cache_size, + self.h, + self.hd, + device=inputs.device, + ), + value=torch.zeros( + batch_size, + decode_cache_size, + self.h, + self.hd, + device=inputs.device, + ), + ) + for _ in range(self.x) + ] + + normed_inputs = revin( + patched_inputs, context_mu, context_sigma, reverse=False + ) + normed_inputs = torch.where(patched_masks, 0.0, normed_inputs) + (_, _, normed_outputs, normed_quantile_spread), decode_caches = self( + normed_inputs, patched_masks, decode_caches + ) + renormed_outputs = torch.reshape( + revin(normed_outputs, context_mu, context_sigma, reverse=True), + (batch_size, -1, self.o, self.q), + ) + renormed_quantile_spread = torch.reshape( + revin(normed_quantile_spread, context_mu, context_sigma, reverse=True), + (batch_size, -1, self.os, self.q), + )[:, -1, ...] + + # Autogressive decode + ar_outputs = [] + last_renormed_output = renormed_outputs[:, -1, :, self.aridx] + + for _ in range(num_decode_steps): + new_patched_input = torch.reshape( + last_renormed_output, (batch_size, self.m, self.p) + ) + new_mask = torch.zeros_like(new_patched_input, dtype=torch.bool) + + n, mu, sigma = last_n, last_mu, last_sigma + new_mus, new_sigmas = [], [] + for i in range(self.m): + (n, mu, sigma), _ = util.update_running_stats( + n, mu, sigma, new_patched_input[:, i], new_mask[:, i] + ) + new_mus.append(mu) + new_sigmas.append(sigma) + last_n, last_mu, last_sigma = n, mu, sigma + new_mu = torch.stack(new_mus, dim=1) + new_sigma = torch.stack(new_sigmas, dim=1) + + new_normed_input = revin( + new_patched_input, new_mu, new_sigma, reverse=False + ) + (_, _, new_normed_output, _), decode_caches = self( + new_normed_input, new_mask, decode_caches + ) + + new_renormed_output = torch.reshape( + revin(new_normed_output, new_mu, new_sigma, reverse=True), + (batch_size, self.m, self.o, self.q), + ) + ar_outputs.append(new_renormed_output[:, -1, ...]) + last_renormed_output = new_renormed_output[:, -1, :, self.aridx] + + if num_decode_steps > 0: + ar_renormed_outputs = torch.stack(ar_outputs, dim=1) + else: + ar_renormed_outputs = None + + return renormed_outputs, renormed_quantile_spread, ar_renormed_outputs + + def forecast_naive(self, horizon: int, inputs: Sequence[np.ndarray]): + """Forecasts the time series.""" + outputs = [] + for each_input in inputs: + input_t = torch.tensor(each_input, dtype=torch.float32) + mask = torch.zeros_like(input_t, dtype=torch.bool) + len_front_mask = self.p - (len(each_input) % self.p) + if len_front_mask < self.p: + input_t = torch.cat( + [torch.zeros(len_front_mask, dtype=torch.float32), input_t], dim=0 + ) + mask = torch.cat( + [torch.ones(len_front_mask, dtype=torch.bool), mask], dim=0 + ) + input_t = input_t[None, ...] + mask = mask[None, ...] + t_pf, _, t_ar = self.decode(horizon, input_t, mask) + to_concat = [t_pf[:, -1, ...]] + if t_ar is not None: + to_concat.append(t_ar.reshape(1, -1, self.q)) + torch_forecast = torch.cat(to_concat, dim=1)[..., :horizon] + torch_forecast = torch_forecast.squeeze(0) + outputs.append(torch_forecast.detach().cpu().numpy()) + return outputs + + +class TimesFM_2p5_200M_torch(timesfm_2p5_base.TimesFM_2p5): + """PyTorch implementation of TimesFM 2.5 with 200M parameters.""" + + model: nn.Module = TimesFM_2p5_200M_torch_module() + + def load_checkpoint( + self, + *, + path: str | None = None, + hf_repo_id: str | None = "gg-hf/timesfm-2.5-200m-pytorch", + ): + """Loads a PyTorch safetensors TimesFM model.""" + if path: + pass + elif hf_repo_id: + logging.info("Downloading checkpoint from HuggingFace repo %s", hf_repo_id) + path = os.path.join( + huggingface_hub.snapshot_download(hf_repo_id), "model.safetensors" + ) + logging.info("Loading checkpoint from: %s", path) + else: + raise ValueError("Either path or hf_repo_id must be provided.") + self.model.load_checkpoint(path) + + def compile(self, forecast_config: configs.ForecastConfig, **kwargs): + if kwargs.get("backend", None) is not None: + self.model.compile(**kwargs) + self.global_batch_size = ( + forecast_config.per_core_batch_size * self.model.device_count + ) + + # Shortcut. + fc = forecast_config + + if fc.max_context % self.model.p != 0: + logging.info( + "When compiling, max context needs to be multiple of the patch size" + " %d. Using max context = %d instead.", + self.model.p, + new_context := math.ceil(fc.max_context / self.model.p) * self.model.p, + ) + fc.max_context = new_context + if fc.max_horizon % self.model.o != 0: + logging.info( + "When compiling, max horizon needs to be multiple of the output patch" + " size %d. Using max horizon = %d instead.", + self.model.o, + new_horizon := math.ceil(fc.max_horizon / self.model.o) * self.model.o, + ) + fc.max_horizon = new_horizon + if fc.max_context + fc.max_horizon > self.model.config.context_limit: + raise ValueError( + "Context + horizon must be less than the context limit." + f" {fc.max_context} + {fc.max_horizon} >" + f" {self.model.config.context_limit}." + ) + if fc.use_continuous_quantile_head and (fc.max_horizon > self.model.os): + raise ValueError( + "Continuous quantile head is not supported for horizons >" + f" {self.model.os}." + ) + self.forecast_config = fc + + def _compiled_decode(horizon, inputs, masks): + if horizon > fc.max_horizon: + raise ValueError( + "Horizon must be less than the max horizon." + f" {horizon} > {fc.max_horizon}." + ) + + inputs = torch.Tensor(np.array(inputs)).to(self.model.device) + masks = torch.Tensor(np.array(masks)).to(self.model.device).to(torch.bool) + batch_size = inputs.shape[0] + + if fc.infer_is_positive: + is_positive = torch.all(inputs >= 0, dim=-1, keepdim=True) + else: + is_positive = None + + if fc.normalize_inputs: + mu = torch.mean(inputs, dim=-1, keepdim=True) + sigma = torch.std(inputs, dim=-1, keepdim=True) + inputs = revin(inputs, mu, sigma, reverse=False) + else: + mu, sigma = None, None + + pf_outputs, quantile_spreads, ar_outputs = self.model.decode( + forecast_config.max_horizon, inputs, masks + ) + full_forecast = torch.cat( + [ + pf_outputs[:, -1, ...], + ar_outputs.reshape(batch_size, -1, self.model.q), + ], + dim=1, + ) + + flip_quantile_fn = lambda x: torch.cat( + [x[..., :1], torch.flip(x[..., 1:], dims=(-1,))], dim=-1 + ) + + if fc.force_flip_invariance: + flipped_pf_outputs, flipped_quantile_spreads, flipped_ar_outputs = ( + self.model.decode(forecast_config.max_horizon, -inputs, masks) + ) + flipped_quantile_spreads = flip_quantile_fn(flipped_quantile_spreads) + flipped_pf_outputs = flip_quantile_fn(flipped_pf_outputs) + flipped_full_forecast = torch.cat( + [ + flipped_pf_outputs[:, -1, ...], + flipped_ar_outputs.reshape(batch_size, -1, self.model.q), + ], + dim=1, + ) + quantile_spreads = (quantile_spreads - flipped_quantile_spreads) / 2 + pf_outputs = (pf_outputs - flipped_pf_outputs) / 2 + full_forecast = (full_forecast - flipped_full_forecast) / 2 + + if fc.use_continuous_quantile_head: + for quantile_index in [1, 2, 3, 4, 6, 7, 8, 9]: + full_forecast[:, :, quantile_index] = ( + quantile_spreads[:, : fc.max_horizon, quantile_index] + - quantile_spreads[:, : fc.max_horizon, 5] + + full_forecast[:, : fc.max_horizon, 5] + ) + full_forecast = full_forecast[:, :horizon, :] + + if fc.return_backcast: + full_backcast = pf_outputs[:, :-1, : self.model.p, :].reshape( + batch_size, -1, self.model.q + ) + full_forecast = torch.cat([full_backcast, full_forecast], dim=1) + + if fc.fix_quantile_crossing: + for i in [4, 3, 2, 1]: + full_forecast[:, :, i] = torch.where( + full_forecast[:, :, i] < full_forecast[:, :, i + 1], + full_forecast[:, :, i], + full_forecast[:, :, i + 1], + ) + for i in [6, 7, 8, 9]: + full_forecast[:, :, i] = torch.where( + full_forecast[:, :, i] > full_forecast[:, :, i - 1], + full_forecast[:, :, i], + full_forecast[:, :, i - 1], + ) + + if fc.normalize_inputs: + full_forecast = revin(full_forecast, mu, sigma, reverse=True) + + if is_positive is not None: + full_forecast = torch.where( + is_positive[..., None], + torch.maximum(full_forecast, torch.zeros_like(full_forecast)), + full_forecast, + ) + + full_forecast = full_forecast.detach().cpu().numpy() + return full_forecast[..., 5], full_forecast + + self.compiled_decode = _compiled_decode diff --git a/datasets/download_data.sh b/src/timesfm/torch/__init__.py similarity index 70% rename from datasets/download_data.sh rename to src/timesfm/torch/__init__.py index 25898a4..0a2669d 100644 --- a/datasets/download_data.sh +++ b/src/timesfm/torch/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2024 The Google Research Authors. +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,9 +11,3 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -#!/bin/bash -gdown --fuzzy https://drive.google.com/file/d/1alE33S1GmP5wACMXaLu50rDIoVzBM4ik/view?usp=share_link -unzip all_six_datasets.zip -mv all_six_datasets/* . -rm -rf all_six_datasets* \ No newline at end of file diff --git a/src/timesfm/torch/dense.py b/src/timesfm/torch/dense.py new file mode 100644 index 0000000..9ebcfcd --- /dev/null +++ b/src/timesfm/torch/dense.py @@ -0,0 +1,94 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Dense layers for TimesFM.""" + +import torch +from torch import nn + +from .. import configs + + +class ResidualBlock(nn.Module): + """Residual block with two linear layers and a linear residual connection.""" + + def __init__(self, config: configs.ResidualBlockConfig): + super().__init__() + self.config = config + self.hidden_layer = nn.Linear( + in_features=config.input_dims, + out_features=config.hidden_dims, + bias=config.use_bias, + ) + self.output_layer = nn.Linear( + in_features=config.hidden_dims, + out_features=config.output_dims, + bias=config.use_bias, + ) + self.residual_layer = nn.Linear( + in_features=config.input_dims, + out_features=config.output_dims, + bias=config.use_bias, + ) + if config.activation == "relu": + self.activation = nn.ReLU() + elif config.activation == "swish": + self.activation = nn.SiLU() + elif config.activation == "none": + self.activation = nn.Identity() + else: + raise ValueError(f"Activation: {config.activation} not supported.") + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.output_layer( + self.activation(self.hidden_layer(x)) + ) + self.residual_layer(x) + + +class RandomFourierFeatures(nn.Module): + """Random Fourier features layer.""" + + def __init__(self, config: configs.RandomFourierFeaturesConfig): + super().__init__() + self.config = config + + if config.output_dims % 4 != 0: + raise ValueError( + f"Output dims must be a multiple of 4: {config.output_dims} % 4 != 0." + ) + num_projected_features = config.output_dims // 4 + + self.phase_shifts = nn.Parameter(torch.zeros(2, num_projected_features)) + self.projection_layer = nn.Linear( + in_features=config.input_dims, + out_features=num_projected_features, + bias=config.use_bias, + ) + self.residual_layer = nn.Linear( + in_features=config.input_dims, + out_features=config.output_dims, + bias=config.use_bias, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + projected = self.projection_layer(x) + cos_features = torch.cos(projected) + sin_features = torch.sin(projected) + sq_wave_1 = torch.sign(torch.sin(projected + self.phase_shifts[0, :])) + sq_wave_2 = torch.sign(torch.sin(projected + self.phase_shifts[1, :])) + fourier_features = torch.cat( + [cos_features, sin_features, sq_wave_1, sq_wave_2], dim=-1 + ) + residual = self.residual_layer(x) + return fourier_features + residual diff --git a/src/timesfm/torch/normalization.py b/src/timesfm/torch/normalization.py new file mode 100644 index 0000000..6836423 --- /dev/null +++ b/src/timesfm/torch/normalization.py @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Normalization layers for TimesFM.""" + +import torch +from torch import nn + + +class RMSNorm(nn.Module): + """RMS normalization.""" + + def __init__( + self, + num_features: int, + *, + epsilon: float = 1e-6, + ): + super().__init__() + self.scale = nn.Parameter(torch.zeros(num_features)) + self.num_features = num_features + self.epsilon = epsilon + + def forward(self, inputs: torch.Tensor) -> torch.Tensor: + var = torch.mean(torch.square(inputs), dim=-1, keepdim=True) + normed_inputs = inputs * torch.rsqrt(var + self.epsilon) + normed_inputs = normed_inputs * self.scale + return normed_inputs diff --git a/src/timesfm/torch/transformer.py b/src/timesfm/torch/transformer.py new file mode 100644 index 0000000..326002a --- /dev/null +++ b/src/timesfm/torch/transformer.py @@ -0,0 +1,336 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Transformer layers for TimesFM.""" + +import math +from typing import Callable + +import torch +from torch import nn +import torch.nn.functional as F + +from .. import configs +from . import normalization +from . import util + +LayerNorm = nn.LayerNorm +RMSNorm = normalization.RMSNorm +DecodeCache = util.DecodeCache + + +def make_attn_mask( + query_length: int, + num_all_masked_kv: torch.Tensor, + query_index_offset: torch.Tensor | None = None, + kv_length: int = 0, +) -> torch.Tensor: + """Makes attention mask.""" + if kv_length == 0: + kv_length = query_length + + q_index = torch.arange(query_length, device=num_all_masked_kv.device)[ + None, None, :, None + ] + if query_index_offset is not None: + q_index = q_index + query_index_offset[:, None, None, None] + kv_index = torch.arange(kv_length, device=num_all_masked_kv.device)[ + None, None, None, : + ] + return torch.logical_and( + q_index >= kv_index, + kv_index >= num_all_masked_kv[:, None, None, None], + ) + + +class RotaryPositionalEmbedding(nn.Module): + """Rotary positional embedding.""" + + def __init__( + self, + embedding_dims: int, + min_timescale: float = 1.0, + max_timescale: float = 10000.0, + ): + super().__init__() + self.embedding_dims = embedding_dims + self.min_timescale = min_timescale + self.max_timescale = max_timescale + + def forward( + self, + inputs: torch.Tensor, + position: torch.Tensor | None = None, + ): + """Generates a JTensor of sinusoids with different frequencies.""" + if self.embedding_dims != inputs.shape[-1]: + raise ValueError( + "The embedding dims of the rotary position embedding" + "must match the hidden dimension of the inputs." + ) + half_embedding_dim = self.embedding_dims // 2 + fraction = ( + 2 + * torch.arange(0, half_embedding_dim, device=inputs.device) + / self.embedding_dims + ) + timescale = ( + self.min_timescale * (self.max_timescale / self.min_timescale) ** fraction + ).to(inputs.device) + if position is None: + seq_length = inputs.shape[1] + position = torch.arange( + seq_length, dtype=torch.float32, device=inputs.device + )[None, :] + + if len(inputs.shape) == 4: + position = position[..., None, None] + timescale = timescale[None, None, None, :] + elif len(inputs.shape) == 3: + position = position[..., None] + timescale = timescale[None, None, :] + else: + raise ValueError("Inputs must be of rank 3 or 4.") + + sinusoid_inp = position / timescale + sin = torch.sin(sinusoid_inp) + cos = torch.cos(sinusoid_inp) + first_half, second_half = torch.chunk(inputs, 2, dim=-1) + first_part = first_half * cos - second_half * sin + second_part = second_half * cos + first_half * sin + return torch.cat([first_part, second_part], dim=-1) + + +def _dot_product_attention( + query, + key, + value, + mask=None, +): + """Computes dot-product attention given query, key, and value.""" + attn_weights = torch.einsum("...qhd,...khd->...hqk", query, key) + if mask is not None: + attn_weights = torch.where( + mask, attn_weights, -torch.finfo(attn_weights.dtype).max / 2 + ) + + attn_weights = F.softmax(attn_weights, dim=-1) + + return torch.einsum("...hqk,...khd->...qhd", attn_weights, value) + + +class PerDimScale(nn.Module): + """Per-dimension scaling.""" + + def __init__(self, num_dims: int): + super().__init__() + self.num_dims = num_dims + self.per_dim_scale = nn.Parameter(torch.zeros(num_dims)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + scale_factor = ( + 1.442695041 / math.sqrt(self.num_dims) * F.softplus(self.per_dim_scale) + ) + return x * scale_factor + + +class MultiHeadAttention(nn.Module): + """Multi-head attention.""" + + def __init__( + self, + num_heads: int, + in_features: int, + *, + use_per_dim_scale: bool = True, + use_rotary_position_embeddings: bool = True, + use_bias: bool = False, + attention_fn: Callable[..., torch.Tensor] = _dot_product_attention, + qk_norm: str = "rms", + ): + super().__init__() + self.num_heads = num_heads + self.in_features = in_features + self.head_dim = in_features // num_heads + self.use_bias = use_bias + self.attention_fn = attention_fn + self.qk_norm = qk_norm + + if self.in_features % self.num_heads != 0: + raise ValueError( + f"Memory dimension ({self.in_features}) must be divisible by " + f"'num_heads' heads ({self.num_heads})." + ) + + self.query = nn.Linear(self.in_features, self.in_features, bias=use_bias) + self.key = nn.Linear(self.in_features, self.in_features, bias=use_bias) + self.value = nn.Linear(self.in_features, self.in_features, bias=use_bias) + self.out = nn.Linear(self.in_features, self.in_features, bias=use_bias) + + if self.qk_norm == "rms": + self.query_ln = RMSNorm(self.head_dim) + self.key_ln = RMSNorm(self.head_dim) + else: + self.query_ln = nn.Identity() + self.key_ln = nn.Identity() + + self.use_rotary_position_embeddings = use_rotary_position_embeddings + if self.use_rotary_position_embeddings: + self.rotary_position_embedding = RotaryPositionalEmbedding( + embedding_dims=self.head_dim, + ) + + self.use_per_dim_scale = use_per_dim_scale + if use_per_dim_scale: + self.per_dim_scale = PerDimScale(num_dims=self.head_dim) + + def forward( + self, + inputs_q: torch.Tensor, + *, + decode_cache: DecodeCache | None = None, + patch_mask: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, DecodeCache | None]: + b, n_patches, _ = inputs_q.shape + if patch_mask is None: + patch_mask = torch.zeros( + b, n_patches, dtype=torch.bool, device=inputs_q.device + ) + + query = self.query(inputs_q).view(b, n_patches, self.num_heads, self.head_dim) + key = self.key(inputs_q).view(b, n_patches, self.num_heads, self.head_dim) + value = self.value(inputs_q).view(b, n_patches, self.num_heads, self.head_dim) + + if decode_cache is None: + num_masked = torch.sum(patch_mask.to(torch.int32), dim=-1) + next_index = torch.zeros_like(num_masked, dtype=torch.int32) + else: + num_masked = ( + torch.sum(patch_mask.to(torch.int32), dim=-1) + decode_cache.num_masked + ) + next_index = decode_cache.next_index.clone() + + if self.use_rotary_position_embeddings: + position = ( + torch.arange(n_patches, device=inputs_q.device)[None, :] + + next_index[:, None] + - num_masked[:, None] + ) + query = self.rotary_position_embedding(query, position) + key = self.rotary_position_embedding(key, position) + + query = self.query_ln(query) + key = self.key_ln(key) + + if self.use_per_dim_scale: + query = self.per_dim_scale(query) + + if decode_cache is not None: + _, decode_cache_size, _, _ = decode_cache.value.shape + for i in range(b): + start = decode_cache.next_index[i] + end = start + n_patches + decode_cache.key[i, start:end] = key[i].clone() + decode_cache.value[i, start:end] = value[i].clone() + key = decode_cache.key.clone() + value = decode_cache.value.clone() + decode_cache.next_index += n_patches + decode_cache.num_masked = num_masked + attn_mask = make_attn_mask( + query_length=n_patches, + num_all_masked_kv=num_masked, + query_index_offset=next_index, + kv_length=decode_cache_size, + ) + else: + attn_mask = make_attn_mask( + query_length=n_patches, num_all_masked_kv=num_masked + ) + + x = self.attention_fn( + query, + key, + value, + mask=attn_mask, + ) + x = x.reshape(b, n_patches, self.in_features) + out = self.out(x) + return out, decode_cache + + +class Transformer(nn.Module): + """Classic Transformer used in TimesFM.""" + + def __init__(self, config: configs.TransformerConfig): + super().__init__() + self.config = config + + if config.attention_norm == "rms": + self.pre_attn_ln = RMSNorm(num_features=config.model_dims) + self.post_attn_ln = RMSNorm(num_features=config.model_dims) + else: + raise ValueError(f"Layer norm: {config.attention_norm} not supported.") + + self.attn = MultiHeadAttention( + num_heads=config.num_heads, + in_features=config.model_dims, + use_per_dim_scale=True, + use_rotary_position_embeddings=config.use_rotary_position_embeddings, + qk_norm=config.qk_norm, + ) + + if config.feedforward_norm == "rms": + self.pre_ff_ln = RMSNorm(num_features=config.model_dims) + self.post_ff_ln = RMSNorm(num_features=config.model_dims) + else: + raise ValueError(f"Layer norm: {config.feedforward_norm} not supported.") + + self.ff0 = nn.Linear( + in_features=config.model_dims, + out_features=config.hidden_dims, + bias=config.use_bias, + ) + self.ff1 = nn.Linear( + in_features=config.hidden_dims, + out_features=config.model_dims, + bias=config.use_bias, + ) + if config.ff_activation == "relu": + self.activation = nn.ReLU() + elif config.ff_activation == "swish": + self.activation = nn.SiLU() + elif config.ff_activation == "none": + self.activation = nn.Identity() + else: + raise ValueError(f"Activation: {config.ff_activation} not supported.") + + def forward( + self, + input_embeddings: torch.Tensor, + patch_mask: torch.Tensor, + decode_cache: DecodeCache | None = None, + ) -> tuple[torch.Tensor, DecodeCache | None]: + attn_output, decode_cache = self.attn( + inputs_q=self.pre_attn_ln(input_embeddings), + decode_cache=decode_cache, + patch_mask=patch_mask, + ) + attn_output = self.post_attn_ln(attn_output) + input_embeddings + output_embeddings = ( + self.post_ff_ln( + self.ff1(self.activation(self.ff0(self.pre_ff_ln(attn_output)))) + ) + + attn_output + ) + return output_embeddings, decode_cache diff --git a/src/timesfm/torch/util.py b/src/timesfm/torch/util.py new file mode 100644 index 0000000..0505bda --- /dev/null +++ b/src/timesfm/torch/util.py @@ -0,0 +1,92 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""PyTorch utility functions for TimesFM layers.""" + +import dataclasses +import torch + +_TOLERANCE = 1e-6 + + +@dataclasses.dataclass(frozen=False) +class DecodeCache: + """Cache for decoding.""" + + next_index: torch.Tensor + num_masked: torch.Tensor + key: torch.Tensor + value: torch.Tensor + + +def update_running_stats( + n: torch.Tensor, + mu: torch.Tensor, + sigma: torch.Tensor, + x: torch.Tensor, + mask: torch.Tensor, +) -> tuple[ + tuple[torch.Tensor, torch.Tensor, torch.Tensor], + tuple[torch.Tensor, torch.Tensor, torch.Tensor], +]: + """Updates the running stats.""" + is_legit = torch.logical_not(mask) + inc_n = torch.sum(is_legit.to(x.dtype), dim=-1) + + inc_mu_numerator = torch.sum(x * is_legit, dim=-1) + inc_n_safe = torch.where(inc_n == 0, 1.0, inc_n) + inc_mu = inc_mu_numerator / inc_n_safe + inc_mu = torch.where(inc_n == 0, 0.0, inc_mu) + + inc_var_numerator = torch.sum(((x - inc_mu.unsqueeze(-1)) ** 2) * is_legit, dim=-1) + inc_var = inc_var_numerator / inc_n_safe + inc_var = torch.where(inc_n == 0, 0.0, inc_var) + inc_sigma = torch.sqrt(inc_var) + + new_n = n + inc_n + new_n_safe = torch.where(new_n == 0, 1.0, new_n) + + new_mu = (n * mu + inc_mu * inc_n) / new_n_safe + new_mu = torch.where(new_n == 0, 0.0, new_mu) + + term1 = n * sigma.pow(2) + term2 = inc_n * inc_sigma.pow(2) + term3 = n * (mu - new_mu).pow(2) + term4 = inc_n * (inc_mu - new_mu).pow(2) + + new_var = (term1 + term2 + term3 + term4) / new_n_safe + new_var = torch.where(new_n == 0, 0.0, new_var) + new_sigma = torch.sqrt(torch.clamp(new_var, min=0.0)) + + return (w := (new_n, new_mu, new_sigma), w) + + +def revin( + x: torch.Tensor, + mu: torch.Tensor, + sigma: torch.Tensor, + reverse: bool = False, +): + """Reversible instance normalization.""" + if len(mu.shape) == len(x.shape) - 1: + mu = mu[..., None] + sigma = sigma[..., None] + elif len(mu.shape) == len(x.shape) - 2: + mu = mu[..., None, None] + sigma = sigma[..., None, None] + + if reverse: + return x * sigma + mu + else: + return (x - mu) / torch.where(sigma < _TOLERANCE, 1.0, sigma) diff --git a/v1/LICENSE b/v1/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/v1/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/v1/README.md b/v1/README.md new file mode 100644 index 0000000..da74ea8 --- /dev/null +++ b/v1/README.md @@ -0,0 +1,313 @@ +# TimesFM + +TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google +Research for time-series forecasting. + +* Paper: [A decoder-only foundation model for time-series forecasting](https://arxiv.org/abs/2310.10688), to appear in ICML 2024. +* [Google Research blog](https://research.google/blog/a-decoder-only-foundation-model-for-time-series-forecasting/) +* [Hugging Face release](https://huggingface.co/collections/google/timesfm-release-66e4be5fdb56e960c1e482a6) + +This repo contains the code to load public TimesFM checkpoints and run model +inference. Please visit our +[Hugging Face release](https://huggingface.co/collections/google/timesfm-release-66e4be5fdb56e960c1e482a6) +to download model checkpoints. + +This is not an officially supported Google product. + +We recommend at least 32GB RAM to load TimesFM dependencies. + +**Need help?** See [TROUBLESHOOTING.md](TROUBLESHOOTING.md) for common installation and usage issues. + +## Update - Dec. 30, 2024 +- We are launching a 500m checkpoint as a part of TimesFM-2.0 release. This new checkpoint can be upto 25% better than v1.0 on leading benchmarks and also has a 4 times longer max. context length. +- Launched [finetuning support](https://github.com/google-research/timesfm/blob/master/notebooks/finetuning.ipynb) that lets you finetune the weights of the pretrained TimesFM model on your own data. +- Launched [~zero-shot covariate support](https://github.com/google-research/timesfm/blob/master/notebooks/covariates.ipynb) with external regressors. More details [here](https://github.com/google-research/timesfm?tab=readme-ov-file#covariates-support). + +## Update - Feb. 17, 2024 +- We are providing the option for [finetuning using Pytorch](https://github.com/google-research/timesfm/blob/master/notebooks/finetuning_torch.ipynb), which mimics the previously added functionality from [finetuning support](https://github.com/google-research/timesfm/blob/master/notebooks/finetuning.ipynb). +- We are also providing the Multi-GPU finetuining with Pytorch. We currently support DDP multi-gpu finetuning, other variants of multi-gpu training (pipeline parallelism/model parallelism) might be added later. In order to use it, follow the steps in [finetuning example](https://github.com/google-research/timesfm/blob/master/finetuning/finetuning_example.py) . + +## Checkpoint timesfm-1.0-200m (-pytorch) + +timesfm-1.0-200m is our first open model checkpoint: + +- It performs univariate time series forecasting for context lengths up to 512 timepoints and any horizon lengths, with an optional frequency indicator. +- It focuses on point forecasts, and does not support probabilistic forecasts. We experimentally offer quantile heads but they have not been calibrated after pretraining. + +## Checkpoint timesfm-2.0-500m (-jax/-pytorch) + +timesfm-2.0-500m is our second open model checkpoint: + +- It performs univariate time series forecasting for context lengths up to 2048 timepoints and any horizon lengths, with an optional frequency indicator. +- It focuses on point forecasts. We experimentally offer 10 quantile heads but they have not been calibrated after pretraining. +- This new checkpoint can be upto 25% better than v1.0 on leading benchmarks and also has a 4 times longer max. context length. + +## Benchmarking + +TimesFM 2.0 has been added to [GIFT-Eval](https://huggingface.co/spaces/Salesforce/GIFT-Eval) which is one of the most comprehensive time-series bechmarks available. It takes the top spot in terms of aggregated MASE and CRPS, where it is 6\% better than the next best model in terms of aggregated MASE. + +## Installation + +### Local installation using poetry + +We will be using `pyenv` and `poetry`. In order to set these things up please follow the instructions [here](https://substack.com/home/post/p-148747960?r=28a5lx&utm_campaign=post&utm_medium=web). Note that the PAX (or JAX) version needs to run on python 3.10.x and the PyTorch version can run on >=3.11.x. Therefore make sure you have two versions of python installed: + +``` +pyenv install 3.10 +pyenv install 3.11 +pyenv versions # to list the versions available (lets assume the versions are 3.10.15 and 3.11.10) +``` + +### For PAX version installation do the following. + +``` +pyenv local 3.10.15 +poetry env use 3.10.15 +poetry lock +poetry install -E pax +``` + +After than you can run the timesfm under `poetry shell` or do `poetry run python3 ...`. + +### For PyTorch version installation do the following. + +``` +pyenv local 3.11.10 +poetry env use 3.11.10 +poetry lock +poetry install -E torch +``` + +After than you can run the timesfm under `poetry shell` or do `poetry run python3 ...`. + +**Additional Note**: + +If you plan to use the **`forecast_with_covariates`** function (which requires external regressors), +you need to install **JAX** and **jaxlib**. If you installed the base version of TimesFM (`torch`), you must manually install the dependencies for **`forecast_with_covariates`** support: +``` +pip install jax jaxlib +``` + +**Why is this needed?** +The `forecast_with_covariates` method relies on the `xreg_lib` module, which depends on JAX and jaxlib. If these packages are not installed, +calling `forecast_with_covariates` will raise an error. However, due to a lazy import mechanism, `xreg_lib` (and hence JAX/jaxlib) is not needed for standard `forecast` calls. + +### Notes + +1. Running the provided benchmarks would require additional dependencies. Please see the `experiments` folder. + +2. The dependency `lingvo` does not support ARM architectures, and the code is not working for machines with Apple silicon. We are aware of this issue and are working on a solution. Stay tuned. + +### Install from PyPI (and publish) + +On python 3.11 you can install the torch version using: + +```pip install timesfm[torch]``` + +On python 3.10 you can install the pax version using: + +```pip install timesfm[pax]``` + + +## Usage + +### Initialize the model and load a checkpoint. +Then the base class can be loaded as, + +```python +import timesfm + +# Loading the timesfm-2.0 checkpoint: +# For PAX +tfm = timesfm.TimesFm( + hparams=timesfm.TimesFmHparams( + backend="gpu", + per_core_batch_size=32, + horizon_len=128, + num_layers=50, + context_len=2048, + + use_positional_embedding=False, + ), + checkpoint=timesfm.TimesFmCheckpoint( + huggingface_repo_id="google/timesfm-2.0-500m-jax"), + ) + +# For Torch +tfm = timesfm.TimesFm( + hparams=timesfm.TimesFmHparams( + backend="gpu", + per_core_batch_size=32, + horizon_len=128, + num_layers=50, + use_positional_embedding=False, + context_len=2048, + ), + checkpoint=timesfm.TimesFmCheckpoint( + huggingface_repo_id="google/timesfm-2.0-500m-pytorch"), + ) + +# Loading the timesfm-1.0 checkpoint: +# For PAX +tfm = timesfm.TimesFm( + hparams=timesfm.TimesFmHparams( + backend="gpu", + per_core_batch_size=32, + horizon_len=128, + ), + checkpoint=timesfm.TimesFmCheckpoint( + huggingface_repo_id="google/timesfm-1.0-200m"), + ) + +# For Torch +tfm = timesfm.TimesFm( + hparams=timesfm.TimesFmHparams( + backend="gpu", + per_core_batch_size=32, + horizon_len=128, + ), + checkpoint=timesfm.TimesFmCheckpoint( + huggingface_repo_id="google/timesfm-1.0-200m-pytorch"), + ) +``` + +Note some of the parameters are fixed to load the 200m and 500m models + +1. The `context_len` in `hparams` here can be set as the max context length **of the model** (a maximum of 2048 for 2.0 models and 512 for 1.0 models). **It needs to be a multiplier of `input_patch_len`, i.e. a multiplier of 32.** You can provide a shorter series to the `tfm.forecast()` function and the model will handle it. The input time series can have **any context length**. Padding / truncation will be handled by the inference code if needed. + +2. The horizon length can be set to anything. We recommend setting it to the largest horizon length you would need in the forecasting tasks for your application. We generally recommend horizon length <= context length but it is not a requirement in the function call. + +3. `backend` is one of "cpu", "gpu", case sensitive. + +### Perform inference + +We provide APIs to forecast from either array inputs or `pandas` dataframe. Both forecast methods expect (1) the input time series contexts, (2) along with their frequencies. Please look at the documentation of the functions `tfm.forecast()` and `tfm.forecast_on_df()` for detailed instructions. + +In particular regarding the frequency, TimesFM expects a categorical indicator valued in {0, 1, 2}: + +- **0** (default): high frequency, long horizon time series. We recommend using this for time series up to daily granularity. +- **1**: medium frequency time series. We recommend using this for weekly and monthly data. +- **2**: low frequency, short horizon time series. We recommend using this for anything beyond monthly, e.g. quarterly or yearly. + +This categorical value should be directly provided with the array inputs. For dataframe inputs, we convert the conventional letter coding of frequencies to our expected categories, that + +- **0**: T, MIN, H, D, B, U +- **1**: W, M +- **2**: Q, Y + +Notice you do **NOT** have to strictly follow our recommendation here. Although this is our setup during model training and we expect it to offer the best forecast result, you can also view the frequency input as a free parameter and modify it per your specific use case. + + +Examples: + +Array inputs, with the frequencies set to low, medium and high respectively. + +```python +import numpy as np +forecast_input = [ + np.sin(np.linspace(0, 20, 100)), + np.sin(np.linspace(0, 20, 200)), + np.sin(np.linspace(0, 20, 400)), +] +frequency_input = [0, 1, 2] + +point_forecast, experimental_quantile_forecast = tfm.forecast( + forecast_input, + freq=frequency_input, +) +``` + +`pandas` dataframe, with the frequency set to "M" monthly. + +```python +import pandas as pd + +# e.g. input_df is +# unique_id ds y +# 0 T1 1975-12-31 697458.0 +# 1 T1 1976-01-31 1187650.0 +# 2 T1 1976-02-29 1069690.0 +# 3 T1 1976-03-31 1078430.0 +# 4 T1 1976-04-30 1059910.0 +# ... ... ... ... +# 8175 T99 1986-01-31 602.0 +# 8176 T99 1986-02-28 684.0 +# 8177 T99 1986-03-31 818.0 +# 8178 T99 1986-04-30 836.0 +# 8179 T99 1986-05-31 878.0 + +forecast_df = tfm.forecast_on_df( + inputs=input_df, + freq="M", # monthly + value_name="y", + num_jobs=-1, +) +``` + +## Covariates Support + +We now have an external regressors library on top of TimesFM that can support static covariates as well as dynamic covariates available in the future. We have an usage example in [notebooks/covariates.ipynb](https://github.com/google-research/timesfm/blob/master/notebooks/covariates.ipynb). + +If you plan to use the **`forecast_with_covariates`** on timesfm `torch` version, you need to install **JAX** and **jaxlib**. +You must manually install the dependencies for **`forecast_with_covariates`** support: +``` +pip install jax jaxlib +``` + +Let's take a toy example of forecasting sales for a grocery store: + +**Task:** Given the observed the daily sales of this week (7 days), forecast the daily sales of next week (7 days). + +``` +Product: ice cream +Daily_sales: [30, 30, 4, 5, 7, 8, 10] +Category: food +Base_price: 1.99 +Weekday: [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6] +Has_promotion: [Yes, Yes, No, No, No, Yes, Yes, No, No, No, No, No, No, No] +Daily_temperature: [31.0, 24.3, 19.4, 26.2, 24.6, 30.0, 31.1, 32.4, 30.9, 26.0, 25.0, 27.8, 29.5, 31.2] +``` + +``` +Product: sunscreen +Daily_sales: [5, 7, 12, 13, 5, 6, 10] +Category: skin product +Base_price: 29.99 +Weekday: [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6] +Has_promotion: [No, No, Yes, Yes, No, No, No, Yes, Yes, Yes, Yes, Yes, Yes, Yes] +Daily_temperature: [31.0, 24.3, 19.4, 26.2, 24.6, 30.0, 31.1, 32.4, 30.9, 26.0, 25.0, 27.8, 29.5, 31.2] +``` + +In this example, besides the `Daily_sales`, we also have covariates `Category`, `Base_price`, `Weekday`, `Has_promotion`, `Daily_temperature`. Let's introduce some concepts: + +**Static covariates** are covariates for each time series. +- In our example, `Category` is a **static categorical covariate**, +- `Base_price` is a **static numerical covariates**. + +**Dynamic covariates** are covaraites for each time stamps. +- Date / time related features can be usually treated as dynamic covariates. +- In our example, `Weekday` and `Has_promotion` are **dynamic categorical covariates**. +- `Daily_temperate` is a **dynamic numerical covariate**. + +**Notice:** Here we make it mandatory that the dynamic covariates need to cover both the forecasting context and horizon. For example, all dynamic covariates in the example have 14 values: the first 7 correspond to the observed 7 days, and the last 7 correspond to the next 7 days. + +We can now provide the past data of the two products along with static and dynamic covariates as a batch input to TimesFM and produce forecasts that take into the account the covariates. To learn more, check out the example in [notebooks/covariates.ipynb](https://github.com/google-research/timesfm/blob/master/notebooks/covariates.ipynb). + +## Finetuning + +We have provided an example of finetuning the model on a new dataset in [notebooks/finetuning.ipynb](https://github.com/google-research/timesfm/blob/master/notebooks/finetuning.ipynb). + +## Contribution Style guide + +If you would like to submit a PR please make sure that you use our formatting style. We use [yapf](https://github.com/google/yapf) for formatting with the following options, + +``` +[style] +based_on_style = google +# Add your custom style rules here +indent_width = 2 +spaces_before_comment = 2 + +``` + +Please run `yapf --in-place --recursive ` on all affected files. diff --git a/TROUBLESHOOTING.md b/v1/TROUBLESHOOTING.md similarity index 100% rename from TROUBLESHOOTING.md rename to v1/TROUBLESHOOTING.md diff --git a/docs/contributing.md b/v1/docs/contributing.md similarity index 100% rename from docs/contributing.md rename to v1/docs/contributing.md diff --git a/experiments/baselines/__init__.py b/v1/experiments/baselines/__init__.py similarity index 100% rename from experiments/baselines/__init__.py rename to v1/experiments/baselines/__init__.py diff --git a/experiments/baselines/timegpt_pipeline.py b/v1/experiments/baselines/timegpt_pipeline.py similarity index 100% rename from experiments/baselines/timegpt_pipeline.py rename to v1/experiments/baselines/timegpt_pipeline.py diff --git a/experiments/extended_benchmarks/README.md b/v1/experiments/extended_benchmarks/README.md similarity index 100% rename from experiments/extended_benchmarks/README.md rename to v1/experiments/extended_benchmarks/README.md diff --git a/experiments/extended_benchmarks/run_timegpt.py b/v1/experiments/extended_benchmarks/run_timegpt.py similarity index 100% rename from experiments/extended_benchmarks/run_timegpt.py rename to v1/experiments/extended_benchmarks/run_timegpt.py diff --git a/experiments/extended_benchmarks/run_timesfm.py b/v1/experiments/extended_benchmarks/run_timesfm.py similarity index 100% rename from experiments/extended_benchmarks/run_timesfm.py rename to v1/experiments/extended_benchmarks/run_timesfm.py diff --git a/experiments/extended_benchmarks/tfm_extended_new.png b/v1/experiments/extended_benchmarks/tfm_extended_new.png similarity index 100% rename from experiments/extended_benchmarks/tfm_extended_new.png rename to v1/experiments/extended_benchmarks/tfm_extended_new.png diff --git a/experiments/extended_benchmarks/tfm_results.png b/v1/experiments/extended_benchmarks/tfm_results.png similarity index 100% rename from experiments/extended_benchmarks/tfm_results.png rename to v1/experiments/extended_benchmarks/tfm_results.png diff --git a/experiments/extended_benchmarks/utils.py b/v1/experiments/extended_benchmarks/utils.py similarity index 100% rename from experiments/extended_benchmarks/utils.py rename to v1/experiments/extended_benchmarks/utils.py diff --git a/experiments/long_horizon_benchmarks/README.md b/v1/experiments/long_horizon_benchmarks/README.md similarity index 100% rename from experiments/long_horizon_benchmarks/README.md rename to v1/experiments/long_horizon_benchmarks/README.md diff --git a/experiments/long_horizon_benchmarks/run_eval.py b/v1/experiments/long_horizon_benchmarks/run_eval.py similarity index 100% rename from experiments/long_horizon_benchmarks/run_eval.py rename to v1/experiments/long_horizon_benchmarks/run_eval.py diff --git a/experiments/long_horizon_benchmarks/tfm_long_horizon.png b/v1/experiments/long_horizon_benchmarks/tfm_long_horizon.png similarity index 100% rename from experiments/long_horizon_benchmarks/tfm_long_horizon.png rename to v1/experiments/long_horizon_benchmarks/tfm_long_horizon.png diff --git a/notebooks/covariates.ipynb b/v1/notebooks/covariates.ipynb similarity index 100% rename from notebooks/covariates.ipynb rename to v1/notebooks/covariates.ipynb diff --git a/notebooks/finetuning.ipynb b/v1/notebooks/finetuning.ipynb similarity index 100% rename from notebooks/finetuning.ipynb rename to v1/notebooks/finetuning.ipynb diff --git a/notebooks/finetuning_torch.ipynb b/v1/notebooks/finetuning_torch.ipynb similarity index 100% rename from notebooks/finetuning_torch.ipynb rename to v1/notebooks/finetuning_torch.ipynb diff --git a/peft/README.md b/v1/peft/README.md similarity index 100% rename from peft/README.md rename to v1/peft/README.md diff --git a/peft/finetune.py b/v1/peft/finetune.py similarity index 100% rename from peft/finetune.py rename to v1/peft/finetune.py diff --git a/peft/finetune.sh b/v1/peft/finetune.sh similarity index 100% rename from peft/finetune.sh rename to v1/peft/finetune.sh diff --git a/peft/usage.ipynb b/v1/peft/usage.ipynb similarity index 100% rename from peft/usage.ipynb rename to v1/peft/usage.ipynb diff --git a/poetry.lock b/v1/poetry.lock similarity index 100% rename from poetry.lock rename to v1/poetry.lock diff --git a/v1/pyproject.toml b/v1/pyproject.toml new file mode 100644 index 0000000..6280f41 --- /dev/null +++ b/v1/pyproject.toml @@ -0,0 +1,75 @@ +[tool.poetry] +name = "timesfm" +packages = [ + { include = "timesfm", from = "src" }, + { include = "finetuning", from = "src" }, +] +description = "Open weights time-series foundation model from Google Research." +version = "1.3.0" +authors = [ + "Rajat Sen ", + "Yichen Zhou ", + "Abhimanyu Das ", + "Petros Mol ", + "Justin Güse ", + "Michael Chertushkin " +] +readme = "README.md" +keywords = ["time series", "timesfm", "forecast", "time series model"] +homepage = "https://github.com/google-research/timesfm" +repository = "https://github.com/google-research/timesfm" +classifiers = [ + "Environment :: Console", + "Framework :: Flake8", + "Operating System :: OS Independent", + "Topic :: Software Development :: Documentation", + "Topic :: Software Development :: Libraries :: Python Modules", + "Topic :: Software Development :: Quality Assurance", +] +include = ["LICENSE"] + +[tool.poetry.dependencies] +python = ">=3.10,<3.12" +einshape = ">=1.0.0" +numpy = ">=1.26.4" +pandas = ">=2.0.0" +utilsforecast = ">=0.1.10" +huggingface_hub = { version = ">=0.23.0", extras = ["cli"] } +scikit-learn = ">=1.2.2" +typer = ">=0.12.3" +wandb = ">=0.17.5" +absl-py = ">=1.4.0" +safetensors = "^0.5.3" + +[tool.poetry.extras] +pax = ["paxml", "lingvo", "jax", "jaxlib"] +torch = ["torch"] + +[tool.poetry.dependencies.paxml] +version = ">=1.4.0" +python = ">=3.10,<3.11" + +[tool.poetry.dependencies.lingvo] +version = ">=0.12.7" +python = ">=3.10,<3.11" + +[tool.poetry.dependencies.jax] +version = ">=0.4.26" +extras = ["cuda12"] +python = ">=3.10,<3.12" # Support both python versions + +[tool.poetry.dependencies.jaxlib] +version = ">=0.4.26" +python = ">=3.10,<3.12" # Support both python versions + +[tool.poetry.dependencies.torch] +version = ">=2.0.0" +extras = ["cuda"] +python = ">=3.11,<3.12" + +[tool.poetry.group.dev.dependencies] +pytest = ">=8.3.2" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/src/adapter/__init__.py b/v1/src/adapter/__init__.py similarity index 100% rename from src/adapter/__init__.py rename to v1/src/adapter/__init__.py diff --git a/src/adapter/dora_layers.py b/v1/src/adapter/dora_layers.py similarity index 100% rename from src/adapter/dora_layers.py rename to v1/src/adapter/dora_layers.py diff --git a/src/adapter/lora_layers.py b/v1/src/adapter/lora_layers.py similarity index 100% rename from src/adapter/lora_layers.py rename to v1/src/adapter/lora_layers.py diff --git a/src/adapter/utils.py b/v1/src/adapter/utils.py similarity index 100% rename from src/adapter/utils.py rename to v1/src/adapter/utils.py diff --git a/src/finetuning/__init__.py b/v1/src/finetuning/__init__.py similarity index 100% rename from src/finetuning/__init__.py rename to v1/src/finetuning/__init__.py diff --git a/src/finetuning/finetuning_example.py b/v1/src/finetuning/finetuning_example.py similarity index 100% rename from src/finetuning/finetuning_example.py rename to v1/src/finetuning/finetuning_example.py diff --git a/src/finetuning/finetuning_torch.py b/v1/src/finetuning/finetuning_torch.py similarity index 100% rename from src/finetuning/finetuning_torch.py rename to v1/src/finetuning/finetuning_torch.py diff --git a/v1/src/timesfm/__init__.py b/v1/src/timesfm/__init__.py new file mode 100644 index 0000000..739807a --- /dev/null +++ b/v1/src/timesfm/__init__.py @@ -0,0 +1,35 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""TimesFM init file.""" + +print( + " See https://github.com/google-research/timesfm/blob/master/README.md for updated APIs." +) +from timesfm.timesfm_base import ( + freq_map, + TimesFmCheckpoint, + TimesFmHparams, + TimesFmBase, +) +import sys + +try: + from timesfm.timesfm_jax import TimesFmJax as TimesFm + from timesfm import data_loader + + print(f"Loaded Jax TimesFM, likely because python version is {sys.version}.") +except Exception as _: + from timesfm.timesfm_torch import TimesFmTorch as TimesFm + + print(f"Loaded PyTorch TimesFM, likely because python version is {sys.version}.") diff --git a/src/timesfm/data_loader.py b/v1/src/timesfm/data_loader.py similarity index 100% rename from src/timesfm/data_loader.py rename to v1/src/timesfm/data_loader.py diff --git a/src/timesfm/patched_decoder.py b/v1/src/timesfm/patched_decoder.py similarity index 100% rename from src/timesfm/patched_decoder.py rename to v1/src/timesfm/patched_decoder.py diff --git a/src/timesfm/pytorch_patched_decoder.py b/v1/src/timesfm/pytorch_patched_decoder.py similarity index 100% rename from src/timesfm/pytorch_patched_decoder.py rename to v1/src/timesfm/pytorch_patched_decoder.py diff --git a/src/timesfm/time_features.py b/v1/src/timesfm/time_features.py similarity index 100% rename from src/timesfm/time_features.py rename to v1/src/timesfm/time_features.py diff --git a/src/timesfm/timesfm_base.py b/v1/src/timesfm/timesfm_base.py similarity index 100% rename from src/timesfm/timesfm_base.py rename to v1/src/timesfm/timesfm_base.py diff --git a/src/timesfm/timesfm_jax.py b/v1/src/timesfm/timesfm_jax.py similarity index 100% rename from src/timesfm/timesfm_jax.py rename to v1/src/timesfm/timesfm_jax.py diff --git a/src/timesfm/timesfm_torch.py b/v1/src/timesfm/timesfm_torch.py similarity index 100% rename from src/timesfm/timesfm_torch.py rename to v1/src/timesfm/timesfm_torch.py diff --git a/src/timesfm/xreg_lib.py b/v1/src/timesfm/xreg_lib.py similarity index 100% rename from src/timesfm/xreg_lib.py rename to v1/src/timesfm/xreg_lib.py diff --git a/tests/test_timesfm.py b/v1/tests/test_timesfm.py similarity index 100% rename from tests/test_timesfm.py rename to v1/tests/test_timesfm.py