Skip to content

feat: make timesfm2_5 onnx export compatible#45233

Open
pdufour wants to merge 6 commits intohuggingface:mainfrom
pdufour:paul.dufour/feat/onnx-timesfm
Open

feat: make timesfm2_5 onnx export compatible#45233
pdufour wants to merge 6 commits intohuggingface:mainfrom
pdufour:paul.dufour/feat/onnx-timesfm

Conversation

@pdufour
Copy link
Copy Markdown

@pdufour pdufour commented Apr 4, 2026

What does this PR do?

This fixes an issue with the padding logic in the forward pass for timesfm not being Onnx export compatible.

Specifically this condition:

if input_len < context_len:

Will give this error when you try to export the timesfm module through torch.onnx.export

Could not guard on data-dependent expression u0 < 16384

The solution is to refactor _preprocess to a branch-free path as seen in this PR.

Test Plan

On main, create a test file in the repo root

text_onnx_export.py:

import os

import torch
import torch.nn as nn
from torch.export import Dim

from transformers.models.timesfm2_5.modeling_timesfm2_5 import TimesFm2_5ModelForPrediction


class BatchToSeq(nn.Module):
    def __init__(self, model):
        super().__init__()
        self.model = model

    def forward(self, past_values):
        out = self.model(past_values.unbind(0))
        return out.mean_predictions, out.full_predictions


def export():
    model_id = "google/timesfm-2.5-200m-transformers"
    print(f"Loading {model_id}...")

    inner = TimesFm2_5ModelForPrediction.from_pretrained(model_id).eval()
    wrapped = BatchToSeq(inner).eval()

    b, t = 2, 512
    past_values = torch.randn(b, t)

    os.makedirs("test_onnx", exist_ok=True)
    path = "test_onnx/model.onnx"
    batch, seq = Dim("batch", min=1, max=1024), Dim("sequence", min=1, max=16384)

    print(f"Dynamo ONNX -> {path} ...")
    torch.onnx.export(
        wrapped,
        (past_values,),
        path,
        input_names=["past_values"],
        output_names=["mean_predictions", "full_predictions"],
        opset_version=21,
        dynamo=True,
        dynamic_shapes={"past_values": {0: batch, 1: seq}},
        external_data=True,
        do_constant_folding=True,
        optimize=False,
    )
    print("Done.")


if __name__ == "__main__":
    export()

Run the export which will export the timesfm2_5 model to onnx

python3 text_onnx_export.py

This gives you the following errors:

  1. Error about the if condition
<class 'torch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode'>: Could not guard on data-dependent expression u0 < 16384 (unhinted: u0 < 16384).  (Size-like symbols: none)

consider using data-dependent friendly APIs such as guard_or_false, guard_or_true and statically_known_true.
Caused by: (src/transformers/models/timesfm2_5/modeling_timesfm2_5.py:705 in _preprocess)

This is the line:

if input_len < context_len:

Now checkout this branch
Run the export again:

python3 text_onnx_export.py

See that it passes!

Run a test:

Create a file test_onnx_infer.py

import numpy as np
import onnxruntime as ort
import torch
import torch.nn as nn
import torch.nn.functional as F

from transformers.models.timesfm2_5.modeling_timesfm2_5 import TimesFm2_5ModelForPrediction


class BatchToSeq(nn.Module):
    def __init__(self, m):
        super().__init__()
        self.m = m

    def forward(self, past_values):
        o = self.m(past_values.unbind(0))
        return o.mean_predictions, o.full_predictions


data = [torch.linspace(0, 1, 100), torch.sin(torch.linspace(0, 20, 67))]

model = TimesFm2_5ModelForPrediction.from_pretrained(
    "google/timesfm-2.5-200m-transformers",
).eval()
ctx = model.context_len


def list_to_matrix(parts, width):
    rows = []
    for p in parts:
        p = p.float()[-width:]
        rows.append(F.pad(p, (width - p.shape[0], 0)))
    return torch.stack(rows).numpy()


matrix = list_to_matrix(data, ctx)
with torch.no_grad():
    torch_out = model(past_values=data)  # default context — matches exported ONNX
    wrap_m, wrap_f = BatchToSeq(model)(torch.from_numpy(matrix))
    print("Padding OK (≈0):", (wrap_m - torch_out.mean_predictions).abs().max().item())

onnx = ort.InferenceSession("test_onnx/model.onnx", providers=["CPUExecutionProvider"])
onnx_mean, onnx_full = onnx.run(None, {onnx.get_inputs()[0].name: matrix})

wrap_m_np, wrap_f_np = wrap_m.numpy(), wrap_f.numpy()
gap_mean = np.abs(onnx_mean - wrap_m_np).max()
gap_full = np.abs(onnx_full - wrap_f_np).max()
print("ONNX vs wrapped PyTorch (what was exported):", gap_mean, gap_full)
np.testing.assert_allclose(onnx_mean, wrap_m_np, rtol=1e-3, atol=1e-3)
np.testing.assert_allclose(onnx_full, wrap_f_np, rtol=1e-3, atol=1e-3)

Run it:

python3 -m venv .venv 
source .venv/bin/activate
pip instal onnxruntime
python3 test_onnx_infer.py

Code Agent Policy

The Transformers repo is currently being overwhelmed by a large number of PRs and issue comments written by
code agents. We are currently bottlenecked by our ability to review and respond to them. As a result,
we ask that new users do not submit pure code agent PRs at this time.
You may use code agents in drafting or to help you diagnose issues. We'd also ask autonomous "OpenClaw"-like agents
not to open any PRs or issues for the moment.

PRs that appear to be fully agent-written will probably be closed without review, and we may block users who do this
repeatedly or maliciously.

This is a rapidly-evolving situation that's causing significant shockwaves in the open-source community. As a result,
this policy is likely to be updated regularly in the near future. For more information, please read CONTRIBUTING.md.

  • I confirm that this is not a pure code agent PR.

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline,
    Pull Request section?
  • Was this discussed/approved via a Github issue or the forum? Please add a link
    to it if that's the case.
  • Did you make sure to update the documentation with your changes? Here are the
    documentation guidelines, and
    here are tips on formatting docstrings.
  • Did you write any new necessary tests?

Who can review?

@xenova @zucchini-nlp @Cyrilvallez @ArthurZucker @vasqu @NielsRogge

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 5, 2026

[For maintainers] Suggested jobs to run (before merge)

run-slow: timesfm, timesfm2_5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant