Skip to content

Commit 3bce9d6

Browse files
committed
Parallelize ONNX external-data saves by default
Expose a configurable max_workers setting through ModelPackage.save and the build CLIs, defaulting to eight workers while allowing one worker for serial saves. Detect support in onnx_ir at runtime so version 1.0 continues to save without the new keyword. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 52b46a71-2bb5-42d0-9ed0-8a6821de9b0f Signed-off-by: Justin Chu <[email protected]>
1 parent 781bbe8 commit 3bce9d6

4 files changed

Lines changed: 163 additions & 9 deletions

File tree

‎src/mobius/__main__.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,8 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
185185
# Validate --max-seq-len is positive
186186
if args.max_seq_len is not None and args.max_seq_len <= 0:
187187
raise SystemExit("Error: --max-seq-len must be a positive integer.")
188+
if args.max_workers <= 0:
189+
raise SystemExit("Error: --max-workers must be a positive integer.")
188190

189191
max_length = getattr(args, "max_length", None)
190192
if max_length is not None and args.runtime != "onnx-genai":
@@ -394,6 +396,7 @@ def _save_package(
394396
output_dir,
395397
external_data=args.external_data,
396398
max_shard_size_bytes=max_shard_size_bytes,
399+
max_workers=args.max_workers,
397400
components=components,
398401
check_weights=not args.no_weights,
399402
)
@@ -529,6 +532,8 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
529532
raise SystemExit("Error: --max-seq-len can only be used with --static-cache.")
530533
if args.max_seq_len is not None and args.max_seq_len <= 0:
531534
raise SystemExit("Error: --max-seq-len must be a positive integer.")
535+
if args.max_workers <= 0:
536+
raise SystemExit("Error: --max-workers must be a positive integer.")
532537
if mmproj_path is not None and args.static_cache:
533538
raise SystemExit("Error: --static-cache cannot be used with --mmproj.")
534539

@@ -545,6 +550,7 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
545550
pkg.save(
546551
output_dir,
547552
external_data=args.external_data,
553+
max_workers=args.max_workers,
548554
)
549555
for name in pkg:
550556
use_subfolders = len(pkg) > 1
@@ -707,6 +713,13 @@ def main(argv: list[str] | None = None) -> None:
707713
default=None,
708714
help="Maximum external-data shard size (e.g. '5GB'). Used by both ONNX and safetensors.",
709715
)
716+
build_parser.add_argument(
717+
"--max-workers",
718+
type=int,
719+
default=8,
720+
metavar="N",
721+
help="Number of threads used to write ONNX external data (default: 8; use 1 for serial saves).",
722+
)
710723
build_parser.add_argument(
711724
"--no-weights",
712725
action="store_true",
@@ -857,6 +870,13 @@ def main(argv: list[str] | None = None) -> None:
857870
default="onnx",
858871
help="External data format (default: onnx).",
859872
)
873+
gguf_parser.add_argument(
874+
"--max-workers",
875+
type=int,
876+
default=8,
877+
metavar="N",
878+
help="Number of threads used to write ONNX external data (default: 8; use 1 for serial saves).",
879+
)
860880
gguf_parser.add_argument(
861881
"--ep",
862882
"--execution-provider",

‎src/mobius/_model_package.py‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,13 @@
2020

2121
__all__ = ["ModelPackage"]
2222

23+
import inspect
2324
import logging
2425
import os
2526
import threading
2627
from collections import UserDict
2728
from collections.abc import Callable
29+
from typing import Any
2830

2931
import onnx_ir as ir
3032
import torch
@@ -72,6 +74,7 @@ def save(
7274
*,
7375
external_data: str = "onnx",
7476
max_shard_size_bytes: int | None = None,
77+
max_workers: int = 8,
7578
components: Callable[[str], bool] | None = None,
7679
progress_bar: bool = True,
7780
check_weights: bool = True,
@@ -108,6 +111,10 @@ def save(
108111
Used by both ONNX and safetensors external-data formats. A
109112
single tensor larger than this value is written in its own
110113
oversized shard.
114+
max_workers: Number of threads used to write ONNX external data.
115+
Defaults to 8. Set to 1 to save serially. Older ``onnx_ir``
116+
versions that do not support concurrent saves fall back to
117+
serial behavior.
111118
components: Optional predicate ``(name) -> bool`` that selects
112119
which components to save. When ``None`` (default), all
113120
components are saved. Examples::
@@ -125,14 +132,17 @@ def save(
125132
126133
Raises:
127134
ValueError: If *external_data* is not ``"onnx"`` or
128-
``"safetensors"``, or if *check_weights* is ``True`` and
129-
any initializer is missing its ``const_value``.
135+
``"safetensors"``, if *max_workers* is not positive, or if
136+
*check_weights* is ``True`` and any initializer is missing its
137+
``const_value``.
130138
"""
131139
if external_data not in {"onnx", "safetensors"}:
132140
raise ValueError(
133141
f"Unknown external_data format {external_data!r}. "
134142
"Expected 'onnx' or 'safetensors'."
135143
)
144+
if max_workers <= 0:
145+
raise ValueError(f"max_workers must be positive, got {max_workers}.")
136146
os.makedirs(directory, exist_ok=True)
137147
selected = {
138148
name: model
@@ -159,13 +169,14 @@ def save(
159169
callback=callback,
160170
)
161171
else:
162-
ir.save(
163-
model,
164-
path,
165-
external_data="model.onnx.data",
166-
max_shard_size_bytes=max_shard_size_bytes,
167-
callback=callback,
168-
)
172+
save_kwargs: dict[str, Any] = {
173+
"external_data": "model.onnx.data",
174+
"max_shard_size_bytes": max_shard_size_bytes,
175+
"callback": callback,
176+
}
177+
if "max_workers" in inspect.signature(ir.save).parameters:
178+
save_kwargs["max_workers"] = max_workers
179+
ir.save(model, path, **save_kwargs)
169180

170181
@classmethod
171182
def load(cls, directory: str) -> ModelPackage:

‎src/mobius/_model_package_test.py‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,77 @@ def test_onnx_external_data_is_sharded(self, tmp_path):
125125
loaded = ModelPackage.load(str(tmp_path))
126126
assert set(loaded.data) == {"model"}
127127

128+
def test_defaults_to_eight_workers_when_supported(self, tmp_path, monkeypatch):
129+
calls = []
130+
131+
def save(
132+
model,
133+
path,
134+
*,
135+
external_data,
136+
max_shard_size_bytes,
137+
callback,
138+
max_workers,
139+
):
140+
calls.append(max_workers)
141+
142+
monkeypatch.setattr(ir, "save", save)
143+
144+
ModelPackage({"m": _make_simple_model()}).save(
145+
str(tmp_path), progress_bar=False, check_weights=False
146+
)
147+
148+
assert calls == [8]
149+
150+
def test_forwards_serial_worker_override(self, tmp_path, monkeypatch):
151+
calls = []
152+
153+
def save(
154+
model,
155+
path,
156+
*,
157+
external_data,
158+
max_shard_size_bytes,
159+
callback,
160+
max_workers,
161+
):
162+
calls.append(max_workers)
163+
164+
monkeypatch.setattr(ir, "save", save)
165+
166+
ModelPackage({"m": _make_simple_model()}).save(
167+
str(tmp_path),
168+
max_workers=1,
169+
progress_bar=False,
170+
check_weights=False,
171+
)
172+
173+
assert calls == [1]
174+
175+
def test_omits_max_workers_for_onnx_ir_1_0(self, tmp_path, monkeypatch):
176+
calls = []
177+
178+
def save(model, path, *, external_data, max_shard_size_bytes, callback):
179+
calls.append((model, path))
180+
181+
monkeypatch.setattr(ir, "save", save)
182+
183+
ModelPackage({"m": _make_simple_model()}).save(
184+
str(tmp_path), progress_bar=False, check_weights=False
185+
)
186+
187+
assert len(calls) == 1
188+
189+
@pytest.mark.parametrize("max_workers", [0, -1])
190+
def test_rejects_non_positive_max_workers(self, tmp_path, max_workers):
191+
with pytest.raises(ValueError, match="max_workers must be positive"):
192+
ModelPackage({"m": _make_simple_model()}).save(
193+
str(tmp_path),
194+
max_workers=max_workers,
195+
progress_bar=False,
196+
check_weights=False,
197+
)
198+
128199

129200
class TestProgressCallback:
130201
class _Tensor:

‎tests/cli_test.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,56 @@ def test_build_with_dtype(self):
6565
)
6666
assert os.path.isfile(os.path.join(tmpdir, "model.onnx"))
6767

68+
def test_max_workers_defaults_to_eight(self):
69+
with (
70+
tempfile.TemporaryDirectory() as tmpdir,
71+
mock.patch(
72+
"mobius._diffusers_builder._load_diffusers_pipeline_index",
73+
return_value=None,
74+
),
75+
mock.patch("mobius.__main__.build", return_value=mock.MagicMock()),
76+
mock.patch("mobius.__main__._save_package") as save_package,
77+
):
78+
main(["build", "--model", "Qwen/Qwen2.5-0.5B", tmpdir, "--no-weights"])
79+
80+
assert save_package.call_args.args[2].max_workers == 8
81+
82+
def test_max_workers_override_reaches_model_package_save(self):
83+
pkg = mock.MagicMock()
84+
pkg.items.return_value = []
85+
pkg.__iter__.return_value = iter(())
86+
args = SimpleNamespace(
87+
max_shard_size=None,
88+
max_workers=1,
89+
external_data="onnx",
90+
execution_provider="cpu",
91+
no_weights=True,
92+
runtime=None,
93+
)
94+
95+
with tempfile.TemporaryDirectory() as tmpdir:
96+
_save_package(pkg, tmpdir, args, None, None)
97+
98+
assert pkg.save.call_args.kwargs["max_workers"] == 1
99+
100+
@pytest.mark.parametrize("max_workers", [0, -1])
101+
def test_non_positive_max_workers_errors(self, max_workers):
102+
with (
103+
tempfile.TemporaryDirectory() as tmpdir,
104+
pytest.raises(SystemExit, match=r"--max-workers must be a positive integer"),
105+
):
106+
main(
107+
[
108+
"build",
109+
"--model",
110+
"Qwen/Qwen2.5-0.5B",
111+
tmpdir,
112+
"--no-weights",
113+
"--max-workers",
114+
str(max_workers),
115+
]
116+
)
117+
68118
def test_build_encoder_decoder_produces_separate_files(self):
69119
with tempfile.TemporaryDirectory() as tmpdir:
70120
main(["build", "--model", "facebook/bart-base", tmpdir, "--no-weights"])
@@ -514,6 +564,7 @@ def test_runtime_onnx_genai_uses_native_vlm_emitter(self):
514564
pkg.config = object()
515565
args = SimpleNamespace(
516566
max_shard_size=None,
567+
max_workers=8,
517568
external_data="onnx",
518569
execution_provider="cpu",
519570
no_weights=True,
@@ -553,6 +604,7 @@ def test_runtime_onnx_genai_does_not_fallback_for_unsupported_vlm(self):
553604
pkg.config = object()
554605
args = SimpleNamespace(
555606
max_shard_size=None,
607+
max_workers=8,
556608
external_data="onnx",
557609
execution_provider="cpu",
558610
no_weights=True,

0 commit comments

Comments
 (0)