Repository navigation
Studio: walk GGUF tokenizer string arrays through one buffer - #15593
Merged
Merged
Conversation
…of a read and seek per entry
… can seek back [skip ci]
danielhanchen
added a commit
that referenced
this pull request
Oct 28, 2026
…, and name any test that still does (#15626) ## Summary Backend CI (`(Python 3.13, a-f)`) and `Repo tests (CPU, rest)` have been failing intermittently with dozens of errors like ``` AttributeError: torch._dynamo.config.recompile_limit does not exist AttributeError: torch._dynamo.config.suppress_errors does not exist AttributeError: torch._inductor.config.emulate_precision_casts does not exist ``` Seen on #15586, #15589, #15590, #15592, #15593, #15596 and #15601. Locally, on pytest 9.1.1, it never reproduced. ### Root cause CI resolves pytest 9.2.0, which changed `MonkeyPatch.setattr` (pytest-dev/pytest#10644). - For a non-class target it now records the old value from the instance `__dict__`. Before, it used `getattr`. - A torch `ConfigModule` (`torch._dynamo.config`, `torch._inductor.config`, and its `SubConfigProxy` children such as `torch._inductor.config.triton`) serves its entries from `__getattr__`. They are never in `__dict__`, so pytest records "not set". - On undo it therefore calls `delattr`. `ConfigModule.__delattr__` marks the entry hidden, and every later read in that process raises `... does not exist`. So every `monkeypatch.setattr(torch._dynamo.config, ...)` in the suite now deletes the entry it patched. Which shard fails depends on which xdist worker such a test lands on. Minimal reproduction: ```python def test_patch(monkeypatch): monkeypatch.setattr(torch._dynamo.config, "suppress_errors", True) def test_after(): assert torch._dynamo.config.suppress_errors is False ``` On pytest 9.1.1 both pass. On 9.2.0 `test_after` fails with `torch._dynamo.config.suppress_errors does not exist`. ## Change `tests/_shared/torch_config_guard.py`, installed from `tests/conftest.py` and `studio/backend/tests/conftest.py`: - **`install_monkeypatch_fix()`:** wraps `pytest.MonkeyPatch.setattr`. When the target is a torch `ConfigModule` or `SubConfigProxy`, including the dotted-string form, it records the real value that was replaced, so `undo()` restores it with `setattr` instead of deleting the entry. Every other target goes through pytest unchanged. The fix is a no-op until torch is imported, and it never imports torch itself. - **`_no_deleted_torch_config_entries` autouse fixture:** any test that still leaves a config entry deleted, by any route, errors at its own teardown with the stack of the delete. The entry is then restored with its previous value, so the rest of the worker is not poisoned. Cost is about 24 us per test. The guard is what found the cause. On the first push (guard only), staging CI named 15 deletes, and every recorded stack ended in `_pytest/monkeypatch.py, line 437, in undo: delattr(obj, name)`. ## Testing **Under pytest 9.2.0** (CI's version): - `tests/test_torch_config_guard.py`: 10 passed. Two tests pin the fix: - `test_monkeypatch_undo_restores_a_config_entry_instead_of_deleting_it` covers `torch._dynamo.config`, `torch._inductor.config` and `torch._inductor.config.triton`. - `test_monkeypatch_undo_restores_a_config_entry_named_by_import_path` covers the dotted-string form. - **Sabotage:** with `install_monkeypatch_fix` turned into a no-op, those 4 cases fail and the guard errors at teardown. - `tests/test_block_compile.py`: 13 failed on main (`suppress_errors` / `recompile_limit does not exist`, the CI signature), 42 passed with this change. **Under pytest 9.1.1:** - `tests/test_torch_config_guard.py`: 10 passed, and `tests/test_block_compile.py`: 42 passed, on both trees. - `studio/backend/tests/test_diffusion_*.py` (about 17,400 tests, run in parallel with main on one loaded host): the guard fired 0 times. The branch had 67 failed / 14 errors against 79 / 26 on main. The 3 failures seen only on the branch pass when rerun alone, so they are load flakes. - Meta-tests that read conftests and `tests/_shared`, plus `test_ci_backend_pytest_shards.py`: 604 passed.
danielhanchen
added a commit
that referenced
this pull request
Oct 28, 2026
…g (pytest 9.2) (#15638) ## Summary `studio/backend/tests/test_mcp_session_cache_reset_between_tests.py::test_the_next_test_starts_with_an_empty_cache_and_the_session_closed` has failed on the `(Python 3.13, g-r)` shard of #15587, #15593, #15601 and #15615 (`assert 0 == 1` on `_Session.closed`). ### Root cause CI now resolves pytest 9.2.0, and pytest-xdist 3.8.0 (the latest release) does not work with it: - `--dist loadgroup` keeps an `xdist_group` on one worker by rewriting `item._nodeid` to `<id>@<group>`. - pytest 9.2 builds `Item.nodeid` from a structured `_id` instead, so that write is lost. - Every grouped test is therefore scheduled like an ungrouped one. The MCP pair (and the other `*_reset_between_tests` pairs) only hold when both tests run on the same worker. With `-v`, the first test ran on `gw0` and the second on `gw3`. Minimal reproduction: ```python pytestmark = pytest.mark.xdist_group("g1") def test_one(): pass def test_two(): pass ``` `pytest -n 2 --dist loadgroup -v`: - pytest 9.1.1 reports `test_one@g1` and `test_two@g1`, both on `gw0`. - pytest 9.2.0 reports `test_one` on `gw0` and `test_two` on `gw1`. The same pytest release is behind the `torch._dynamo.config.* does not exist` failures (#15624 pins Backend CI below 9.2 for that; #15626 makes the suite tolerate it). ## Change This builds on #15624 (merged), which pins `'pytest<9.2'` in `studio-backend-ci.yml`, the only workflow that runs `--dist loadgroup`. - **`version-compat-ci.yml`**: `'pytest>=8'` becomes `'pytest>=8,<9.2'`. These lanes run the CPU-spoof fixtures that monkeypatch `torch._dynamo.config`, which pytest 9.2 deletes on undo. - **`tests/_shared/xdist_group_check.py`**, installed as a `trylast` `pytest_collection_modifyitems` hook in `tests/conftest.py` and `studio/backend/tests/conftest.py`: - On an xdist worker running `--dist loadgroup`, any test that carries an `xdist_group` mark but whose node id has no `@group` tag now fails with the reason. - Before, it would sometimes pass and sometimes fail depending on scheduling. If the pin is lifted before pytest-xdist catches up, the grouped tests fail by name with an explanation instead of flaking. - Raising a usage error at collection time would be swallowed into an xdist `INTERNALERROR`, so each affected test fails individually instead. - **`tests/test_xdist_group_check.py`**: unit tests for the check, the conftest wiring, and both pins (Backend CI from #15624 and version-compat from this PR). ## Testing Run on `studio/backend/tests/test_mcp_*.py` with `-n 4 --dist loadgroup`: - **pytest 9.1.1:** 2089 passed, twice. - **pytest 9.2.0:** the MCP pair failed in both runs. - **Serially on 9.2.0:** 2089 passed, so the failure needs xdist. With the check in place, the two grouped pair files under `-n 2 --dist loadgroup`: - **pytest 9.1.1:** 4 passed. - **pytest 9.2.0:** all 4 grouped tests fail with "--dist loadgroup did not tag this xdist_group test ...". `tests/test_xdist_group_check.py` with `tests/test_torch_config_guard.py` (from #15626) after merging main: 18 passed.
danielhanchen
marked this pull request as ready for review
October 28, 2026 05:57
Member
Author
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
danielhanchen
added a commit
to Etherll/unsloth
that referenced
this pull request
Oct 28, 2026
… it on later reads (unslothai#15687) Follow-up to unslothai#15593 (buffered GGUF string walks, merged). A cold local GGUF load reads the header many times before llama-server starts: `_read_gguf_metadata` runs for the route preflight, the diffusion check, the non-chat refusal check and the real read, and `_gguf_scan_tensor_bytes` plus each `gguf_metadata` reader (general, chat template, nextn, embedding length, staged dims, MTP standalone, mrope, TTS) walks the same tokenizer arrays again. With unslothai#15593 each walk is buffered, but there are still 23 to 36 walks of 150k to 262k entries per file. This PR walks each array once per process and replays later walks of the same unchanged file as one seek. ## What changes - `utils/models/gguf_metadata.py`: `skip_gguf_strings` and `take_gguf_strings_by_first_byte` get a small memo in front of the unchanged walks. A hit seeks to the remembered end and returns the remembered count (and, for `take`, a new list of the remembered entries). - Key: `(st_dev, st_ino, st_size, st_mtime_ns, st_ctime_ns)` from `os.fstat` on the open file, plus the start offset, the entry count and the kind of walk. A finished `take` also answers a `skip` of the same array, since every entry was whole and at most 1 MiB. - Only plain files opened with `open(path, "rb")` take part. `BytesIO`, wrappers, pipes and streams that cannot seek back never do. - A walk is not remembered when the file reports inode 0, when its mtime or ctime is less than 3 s before the walk began (covers FAT's 2 s and HFS+ 1 s timestamps, so a later same-size rewrite always moves a timestamp past the stored one), when `fstat` after the walk differs from before it (written during the walk), or when the kept entries of a `take` exceed 1 MiB. Growing files (downloads) change size and are recent. - LRU of 256 entries under one lock. In practice only the load path calls `take`, and its kept entries are tens of KB. - Nothing changes in what any reader returns, raises, or where it leaves the file position. ## Results Fresh process per sample, running the readers of a cold local load in order (4x `_read_gguf_metadata`, `_gguf_scan_tensor_bytes`, 8 `gguf_metadata` readers), base = unslothai#15593 head, interleaved, n=8 per arm. Walk counts and bytes read are deterministic. | file (vocab) | base CPU ms median [range] | this PR | walks | bytes read | |---|---|---|---|---| | Qwen3-0.6B Q8_0 (152k) | 761 [528-800] | 161 [120-186] | 23 -> 2 | 66.9 MB -> 9.0 MB | | Qwen3.5-9B Q8_0 (248k) | 1237 [850-1305] | 262 [174-292] | 36 -> 3 | 127.3 MB -> 16.6 MB | | gemma-4-E2B Q4_K_M (262k) | 1667 [1347-1960] | 320 [256-390] | 36 -> 3 | 171.6 MB -> 20.0 MB | | gpt-oss-20b Q2_K (201k) | 1385 [1092-1631] | 254 [214-290] | 36 -> 3 | 152.4 MB -> 17.4 MB | | Mistral-Small-3.2-24B Q4_K_M (131k) | 834 [667-1003] | 173 [130-190] | 23 -> 2 | 92.0 MB -> 10.7 MB | Base and head ranges do not overlap for any file. A separate rerun of the Qwen3-0.6B row (3 rounds per arm) gave 543 to 575 ms vs 93 to 140 ms, with the same 23 -> 2 walks and 66.9 MB -> 9.0 MB read. Equivalence: 60 real GGUF headers plus 300 fuzzed ones (chunk straddles, entries over 1 MiB, corrupt lengths, truncation, invalid UTF-8) through 18 reader entry points, comparing return values, exception type and message and the final `tell()` on files and `BytesIO`: 17,736 checks, 0 differences, with the memo warm across readers. Calling every reader three times on a warm memo also gives 0 differences. Python 3.9, 3.10, 3.11, 3.12 and 3.14: 0 mismatches. ## Tests - New `tests/test_gguf_walk_memo.py` (20): a hit reads no entries and equals a fresh walk; a finished take answers the skip; hits return a new list; offset and count are part of the key; a same-size rewrite with the old mtime restored, a rename over the file with the old mtime, an in-place rewrite where ctime is the creation time (as on Windows), a recently changed file, a growing file, inode 0, a change during the walk and `BytesIO` are all walked again; the LRU bound and the 1 MiB kept cap hold; 8 threads agree; the llama reader and the metadata readers share one walk. Base (unslothai#15593 head, test copied in): 2 failed, 12 errors. This PR: 20 passed. - Existing `test_gguf_string_walk.py`, `test_gguf_metadata.py`, `test_gguf_header_delta.py`, `test_gguf_admission_token_count.py`, `test_gguf_image_capability.py`, `test_gguf_metadata_log_volume.py`: all pass on both base and this PR. ## Not covered - Run on Linux x64 only. No Windows, macOS or ARM64 run, and no FAT, SMB or OneDrive volume. The code is standard library only (`os.fstat`, `stat.S_ISREG`, `time.time_ns`) with no OS branches. - On Windows `st_ctime` is the creation time, so a rewrite in place that keeps the same size and also restores the exact old mtime (to 100 ns) would not be seen until the process restarts. A rename or copy over the file changes the file index, and any normal write moves mtime. The existing metadata caches in this module trust the same fields. - Network shares whose server clock is more than 3 s behind the client, combined with a same-size rewrite inside one timestamp tick, are not covered by the settle window. - No full Studio load with llama-server; the read sequence comes from the call sites.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Every GGUF metadata read walks the tokenizer string arrays (tokens and merges, 150k to 262k entries each) with one
read, onestruct.unpackand oneseekper entry, about 180 ns per entry. That is 50 to 200 ms of CPU per read, and a cold GGUF load reads the header several times (the main metadata read at least three times, plus one walk per other metadata reader the load touches) before llama-server starts.What changes
utils/models/gguf_metadata.py: two helpers walk a run of length-prefixed strings inside one 256 KiB buffer (skip, or collect the matching entries). They are used by_skip_gguf_value,_gguf_read_array_value, andLlamaCppBackend._gguf_skip_valueincore/inference/llama_cpp.py.seekable()is missing (as onmmap.mmapbefore Python 3.13), raises, or returns False takes the per-entry loop from its first entry.Results
CPU time, best of 9 runs per process, 3 processes per side interleaved (main against itself varies about 5 to 15%):
About 180 ns per entry before, 90 ns after.
Equivalence
Tests
studio/backend/tests/test_gguf_string_walk.py(81 cases): both skip paths and the read path match the per-entry loop on every fixture, the collector returns every matching entry in order, the walk reads in chunks rather than per entry, a non-seekable stream falls back to per-entry reads, and a forward-only stream (skips ahead, raises on a backward seek) or a reader withoutseekable()gets 0 from both helpers, with the caller's loop ending at the same offset as on an ordinary file. Deliberately broken versions of the walk are each caught.test_architecture_read_stops_before_a_large_tokenizer_arrayintest_gguf_metadata.pycounted per-entry file calls as its "does scan" control; it now checks how far into the file each read reaches, and passes on both main and this branch.Not covered