Skip to main content

Retrieval-Augmented Extended Forecasting

Juan Pablo Villa Serna, Rohan Asthana, Vasileios Belagiannis

This repository contains the code for the paper titled "Model-Agnostic Retrieval-Augmented Extended Forecasting for time series" [link].

PDF preview

Abstract

Time series forecasting with pretrained foundation models has demonstrated strong zero-shot capabilities. However, achieving optimal performance on time series with short or negligible historical data in domain-specific applications typically requires adaptation via either fine-tuning or RAG. While fine-tuning is effective, it incurs substantial computational costs. This work explores RAG within univariate time series (Retrieval Augmented Generation) as a more efficient alternative, in particular RAF (Retrieval Augmented Forecasting), and introduces RAEF (Retrieval-Augmented Extended Forecasting), a model-agnostic method built upon RAF. RAEF incorporates key refinements to the retrieval and aggregation mechanisms: (1) direct retrieval in input-space rather than embedding-space, reducing inference overhead, and (2) concatenation-based aggregation that preserves temporal structure instead of averaging. Empirical evaluation across multiple benchmark datasets demonstrates that RAEF outperforms RAF in both accuracy and inference overhead. Furthermore, comprehensive comparisons with zero-shot and fine-tuned foundation models show that RAEF achieves competitive or superior performance to fine-tuning while avoiding its computational burden, establishing it as a practical and scalable approach for domain adaptation in time series forecasting.

Environment

All tests and experiments were performed in Ubuntu 24.04.2 LTS, using an GPU NVIDIA GeForce RTX 5090.

Execution

Execute everything in the root folder using ./python, this script overwrites the needed configuration to run uv

Experiments

./python runExperiment.py -e main -i # Run main experiments with horizon 16 and include Chronos
./python runExperiment.py -e extended -i # Run Extended experiments with horizon 32
./python runExperiment.py -e embedding -i # Run Experiment, comparing embedding space vs input space
./python runExperiment.py -e performance # Run performance experiment to compare inference time

If the RAG databases were previously ingested, then the parameter -i can be removed to save time. The seeds can be changed from the file src/config.yaml.

Results are generated in the folder experiments/

Usage

RAG database Creation

import torch
import numpy as np
from raef.vectorDB.vectorDB import vectorDB

# Ingest samples to RAG database

collectionName = "collectionName"
dataset = "dataset"
ragDatabase = vectorDB = vectorDB()

# In case the collection and dataset need to be delete use the following calls
ragDatabase.deleteDataset(dataset) # Delete samples of corresponding dataset
ragDatabase.deleteCollection(collectionName, dataset) # Delete collection entirely

# Set collection
ragDatabase.setCollection(
    collectionName,
    dataset,
    lambda x : torch.tensor(x).reshape(1, len(x)),
    {"hnsw:space" : "l2"},
)


# Iterate sample by sample and ingest to the RAG database
count = 0
while count < 100:
    timeseries = np.random.rand(144) # Creates a random 144 points vector
    sample = timeseries[:128]
    prediction = timeseries[128:]

    ragDatabase.ingestTimeseries(sample, prediction, dataset)

    count += 1

RAEF (Extended Augmentation)

import numpy as np
import torch
from raef.vectorDB.vectorDB import vectorDB
from raef.model.raef import RAEF

# Load RAG database

collectionName = "collectionName"
dataset = "dataset"
ragDatabase = vectorDB = vectorDB()

# Set collection
ragDatabase.setCollection(
    collectionName,
    dataset,
    lambda x : torch.tensor(x).reshape(1, len(x)),
    {"hnsw:space" : "l2"},
)

raef : RAEF = RAEF()

timeseries = np.random.rand(144) # Creates a random 144 points vector
sample = timeseries[:128]
prediction = timeseries[128:]
k = 16

query : torch.tensor = torch.tensor(sample, dtype=torch.float32)
queried, score = ragDatabase.queryTimeseries(query, k)
if queried is not None:
    xContext : torch.Tensor = query.unsqueeze(0)
    queriedTorch : torch.Tensor = torch.Tensor(queried).unsqueeze(0)
    scoreTensor : torch.Tensor = torch.Tensor(score).unsqueeze(0)

    augmentedSample, mean, std = raef.inference(
        xContext,
        queriedTorch,
        scoreTensor,
        thresholdDistance = 1.0, # By default is set to 1.0, but can be modified
    )

    # Augmented sample is normalized, hence mean and std are needed to denormalize the prediction

    prediction = model(augmentedSample)

    stdNp : np.ndarray = std.to("cpu").squeeze(-1).squeeze(-1).numpy()
    meanNp : np.ndarray = mean.to("cpu").squeeze(-1).squeeze(-1).numpy()
    prediction = (prediction * stdNp) + meanNp
else:
    prediction = model(query)

Run in Docker

The same commands can be executed inside a docker container:

touch results.yaml
# Cuda not available
docker run -it -v ./data:/app/src/data -v ./results.yaml:/app/src/results.yaml -v ./pretrained:/app/src/pretrained ghcr.io/jpvilla1990/raef_env:0.1.0 /bin/bash

# Cuda available
docker run -it --gpus all -v ./data:/app/src/data -v ./results.yaml:/app/src/results.yaml -v ./pretrained:/app/src/pretrained ghcr.io/jpvilla1990/raef_env:0.1.0 /bin/bash

# Inside docker session
uv run python runExperiment.py -e main -i

License

This project is licensed under the Apache License 2.0.
You can read it here:
https://www.apache.org/licenses/LICENSE-2.0

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

raef-0.2.0.tar.gz (33.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

raef-0.2.0-py3-none-any.whl (37.5 kB view details)

Uploaded Python 3

File details

Details for the file raef-0.2.0.tar.gz.

File metadata

  • Download URL: raef-0.2.0.tar.gz
  • Upload date:
  • Size: 33.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.11 {"installer":{"name":"uv","version":"0.9.11"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for raef-0.2.0.tar.gz
Algorithm Hash digest
SHA256 059330696118180752a8c88b32adebfabe933a1c4eaa1016380ea3802a522e79
MD5 c91278234224c08b37b910230461ec03
BLAKE2b-256 a042e09057d60170ebf1966f0b9e2b4fc67b33f6a98591178f1f505b84015ac3

See more details on using hashes here.

File details

Details for the file raef-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: raef-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 37.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.11 {"installer":{"name":"uv","version":"0.9.11"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for raef-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2cbec37e14023a753eaf01f6713e73a2194a04519a460148fdbdf6fd2981f29e
MD5 2ce90fd49388311c2e8532ebbb48cef3
BLAKE2b-256 f42429dffbf9dcc31e8eab4f8a5fc034a6979784bebe3e25c782f11293e8c375

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page