Skip to content

Commit db7c0ca

Browse files
justinchubyCopilotCopilotJustin Chu
authored
fix: genai_config defaults and tokenizer copy for --config mode (#153)
## Summary Addresses Issues 5 and 6 from Edge LLM evaluation. ### Issue 5: `past_present_share_buffer` defaults - **`do_sample`**: Changed from `False` to `True` to match production reference configs (e.g. `testdata/qwen2_5_genai_config/genai_config.json`) - **`max_length`**: Changed from hardcoded `4096` to `context_length` (derived from the model's `max_position_embeddings`) - **`past_present_share_buffer`**: Set to `True` for WebGPU EP — the WebGPU runtime allocates a fixed KV-cache buffer up-front and requires past/present tensors to share backing memory ### Issue 6: Tokenizer files not copied with `--config` - Added `_copy_tokenizer_files_from_local(source_dir, output_dir)` that copies tokenizer files from a local directory - `write_ort_genai_config()` gains a `local_config_path` parameter; when `hf_model_id` is `None` and `local_config_path` is set, tokenizer files are copied from the local directory - `_save_package()` in the CLI now passes `args.config` as `local_config_path` - Updated `--runtime` help text to document both modes ### Tests - Updated `genai_config_test.py`: fixed `do_sample` assertion, added WebGPU/CUDA tests for `past_present_share_buffer` and `max_length` - Added `TestCopyTokenizerFilesFromLocal` and `TestWriteOrtGenaiConfigLocalPath` test classes to `auto_export_test.py` All 2419 tests pass. --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Justin Chu <[email protected]>
1 parent 8693678 commit db7c0ca

6 files changed

Lines changed: 343 additions & 18 deletions

File tree

‎src/mobius/__main__.py‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,16 @@ def _save_package(
236236

237237
hf_model_id = getattr(args, "model", None)
238238
ep = getattr(args, "execution_provider", "cpu")
239-
artifacts = write_ort_genai_config(pkg, output_dir, hf_model_id=hf_model_id, ep=ep)
239+
# When --config (local dir) is used instead of --model, copy tokenizer
240+
# files from the local directory rather than downloading from HF.
241+
local_config_dir = getattr(args, "config", None)
242+
artifacts = write_ort_genai_config(
243+
pkg,
244+
output_dir,
245+
hf_model_id=hf_model_id,
246+
ep=ep,
247+
local_config_dir=local_config_dir,
248+
)
240249
for name, path in artifacts.items():
241250
print(f" {name}: {path}")
242251

@@ -502,8 +511,9 @@ def main(argv: list[str] | None = None) -> None:
502511
help=(
503512
"Generate runtime-specific config files after building. "
504513
"Currently supports: 'ort-genai' (writes genai_config.json and "
505-
"copies tokenizer files). Requires --model (not --config) for "
506-
"tokenizer file download."
514+
"copies tokenizer files). When used with --model, tokenizer files "
515+
"are downloaded from HuggingFace. When used with --config (local "
516+
"directory), tokenizer files are copied from that directory."
507517
),
508518
)
509519
build_parser.set_defaults(func=_cmd_build)

‎src/mobius/_execution_providers.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,12 @@ class EpCapabilities:
7171
quantization (0 = highest accuracy, 4 = fastest).
7272
provider_options: Default ORT GenAI provider options dict for this EP.
7373
enable_graph_capture: Whether this EP defaults to GPU graph capture.
74+
supports_past_present_share_buffer: Whether this EP requires past and present
75+
KV-cache tensors to share the same pre-allocated backing buffer.
76+
``True`` for WebGPU, which allocates the full KV-cache at model
77+
load time and maps both past and present views into it. ``False``
78+
for all other EPs where the runtime manages KV-cache memory
79+
dynamically.
7480
"""
7581

7682
name: str
@@ -83,6 +89,7 @@ class EpCapabilities:
8389
default_int4_accuracy_level: int = 0
8490
provider_options: dict[str, str] = dataclasses.field(default_factory=dict)
8591
enable_graph_capture: bool = False
92+
supports_past_present_share_buffer: bool = False
8693

8794
def __post_init__(self) -> None:
8895
if not self.supports_fused_rope and self.qkv_pack_dtypes:
@@ -221,6 +228,7 @@ def _register_builtins() -> None:
221228
qkv_pack_dtypes=frozenset({ir.DataType.FLOAT, ir.DataType.FLOAT16}),
222229
default_int4_accuracy_level=4,
223230
provider_options={"enableGraphCapture": "0", "validationMode": "basic"},
231+
supports_past_present_share_buffer=True,
224232
),
225233
EpCapabilities(
226234
name="trt-rtx",

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

Lines changed: 62 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,43 @@ def _copy_tokenizer_files(
9999
return copied
100100

101101

102+
def _copy_tokenizer_files_from_local(
103+
source_dir: str,
104+
output_dir: str,
105+
) -> list[str]:
106+
"""Copy tokenizer files from a local model directory.
107+
108+
Silently skips files that are absent (not all tokenizer variants have
109+
all files — e.g. SentencePiece models have ``tokenizer.model`` but not
110+
``merges.txt``).
111+
112+
Returns list of copied filenames.
113+
"""
114+
if not os.path.isdir(source_dir):
115+
logger.warning(
116+
"Local tokenizer source directory does not exist: %s — no tokenizer files copied.",
117+
source_dir,
118+
)
119+
return []
120+
tokenizer_files = [
121+
"tokenizer.json",
122+
"tokenizer_config.json",
123+
"special_tokens_map.json",
124+
"tokenizer.model", # SentencePiece
125+
"added_tokens.json",
126+
"merges.txt", # BPE
127+
"vocab.json", # BPE
128+
]
129+
copied: list[str] = []
130+
for filename in tokenizer_files:
131+
src = os.path.join(source_dir, filename)
132+
if os.path.isfile(src):
133+
dst = os.path.join(output_dir, filename)
134+
shutil.copy2(src, dst)
135+
copied.append(filename)
136+
return copied
137+
138+
102139
def _write_processor_config(
103140
config: Any,
104141
output_dir: str,
@@ -181,13 +218,15 @@ def write_ort_genai_config(
181218
hf_model_id: str | None = None,
182219
ep: str = "cpu",
183220
context_length: int = 4096,
221+
local_config_dir: str | None = None,
184222
) -> dict[str, str]:
185223
"""Generate ORT-GenAI config artifacts for an already-built ModelPackage.
186224
187225
Writes ``genai_config.json``, optionally copies tokenizer files from
188-
HuggingFace Hub, and writes ``processor_config.json`` for VLM models.
189-
Does NOT build or save ONNX models — call :meth:`~mobius._model_package.ModelPackage.save`
190-
separately before or after this function.
226+
HuggingFace Hub or a local directory, and writes ``processor_config.json``
227+
for VLM models. Does NOT build or save ONNX models — call
228+
:meth:`~mobius._model_package.ModelPackage.save` separately before or
229+
after this function.
191230
192231
Args:
193232
pkg: Already-built :class:`~mobius._model_package.ModelPackage` with
@@ -198,13 +237,18 @@ def write_ort_genai_config(
198237
When ``None``, token IDs are read from ``pkg.config`` fields
199238
(``bos_token_id``, ``eos_token_id``, ``pad_token_id``) populated
200239
by :meth:`~mobius._configs.ArchitectureConfig.from_transformers`,
201-
and tokenizer files are not copied.
240+
and tokenizer files are not copied unless ``local_config_dir`` is set.
202241
ep: Execution provider for ``session_options`` in
203242
``genai_config.json`` (e.g. ``"cpu"``, ``"cuda"``, ``"dml"``,
204243
``"trt-rtx"``). Defaults to ``"cpu"``.
205244
context_length: Minimum context length written to
206245
``genai_config.json``. Overridden upward by
207246
``max_position_embeddings`` from ``pkg.config``.
247+
local_config_dir: Path to a local model directory. When provided
248+
and ``hf_model_id`` is ``None``, tokenizer files are copied from
249+
this directory instead of downloaded from HuggingFace Hub.
250+
Typically set when the CLI ``--config`` flag points to a local
251+
directory rather than a HuggingFace model ID.
208252
209253
Returns:
210254
Dict mapping artifact name to file path, e.g.::
@@ -297,12 +341,25 @@ def write_ort_genai_config(
297341

298342
result: dict[str, str] = {"genai_config": genai_path}
299343

300-
# Copy tokenizer files when a HF model ID is available
344+
# Copy tokenizer files — HF Hub takes precedence; local dir is the fallback
345+
# for --config mode where no HF model ID is available.
301346
if hf_model_id is not None:
302347
logger.info("Copying tokenizer files from %s", hf_model_id)
303348
tokenizer_files = _copy_tokenizer_files(hf_model_id, directory)
304349
for tf in tokenizer_files:
305350
result[tf] = os.path.join(directory, tf)
351+
elif local_config_dir is not None:
352+
logger.info("Copying tokenizer files from local directory %s", local_config_dir)
353+
tokenizer_files = _copy_tokenizer_files_from_local(local_config_dir, directory)
354+
if not tokenizer_files:
355+
logger.warning(
356+
"No tokenizer files were copied from local directory %s. "
357+
"The export may be missing tokenizer artifacts required by ORT-GenAI.",
358+
local_config_dir,
359+
)
360+
361+
for tf in tokenizer_files:
362+
result[tf] = os.path.join(directory, tf)
306363

307364
# Write processor_config.json for VLMs
308365
processor_path = _write_processor_config(config, directory)

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

Lines changed: 142 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@
1414

1515
from mobius.integrations.ort_genai.auto_export import (
1616
_copy_tokenizer_files,
17+
_copy_tokenizer_files_from_local,
1718
_resolve_ort_genai_model_type,
1819
_write_processor_config,
20+
write_ort_genai_config,
1921
)
2022

2123

@@ -77,6 +79,146 @@ def test_copies_available_files(self, tmp_path):
7779
assert (dst / "tokenizer.json").exists()
7880

7981

82+
class TestCopyTokenizerFilesFromLocal:
83+
"""Tests for _copy_tokenizer_files_from_local."""
84+
85+
def test_copies_present_files(self, tmp_path):
86+
"""Copies tokenizer files that exist in the source directory."""
87+
src = tmp_path / "model"
88+
src.mkdir()
89+
(src / "tokenizer.json").write_text('{"test": true}')
90+
(src / "tokenizer_config.json").write_text('{"model_type": "llama"}')
91+
92+
dst = tmp_path / "output"
93+
dst.mkdir()
94+
copied = _copy_tokenizer_files_from_local(str(src), str(dst))
95+
96+
assert set(copied) == {"tokenizer.json", "tokenizer_config.json"}
97+
assert (dst / "tokenizer.json").read_text() == '{"test": true}'
98+
assert (dst / "tokenizer_config.json").read_text() == '{"model_type": "llama"}'
99+
100+
def test_skips_absent_files(self, tmp_path):
101+
"""Files not present in the source directory are silently skipped."""
102+
src = tmp_path / "model"
103+
src.mkdir()
104+
# Only tokenizer.json present — tokenizer.model (SentencePiece), etc. absent
105+
106+
(src / "tokenizer.json").write_text("{}")
107+
108+
dst = tmp_path / "output"
109+
dst.mkdir()
110+
copied = _copy_tokenizer_files_from_local(str(src), str(dst))
111+
112+
assert copied == ["tokenizer.json"]
113+
assert not (dst / "tokenizer.model").exists()
114+
115+
def test_empty_source_returns_empty_list(self, tmp_path):
116+
"""No tokenizer files in source returns an empty list."""
117+
src = tmp_path / "model"
118+
src.mkdir()
119+
dst = tmp_path / "output"
120+
dst.mkdir()
121+
copied = _copy_tokenizer_files_from_local(str(src), str(dst))
122+
assert copied == []
123+
124+
def test_missing_source_dir_warns_and_returns_empty(self, tmp_path, caplog):
125+
"""Non-existent source_dir emits a warning and returns empty list."""
126+
import logging
127+
128+
dst = tmp_path / "output"
129+
dst.mkdir()
130+
with caplog.at_level(
131+
logging.WARNING, logger="mobius.integrations.ort_genai.auto_export"
132+
):
133+
copied = _copy_tokenizer_files_from_local(str(tmp_path / "nonexistent"), str(dst))
134+
assert copied == []
135+
assert "does not exist" in caplog.text
136+
137+
138+
class TestWriteOrtGenaiConfigLocalDir:
139+
"""Tests for write_ort_genai_config with local_config_dir."""
140+
141+
@staticmethod
142+
def _make_pkg():
143+
import dataclasses
144+
145+
from mobius._model_package import ModelPackage
146+
147+
@dataclasses.dataclass
148+
class FakeConfig:
149+
model_type: str = "llama"
150+
vocab_size: int = 256
151+
hidden_size: int = 64
152+
num_hidden_layers: int = 2
153+
num_attention_heads: int = 4
154+
num_key_value_heads: int = 2
155+
head_dim: int = 16
156+
max_position_embeddings: int = 128
157+
158+
return ModelPackage({"model": mock.MagicMock()}, config=FakeConfig())
159+
160+
def test_local_config_dir_copies_tokenizer_files(self, tmp_path):
161+
"""When local_config_dir is set, tokenizer files are copied from it."""
162+
src = tmp_path / "local_model"
163+
src.mkdir()
164+
(src / "tokenizer.json").write_text('{"local": true}')
165+
(src / "tokenizer_config.json").write_text('{"type": "llama"}')
166+
167+
out = tmp_path / "output"
168+
out.mkdir()
169+
pkg = self._make_pkg()
170+
171+
result = write_ort_genai_config(
172+
pkg,
173+
str(out),
174+
local_config_dir=str(src),
175+
)
176+
177+
assert "tokenizer.json" in result
178+
assert (out / "tokenizer.json").read_text() == '{"local": true}'
179+
assert "tokenizer_config.json" in result
180+
181+
def test_hf_model_id_takes_precedence_over_local_dir(self, tmp_path):
182+
"""When both hf_model_id and local_config_dir are set, HF takes precedence."""
183+
src = tmp_path / "local_model"
184+
src.mkdir()
185+
(src / "tokenizer.json").write_text('{"local": true}')
186+
187+
out = tmp_path / "output"
188+
out.mkdir()
189+
pkg = self._make_pkg()
190+
191+
with (
192+
mock.patch(
193+
"mobius.integrations.ort_genai.auto_export._copy_tokenizer_files",
194+
return_value=["tokenizer.json"],
195+
) as mock_hf,
196+
mock.patch(
197+
"mobius.integrations.ort_genai.auto_export._copy_tokenizer_files_from_local",
198+
return_value=[],
199+
) as mock_local,
200+
mock.patch(
201+
"transformers.AutoConfig.from_pretrained",
202+
return_value=mock.MagicMock(
203+
model_type="llama",
204+
bos_token_id=1,
205+
eos_token_id=2,
206+
pad_token_id=0,
207+
),
208+
),
209+
):
210+
(out / "tokenizer.json").write_text("{}") # pretend HF copy happened
211+
write_ort_genai_config(
212+
pkg,
213+
str(out),
214+
hf_model_id="meta-llama/Llama-3-8B",
215+
local_config_dir=str(src),
216+
)
217+
218+
mock_hf.assert_called_once()
219+
mock_local.assert_not_called()
220+
221+
80222
class TestExportForOrtGenai:
81223
"""Unit tests for write_ort_genai_config()."""
82224

@@ -103,8 +245,6 @@ class FakeConfig:
103245

104246
def test_genai_config_json_is_written(self, tmp_path):
105247
"""genai_config.json is always written to the output directory."""
106-
from mobius.integrations.ort_genai.auto_export import write_ort_genai_config
107-
108248
pkg = self._make_pkg()
109249
result = write_ort_genai_config(pkg, str(tmp_path))
110250

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

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,16 +44,39 @@ def _default_decoder_outputs() -> dict[str, str]:
4444
}
4545

4646

47-
def _default_search_params() -> dict[str, Any]:
48-
"""Return sensible default search parameters."""
47+
_SHARE_BUFFER_MAX_LENGTH_CAP = 4096
48+
49+
50+
def _default_search_params(*, ep: str, context_length: int) -> dict[str, Any]:
51+
"""Return sensible default search parameters.
52+
53+
Args:
54+
ep: Execution provider (``"cpu"``, ``"cuda"``, ``"dml"``,
55+
``"webgpu"``, ``"trt-rtx"``). Capability flags are read from
56+
:data:`~mobius._execution_providers.ep_registry`.
57+
context_length: Model context window; used as the default
58+
``max_length`` for generation so the limit matches the model.
59+
"""
60+
from mobius._execution_providers import ep_registry
61+
62+
caps = ep_registry.get(ep)
63+
share_buffer = caps.supports_past_present_share_buffer if caps is not None else False
64+
if share_buffer:
65+
# EPs that pre-allocate KV-cache for the full max_length at load time
66+
# (e.g. WebGPU) need a capped default to avoid pre-allocating huge
67+
# buffers (~8 GB for 128K-token models) on consumer hardware. Users
68+
# can raise the limit in genai_config.json for their target device.
69+
max_length = min(context_length, _SHARE_BUFFER_MAX_LENGTH_CAP)
70+
else:
71+
max_length = context_length
4972
return {
50-
"do_sample": False,
73+
"do_sample": True,
5174
"early_stopping": True,
52-
"max_length": 4096,
75+
"max_length": max_length,
5376
"min_length": 0,
5477
"num_beams": 1,
5578
"num_return_sequences": 1,
56-
"past_present_share_buffer": False,
79+
"past_present_share_buffer": share_buffer,
5780
"repetition_penalty": 1.0,
5881
"temperature": 1.0,
5982
"top_k": 1,
@@ -347,7 +370,7 @@ def generate(self) -> dict[str, Any]:
347370

348371
return {
349372
"model": model,
350-
"search": _default_search_params(),
373+
"search": _default_search_params(ep=self.ep, context_length=self.context_length),
351374
}
352375

353376
def write(self, output_dir: str) -> str:

0 commit comments

Comments
 (0)