ONNX export of MASTER keeps only as many decoding steps as the dummy input needed (the early stop in `decode` is traced)
Bug description
Since #2118, MASTER.decode stops its loop as soon as every sequence has emitted EOS:
if (ys == self.vocab_size).any(dim=-1).all(): # every sequence has emitted EOS
break
export_model_to_onnx traces the model (dynamo=False), so this Python condition is evaluated once, on the dummy input, and the exported graph keeps exactly the number of decoding steps the dummy needed. With a random dummy (as in test_models_onnx_export) that is a handful of steps. The exported model then returns truncated words, or words filled with a repeated character, for anything longer. PyTorch inference is not affected.
Observed with master(pretrained=True, exportable=True) on main (dbcee0d; the same lines are in v1.1.0): 24 rendered words of 1 to 22 characters, all 24 read correctly by PyTorch, and the model exported with torch.rand((2, 3, 32, 128)) under five seeds:
| seed | decoding steps the dummy needed | ONNX == PyTorch on the dummy (atol 1e-4) | words identical to PyTorch |
|---|---|---|---|
| 0 | 3 | yes | 3 / 24 |
| 1 | 12 | yes | 16 / 24 |
| 2 | 5 | yes | 6 / 24 |
| 3 | 5 | yes | 6 / 24 |
| 4 | 2 | yes | 1 / 24 |
Expected: the exported model decodes any input like the PyTorch model.
PARSeq already guards the same stop (if not self.exportable and ..., with the note that break isn't correctly translated to ONNX). With the same guard in MASTER, the five exports above give 24 / 24.
test_models_onnx_export does not see it because it compares ONNX and PyTorch on the dummy input the graph was traced with, where the two always agree (and the master case is skipped below 16 GB of memory).
I have a small fix with a test ready and will open a pull request.
Code snippet to reproduce the bug
import os
import tempfile
import numpy as np
import onnxruntime
import torch
from PIL import Image, ImageDraw, ImageFont
from doctr.models import recognition
from doctr.models.preprocessor import PreProcessor
from doctr.models.utils import export_model_to_onnx
model = recognition.master(pretrained=True, exportable=True).eval()
def word_image(word):
font = ImageFont.load_default(size=40)
img = Image.new("RGB", (int(font.getlength(word)) + 24, 64), "white")
ImageDraw.Draw(img).text((12, 8), word, fill="black", font=font)
return np.asarray(img)
words = ["cat", "table", "international"]
pre = PreProcessor((32, 128), batch_size=len(words), mean=model.cfg["mean"], std=model.cfg["std"], preserve_aspect_ratio=True)
x = pre([word_image(w) for w in words])[0]
torch.manual_seed(0)
dummy = torch.rand((2, 3, 32, 128)) # as in tests/pytorch/test_models_recognition_pt.py::test_models_onnx_export
with tempfile.TemporaryDirectory() as tmp:
path = export_model_to_onnx(model, model_name=os.path.join(tmp, "master"), dummy_input=dummy)
sess = onnxruntime.InferenceSession(path, providers=["CPUExecutionProvider"])
onnx_dummy = sess.run(["logits"], {"input": dummy.numpy()})[0]
onnx_words = sess.run(["logits"], {"input": x.numpy()})[0]
del sess
with torch.no_grad():
pt_dummy = model(dummy)["logits"].numpy()
pt_words = model(x)["logits"]
print("ONNX == PyTorch on the dummy input:", np.allclose(onnx_dummy, pt_dummy, atol=1e-4))
print("PyTorch:", [w for w, _ in model.postprocessor(pt_words)])
print("ONNX :", [w for w, _ in model.postprocessor(torch.from_numpy(onnx_words))])
Error traceback
No exception is raised: the exported model silently returns wrong text. Output of the snippet (torch prints a TracerWarning at the line during the export):
doctr/models/recognition/master/pytorch.py:256: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. [...]
if (ys == self.vocab_size).any(dim=-1).all(): # every sequence has emitted EOS
ONNX == PyTorch on the dummy input: True
PyTorch: ['cat', 'table', 'international']
ONNX : ['cat', 'tabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'int']
Environment
DocTR version: 1.1.1a0 (main, dbcee0d)
PyTorch version: 2.15.0+cpu (torchvision 0.29.2+cpu)
OpenCV version: 5.0.0
OS: Windows 11 (the script could not collect it)
Python version: 3.12.10
Is CUDA available (PyTorch): No
CUDA runtime version: Could not collect
GPU models and configuration: Could not collect
Nvidia driver version: Could not collect
cuDNN version: Could not collect
onnx 1.23.2, onnxruntime 1.31.1