Image Classification
ONNX
onnxruntime
document-orientation
deskew
ocr
image-preprocessing
cpu
folio-orient / training /export.py
foliokestrel's picture
Add an optional eight-way mirrored-print model, offline CLI and evaluated operating points
5c3729a verified
Raw History Blame Contribute Delete
1.55 kB
"""Export the trained checkpoint and verify a dynamic batch against PyTorch."""
import argparse
from pathlib import Path
import numpy as np
import onnxruntime as ort
import torch
from network import PatchOrient
def export(checkpoint, output, reflection=False):
model = PatchOrient(8 if reflection else 4)
model.load_state_dict(torch.load(checkpoint, map_location="cpu", weights_only=True))
model.eval()
example = torch.randn(3, 1, 96, 96)
torch.onnx.export(
model,
example,
output,
opset_version=17,
dynamo=False,
input_names=["patches"],
output_names=["logits"],
dynamic_axes={"patches": {0: "batch"}, "logits": {0: "batch"}},
)
session = ort.InferenceSession(str(output), providers=["CPUExecutionProvider"])
for n in (1, 5, 24):
inputs = torch.randn(n, 1, 96, 96)
with torch.no_grad():
expected = model(inputs).numpy()
actual = session.run(None, {"patches": inputs.numpy()})[0]
np.testing.assert_allclose(actual, expected, rtol=1e-4, atol=2e-5)
print(
f"Verified dynamic batch sizes 1, 5 and 24. ONNX size {output.stat().st_size:,} bytes."
)
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("checkpoint", type=Path)
p.add_argument("output", type=Path)
p.add_argument(
"--reflection", action="store_true", help="Export an eight-class checkpoint"
)
args = p.parse_args()
export(args.checkpoint, args.output, args.reflection)