Skip to content

Adding --direct-io flag for model loading - #18166

Merged
ggerganov merged 11 commits into
ggml-org:masterfrom
JTischbein:direct_io_flag
Jan 8, 2026
Merged

ggerganov merged 11 commits into
ggml-org:masterfrom
JTischbein:direct_io_flag

Conversation

@JTischbein

Copy link
Copy Markdown
Contributor

Follow up for PR #18012 (comment).

To enable Direct IO model reading by default on Linux and Windows, but to stay with --mmap as default on Mac, this PR adds an additional flag for enabling/disabling Direct IO. This flag is by default true and overrules the mmap parameter. In case --direct-io is true and Direct IO is available, --mmap gets disabled. And if --no-direct-io is set or Direct IO is not available (e.g. on Mac), the specified mmap value is used.

@ggerganov

Copy link
Copy Markdown
Member

I think you need this:

diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp
index 1355eea95..2db2115a0 100644
--- a/src/llama-model-loader.cpp
+++ b/src/llama-model-loader.cpp
@@ -918,8 +918,7 @@ void llama_model_loader::load_data_for(struct ggml_tensor * cur) const {
         GGML_ASSERT(cur->data != nullptr);
         GGML_ASSERT(w.idx < files.size());
         const auto & file = files.at(w.idx);
-        file->seek(w.offs, SEEK_SET);
-        file->read_raw(cur->data, ggml_nbytes(cur));
+        file->read_raw_at(cur->data, ggml_nbytes(cur), w.offs);
     }
 
     if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {

Probably need to assert that llama_file::read_raw is never used with direct io?

@JTischbein

Copy link
Copy Markdown
Contributor Author

Thanks for the hint, changed that.

I think an assert would not work as read_raw in the current form is needed. Would you suggest to rename read_raw_at to be read_raw (and using tell instead of the offset argument)? Like this read_raw can be safely used again and in the loop of load_all_data the current read_raw is called (as read_raw_direct?)

@ggerganov

Copy link
Copy Markdown
Member

Would you suggest to rename read_raw_at to be read_raw (and using tell instead of the offset argument)? Like this read_raw can be safely used again and in the loop of load_all_data the current read_raw is called (as read_raw_direct?)

Ok. Would we even need to have read_raw_direct in this case? If we still needed for some reason, then maybe call it read_raw_unsafe to not overload the "direct" word with more meanings.


Also some suggestions that I have not tested, but should at least convey what I mean:

diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp
index 2db2115a0..ae0c698be 100644
--- a/src/llama-model-loader.cpp
+++ b/src/llama-model-loader.cpp
@@ -508,8 +508,11 @@ llama_model_loader::llama_model_loader(
     files.emplace_back(new llama_file(fname.c_str(), "rb", use_direct_io));
     contexts.emplace_back(ctx);
 
-    // Disable mmap in case Direct I/O is enabled and available
-    if (use_direct_io && files.at(0)->has_direct_io()) {
+    // check if direct io is enabled and supported
+    use_direct_io = use_direct_io && files.back()->has_direct_io();
+
+    if (use_direct_io && use_mmap) {
+        LLAMA_LOG_WARN("%s: direct I/O is enabled, disabling mmap\n", __func__);
         use_mmap = false;
     }
 
@@ -581,6 +584,10 @@ llama_model_loader::llama_model_loader(
             files.emplace_back(new llama_file(fname_split, "rb", use_direct_io));
             contexts.emplace_back(ctx);
 
+            if (use_direct_io && !files.back()->has_direct_io()) {
+                throw std::runtime_error(format("unexpected: direct I/O is not supported for split file %s", fname_split));
+            }
+
             // Save tensors data offset info of the shard.
             for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
                 std::string tensor_name = std::string(cur->name);
@@ -722,6 +729,7 @@ llama_model_loader::llama_model_loader(
     }
 
     this->use_mmap = use_mmap;
+    this->use_direct_io = use_direct_io;
     this->check_tensors = check_tensors;
     this->no_alloc = no_alloc;
 }
diff --git a/src/llama-model-loader.h b/src/llama-model-loader.h
index de06b5283..6f15115ce 100644
--- a/src/llama-model-loader.h
+++ b/src/llama-model-loader.h
@@ -70,6 +70,7 @@ struct llama_model_loader {
     size_t   n_bytes    = 0;
 
     bool use_mmap = false;
+    bool use_direct_io = false;
     bool check_tensors;
     bool no_alloc;
 
diff --git a/src/llama-model.cpp b/src/llama-model.cpp
index cf0c39475..502859d2e 100644
--- a/src/llama-model.cpp
+++ b/src/llama-model.cpp
@@ -2337,7 +2337,8 @@ bool llama_model::load_tensors(llama_model_loader & ml) {
 
     const bool use_mmap_buffer = true;
 
-    LLAMA_LOG_INFO("%s: loading model tensors, this can take a while... (mmap = %s)\n", __func__, ml.use_mmap ? "true" : "false");
+    LLAMA_LOG_INFO("%s: loading model tensors, this can take a while... (mmap = %s, direct_io = %s)\n",
+            __func__, ml.use_mmap ? "true" : "false", ml.use_direct_io ? "true" : "false");
 
     // build a list of buffer types for the CPU and GPU devices
     pimpl->cpu_buft_list = make_cpu_buft_list(devices, params.use_extra_bufts, params.no_host);

@askmyteapot

Copy link
Copy Markdown

Just an FYI. #18012 Broke loading with mmap disabled on windows.

@JTischbein

Copy link
Copy Markdown
Contributor Author

@askmyteapot Thank you for the hint. Issue was that I used off_t, which is a signed long on windows. The fix is in this PR.

@JTischbein

Copy link
Copy Markdown
Contributor Author

@ggerganov Should I isolate the changes with the Windows fix in a new PR?

@ggerganov

Copy link
Copy Markdown
Member

Yes, would like to take extra look at the changes here, so better to fix the windows issue in the meantime. Thanks

@NeoZhangJianyu NeoZhangJianyu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the parameters to load the model file in this PR?
Here is my understanding, please correct me if it's wrong:
--no-mmap -ndio
--no-mmap -dio
--mmap

When must user use -ndio?

I think the parameters are a little complex.
Here is my suggestion:
We should keep: --mmap and --no-mmap.
In the case of --no-mmap, the code should detect & switch to use dio or ndio smartly in windows/linux/mac.

@ehoogeveen-medweb

Copy link
Copy Markdown

IIUC, the implementation in this PR currently requires passing --no-direct-io in order to enable mmap, and --no-direct-io --no-mmap to disable both. I think it should also recognize that if a user passes just --mmap, they want to disable Direct IO and use mmap (as the two options are mutually exclusive).

In other words, --mmap should imply --no-direct-io (and --direct-io should imply --no-mmap, although that doesn't matter with the current logic). Aside from that case, I think the logic is reasonable assuming that preferring Direct IO over mmap is the way to go.

@JTischbein

Copy link
Copy Markdown
Contributor Author

I agree with @ehoogeveen-medweb, now explicitly specifying --mmap disables direct io. Only handling the model load using --mmap and --no-mmap does not work with the current implementation, as we need the code paths for loading via mmap, read() and std::fread().

Now there are three ways:

  • Default (implicitly -dio --mmap): Load via direct io and if it is not available fallback to mmap
  • Explicitly specifying --mmap: Load via mmap
  • Explicitly specifying --no-mmap -ndio: Load via std::fread()

@NeoZhangJianyu

NeoZhangJianyu commented Dec 29, 2025 •

Copy link
Copy Markdown
Contributor

@JTischbein
I test this PR with SYCL backend on Ubuntu 22.04.
All parameters case are work.
But the parameter -dio will make the load slower than other -ndio case, about 2-4 times as my feeling.

Here is my test cases and result:

Parameters Ubuntu 22.04/SYCL
--mmap quick
--no-mmap slow
--mmap -dio show
--mmap -ndio quick
--no-mmap -dio show
--no-mmap -ndio quick
empty: none above parameters slow

Why "-dio" make the performance to be reduced?
It's far away of the purpose of this PR.

Could you confirm it on any Intel Core CPU (12th or newer) with iGPU (windows/linux)?
And add more test result in above table for different OS and backend.
So that we could know the impact of new feature.

Here is the test cmd:

./build/bin/llama-server --model ./models/llama-2-7b.Q4_0.gguf -ngl 99  --ctx-size 5000 --no-mmap -dio

Thank you!

@JTischbein

JTischbein commented Dec 29, 2025 •

Copy link
Copy Markdown
Contributor Author

@NeoZhangJianyu I have found the issue for the performance drop and probably why it is working on some devices with the SYCL backend and Vulkan backend. The current code uses an additional CPU buffer, from which the tensors are then copied into the pinned memory buffers (making it slower depending on the memcpy speed). If I disable this additional buffer again we are seeing on some devices (only SYCL and Vulkan backend so far) the error Bad address. The issue is most likely that the allocated buffer is not in the CPU RAM pages so that a DMA from disk can be done, but the allocated buffer is on device and the pages are mapped into CPU memory (which then leads to Bad address). I unfortunately don't have access to an Intel iGPU and I have no experience with the SYCL backend, could you help fix the allocation of pinned memory? Thank you

@jeffbolznv

Copy link
Copy Markdown
Contributor

I don't fully understand this theory. These are UMA systems, are you suggesting that these pages are in a carveout region or something similar that makes them inaccessible for DMA? I don't think we have a way to detect that in the backend. Something like #18317 (comment) is the best we could try but that didn't work.

Is it possible to handle this error in the model loader and fallback to the non-directio path? That seems like it would be a more robust solution.

@jeffbolznv

Copy link
Copy Markdown
Contributor

Another solution might be to allocate these buffers with (aligned)malloc and use the buffer_from_host_ptr function to make them GPU-accessible. This isn't currently implemented in ggml-vulkan but it's probably not too difficult to do so.

@JTischbein

Copy link
Copy Markdown
Contributor Author

@jeffbolznv Yes, that is currently my guess. Multiple people reported now that this PR fixed the reading issues and the difference between master and this PR is that the buffer pointer given to read points to a posix_memalign buffer and not into the buffer provided by the backend.

read with O_DIRECT enabled prompts the DMA controller to copy the data from disk directly into physical memory and bypasses the paging. Is it possible that mapped memory leads to issues here?

In case that can be tested without too much effort it would be great to know whether buffer_from_host_ptr works

Comment thread src/llama-mmap.cpp Resolved
Co-authored-by: Georgi Gerganov <[email protected]>
@engrtipusultan

Copy link
Copy Markdown

llama-bench is not having -dio or -ndio switch. Be default it is now showing mmap = false, direct_io = true. Which is correct combination for me, but I just wanted to report. If you wanted to add these to llama-bench as well. In llama-server and llama-cli it is working fine.

@ggerganov

Copy link
Copy Markdown
Member

llama-bench is not having -dio or -ndio switch. Be default it is now showing mmap = false, direct_io = true.

Do we have a case in which dio = 1 leads to slower inference compared to dio = 0? If not, then, no need to change llama-bench.

@JTischbein

Copy link
Copy Markdown
Contributor Author

@ggerganov So far --no-mmap -dio lead to better performance with some backends, but no perf regression.

With --mmap enabled the CUDA backend shows slower cuda graph launches due to the thread being blocked. With --no-mmap and -dio the thread does not get blocked.

@ggerganov ggerganov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok let's merge after CI

@jukofyork

Copy link
Copy Markdown
Collaborator

Just recompiled today and found this is causing a big performance regression for NUMA on my dual Xeon Gold 6248 system, so might be worth investigating and/or turning off as default for NUMA too:

  • Before this change I got around 7-8 tokens/s generation using Kimi-K2 (with Q4_K MoE tensors off-loaded to CPU) by always dropping caches before loading.
  • I now only get around 1/2 this (~4 tokens/s) and it doesn't appear to be loading the data properly into the NUMA buffers during warmup (ie: dropping caches containing ~500GB after loading is instant now, rather than taking 20-30s before).
  • Adding --no-direct-io gets me back to the original 7-8 tokens/s generation and everything seems to work as before.

Sorry I can't really help much more as at holiday home for next 3 weeks and have 4 young kittens who refuse to let me near the PC! 😼

If it's any help, then here is my script:

#!/bin/bash

host_address=192.168.1.1
port_number=8080

# Turn off NUMA balancing
echo 0 | sudo tee /proc/sys/kernel/numa_balancing > /dev/null

# Ask for permission to drop caches
read -p "Do you want to drop caches? (y/n) " -n 1 -r
echo    # Move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
    echo "Dropping caches..."
    echo 3 | sudo tee /proc/sys/vm/drop_caches > /dev/null
fi

# Run the main command
CUDA_VISIBLE_DEVICES=0 GGML_OP_OFFLOAD_MIN_BATCH=2560 ~/llama.cpp/build/bin/llama-server \
        --host "$host_address" \
        --port "$port_number" \
        --alias "local/kimi-k2-0905" \
        --jinja \
        --model ~/models/gguf/Kimi-K2-Instruct-0905-Q4_X.gguf \
        --n-gpu-layers 99 \
        --no-direct-io \
        --numa distribute \
        --threads "$(nproc)" \
        --override-tensor exps=CPU \
        --flash-attn 1 \
        --parallel 1 \
        --ctx_size 131072 \
        --cache-type-k f16 \
        --cache-type-v q4_0 \
        --batch-size 14336 \
        --ubatch-size 14336 \
        --cache-ram 65536 \
        --temp 0.6 \
        --min-p 0.01

@jukofyork

Copy link
Copy Markdown
Collaborator

Weirdly, it may actually be giving me (a lot) better PP due improved RAM --> PCI-E 3.0 16x --> GPU bandwidth using the new code!? If nvtop is to be believed: I used to only get around 4-5GB/s out of a theoretical maximum of 16GB/s, but now I seem to be getting significantly more.

I will try remote logging in using a tablet and Bluetooth keyboard tomorrow and see if I can run some proper experiments to see if I can figure it out... I suspect that mmap with --numa distribute is somehow loading the model "nicely" for NUMA for TG and the new code is loading the model "nicely" for PCI transfers.

@jukofyork

Copy link
Copy Markdown
Collaborator

It seems to be the NUMA "first-touch" policy causing the problems (the instantaneous drop caches was a red herring and just because it's not getting stored in the usual RAM buffers I think).

It might be worth auto disabling this when using NUMA unless some better way can be found to use at least 1 thread per NUMA node to do the loading?

@jukofyork

Copy link
Copy Markdown
Collaborator

Weirdly, it may actually be giving me (a lot) better PP due improved RAM --> PCI-E 3.0 16x --> GPU bandwidth using the new code!? If nvtop is to be believed: I used to only get around 4-5GB/s out of a theoretical maximum of 16GB/s, but now I seem to be getting significantly more.

Yeah, this doesn't work at all with NUMA as it's putting all the tensors on whatever node the thread is running on and then having to pass everything through the QPI interconnect (around 80GB/s for my Xeon Gold 6248 CPUs). Not sure if it's bypassing NUMA altogether, as even numactl --interleave=all didn't seem to make any difference...

So I went back to using a single NUMA node only and these are the results for Kimi-K2 using Q4_K for offloaded MoE tensors:

  • TG: 7-8 tokens/s --> 6 tokens/s
  • PP: 33 tokens/s --> 17 tokens/s

At first these seemed disappointing, but whatever this PR does to lay the tensors out in RAM means that I can now get way better offload PP to the RTX 6000 Ada GPU:

  • RAM --> PCI-E 3.0 16x --> GPU: 4.7GB/s --> 12.7GB/s

and this now brought the the break-even batch size for GGML_OP_OFFLOAD_MIN_BATCH (see #18535) down from ~2500 tokens to ~650 tokens, and as a result for large prompt ingests I can get 150-200 tokens/s PP with ubatch = 14336 compared to ~75 tokens/s before.


Not had chance to run it yet, but the break-even batch size for GGML_OP_OFFLOAD_MIN_BATCH will reduce further for:

  • Deepseek using 8/256 experts per token.
  • GLM-4-MoE using 8/160 experts per token.
  • Qwen-3-MoE using 8/128 experts per token.

Compared to Kimi-K2 using 8/384 experts per token.

Seunghhon pushed a commit to Seunghhon/llama.cpp that referenced this pull request Apr 26, 2026
* Adding --direct-io flag for model loading

* Fixing read_raw() calls

* Fixing Windows read_raw_at

* Changing type off_t to size_t for windows and Renaming functions

* disable direct io when mmap is explicitly enabled

* Use read_raw_unsafe when upload_backend is available, not functional on some devices with Vulkan and SYCL

* Fallback to std::fread in case O_DIRECT fails due to bad address

* Windows: remove const keywords and unused functions

* Update src/llama-mmap.cpp

Co-authored-by: Georgi Gerganov <[email protected]>

---------

Co-authored-by: jtischbein <[email protected]>
Co-authored-by: Georgi Gerganov <[email protected]>
my-other-github-account pushed a commit to my-other-github-account/llama.cpp that referenced this pull request May 15, 2026
* Adding --direct-io flag for model loading

* Fixing read_raw() calls

* Fixing Windows read_raw_at

* Changing type off_t to size_t for windows and Renaming functions

* disable direct io when mmap is explicitly enabled

* Use read_raw_unsafe when upload_backend is available, not functional on some devices with Vulkan and SYCL

* Fallback to std::fread in case O_DIRECT fails due to bad address

* Windows: remove const keywords and unused functions

* Update src/llama-mmap.cpp

Co-authored-by: Georgi Gerganov <[email protected]>

---------

Co-authored-by: jtischbein <[email protected]>
Co-authored-by: Georgi Gerganov <[email protected]>
fukuro-kun pushed a commit to fukuro-kun/fukuro-llama-cpp-turboquant that referenced this pull request Jul 5, 2026
* Adding --direct-io flag for model loading

* Fixing read_raw() calls

* Fixing Windows read_raw_at

* Changing type off_t to size_t for windows and Renaming functions

* disable direct io when mmap is explicitly enabled

* Use read_raw_unsafe when upload_backend is available, not functional on some devices with Vulkan and SYCL

* Fallback to std::fread in case O_DIRECT fails due to bad address

* Windows: remove const keywords and unused functions

* Update src/llama-mmap.cpp

Co-authored-by: Georgi Gerganov <[email protected]>

---------

Co-authored-by: jtischbein <[email protected]>
Co-authored-by: Georgi Gerganov <[email protected]>
MrLordCat referenced this pull request in MrLordCat/llama.cpp-rdna-lab Jul 16, 2026
* Adding --direct-io flag for model loading

* Fixing read_raw() calls

* Fixing Windows read_raw_at

* Changing type off_t to size_t for windows and Renaming functions

* disable direct io when mmap is explicitly enabled

* Use read_raw_unsafe when upload_backend is available, not functional on some devices with Vulkan and SYCL

* Fallback to std::fread in case O_DIRECT fails due to bad address

* Windows: remove const keywords and unused functions

* Update src/llama-mmap.cpp

Co-authored-by: Georgi Gerganov <[email protected]>

---------

Co-authored-by: jtischbein <[email protected]>
Co-authored-by: Georgi Gerganov <[email protected]>
zommiommy pushed a commit to zommiommy/llama.cpp that referenced this pull request Aug 18, 2026
* Adding --direct-io flag for model loading

* Fixing read_raw() calls

* Fixing Windows read_raw_at

* Changing type off_t to size_t for windows and Renaming functions

* disable direct io when mmap is explicitly enabled

* Use read_raw_unsafe when upload_backend is available, not functional on some devices with Vulkan and SYCL

* Fallback to std::fread in case O_DIRECT fails due to bad address

* Windows: remove const keywords and unused functions

* Update src/llama-mmap.cpp

Co-authored-by: Georgi Gerganov <[email protected]>

---------

Co-authored-by: jtischbein <[email protected]>
Co-authored-by: Georgi Gerganov <[email protected]>
frostyautumnleaf pushed a commit to frostyautumnleaf/llama.cpp that referenced this pull request Oct 5, 2026
* Adding --direct-io flag for model loading

* Fixing read_raw() calls

* Fixing Windows read_raw_at

* Changing type off_t to size_t for windows and Renaming functions

* disable direct io when mmap is explicitly enabled

* Use read_raw_unsafe when upload_backend is available, not functional on some devices with Vulkan and SYCL

* Fallback to std::fread in case O_DIRECT fails due to bad address

* Windows: remove const keywords and unused functions

* Update src/llama-mmap.cpp

Co-authored-by: Georgi Gerganov <[email protected]>

---------

Co-authored-by: jtischbein <[email protected]>
Co-authored-by: Georgi Gerganov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants