Repository navigation
Windows unbuffered model load - #26014
Conversation
|
Hi @JTischbein, thanks for your contribution! Per our contribution guidelines, the automated PR checker found the following issue(s) that need your attention:
Please note that maintainers reserve the right to make final decisions on PRs. If you believe there is a mistake, please comment below. |
ORippler
left a comment
There was a problem hiding this comment.
Thanks for bringing this feature to Windows as well!
- Regarding the refactor: nice to have, but beyond the scope of this PR imo - this PR aims to bring Windows to performance parity with Linux for the direct-io path
- What would be nice is some tests for file loading (both for Linux and Windows). Not sure how difficult they are to spin up and if they should be part of this PR.
- Do you have some perf numbers for dGPU systems you could share?
| } | ||
| const size_t bytes_to_read = (offset_from_alignment + len + alignment - 1) & ~(alignment - 1); | ||
|
|
||
| void * raw_buffer = _aligned_malloc(bytes_to_read, alignment); |
There was a problem hiding this comment.
I guess adding a chunked read is not advisable from a perf perspective? LM Head may be a couple of 100 MB in size (500 MB for Qwen3.6-35BA3B if we have 8 BPW)
There was a problem hiding this comment.
Actually we sometimes have regressing performance with larger read size, in my tests above 512MB (1GB compared to 512MB loads 16% slower). I will add chunked reads in the upcoming PR
There was a problem hiding this comment.
I can remember a 'trick' to deal with this more efficiently.
- first check if the buffer given is already aligned.
- If not, we read unaligned until we are at the aligned boundary.
- Handle the left over bytes as an aligned read.
That would avoid the memory allocation
|
Just FYI, no critic at all or anything like that: PR#26542 covers the "OVERLAPPED" and "Handle/Thread" part of this problem - both PRs combined, should solve this problem. Shared handle at depth 8: 1.01x Yours |
Yes, it shouldn't be difficult to unit-test the
Then we can run these tests on multiple devices on |
2cd2f5f to
a2923f6
Compare
|
We should add buffered fall-back path similar to #29749 for Windows also |
a2923f6 to
5a8a96a
Compare
65e52db to
6948422
Compare
|
Unrelated, we should not add those perf counters here imo, it's scope-creep |
…een linux and windows
Assisted-by: Codex
a7b5345 to
5cb342b
Compare
| const size_t read_size = std::min(len, size - read_offset); | ||
| size_t bytes_read = 0; | ||
| while (bytes_read < read_size) { | ||
| const DWORD to_read = (DWORD) std::min<size_t>(read_size - bytes_read, MAXDWORD); |
There was a problem hiding this comment.
Do we see perf gains from shifting from 64 MiB to 4 GB?
EDIT: For NVIDIA paths we do 64 MiB for async uploads, so this is something to potentially change behavior only on other backends.
Co-authored-by: Oliver Simons <[email protected]>
ORippler
left a comment
There was a problem hiding this comment.
@JTischbein please share some perf numbers for model loading on RTX Spark/dGPU + NVME to motivate this.
|
Gently pinging @CISC / @ggerganov for review |
|
I only have a RTX Spark to test, the SSD reads with 7GB/s max. Qwen3.6-35B-A3B-UD-Q4_K_M.gguf is 21.1GB large. Using llama-bench with load mode none, mmap and dio:
The read speed can be optimized further by modying |
|
Tested on a small Windows 11 box I only use to test llama.cpp like the CI does: RTX 5060 Ti 16 GB, 64 GB RAM and an older Samsung 970 PRO (PCIe 3.0 NVMe). I loaded Qwen3.6-35B-A3B UD-Q2_K_XL (12.3 GB) with llama-completion and evicted the page cache before each cold run. Without this PR, -lm dio on Windows is just the buffered path: it loads exactly like -lm none, and test-llama-mmap fails 81 assertions because has_direct_io() always returns true. With this PR, full offload loads in 4.4 s with -lm dio, cold or warm, against 6.7 s cold with -lm none, so about the raw speed of the drive every time. Greedy outputs are identical between none and dio, and test-llama-mmap passes. @JTischbein few small nits, nothing blocking:
|
Assisted-by: Codex
|
@ServeurpersoCom Thanks for the hint, just added Yes, that would be also good for the followup PR. I will check if we can efficiently handle some async memcpy on CPU. |
ggerganov
left a comment
There was a problem hiding this comment.
Only had a cursory look. I'll look in more details in a few days - feel free to merge in the meantime.
One thing that would be worth considering is to split the llama-mmap.cpp into separate sources - one for windows and one for linux. The reason is even though with the current implementation we deduplicate most of the implementation, it's a bit difficult to follow. I think with separate files and using LLMs it would be much simpler to maintain.
Alternatively, we could try to merge scaffolding and just ifdef/specialize on the file handles. Though iirc we needed some "workers" on window file-handles to achieve maximum throughput on RTX Spark.
ack, will wait for CI to progress a bit further and merge then |
…5 на любой модели Комплектный `llama-server.exe` умирал с 0xC0000005 сразу после `load_model: loading model` и до чтения тензоров: на крошечной CI-модели (1 185 376 Б) и на рабочей 15-ГБ GGUF одинаково. Перебор флагов (`--device none`, `--flash-attn off`, `--no-webui`, `--load-mode none`, `GGML_CUDA_GRAPH_NODES=1`) исход не менял; master-сборка на той же модели жила, а посадка комплектного `llama.dll` в master убивала и её - значит дефект в этом dll. Что изменено? - Откат `9d340ec34` «Windows unbuffered model load (ggml-org#26014)»: `src/llama-mmap.cpp` возвращён к прежнему пути чтения (+35/-265), `tests/test-llama-mmap.cpp` удалён (0/-232), строка теста в `tests/CMakeLists.txt` убрана (0/-7). Зачем? Без отката portable-комплект приезжает с мёртвым llama-движком: пользователь скачивает архив, запускает сервер с моделью и получает падение на первой же секунде. Замеры? - После отката и пересборки (`--target llama-server`, arch `86;89;120a`, CUDA 13.3): `--version` = `1.0.0-dev (build 1337, commit d9eed0832)`. - Крошечная GPU-модель: процесс жив 30 с (падения нет). - Рабочая `Qwen3.6-35B-A3B-UD-IQ3_S` (15 346 432 288 Б): процесс жив 25 с. - Комплект после подмены набора: `/props` = 200, `/` отдаёт 12 658 Б страницы с `index.html`. - `git diff a003983 HEAD -- src/llama-mmap.cpp` пуст: код чтения совпадает с той сборкой, которая на этой модели работала. Принятый остаток? Откат убирает выигрыш unbuffered-чтения на Windows; вернуть его нужно отдельной правкой с выравниванием буферов, а не молчаливым откатом. Пуш в форк и пересборка ассета - отдельными шагами. Итог Комплектный llama-сервер снова загружает модель и отдаёт встроенный UI; регресс пойман на уровне мутационного контроля (посадка dll в живую сборку), а не на глаз. --- EN: llama: revert the unbuffered load - the kit server crashed with 0xC0000005 on any model The kit `llama-server.exe` died with 0xC0000005 right after `load_model: loading model`, before reading tensors: identically on the tiny CI model (1,185,376 bytes) and on a working 15 GB GGUF. Trying flags (`--device none`, `--flash-attn off`, `--no-webui`, `--load-mode none`, `GGML_CUDA_GRAPH_NODES=1`) changed nothing; a master build lived on the same model, and planting the kit `llama.dll` into master killed it too - so the defect is in that dll. What changed? - Revert of `9d340ec34` "Windows unbuffered model load (ggml-org#26014)": `src/llama-mmap.cpp` is back to the previous read path (+35/-265), `tests/test-llama-mmap.cpp` is removed (0/-232), and its entry in `tests/CMakeLists.txt` is dropped (0/-7). Why? Without the revert the portable kit ships a dead llama engine: the user downloads the archive, starts the server with a model and gets a crash within the first second. Verified - After the revert and a rebuild (`--target llama-server`, arch `86;89;120a`, CUDA 13.3): `--version` = `1.0.0-dev (build 1337, commit d9eed0832)`. - Tiny GPU model: the process stays alive for 30 s (no crash). - Working `Qwen3.6-35B-A3B-UD-IQ3_S` (15,346,432,288 bytes): the process stays alive for 25 s. - Kit after the binary swap: `/props` = 200, `/` returns 12,658 bytes containing `index.html`. - `git diff a003983 HEAD -- src/llama-mmap.cpp` is empty: the read path matches the build that worked on this model. Accepted remainder The revert gives up the Windows unbuffered read win; restoring it needs a separate fix with aligned buffers, not a silent revert. Fork push and asset rebuild are separate steps. Result The kit llama server loads models and serves its built-in UI again; the regression was caught by a mutation control (planting the dll into a live build), not by eye.
…rigin/master Что изменено? - мерж sync1617-replay cc4399a в kit-all-sync: 106 путей (+7540/-2315 относительно HEAD до мержа); окно апстрима 6d3568e..origin/master (tip 9fba51d, 15.11) проиграно поверх конца прежней цепочки e574a17 22 cherry-pick с сохранением автора, коммиттера и коммиттер-даты источника; - гейт: дерево sync1617-replay побайтово равно дереву origin/master (d5afec5) - покрытие апстрима доказано содержимым, а не хешами; - .github/workflows/build-cuda-ubuntu.yml: ихняя однострочная правка из ggml-org#31617 отброшена, наше удаление унаследованного workflow (39628e5) сохранено через git rm; - находка замера: апстримный 6d3568e (opencl A7 Q6_K binary kernel, ggml-org#30949, 14.11) влился ПОСЛЕ конца прежней цепочки (ggml-org#32296) и не был покрыт ни синком 15.11 («34 коммита»), ни окном из 21, которое считалось от него; дыра ровно в 1 файл/84 строки, вскрыта гейтом деревьев и закрыта 22-м cherry-pick. Зачем? Комплект собирается из kit-all-sync, и ветка обязана догонять апстрим целиком: обвал llama-ноги с 0xC0000005 (апстримный ggml-org#26014) закрыт только нашим ревертом unbuffered load, поэтому после каждого синка реверт обязан остаться сверху, а расхождение деревьев означало бы тихую потерю чужих фиксов (как opencl-дыра выше). Замеры? - префлайт 16.11: llama-kit чист на 0f94ea7, тег backup/llama-kit-all-sync-2026-11-16. - shallow-состояние: .git/shallow держит границы 3cf0325 и 5a4afd8; после fetch --deepen 200 родитель окна 6d3568e стал настоящим объектом, окно переснято и сверено множеством хешей с прежним списком (0 различий). - replay: 21+1 cherry-pick rc=0 каждый; итоговое дерево == origin/master (выше). - мерж: 1 конфликт (build-cuda-ubuntu.yml, DU), после git rm - 0; наши серии остались сверху (origin/master..kit-all-sync по хешам 26 до мержа). - зонд ggml-org#26014 в head апстрима: коммит 9d340ec жив в истории, src/llama-mmap.cpp содержит unbuffered-ветки (строки 100/166/409/416), tests/test-llama-mmap.cpp присутствует - реверт d9eed0832 по-прежнему нужен. Принятый остаток? Хешы replay-цепочки отличаются от апстримных (иначе и не может при мерже в синтетическую историю); сборка и приёмка kit-ноги - шаг 2 плана; пуш fork - этим же планом. Итог kit-all-sync закрывает весь апстрим до 9fba51d включительно: покрытие подтверждено побайтовым совпадением деревьев, наши правки остались сверху. --- EN: sync: kit-all-sync took 22 upstream commits, replay tree == origin/master What changed? - merge of sync1617-replay cc4399a into kit-all-sync: 106 paths (+7540/-2315 vs the pre-merge HEAD); the upstream window 6d3568e..origin/master (tip 9fba51d, 15.11) replayed as 22 cherry-picks over the previous chain end e574a17, preserving author, committer and committer date of each source commit; - gate: the sync1617-replay tree is byte-identical to the origin/master tree (d5afec5) - upstream coverage proven by content, not by hashes; - .github/workflows/build-cuda-ubuntu.yml: their one-line edit from ggml-org#31617 dropped, our removal of the inherited workflow (39628e5) kept via git rm; - measurement finding: upstream 6d3568e (opencl A7 Q6_K binary kernel, ggml-org#30949, 14.11) landed AFTER the end of the previous chain (ggml-org#32296) and was covered neither by the 15.11 sync ("34 commits") nor by the 21-commit window computed from it; the hole was exactly 1 file / 84 lines, exposed by the tree gate and closed as the 22nd cherry-pick. Why? The kit builds llama from kit-all-sync, so the branch must chase upstream as a whole: the llama leg needs fresh upstream plus our unbuffered-load revert, and any tree divergence would mean silently losing foreign fixes (like the opencl hole above). Verified? - preflight 16.11: llama-kit clean at 0f94ea7, tag backup/llama-kit-all-sync-2026-11-16. - shallow state: .git/shallow held boundaries 3cf0325 and 5a4afd8; after fetch --deepen 200 the window parent 6d3568e became a real object, the window was re-shot and hash-set-compared with the earlier list (0 diffs). - replay: 21+1 cherry-picks, each rc=0; final tree == origin/master (above). - merge: 1 conflict (build-cuda-ubuntu.yml, DU), 0 after git rm; our series stayed on top (origin/master..kit-all-sync was 26 by hashes pre-merge). - ggml-org#26014 probe in upstream head: commit 9d340ec alive in history, src/llama-mmap.cpp still carries unbuffered branches (lines 100/166/409/416), tests/test-llama-mmap.cpp present - revert d9eed0832 still required. Accepted remainder? Replay-chain hashes differ from upstream ones (unavoidable when merging into a synthetic history); the kit build and acceptance are plan step 2; pushing the fork is covered by the same plan. Result kit-all-sync now covers all of upstream through 9fba51d, proven by byte-identical trees, with our edits preserved on top.
…-org#26014 сохранён Что изменено? - мерж origin/master 6b01a47 (16.11) в kit-all-sync: 16 путей (+176/-29 относительно HEAD до мержа) — CI-триггер spec-dec тестов (ggml-org#32281), фикс MUL_MAT_ID на чётных колонках для AMD (ggml-org#32385), kv-cells без O(n_cells) скана (ggml-org#32380), reasoning_effort 400 (ggml-org#32332), MoE-регрессия HIP (ggml-org#32344), серверный refactor slot_sched (ggml-org#32154). - .github/workflows/build-cuda-ubuntu.yml и server-speculative.yml: DU — апстрим правил файлы из числа наших осознанных удалений унаследованных workflow; удаления сохранены через git rm. - tools/server/tests/unit/test_compat_anthropic.py (UU): наш борт нёс параметризованный вариант теста effort (реплей промежуточного коммита ggml-org#32321), актуальный head апстрима вернул непараметризованный; принят THEIRS — после разбора файл побайтово равен blob апстрима 0b65ad1 (наш собственный код в этом файле отсутствует, терять нечего). Зачем? kit-all-sync — носитель ветки сборки llama-ноги комплекта; отставание на 27 коммитов за ночь ломало бы сопоставимость следующего прогона носителя с апстримом и оставило бы нас без свежих фиксов CUDA/HIP на 3060 Ti-пути. Замеры? - префлайт: HEAD kit-all-sync = c9f6a82, дерево чисто, мерж-состояния нет. - дельта: 27 новых коммитов поверх merge-base e574a17; mmap/load апстрим не трогал (0 коммитов по src/llama-mmap.cpp в окне) — upstream-delta-2026-11-16b.md. - реверт ggml-org#26014: staged src/llama-mmap.cpp blob 4d1cd31 — равен blob реверта 0e6d623; зонд: unbuffered-код жив в head апстрима (тест test-llama-mmap.cpp присутствует) ⇒ реверт нужен и дальше. - маркеры наших рычагов в staged-дереве: GGML_CUDA_GRAPH_NODES 2 файла, GGML_CUDA_UPLOAD_STREAM 2, n_copies 10, moe_cache 14. - git cherry origin/master kit-all-sync: 20 непокрытых (наши патчи, CI и упаковка, реверт) / 22 покрытых patch-id (вчерашний replay-цепочечный окно). - неразобранных конфликтов: 0, маркеров конфликта: 0. Принятый остаток? Сборка llama-ноги с этим мержем — после освобождения бинарников стенда (сетка замеров идёт); пуш fork/kit-all-sync — этим же планом, отдельной командой. Итог kit-all-sync содержит head ggml-org 16.11 с сохранёнными ревертом ggml-org#26014 и всеми нашими рычагами, доказанными маркерной меркой до коммита. --- EN: sync: kit-all-sync took in origin/master (27 commits), revert ggml-org#26014 kept What changed? - merge of origin/master 6b01a47 (16.11) into kit-all-sync: 16 paths (+176/-29 vs HEAD before the merge) — spec-dec CI trigger (ggml-org#32281), MUL_MAT_ID fix for odd src0 columns on AMD (ggml-org#32385), kv-cells O(n_cells) scan removal (ggml-org#32380), reasoning_effort 400 (ggml-org#32332), HIP MoE regression fix (ggml-org#32344), server slot_sched refactor (ggml-org#32154). - .github/workflows/build-cuda-ubuntu.yml and server-speculative.yml: DU — upstream edited files among our deliberate deletions of inherited workflows; deletions kept via git rm. - tools/server/tests/unit/test_compat_anthropic.py (UU): our side carried the parametrized effort test (a replay of the intermediate ggml-org#32321), the current upstream head reverted it to non-parametrized; THEIRS taken — after resolution the file is byte-equal to upstream blob 0b65ad1 (no code of ours lives in this file, nothing to lose). Why? kit-all-sync is the build branch for the llama leg of the kit; a 27-commit overnight lag would break comparability of the next carrier run with upstream and leave us without fresh CUDA/HIP fixes on the 3060 Ti path. Verified - preflight: kit-all-sync HEAD = c9f6a82, clean tree, no merge state. - delta: 27 new commits over merge-base e574a17; upstream did not touch mmap/load (0 commits on src/llama-mmap.cpp in the window) — upstream-delta-2026-11-16b.md. - revert ggml-org#26014: staged src/llama-mmap.cpp blob 4d1cd31 equals the blob of revert 0e6d623; probe: unbuffered code still lives in the upstream head (test-llama-mmap.cpp present) ⇒ the revert remains necessary. - our lever markers in the staged tree: GGML_CUDA_GRAPH_NODES 2 files, GGML_CUDA_UPLOAD_STREAM 2, n_copies 10, moe_cache 14. - git cherry origin/master kit-all-sync: 20 uncovered (our patches, CI and packaging, the revert) / 22 patch-id covered (yesterday's replay chain). - unresolved conflicts: 0, conflict markers: 0. Accepted remainder Building the llama leg with this merge waits for the stand binaries to free up (a measurement grid is running); pushing fork/kit-all-sync is done by this plan as a separate command. Result kit-all-sync contains the 16.11 ggml-org head with revert ggml-org#26014 and all our levers preserved, marker-proven before commit.
Testing
As the DirectIO change on Linux lead to many new issues with several backends and devices, I'd appreciate it if people could test this PR on different devices and let me know if it works.
Overview
Linux supported unbuffered reading from disk via DirectIO for fast model loading. On my machine with PCIe5.0 NVMe drive this path increases the model loading performance from 1-3GB/s to >9GB/s.
For Windows this change is needed, as using mmap of large models on setups with small CPU RAM lead to Sysmem pressure and eviction of runtime pages.
Additional information
This PR introduces the unbuffered read file API of Windows. #18012 is the merged Linux PR.
Requirements