Skip to content

Commit 661b235

Browse files
authored
Add Gemma4 image_processor.json generation with onnxruntime-extension… (#209)
## Summary Updates the ort-genai runtime integration to generate the correct image processor config format for Gemma4 models. ## Problem The `OrtxCreateProcessor` API in onnxruntime-extensions requires a JSON config with a `processor.transforms` array defining an ordered pipeline of image processing operations. Previously, Gemma4 models generated a HuggingFace-style `processor_config.json` with raw config values (`image_size`, `patch_size`, etc.), which caused a runtime crash: RuntimeError: [json.exception.out_of_range.403] key 'transforms' not found ## Changes **`src/mobius/integrations/ort_genai/auto_export.py`** - `_write_processor_config()`: For `gemma4`/`gemma4_text` models, generates `image_processor.json` with the onnxruntime-extensions transforms pipeline format (`DecodeImage` → `Gemma4ImageTransform`) instead of the HF-style `processor_config.json`. Reads `patch_size`, `max_soft_tokens`, and `pooling_kernel_size` from the model config. - `_write_genai_config()`: Sets `vision.config_filename` to `"image_processor.json"` for Gemma4 models so the genai runtime points to the correct file. Non-Gemma4 models are unaffected and continue generating `processor_config.json`. ## Generated `image_processor.json` example ```json { "processor": { "name": "gemma_4_image_processing", "transforms": [ { "operation": { "name": "decode_image", "type": "DecodeImage", "attrs": { "color_space": "RGB" } } }, { "operation": { "name": "gemma4_image_transform", "type": "Gemma4ImageTransform", "attrs": { "patch_size": 16, "max_soft_tokens": 280, "pooling_kernel_size": 3 } } } ] } }
1 parent d562440 commit 661b235

2 files changed

Lines changed: 114 additions & 19 deletions

File tree

‎src/mobius/integrations/ort_genai/auto_export.py‎

Lines changed: 47 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -158,13 +158,22 @@ def _copy_tokenizer_files_from_local(
158158
return copied
159159

160160

161-
def _write_processor_config(
161+
def _write_vision_processor_config(
162162
config: Any,
163163
output_dir: str,
164164
) -> str | None:
165-
"""Write a minimal processor_config.json for VLM models.
165+
"""Write the vision processor config file for VLM models.
166166
167-
Returns the path if written, None otherwise.
167+
The output format depends on the model type:
168+
169+
- **Gemma4** (``gemma4``, ``gemma4_text``): Writes ``image_processor.json``
170+
in the onnxruntime-extensions transforms pipeline format required by
171+
``OrtxCreateProcessor``. The pipeline is
172+
``DecodeImage → Gemma4ImageTransform``.
173+
- **Other models**: Writes ``processor_config.json`` with a minimal
174+
HuggingFace-style schema (``image_size``, ``patch_size``).
175+
176+
Returns the written file path, or None if the config has no vision section.
168177
"""
169178
vision = getattr(config, "vision", None)
170179
if vision is None:
@@ -173,30 +182,52 @@ def _write_processor_config(
173182
model_type = getattr(config, "model_type", "")
174183

175184
if model_type in ("gemma4", "gemma4_text"):
176-
# Gemma4 needs a processor wrapper with model-specific fields
177-
tokens_per_image = (
185+
# Gemma4 needs an onnxruntime-extensions format processor config
186+
# with a transforms pipeline (DecodeImage -> Gemma4ImageTransform).
187+
# The OrtxCreateProcessor API requires this format.
188+
#
189+
# max_soft_tokens: maps from HF's mm_tokens_per_image (the number of
190+
# vision tokens per image after pooling) into the Gemma4ImageTransform's
191+
# max_soft_tokens attribute, which controls the padded patch budget.
192+
max_soft_tokens = (
178193
getattr(vision, "mm_tokens_per_image", None)
179194
or getattr(config, "mm_tokens_per_image", None)
180-
or getattr(vision, "max_soft_tokens", None)
181195
or 280
182196
)
183-
image_size = getattr(vision, "image_size", None) or 448
184197
patch_size = getattr(vision, "patch_size", None) or 16
185-
processor: dict[str, Any] = {
198+
pooling_kernel_size = getattr(vision, "pooling_kernel_size", None) or 3
199+
processor = {
186200
"processor": {
187-
"name": "gemma4_image_processor",
188-
"image_size": image_size,
189-
"patch_size": patch_size,
190-
"tokens_per_image": tokens_per_image,
201+
"name": "gemma_4_image_processing",
202+
"transforms": [
203+
{
204+
"operation": {
205+
"name": "decode_image",
206+
"type": "DecodeImage",
207+
"attrs": {"color_space": "RGB"},
208+
}
209+
},
210+
{
211+
"operation": {
212+
"name": "gemma4_image_transform",
213+
"type": "Gemma4ImageTransform",
214+
"attrs": {
215+
"patch_size": patch_size,
216+
"max_soft_tokens": max_soft_tokens,
217+
"pooling_kernel_size": pooling_kernel_size,
218+
},
219+
}
220+
},
221+
],
191222
}
192223
}
224+
proc_filename = "image_processor.json"
193225
else:
194226
processor = {
195227
"image_size": getattr(vision, "image_size", None) or 448,
196228
"patch_size": getattr(vision, "patch_size", None) or 14,
197229
}
198-
199-
proc_filename = "processor_config.json"
230+
proc_filename = "processor_config.json"
200231

201232
path = os.path.join(output_dir, proc_filename)
202233
with open(path, "w", encoding="utf-8") as f:
@@ -280,6 +311,7 @@ def _write_genai_config(
280311
vision_cfg = getattr(config, "vision", None)
281312
sms = getattr(vision_cfg, "spatial_merge_size", 2)
282313
vision_kwargs["spatial_merge_size"] = sms
314+
vision_kwargs["config_filename"] = "image_processor.json"
283315

284316
if vision_input_mapping is not None:
285317
vision_kwargs["input_names"] = vision_input_mapping
@@ -450,7 +482,7 @@ def write_ort_genai_config(
450482
result[tf] = os.path.join(directory, tf)
451483

452484
# Write processor_config.json for VLMs
453-
processor_path = _write_processor_config(config, directory)
485+
processor_path = _write_vision_processor_config(config, directory)
454486
if processor_path:
455487
result["processor_config"] = processor_path
456488

‎src/mobius/integrations/ort_genai/auto_export_test.py‎

Lines changed: 67 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
_graph_input_names,
1919
_resolve_ort_genai_model_type,
2020
_write_genai_config,
21-
_write_processor_config,
21+
_write_vision_processor_config,
2222
write_ort_genai_config,
2323
)
2424

@@ -42,7 +42,7 @@ class TestWriteProcessorConfig:
4242
def test_no_vision_returns_none(self, tmp_path):
4343
config = mock.MagicMock(spec=[])
4444
del config.vision # ensure no vision attribute
45-
assert _write_processor_config(config, str(tmp_path)) is None
45+
assert _write_vision_processor_config(config, str(tmp_path)) is None
4646

4747
def test_writes_vision_config(self, tmp_path):
4848
vision = mock.MagicMock()
@@ -51,7 +51,7 @@ def test_writes_vision_config(self, tmp_path):
5151
config = mock.MagicMock()
5252
config.vision = vision
5353

54-
path = _write_processor_config(config, str(tmp_path))
54+
path = _write_vision_processor_config(config, str(tmp_path))
5555
assert path is not None
5656
with open(path) as f:
5757
data = json.load(f)
@@ -314,6 +314,69 @@ def test_processor_config_not_written_without_vision(self, tmp_path):
314314
assert "processor_config" not in result
315315
assert not os.path.exists(os.path.join(str(tmp_path), "processor_config.json"))
316316

317+
def test_gemma4_image_processor_json_written(self, tmp_path):
318+
"""Gemma4 writes image_processor.json with onnxruntime-extensions transforms pipeline."""
319+
import dataclasses
320+
321+
from mobius._model_package import ModelPackage
322+
from mobius.integrations.ort_genai.auto_export import write_ort_genai_config
323+
324+
@dataclasses.dataclass
325+
class FakeVision:
326+
image_size: int = 448
327+
patch_size: int = 16
328+
mm_tokens_per_image: int = 260
329+
pooling_kernel_size: int = 3
330+
331+
@dataclasses.dataclass
332+
class FakeConfig:
333+
model_type: str = "gemma4"
334+
vocab_size: int = 262144
335+
hidden_size: int = 1536
336+
num_hidden_layers: int = 35
337+
num_attention_heads: int = 8
338+
num_key_value_heads: int = 1
339+
head_dim: int = 256
340+
vision: FakeVision = dataclasses.field(default_factory=FakeVision)
341+
342+
pkg = ModelPackage(
343+
{
344+
"model": mock.MagicMock(),
345+
"vision": mock.MagicMock(),
346+
"embedding": mock.MagicMock(),
347+
},
348+
config=FakeConfig(),
349+
)
350+
result = write_ort_genai_config(pkg, str(tmp_path))
351+
352+
# Should write image_processor.json, not processor_config.json
353+
assert "processor_config" in result
354+
proc_path = result["processor_config"]
355+
assert proc_path.endswith("image_processor.json")
356+
assert os.path.isfile(proc_path)
357+
assert not os.path.exists(os.path.join(str(tmp_path), "processor_config.json"))
358+
359+
with open(proc_path) as f:
360+
data = json.load(f)
361+
362+
# Verify onnxruntime-extensions transforms pipeline structure
363+
assert "processor" in data
364+
assert "transforms" in data["processor"]
365+
transforms = data["processor"]["transforms"]
366+
assert len(transforms) == 2
367+
368+
# First op: DecodeImage
369+
op0 = transforms[0]["operation"]
370+
assert op0["type"] == "DecodeImage"
371+
assert op0["attrs"]["color_space"] == "RGB"
372+
373+
# Second op: Gemma4ImageTransform with correct attrs from config
374+
op1 = transforms[1]["operation"]
375+
assert op1["type"] == "Gemma4ImageTransform"
376+
assert op1["attrs"]["patch_size"] == 16
377+
assert op1["attrs"]["max_soft_tokens"] == 260
378+
assert op1["attrs"]["pooling_kernel_size"] == 3
379+
317380
def test_tokenizer_not_copied_without_model_id(self, tmp_path):
318381
"""No tokenizer files copied when hf_model_id=None."""
319382
from mobius.integrations.ort_genai.auto_export import write_ort_genai_config
@@ -780,7 +843,7 @@ def test_gemma4_genai_config_from_real_model(self, tmp_path):
780843
# Config-level properties are still present
781844
assert data["model"]["image_token_id"] == 255999
782845
assert data["model"]["vision"]["spatial_merge_size"] == 2
783-
assert data["model"]["vision"]["config_filename"] == "processor_config.json"
846+
assert data["model"]["vision"]["config_filename"] == "image_processor.json"
784847

785848
def test_auto_export_produces_genai_config(self, tmp_path):
786849
"""Mock build() to return a tiny package, verify genai_config."""

0 commit comments

Comments
 (0)