perf: Import onnx quantization and matplotlib only where used

KR
1mo ago
+38-3

Summary

Importing the layout API loaded two large libraries that most runs never use:

  • models/detectron2onnx.py imported onnxruntime.quantization at module load, which loads all of onnx. models/base.py imports detectron2onnx for every model, YOLOX included, but quantization only runs when a quantized Detectron2 model doesn't exist on disk yet.
  • visualize.py imported matplotlib.pyplot, and inference/layout.py imports visualize for draw_bbox. Only show_plot uses matplotlib.

Each import now happens at its single call site.

Impact

Measured on macOS, Python 3.13:

BeforeAfter
RSS after importing inference.layout + models.base367 MiB149 MiB
Import time (warm)~1.2–1.5 s~0.5–0.6 s
Peak RSS, 16-page PDF through YOLOX (process_file_with_model)1013 MiB792 MiB

The YOLOX run produced identical output (161 elements) on both sides.

Verification

  • New test_unstructured_inference/test_imports.py imports inference.layout, models.base, models.detectron2onnx and visualize in a fresh interpreter and asserts that neither onnx nor matplotlib gets loaded. It fails on main and passes here.
  • The existing show_plot tests still patch matplotlib.pyplot.subplots/show and pass, because the module attributes are looked up at call time.
  • make test: 383 passed, 1 skipped. ruff check / ruff format --check clean.

Version bumped to 1.6.17 with a CHANGELOG entry. #530 also targets 1.6.17, so whichever merges second needs the next patch version.