Chronos Forecasting

repository·main·Indexed 26 days ago

https://github.com/amazon-science/chronos-forecasting

A family of pretrained time series forecasting models that use language model architectures for zero-shot forecasting. Chronos supports univariate, multivariate, and covariate-informed tasks through variants such as Chronos-2 and Chronos-Bolt. The library provides high-level APIs like Chronos2Pipeline for pandas DataFrame integration, low-level Numpy/Torch APIs for advanced use cases, and tools for pretraining, fine-tuning (including LoRA), and evaluation.

Tokens
9.1K
Snippets
16
Records
42
Agent score
90%

What's inside chronos-forecasting

  1. Deploy Chronos-2 to AWS for production

    main

    For production use, it is recommended to deploy Chronos-2 to Amazon SageMaker using one of these methods:

    1. AutoGluon-Cloud (Recommended): Provides a high-level Python API for real-time, serverless, or batch inference. It accepts pandas DataFrames and returns forecasts.
    2. Amazon SageMaker JumpStart: Provides production-ready real-time endpoints on CPU or GPU that integrate into existing AWS workflows.
  2. Generate synthetic time series using KernelSynth

    main

    You can generate synthetic time series data using the kernel-synth.py script. This is useful for testing or creating datasets for pretraining. The output is a GluonTS-compatible arrow file named kernelsynth-data.arrow.

    To use this feature, you must install the package with the dev extra.

    # Install with dev extras
    pip install "chronos-forecasting[dev] @ git+https://github.com/amazon-science/chronos-forecasting.git"
    
    # Run with default settings (1M series, 5 max_kernels)
    python kernel-synth.py
    
    # Run with custom parameters
    python kernel-synth.py \
        --num-series <num of series to generate> \
        --max-kernels <max number of kernels to use per series>
  3. Push fine-tuned models to HuggingFace Hub

    main

    After fine-tuning, you can upload your model to the HuggingFace Hub. Ensure you have a HuggingFace access token with write permissions saved in ~/.cache/huggingface/token.

    from chronos import ChronosPipeline
    
    pipeline = ChronosPipeline.from_pretrained("/path/to/fine-tuned/model/ckpt/dir/")
    pipeline.model.model.push_to_hub("chronos-t5-small-fine-tuned")
  4. Pretrain or fine-tune Chronos models

    main

    You can train Chronos models from scratch or fine-tune existing checkpoints.

    Configuration

    Modify the training configs in training/configs. Key keys include:

    • training_data_paths: A list of paths to your Arrow files.
    • probability: A list of mixing probabilities for each dataset file.

    To fine-tune a pretrained model, set model_id to the checkpoint (e.g., amazon/chronos-t5-small), set random_init: false, and adjust max_steps and learning_rate.

    Execution

    Run the training script using python training/train.py with a --config flag.

    Tips:

    • If training is slow, try setting torch_compile to false or adjusting shuffle_buffer_length.
    • Important: When pretraining causal models (like GPT2), the script uses LastValueImputation for missing values. Ensure your input data is imputed similarly for consistent results in ChronosPipeline.predict().

    Outputs and checkpoints are saved in output/run-{id}/.

    # On single GPU
    CUDA_VISIBLE_DEVICES=0 python training/train.py --config /path/to/modified/config.yaml
    
    # On multiple GPUs (example with 8 GPUs)
    torchrun --nproc-per-node=8 training/train.py --config /path/to/modified/config.yaml
    
    # Fine-tune amazon/chronos-t5-small for 1000 steps
    CUDA_VISIBLE_DEVICES=0 python training/train.py --config /path/to/modified/config.yaml \
        --model-id amazon/chronos-t5-small \
        --no-random-init \
        --max-steps 1000 \
        --learning-rate 0.001
  5. Evaluate Chronos models

    main

    Evaluate models using the evaluation/evaluate.py script to compute WQL and MASE values for in-domain or zero-shot benchmarks.

    Running Evaluation

    Use the --chronos-model-id to specify the model, --batch-size, --device, and --num-samples.

    Aggregating Scores

    You can use the following logic to compute aggregated relative WQL and MASE scores against a baseline using scipy.stats.gmean.

    # In-domain evaluation
    python evaluation/evaluate.py evaluation/configs/in-domain.yaml evaluation/results/chronos-t5-small-in-domain.csv \
        --chronos-model-id "amazon/chronos-t5-small" \
        --batch-size=32 \
        --device=cuda:0 \
        --num-samples 20
    
    # Zero-shot evaluation
    python evaluation/evaluate.py evaluation/configs/zero-shot.yaml evaluation/results/chronos-t5-small-zero-shot.csv \
        --chronos-model-id "amazon/chronos-t5-small" \
        --batch-size=32 \
        --device=cuda:0 \
        --num-samples 20
    import pandas as pd
    from scipy.stats import gmean
    
    
    def agg_relative_score(model_df: pd.DataFrame, baseline_df: pd.DataFrame):
        relative_score = model_df.drop("model", axis="columns") / baseline_df.drop(
            "model", axis="columns"
        )
        return relative_score.agg(gmean)
    
    
    result_df = pd.read_csv("evaluation/results/chronos-t5-small-in-domain.csv").set_index("dataset")
    baseline_df = pd.read_csv("evaluation/results/seasonal-naive-in-domain.csv").set_index("dataset")
    
    agg_score_df = agg_relative_score(result_df, baseline_df)
  6. Use Chronos forecasting pipelines

    main

    The chronos-forecasting package provides several pipeline implementations for time series forecasting. The primary entry points are:

    • ChronosPipeline: The standard forecasting pipeline.
    • Chronos2Pipeline: The next-generation forecasting pipeline.
    • ChronosBoltPipeline: A specialized version of the forecasting pipeline.

    All pipelines inherit from BaseChronosPipeline and are used to perform forecasting tasks using their respective model and configuration classes.

  7. Deploy Chronos-2 to AWS with Amazon SageMaker

    main

    This guide provides instructions for deploying Chronos-2 models to AWS using Amazon SageMaker. It covers three primary deployment modes:

    1. Real-time Inference: Best for low-latency, interactive applications. Supports GPU and CPU instances. Simplest setup via SageMaker JumpStart.
    2. Serverless Inference (CPU only): Best for intermittent or unpredictable traffic. You pay only for active inference time. Note: Requires repackaging model artifacts and has cold start latency.
    3. Batch Transform: Best for large-scale offline forecasting. Most cost-efficient for massive datasets as it shuts down after processing. Requires data in S3 and repackaging artifacts.

    Setup Requirement: Install the SageMaker Python SDK:

    pip install -U -q "sagemaker<3"
  8. Deploy Chronos-2 for Serverless Inference

    main

    Serverless inference is cost-effective for sporadic traffic. It requires a custom SageMaker Model created from repackaged artifacts (since JumpStart direct deployment is for real-time).

    Limitations:

    • Max memory: 6GB.
    • Cold start latency: 30-60 seconds.

    Steps:

    1. Repackage JumpStart artifacts into a model.tar.gz on S3.
    2. Create a sagemaker.model.Model using the repackaged URI and the JumpStart image_uri.
    3. Deploy using ServerlessInferenceConfig.
    from sagemaker.serverless import ServerlessInferenceConfig
    
    serverless_predictor = chronos_model.deploy(
        serverless_inference_config=ServerlessInferenceConfig(
            memory_size_in_mb=6144,  # Maximum available memory
            max_concurrency=1,
        ),
        serializer=JSONSerializer(),
        deserializer=JSONDeserializer(),
    )
    
    # Query as usual
    response = serverless_predictor.predict(payload)
  9. Enable Cross-Learning for Joint Prediction

    main

    Chronos-2 supports cross-learning via the cross_learning=True parameter. This allows the model to share information across all time series in a batch, which is particularly beneficial for forecasting multiple related time series with short historical context.

    Important Considerations:

    • Task-dependent results: Cross-learning may not always improve forecasts; evaluate it for your specific use case.
    • Batch size dependency: Results depend on batch_size. For optimal results, consider a batch size around 100.
    • Input homogeneity: Works best with homogeneous inputs (e.g., multiple univariate time series of the same type).
    • Short context benefit: Most helpful when individual series have limited historical context.
    # Enable cross-learning for joint prediction
    joint_pred_df = pipeline.predict_df(
        context_df,
        prediction_length=24,
        quantile_levels=[0.1, 0.5, 0.9],
        cross_learning=True,
        batch_size=100,
    )
  10. Run Chronos-2 Batch Transform Jobs

    main

    Batch Transform is used for large-scale offline processing. Data must be staged in S3 in JSONL format, where each line is a valid Chronos API payload.

    Workflow:

    1. Prepare input data: Convert DataFrames to JSON payloads and split into chunks (e.g., 100 series per line).
    2. Upload JSONL files to S3.
    3. Use sagemaker.transformer.Transformer to run the job.

    Configuration:

    • strategy="SingleRecord": Processes one JSON line at a time.
    • assemble_with="Line": Combines results line by line.
    • accept="application/json".
    from sagemaker.transformer import Transformer
    
    output_s3_uri = f"s3://{bucket}/{s3_prefix}/batch-output/"
    
    transformer = Transformer(
        model_name=chronos_model.name,
        instance_count=1,
        instance_type="ml.c5.4xlarge",
        output_path=output_s3_uri,
        strategy="SingleRecord",
        assemble_with="Line",
        accept="application/json",
    )
    
    transformer.transform(
        data=input_s3_uri,
        content_type="application/json",
        split_type="Line",
        wait=True,
    )
  11. Load the Chronos-2 Pipeline

    main

    Load the pretrained Chronos-2 model using BaseChronosPipeline.from_pretrained. You can specify the device using device_map. Use device_map="cuda" for GPU acceleration (recommended) or device_map="cpu" if a GPU is unavailable.

    from chronos import BaseChronosPipeline, Chronos2Pipeline
    
    # Load the Chronos-2 pipeline
    pipeline: Chronos2Pipeline = BaseChronosPipeline.from_pretrained("amazon/chronos-2", device_map="cuda")