Adding v2.0 support
This commit is contained in:
@@ -23,7 +23,7 @@ jobs:
|
||||
# e.g. poetry version 0.1.${{ github.run_number }}
|
||||
- name: Set Version number
|
||||
run: |
|
||||
poetry version 1.2.4
|
||||
poetry version 1.2.5
|
||||
- name: Build and Publish to PyPI
|
||||
run: |
|
||||
poetry config pypi-token.pypi ${{ secrets.PYPI_API_TOKEN }}
|
||||
|
||||
@@ -16,10 +16,8 @@ This is not an officially supported Google product.
|
||||
|
||||
We recommend at least 16GB RAM to load TimesFM dependencies.
|
||||
|
||||
## Update - Sep. 12, 2024
|
||||
- We have released full pytorch support (excluding PEFT parts).
|
||||
- Shoutout to @tanmayshishodia for checking in PEFT methods like LoRA and DoRA.
|
||||
- To install TimesFM, you can now simply do: `pip install timesfm`.
|
||||
## Update - Dec. 30, 2024
|
||||
- We are launching a 500m checkpoint as a part of TimesFM-2.0 release.
|
||||
- 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).
|
||||
|
||||
@@ -31,6 +29,14 @@ timesfm-1.0-200m is the first open model checkpoint:
|
||||
- It focuses on point forecasts, and does not support probabilistic forecasts. We experimentally offer quantile heads but they have not been calibrated after pretraining.
|
||||
- It requires the context to be contiguous (i.e. no "holes"), and the context and the horizon to be of the same frequency.
|
||||
|
||||
## Checkpoint timesfm-2.0-500m (-jax/-pytorch)
|
||||
|
||||
timesfm-2.0-500m is the 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.
|
||||
- It requires the context to be contiguous (i.e. no "holes"), and the context and the horizon to be of the same frequency.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Please refer to our result tables on the [extended benchmarks](https://github.com/google-research/timesfm/tree/master/experiments/extended_benchmarks) and the [long horizon benchmarks](https://github.com/google-research/timesfm/tree/master/experiments/long_horizon_benchmarks).
|
||||
@@ -103,6 +109,37 @@ 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(
|
||||
@@ -126,9 +163,9 @@ tfm = timesfm.TimesFm(
|
||||
)
|
||||
```
|
||||
|
||||
Note some of the parameters are fixed to load the 200m model
|
||||
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**. **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. Currently, the model handles a max context length of 512, which can be increased in later releases. The input time series can have **any context length**. Padding / truncation will be handled by the inference code if needed.
|
||||
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.
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ poetry run python3 -m experiments.extended_benchmarks.run_timesfm --model_path=g
|
||||
|
||||
Note: In the current version of TimesFM we focus on point forecasts and therefore the mase, smape have been calculated using the quantile head corresponding to the median i.e 0.5 quantile. We do offer 10 quantile heads but they have not been calibrated after pretraining. We recommend using them with caution or calibrate/conformalize them on a hold out for your applications. More to follow on later versions.
|
||||
|
||||
## Benchmark Results
|
||||
## Benchmark Results for TimesFM-1.0
|
||||
|
||||

|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ poetry run python3 -m experiments.long_horizon_benchmarks.run_eval \
|
||||
|
||||
You can change the model size from "mini" to "large" as required. The datasets we benchmark on are etth1, etth2, ettm1 and ettm2.
|
||||
|
||||
## Benchmark Results
|
||||
## Benchmark Results for TimesFM-1.0
|
||||
|
||||

|
||||
|
||||
|
||||
+33
-53
@@ -9,7 +9,8 @@
|
||||
"This toturial notebook demonstrates how to utilize exogenous covariates with TimesFM when making forecasts. Before running this notebook, make sure:\n",
|
||||
"\n",
|
||||
"- You've read through the README of TimesFM.\n",
|
||||
"- A local kernel with Python 3.10 is up and running."
|
||||
"- A local kernel with Python 3.10 is up and running, for the jax version.\n",
|
||||
"- Install the JAX version following the installation instructions."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -19,36 +20,15 @@
|
||||
"## Setup the environment and install TimesFM."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"os.environ['XLA_PYTHON_CLIENT_PREALLOCATE'] = 'false'\n",
|
||||
"os.environ['JAX_PMAP_USE_TENSORSTORE'] = 'false'"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install timesfm\n",
|
||||
"import timesfm"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Load the checkpoint\n",
|
||||
"\n",
|
||||
"**Notice:** Please set up the backend as per your machine (\"cpu\", \"gpu\" or \"tpu\"). This notebook will run by default on CPU.\n",
|
||||
"**Notice:** Please set up the backend as per your machine (\"cpu\", \"gpu\" or \"tpu\"). This notebook will run by default on GPU.\n",
|
||||
"\n",
|
||||
"We load the 1.0-200m model checkpoint from HuggingFace."
|
||||
"We load the 2.0-500m model checkpoint from HuggingFace."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -57,23 +37,21 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"timesfm_backend = \"cpu\" # @param\n",
|
||||
"\n",
|
||||
"from jax._src import config\n",
|
||||
"config.update(\n",
|
||||
" \"jax_platforms\", {\"cpu\": \"cpu\", \"gpu\": \"cuda\", \"tpu\": \"\"}[timesfm_backend]\n",
|
||||
")\n",
|
||||
"import timesfm\n",
|
||||
"timesfm_backend = \"gpu\" # @param\n",
|
||||
"\n",
|
||||
"model = timesfm.TimesFm(\n",
|
||||
" context_len=512,\n",
|
||||
" horizon_len=128,\n",
|
||||
" input_patch_len=32,\n",
|
||||
" output_patch_len=128,\n",
|
||||
" num_layers=20,\n",
|
||||
" model_dims=1280,\n",
|
||||
" backend=timesfm_backend,\n",
|
||||
")\n",
|
||||
"model.load_from_checkpoint(repo_id=\"google/timesfm-1.0-200m\")"
|
||||
" hparams=timesfm.TimesFmHparams(\n",
|
||||
" backend=timesfm_backend,\n",
|
||||
" per_core_batch_size=32,\n",
|
||||
" horizon_len=128,\n",
|
||||
" num_layers=50,\n",
|
||||
" use_positional_embedding=False,\n",
|
||||
" context_len=2048,\n",
|
||||
" ),\n",
|
||||
" checkpoint=timesfm.TimesFmCheckpoint(\n",
|
||||
" huggingface_repo_id=\"google/timesfm-2.0-500m-jax\"),\n",
|
||||
" )"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -140,7 +118,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -176,7 +154,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -208,7 +186,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -239,13 +217,15 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import time\n",
|
||||
"\n",
|
||||
"# Benchmark\n",
|
||||
"batch_size = 128\n",
|
||||
"context_len = 120\n",
|
||||
"horizon_len = 24\n",
|
||||
"input_data = get_batched_data_fn(batch_size = 128)\n",
|
||||
"metrics = defaultdict(list)\n",
|
||||
"import time\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"for i, example in enumerate(input_data()):\n",
|
||||
" raw_forecast, _ = model.forecast(\n",
|
||||
@@ -307,15 +287,15 @@
|
||||
"source": [
|
||||
"You should see results close to \n",
|
||||
"```\n",
|
||||
"eval_mae_timesfm: 6.762283045916956\n",
|
||||
"eval_mae_xreg_timesfm: 5.39219617611074\n",
|
||||
"eval_mae_xreg: 37.15275842572484\n",
|
||||
"eval_mse_timesfm: 166.7771466306823\n",
|
||||
"eval_mse_xreg_timesfm: 120.64757721021306\n",
|
||||
"eval_mse_xreg: 1672.2116821201796\n",
|
||||
"eval_mae_timesfm: 6.729583250571446\n",
|
||||
"eval_mae_xreg_timesfm: 5.3375301110158\n",
|
||||
"eval_mae_xreg: 37.152760709266\n",
|
||||
"eval_mse_timesfm: 162.3132151851567\n",
|
||||
"eval_mse_xreg_timesfm: 120.9900627409689\n",
|
||||
"eval_mse_xreg: 1672.208769045399\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"With the covariates, the TimesFM forecast Mean Absolute Error improves from 6.76 to 5.39, and Mean Squred Error from 166.78 to 120.65. The results of purely fitting the linear model are also provided for reference."
|
||||
"With the covariates, the TimesFM forecast Mean Absolute Error improves from 6.73 to 5.34, and Mean Squred Error from 162.31 to 120.99. The results of purely fitting the linear model are also provided for reference."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -381,9 +361,9 @@
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "cuda-gpt",
|
||||
"display_name": "chronos-v2",
|
||||
"language": "python",
|
||||
"name": "cuda"
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
@@ -395,7 +375,7 @@
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.14"
|
||||
"version": "3.10.15"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
+28
-20
@@ -9,7 +9,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -34,7 +34,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -61,14 +61,22 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"timesfm_backend = \"gpu\" # @param\n",
|
||||
"\n",
|
||||
"tfm = timesfm.TimesFm(\n",
|
||||
" hparams=timesfm.TimesFmHparams(\n",
|
||||
" backend=\"gpu\",\n",
|
||||
" backend=timesfm_backend,\n",
|
||||
" per_core_batch_size=32,\n",
|
||||
" horizon_len=128,\n",
|
||||
" num_layers=50,\n",
|
||||
" # Se this to True for v1.0 checkpoints\n",
|
||||
" use_positional_embedding=False,\n",
|
||||
" # Note that we could set this to as high as 2048 but keeping it 512 here so that\n",
|
||||
" # both v1.0 and 2.0 checkpoints work\n",
|
||||
" context_len=512,\n",
|
||||
" ),\n",
|
||||
" checkpoint=timesfm.TimesFmCheckpoint(\n",
|
||||
" huggingface_repo_id=\"google/timesfm-1.0-200m\"),\n",
|
||||
" huggingface_repo_id=\"google/timesfm-2.0-500m-jax\"),\n",
|
||||
" )"
|
||||
]
|
||||
},
|
||||
@@ -81,7 +89,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -126,7 +134,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -147,7 +155,7 @@
|
||||
"pred_len = 96\n",
|
||||
"\n",
|
||||
"num_ts = len(ts_cols)\n",
|
||||
"batch_size = 16\n",
|
||||
"batch_size = 8\n",
|
||||
"\n",
|
||||
"dtl = data_loader.TimeSeriesdata(\n",
|
||||
" data_path=data_path,\n",
|
||||
@@ -187,7 +195,7 @@
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"for tbatch in tqdm(train_batches.as_numpy_iterator()):\n",
|
||||
" pass\n",
|
||||
" break\n",
|
||||
"print(tbatch[0].shape)"
|
||||
]
|
||||
},
|
||||
@@ -224,7 +232,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 9,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -248,7 +256,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 10,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -276,7 +284,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 11,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -296,7 +304,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 12,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -325,7 +333,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 13,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -416,7 +424,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 19,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -445,7 +453,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 20,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -455,7 +463,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 21,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -470,7 +478,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 22,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
@@ -583,13 +591,13 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## There is around a __9%__ reduction in MAE from finetuning."
|
||||
"## There is around a __7%__ reduction in MAE from finetuning."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "tfm_env_v3",
|
||||
"display_name": "chronos-v2",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
@@ -603,7 +611,7 @@
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.14"
|
||||
"version": "3.10.15"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
Generated
+1288
-1265
File diff suppressed because it is too large
Load Diff
+2
-2
@@ -2,7 +2,7 @@
|
||||
name = "timesfm"
|
||||
packages = [{ include = "timesfm", from = "src" }]
|
||||
description = "Open weights time-series foundation model from Google Research."
|
||||
version = "1.0.1"
|
||||
version = "1.2.5"
|
||||
authors = [
|
||||
"Rajat Sen <senrajat@google.com>",
|
||||
"Yichen Zhou <yichenzhou@google.com>",
|
||||
@@ -28,7 +28,7 @@ include = ["LICENSE"]
|
||||
python = ">=3.10,<3.12"
|
||||
einshape = ">=1.0.0"
|
||||
numpy = ">=1.26.4"
|
||||
pandas = ">=2.1.4"
|
||||
pandas = ">=2.0.0"
|
||||
utilsforecast = ">=0.1.10"
|
||||
huggingface_hub = { version = ">=0.23.0", extras = ["cli"] }
|
||||
scikit-learn = ">=1.2.2"
|
||||
|
||||
@@ -333,7 +333,7 @@ class PatchedTimeSeriesDecoder(base_layer.BaseLayer):
|
||||
model_input = self.input_ff_layer(concat_inputs)
|
||||
# A patch should not be padded even if there is at least one zero.
|
||||
patched_padding = jnp.min(patched_pads, axis=-1)
|
||||
|
||||
|
||||
if self.use_pos_emb:
|
||||
if pos_emb is None:
|
||||
position_emb = self.position_emb(seq_length=model_input.shape[1])
|
||||
@@ -401,7 +401,7 @@ class PatchedTimeSeriesDecoder(base_layer.BaseLayer):
|
||||
inputs: NestedMap,
|
||||
horizon_len: int,
|
||||
output_patch_len: Optional[int] = None,
|
||||
max_len: int = 512,
|
||||
max_len: int | None = None,
|
||||
return_forecast_on_context: bool = False,
|
||||
) -> tuple[JTensor, JTensor]:
|
||||
"""Auto-regressive decoding without caching.
|
||||
@@ -427,6 +427,8 @@ class PatchedTimeSeriesDecoder(base_layer.BaseLayer):
|
||||
final_out = inputs[_INPUT_TS]
|
||||
context_len = final_out.shape[1]
|
||||
paddings = inputs[_INPUT_PADDING]
|
||||
if max_len is None:
|
||||
max_len = context_len
|
||||
if self.use_freq:
|
||||
freq = inputs[_FREQ].astype(jnp.int32)
|
||||
else:
|
||||
|
||||
@@ -730,7 +730,7 @@ class PatchedTimeSeriesDecoder(nn.Module):
|
||||
freq: torch.LongTensor,
|
||||
horizon_len: int,
|
||||
output_patch_len: int | None = None,
|
||||
max_len: int = 512,
|
||||
max_len: int | None = None,
|
||||
return_forecast_on_context: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Auto-regressive decoding without caching.
|
||||
@@ -757,6 +757,8 @@ class PatchedTimeSeriesDecoder(nn.Module):
|
||||
final_out = input_ts
|
||||
context_len = final_out.shape[1]
|
||||
full_outputs = []
|
||||
if max_len is None:
|
||||
max_len = context_len
|
||||
if paddings.shape[1] != final_out.shape[1] + horizon_len:
|
||||
raise ValueError(
|
||||
"Length of paddings must match length of input + horizon_len:"
|
||||
@@ -773,9 +775,9 @@ class PatchedTimeSeriesDecoder(nn.Module):
|
||||
if return_forecast_on_context and step_index == 0:
|
||||
# For the first decodings step, collect the model forecast on the
|
||||
# context except the unavailable first input batch forecast.
|
||||
new_full_ts = fprop_outputs[:, :-1, :self.config.patch_len, :]
|
||||
new_full_ts = fprop_outputs.view(new_full_ts.size(0), -1,
|
||||
new_full_ts.size(3))
|
||||
new_full_ts = fprop_outputs[:, 0:-1, 0:self.config.patch_len, :]
|
||||
new_full_ts = new_full_ts.reshape(new_full_ts.size(0), -1,
|
||||
new_full_ts.size(3))
|
||||
|
||||
full_outputs.append(new_full_ts)
|
||||
|
||||
|
||||
@@ -61,6 +61,7 @@ def freq_map(freq: str):
|
||||
else:
|
||||
raise ValueError(f"Invalid frequency: {freq}")
|
||||
|
||||
|
||||
def strip_leading_nans(arr):
|
||||
"""
|
||||
Removes contiguous NaN values from the beginning of a NumPy array.
|
||||
@@ -77,6 +78,7 @@ def strip_leading_nans(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.
|
||||
@@ -95,7 +97,9 @@ def linear_interpolation(arr):
|
||||
if not np.any(nans): # Check if there are any NaNs
|
||||
return arr
|
||||
|
||||
x = lambda z: z.nonzero()[0]
|
||||
def x(z):
|
||||
return z.nonzero()[0]
|
||||
|
||||
nans_indices = x(nans)
|
||||
non_nans_indices = x(~nans)
|
||||
non_nans_values = arr[~nans]
|
||||
@@ -363,7 +367,7 @@ class TimesFmBase:
|
||||
ValueError: If the checkpoint is not properly loaded.
|
||||
"""
|
||||
stats = None
|
||||
|
||||
|
||||
tmp_inputs = []
|
||||
for each_input in inputs:
|
||||
arr = np.array(each_input)
|
||||
@@ -372,7 +376,7 @@ class TimesFmBase:
|
||||
arr = strip_leading_nans(arr)
|
||||
arr = linear_interpolation(arr)
|
||||
tmp_inputs.append(arr)
|
||||
|
||||
|
||||
inputs = tmp_inputs
|
||||
if normalize:
|
||||
inputs, stats = _normalize(inputs)
|
||||
|
||||
@@ -58,8 +58,8 @@ class TimesFmTorch(timesfm_base.TimesFmBase):
|
||||
repo_id = checkpoint.huggingface_repo_id
|
||||
if checkpoint_path is None:
|
||||
checkpoint_path = path.join(
|
||||
snapshot_download(repo_id, local_dir=checkpoint.local_dir),
|
||||
"torch_model.ckpt")
|
||||
snapshot_download(repo_id, local_dir=checkpoint.local_dir),
|
||||
"torch_model.ckpt")
|
||||
self._model = ppd.PatchedTimeSeriesDecoder(self._model_config)
|
||||
loaded_checkpoint = torch.load(checkpoint_path, weights_only=True)
|
||||
logging.info("Loading checkpoint from %s", checkpoint_path)
|
||||
@@ -79,36 +79,33 @@ class TimesFmTorch(timesfm_base.TimesFmBase):
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Forecasts on a list of time series.
|
||||
|
||||
Args:
|
||||
inputs: list of time series forecast contexts. Each context time series
|
||||
should be in a format convertible to JTensor by `jnp.array`.
|
||||
freq: frequency of each context time series. 0 for high frequency
|
||||
(default), 1 for medium, and 2 for low. Notice this is different from
|
||||
the `freq` required by `forecast_on_df`.
|
||||
window_size: window size of trend + residual decomposition. If None then
|
||||
we do not do decomposition.
|
||||
forecast_context_len: optional max context length.
|
||||
return_forecast_on_context: True to return the forecast on the context
|
||||
when available, i.e. after the first input patch.
|
||||
Args:
|
||||
inputs: list of time series forecast contexts. Each context time series
|
||||
should be in a format convertible to JTensor by `jnp.array`.
|
||||
freq: frequency of each context time series. 0 for high frequency
|
||||
(default), 1 for medium, and 2 for low. Notice this is different from
|
||||
the `freq` required by `forecast_on_df`.
|
||||
window_size: window size of trend + residual decomposition. If None then
|
||||
we do not do decomposition.
|
||||
forecast_context_len: optional max context length.
|
||||
return_forecast_on_context: True to return the forecast on the context
|
||||
when available, i.e. after the first input patch.
|
||||
|
||||
Returns:
|
||||
A tuple for JTensors:
|
||||
- the mean forecast of size (# inputs, # forecast horizon),
|
||||
- the full forecast (mean + quantiles) of size
|
||||
(# inputs, # forecast horizon, 1 + # quantiles).
|
||||
Returns:
|
||||
A tuple for JTensors:
|
||||
- the mean forecast of size (# inputs, # forecast horizon),
|
||||
- the full forecast (mean + quantiles) of size
|
||||
(# inputs, # forecast horizon, 1 + # quantiles).
|
||||
|
||||
Raises:
|
||||
ValueError: If the checkpoint is not properly loaded.
|
||||
"""
|
||||
if self._model is None:
|
||||
raise ValueError("Checkpoint is not properly loaded.")
|
||||
|
||||
Raises:
|
||||
ValueError: If the checkpoint is not properly loaded.
|
||||
"""
|
||||
if not self._model:
|
||||
raise ValueError(
|
||||
"Checkpoint not loaded. Call `load_from_checkpoint` before"
|
||||
" `forecast`.")
|
||||
if forecast_context_len is None:
|
||||
fcontext_len = self.context_len
|
||||
else:
|
||||
fcontext_len = forecast_context_len
|
||||
inputs = [np.array(ts)[-fcontext_len:] for ts in inputs]
|
||||
forecast_context_len = self.context_len
|
||||
inputs = [np.array(ts)[-forecast_context_len:] for ts in inputs]
|
||||
|
||||
if window_size is not None:
|
||||
new_inputs = []
|
||||
@@ -121,36 +118,39 @@ class TimesFmTorch(timesfm_base.TimesFmBase):
|
||||
freq = [0] * len(inputs)
|
||||
|
||||
input_ts, input_padding, inp_freq, pmap_pad = self._preprocess(inputs, freq)
|
||||
|
||||
with torch.no_grad():
|
||||
mean_outputs = []
|
||||
full_outputs = []
|
||||
assert input_ts.shape[0] % self.global_batch_size == 0
|
||||
for i in range(input_ts.shape[0] // self.global_batch_size):
|
||||
input_ts_in = torch.from_numpy(
|
||||
np.array(input_ts[i * self.global_batch_size:(i + 1) *
|
||||
self.global_batch_size],
|
||||
dtype=np.float32)).to(self._device)
|
||||
input_padding_in = torch.from_numpy(
|
||||
np.array(input_padding[i * self.global_batch_size:(i + 1) *
|
||||
self.global_batch_size],
|
||||
dtype=np.float32)).to(self._device)
|
||||
inp_freq_in = torch.from_numpy(
|
||||
np.array(inp_freq[
|
||||
i * self.global_batch_size:(i + 1) * self.global_batch_size,
|
||||
:,
|
||||
],
|
||||
dtype=np.int32)).long().to(self._device)
|
||||
t_input_ts = torch.Tensor(input_ts[i * self.global_batch_size:(i + 1) *
|
||||
self.global_batch_size]).to(
|
||||
self._device)
|
||||
t_input_padding = torch.Tensor(
|
||||
input_padding[i * self.global_batch_size:(i + 1) *
|
||||
self.global_batch_size]).to(self._device)
|
||||
t_inp_freq = torch.LongTensor(
|
||||
inp_freq[i * self.global_batch_size:(i + 1) *
|
||||
self.global_batch_size, :]).to(self._device)
|
||||
|
||||
mean_output, full_output = self._model.decode(
|
||||
input_ts=input_ts_in,
|
||||
paddings=input_padding_in,
|
||||
freq=inp_freq_in,
|
||||
input_ts=t_input_ts,
|
||||
paddings=t_input_padding,
|
||||
freq=t_inp_freq,
|
||||
horizon_len=self.horizon_len,
|
||||
return_forecast_on_context=return_forecast_on_context,
|
||||
output_patch_len=self.output_patch_len,
|
||||
# Returns forecasts on context for parity with the Jax version.
|
||||
return_forecast_on_context=True,
|
||||
)
|
||||
mean_output = mean_output.detach().cpu().numpy()
|
||||
full_output = full_output.detach().cpu().numpy()
|
||||
mean_output = np.array(mean_output)
|
||||
full_output = np.array(full_output)
|
||||
if not return_forecast_on_context:
|
||||
mean_output = mean_output[:, self._horizon_start:, ...]
|
||||
full_output = full_output[:, self._horizon_start:, ...]
|
||||
|
||||
if self.backend == "gpu":
|
||||
mean_output = mean_output.cpu()
|
||||
full_output = full_output.cpu()
|
||||
mean_output = mean_output.detach().numpy()
|
||||
full_output = full_output.detach().numpy()
|
||||
mean_outputs.append(mean_output)
|
||||
full_outputs.append(full_output)
|
||||
|
||||
@@ -164,4 +164,5 @@ class TimesFmTorch(timesfm_base.TimesFmBase):
|
||||
if window_size is not None:
|
||||
mean_outputs = mean_outputs[0::2, ...] + mean_outputs[1::2, ...]
|
||||
full_outputs = full_outputs[0::2, ...] + full_outputs[1::2, ...]
|
||||
|
||||
return mean_outputs, full_outputs
|
||||
|
||||
Reference in New Issue
Block a user