Skip to content

Commit 9d540af

Browse files
justinchubyCopilot
andauthored
Enable ONNX external-data sharding (#503)
## Summary - Raise the minimum supported `onnx_ir` version from 0.2.1 to 1.0.0. - Forward `--max-shard-size` to ONNX external-data saves as `max_shard_size_bytes`, an API already available in `onnx_ir` 1.0.0. - Make the save progress callback thread-safe. With newer `onnx_ir` versions it renders one fixed-position tqdm bar per shard; with `onnx_ir` 1.0.0 it falls back to one global bar. - Keep Mobius independent of the pending parallel-save API: Mobius does not expose or pass `max_workers`. ## Validation The ONNX sharding round-trip and callback tests pass against both the published `onnx_ir==1.0.0` package and the current onnx/ir-py#476 branch. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Copilot-Session: af83bc37-b9d6-4b94-be64-a4daa5a7ce40
1 parent 55dd674 commit 9d540af

4 files changed

Lines changed: 221 additions & 19 deletions

File tree

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ dependencies = [
1616
"huggingface_hub",
1717
"ml_dtypes",
1818
"numpy>=1.24.0",
19-
"onnx_ir>=0.2.1",
19+
"onnx_ir>=1.0.0",
2020
"onnx-shape-inference>=0.3.1",
2121
"onnxscript>=0.7.1",
2222
"safetensors",

‎src/mobius/__main__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -705,7 +705,7 @@ def main(argv: list[str] | None = None) -> None:
705705
"--max-shard-size",
706706
metavar="SIZE",
707707
default=None,
708-
help="Max shard size for safetensors (e.g. '5GB'). Only used with --external-data safetensors.",
708+
help="Maximum external-data shard size (e.g. '5GB'). Used by both ONNX and safetensors.",
709709
)
710710
build_parser.add_argument(
711711
"--no-weights",

‎src/mobius/_model_package.py‎

Lines changed: 52 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
import logging
2424
import os
25+
import threading
2526
from collections import UserDict
2627
from collections.abc import Callable
2728

@@ -103,8 +104,10 @@ def save(
103104
errors on some CUDA/cuBLAS versions when loading weights
104105
via memory-mapped I/O. Use ``"onnx"`` (the default) for
105106
models targeting CUDA execution.
106-
max_shard_size_bytes: Maximum shard size in bytes for safetensors
107-
format. Only used when *external_data* is ``"safetensors"``.
107+
max_shard_size_bytes: Maximum external-data shard size in bytes.
108+
Used by both ONNX and safetensors external-data formats. A
109+
single tensor larger than this value is written in its own
110+
oversized shard.
108111
components: Optional predicate ``(name) -> bool`` that selects
109112
which components to save. When ``None`` (default), all
110113
components are saved. Examples::
@@ -131,8 +134,6 @@ def save(
131134
"Expected 'onnx' or 'safetensors'."
132135
)
133136
os.makedirs(directory, exist_ok=True)
134-
callback = _make_progress_callback() if progress_bar else None
135-
136137
selected = {
137138
name: model
138139
for name, model in self.data.items()
@@ -141,6 +142,7 @@ def save(
141142
use_subfolders = len(selected) > 1
142143

143144
for name, model in selected.items():
145+
callback = _make_progress_callback() if progress_bar else None
144146
if check_weights:
145147
_check_weights(name, model)
146148
if use_subfolders:
@@ -157,7 +159,13 @@ def save(
157159
callback=callback,
158160
)
159161
else:
160-
ir.save(model, path, external_data="model.onnx.data", callback=callback)
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+
)
161169

162170
@classmethod
163171
def load(cls, directory: str) -> ModelPackage:
@@ -267,19 +275,47 @@ def apply_weights(
267275

268276

269277
def _make_progress_callback():
270-
"""Create a tqdm progress-bar callback for ``ir.save``."""
271-
pbar = tqdm.tqdm()
272-
total_set = False
278+
"""Create a thread-safe tqdm progress-bar callback for ``ir.save``.
279+
280+
Newer ``onnx_ir`` versions may invoke callbacks concurrently and out of
281+
index order. Count invocations instead of tracking ``metadata.index`` and
282+
derive each bar's position from its shard filename so rendering order is
283+
deterministic. Serialize all progress-bar mutations. This remains compatible
284+
with ``onnx_ir`` 1.0, where callbacks are invoked serially.
285+
"""
286+
lock = threading.Lock()
287+
bars: dict[str, tqdm.tqdm] = {}
273288

274289
def callback(tensor: ir.TensorProtocol, metadata: ir.external_data.CallbackInfo) -> None:
275-
nonlocal total_set
276-
if not total_set:
277-
pbar.total = metadata.total
278-
total_set = True
279-
pbar.update()
280-
pbar.set_description(
281-
f"Saving {tensor.name} ({tensor.dtype.short_name()}, {tensor.shape})"
282-
)
290+
with lock:
291+
shard_total = getattr(metadata, "shard_total", None)
292+
key = metadata.filename if shard_total is not None else "__all__"
293+
pbar = bars.get(key)
294+
if pbar is None:
295+
description = (
296+
f"Saving {metadata.filename}"
297+
if shard_total is not None
298+
else "Saving external data"
299+
)
300+
position = 0
301+
if shard_total is not None:
302+
shard_prefix, separator, _ = metadata.filename.rpartition("-of-")
303+
shard_number = shard_prefix.rpartition("-")[2]
304+
if separator and shard_number.isdigit():
305+
position = int(shard_number) - 1
306+
pbar = tqdm.tqdm(
307+
total=shard_total if shard_total is not None else metadata.total,
308+
desc=description,
309+
position=position,
310+
leave=True,
311+
)
312+
bars[key] = pbar
313+
pbar.update()
314+
pbar.set_postfix_str(
315+
f"{tensor.name} ({tensor.dtype.short_name()}, {tensor.shape})"
316+
)
317+
if pbar.n >= pbar.total:
318+
pbar.close()
283319

284320
return callback
285321

‎src/mobius/_model_package_test.py‎

Lines changed: 167 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,16 @@
66
from __future__ import annotations
77

88
import logging
9+
import threading
10+
import types
911

1012
import onnx_ir as ir
1113
import pytest
1214
import torch
1315

1416
from mobius._builder import build_from_module
1517
from mobius._configs import VisionConfig
16-
from mobius._model_package import ModelPackage
18+
from mobius._model_package import ModelPackage, _make_progress_callback
1719
from mobius._testing import make_config
1820
from mobius.models.base import CausalLMModel
1921
from mobius.models.gemma3 import Gemma3MultiModalModel
@@ -86,6 +88,170 @@ def test_config_stored(self):
8688
assert pkg.config is config
8789

8890

91+
class TestOnnxShardedSave:
92+
def test_onnx_external_data_is_sharded(self, tmp_path):
93+
graph = ir.Graph([], [], nodes=[], name="m")
94+
for index in range(6):
95+
name = f"weight_{index}"
96+
graph.register_initializer(
97+
ir.Value(
98+
name=name,
99+
const_value=ir.Tensor(
100+
torch.full((1024,), index, dtype=torch.float32),
101+
name=name,
102+
dtype=ir.DataType.FLOAT,
103+
),
104+
)
105+
)
106+
pkg = ModelPackage({"m": ir.Model(graph, ir_version=10)})
107+
108+
pkg.save(
109+
str(tmp_path),
110+
external_data="onnx",
111+
max_shard_size_bytes=8192,
112+
progress_bar=False,
113+
)
114+
115+
shards = sorted(
116+
[
117+
*tmp_path.glob("model-*-of-*.onnx.data"),
118+
# onnx_ir 1.0.0 did not yet recognize .onnx.data as a
119+
# compound suffix.
120+
*tmp_path.glob("model.onnx-*-of-*.data"),
121+
]
122+
)
123+
assert len(shards) == 3
124+
assert all(shard.stat().st_size <= 8192 for shard in shards)
125+
loaded = ModelPackage.load(str(tmp_path))
126+
assert set(loaded.data) == {"model"}
127+
128+
129+
class TestProgressCallback:
130+
class _Tensor:
131+
name = "w"
132+
shape = (2, 2)
133+
134+
class dtype: # noqa: N801
135+
@staticmethod
136+
def short_name():
137+
return "f32"
138+
139+
class _Bar:
140+
def __init__(self, *, total, desc, position, leave):
141+
self.total = total
142+
self.desc = desc
143+
self.position = position
144+
self.leave = leave
145+
self.n = 0
146+
self.postfix = ""
147+
self.closed = False
148+
149+
def update(self):
150+
self.n += 1
151+
152+
def set_postfix_str(self, value):
153+
self.postfix = value
154+
155+
def close(self):
156+
self.closed = True
157+
158+
def test_orders_progress_bars_by_shard_number(self, monkeypatch):
159+
bars = []
160+
161+
def make_bar(**kwargs):
162+
bar = self._Bar(**kwargs)
163+
bars.append(bar)
164+
return bar
165+
166+
monkeypatch.setattr("mobius._model_package.tqdm.tqdm", make_bar)
167+
callback = _make_progress_callback()
168+
for filename in (
169+
"model-00002-of-00002.onnx.data",
170+
"model-00001-of-00002.onnx.data",
171+
):
172+
for shard_index in reversed(range(2)):
173+
callback(
174+
self._Tensor(),
175+
types.SimpleNamespace(
176+
total=4,
177+
index=shard_index,
178+
offset=0,
179+
filename=filename,
180+
shard_total=2,
181+
shard_index=shard_index,
182+
),
183+
)
184+
185+
assert len(bars) == 2
186+
assert [bar.position for bar in bars] == [1, 0]
187+
assert all(bar.total == 2 and bar.n == 2 and bar.closed for bar in bars)
188+
assert "model-00002-of-00002.onnx.data" in bars[0].desc
189+
assert "model-00001-of-00002.onnx.data" in bars[1].desc
190+
191+
def test_falls_back_to_one_bar_with_onnx_ir_1_0(self, monkeypatch):
192+
bars = []
193+
194+
def make_bar(**kwargs):
195+
bar = self._Bar(**kwargs)
196+
bars.append(bar)
197+
return bar
198+
199+
monkeypatch.setattr("mobius._model_package.tqdm.tqdm", make_bar)
200+
callback = _make_progress_callback()
201+
for index in range(4):
202+
callback(
203+
self._Tensor(),
204+
types.SimpleNamespace(
205+
total=4,
206+
index=index,
207+
offset=0,
208+
filename=f"model-{index}.data",
209+
),
210+
)
211+
212+
assert len(bars) == 1
213+
assert bars[0].total == 4
214+
assert bars[0].n == 4
215+
assert bars[0].position == 0
216+
assert bars[0].closed
217+
218+
def test_is_thread_safe(self, monkeypatch):
219+
bars = []
220+
221+
def make_bar(**kwargs):
222+
bar = self._Bar(**kwargs)
223+
bars.append(bar)
224+
return bar
225+
226+
monkeypatch.setattr("mobius._model_package.tqdm.tqdm", make_bar)
227+
callback = _make_progress_callback()
228+
total = 200
229+
230+
def invoke(index):
231+
callback(
232+
self._Tensor(),
233+
types.SimpleNamespace(
234+
total=total,
235+
index=index,
236+
offset=0,
237+
filename="model.onnx.data",
238+
shard_total=total,
239+
shard_index=index,
240+
),
241+
)
242+
243+
threads = [threading.Thread(target=invoke, args=(index,)) for index in range(total)]
244+
for thread in threads:
245+
thread.start()
246+
for thread in threads:
247+
thread.join()
248+
249+
assert len(bars) == 1
250+
assert bars[0].total == total
251+
assert bars[0].n == total
252+
assert bars[0].closed
253+
254+
89255
class TestModelPackageSaveLoad:
90256
def test_save_creates_files(self, tmp_path):
91257
pkg = ModelPackage(

0 commit comments

Comments
 (0)