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 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 vectorDB.vectorDB import vectorDB
from 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.1.0.tar.gz (32.7 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.1.0-py3-none-any.whl (37.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: raef-0.1.0.tar.gz
  • Upload date:
  • Size: 32.7 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.1.0.tar.gz
Algorithm Hash digest
SHA256 8f68f5798f6bacc4a662cabc4248c4ddf3bb254612a686f968a94d7bcb674942
MD5 572cc626a88eb36b702596d3b00bfb5c
BLAKE2b-256 213be8267ad698114033c4fb19b34a404af98bab514e5965378e850783aca8c3

See more details on using hashes here.

File details

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

File metadata

  • Download URL: raef-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 37.4 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.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a7a406f96b7515699a30ff89125a22cdca531a1fc182a980877fffac5dc46383
MD5 1ee3f08f4d9b35551e59f04d40fa4b2d
BLAKE2b-256 f55f1f4a3f2c36f558171ebd574ca5981d1e7cf4188354cb476c0c6e6b943b48

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