Commit 2ed8d0971 for llama.cpp

commit 2ed8d0971bdc7b488dd58d21fd6ce1a0dc2b5737
Author: Aman Gupta <amangupta052@gmail.com>
Date:   Sun Dec 6 11:21:58 2026 +0800

    moe-cache : pipelined direct I/O reads of the uploaded experts (#33698)

diff --git a/common/common.h b/common/common.h
index e5f4fb2af..7e2741c91 100644
--- a/common/common.h
+++ b/common/common.h
@@ -617,8 +617,8 @@ struct common_params {
     ggml_type cache_type_k = GGML_TYPE_F16; // KV cache data type for the K
     ggml_type cache_type_v = GGML_TYPE_F16; // KV cache data type for the V

-    size_t moe_cache_size      = 0;    // GPU cache size in bytes for the MoE experts kept in the CPU, split among the GPUs like the layers
-    float  moe_cache_cpu_share = 0.0f; // share of the MoE cache misses computed on the CPU instead of uploaded
+    size_t moe_cache_size      = 0;     // GPU cache size in bytes for the MoE experts kept in the CPU, split among the GPUs like the layers
+    float  moe_cache_cpu_share = 0.0f;  // share of the MoE cache misses computed on the CPU instead of uploaded

     common_conversation_mode conversation_mode = COMMON_CONVERSATION_MODE_AUTO;

diff --git a/docs/moe-cache.md b/docs/moe-cache.md
index 7491a2a31..c320acb10 100644
--- a/docs/moe-cache.md
+++ b/docs/moe-cache.md
@@ -9,6 +9,8 @@ When the experts of MoE layers stay in host memory (`-cmoe`, `-ncmoe`, `-ot`), t

 The cache hits run on the device. With `--moe-cache-cpu-share F` the CPU computes a share `F` of the misses while the device computes the hits and uploads the other misses into the cache. This is faster when the CPU reads the host experts faster than the device can upload them, for example with fast RAM, a PCIe 4 link or experts that are not in pinned memory. The host experts are pinned with `-lm none`, `-lm mlock` and `-lm dio`, unless `--no-host`, but not when they are mmap'd (the default). The device uploads pinned experts at the full speed of the link, so the CPU share often does not help then. Until the cache is full every miss is uploaded, so the cache fills as fast as without the CPU share. The best share depends on the machine, the model and the cache size.

+When the model does not fit in RAM, the experts that are not in the page cache are read from the disk when they are uploaded. Through mmap, these reads are page faults: the upload takes them one at a time, far below the speed of the disk, and faults from more threads wait on the page cache lock of the model file. So when the mmap'd host experts are more than 1.2 times the available memory (the smaller of the available RAM and the cgroup limit), the MoE cache reads them with direct I/O (`O_DIRECT` on Linux, unbuffered overlapped reads on Windows) on 8 threads into a ring of pinned slots (64 MiB per GPU), and uploads each slot as soon as its read is done, so that the reads overlap the uploads. This applies to the cache misses and to the experts uploaded for large batches (prompt processing), and only to experts that are mmap'd (the default load mode). Closer to the limit, the page cache still holds most of the experts used in decode, so mmap stays faster there. `LLAMA_MOE_CACHE_DIRECT_IO=0` keeps the reads through mmap, `LLAMA_MOE_CACHE_DIRECT_IO=1` uses direct I/O whatever the model size.
+
 ## Picking the arguments

 Put the script in front of your server command:
diff --git a/src/llama-context.cpp b/src/llama-context.cpp
index 54b30f8e2..4485e4436 100644
--- a/src/llama-context.cpp
+++ b/src/llama-context.cpp
@@ -3258,7 +3258,7 @@ bool llama_context::sched_copy_experts(ggml_backend_t backend, const ggml_tensor
                 e++;
                 continue;
             }
-            if (next < e) {
+            if (next < e && !lctx->moe_cache->upload_experts(src, dst, next*expert_size, (e - next)*expert_size)) {
                 ggml_backend_tensor_set_async(backend, dst, (const uint8_t *) src->data + next*expert_size, next*expert_size, (e - next)*expert_size);
             }
             e   += n;
@@ -3269,13 +3269,17 @@ bool llama_context::sched_copy_experts(ggml_backend_t backend, const ggml_tensor
         const size_t offset  = next*expert_size;
         const size_t padding = last < n_expert - 1 ? std::min<size_t>(expert_size, 512) : 0;
         const size_t size    = (last + 1 - next)*expert_size + padding;
-        if (size > 0) {
+        if (size > 0 && !(lctx->moe_cache && lctx->moe_cache->upload_experts(src, dst, offset, size))) {
             ggml_backend_tensor_set_async(backend, dst, (const uint8_t *) src->data + offset, offset, size);
         }

         first = last + 1;
     }

+    if (lctx->moe_cache) {
+        lctx->moe_cache->flush_uploads(backend);
+    }
+
     return true;
 }

diff --git a/src/llama-mmap.cpp b/src/llama-mmap.cpp
index 02e4ede7c..5f158b6af 100644
--- a/src/llama-mmap.cpp
+++ b/src/llama-mmap.cpp
@@ -652,6 +652,8 @@ size_t llama_file::size() const { return pimpl->size; }
 size_t llama_file::read_alignment() const { return pimpl->read_alignment(); }
 bool llama_file::has_direct_io() const { return pimpl->has_direct_io(); }

+const char * llama_file::path() const { return pimpl->fname.c_str(); }
+
 int llama_file::file_id() const {
 #ifdef _WIN32
     return _fileno(pimpl->fp);
diff --git a/src/llama-mmap.h b/src/llama-mmap.h
index 39715bfc3..6f2645ead 100644
--- a/src/llama-mmap.h
+++ b/src/llama-mmap.h
@@ -38,6 +38,7 @@ struct llama_file {
     void write_u32(uint32_t val) const;

     size_t read_alignment() const;
+    const char * path() const;
     bool has_direct_io() const;
 private:
     struct impl;
diff --git a/src/llama-model.cpp b/src/llama-model.cpp
index d2b774709..83c9f9444 100644
--- a/src/llama-model.cpp
+++ b/src/llama-model.cpp
@@ -1478,6 +1478,7 @@ struct llama_model::impl {

     // model memory mapped files
     llama_mmaps mappings;
+    std::vector<std::string> mapping_paths;

     // objects representing data potentially being locked in memory
     llama_mlocks mlock_bufs;
@@ -2175,8 +2176,9 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
     }

     if (use_mmap_buffer) {
-        for (auto & mapping : ml.mappings) {
-            pimpl->mappings.emplace_back(std::move(mapping));
+        for (size_t idx = 0; idx < ml.mappings.size(); idx++) {
+            pimpl->mapping_paths.emplace_back(ml.files.at(idx)->path());
+            pimpl->mappings.emplace_back(std::move(ml.mappings[idx]));
         }
     }

@@ -2627,6 +2629,14 @@ llama_split_mode llama_model::split_mode() const {
     return params.split_mode;
 }

+std::vector<llama_model::mapping> llama_model::get_mappings() const {
+    std::vector<mapping> res;
+    for (size_t i = 0; i < pimpl->mappings.size(); i++) {
+        res.push_back({ pimpl->mapping_paths[i], pimpl->mappings[i]->addr(), pimpl->mappings[i]->size() });
+    }
+    return res;
+}
+
 bool llama_model::no_alloc() const {
     return params.no_alloc;
 }
diff --git a/src/llama-model.h b/src/llama-model.h
index 768e513b6..99509395e 100644
--- a/src/llama-model.h
+++ b/src/llama-model.h
@@ -994,6 +994,14 @@ struct llama_model {
     // list of devices used in this model
     std::vector<llama_device> devices;

+    // the model files memory mapped in host memory
+    struct mapping {
+        std::string  path;
+        const void * addr;
+        size_t       size;
+    };
+    std::vector<mapping> get_mappings() const;
+
     // for quantize-stats only
     std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;

diff --git a/src/llama-moe-cache.cpp b/src/llama-moe-cache.cpp
index db30860ca..709c9c55f 100644
--- a/src/llama-moe-cache.cpp
+++ b/src/llama-moe-cache.cpp
@@ -3,20 +3,38 @@
 #include "llama-graph.h"
 #include "llama-impl.h"
 #include "llama-memory.h"
+#include "llama-mmap.h"
 #include "llama-model.h"

 #include "ggml-cpp.h"

 #include <algorithm>
 #include <array>
+#include <cerrno>
 #include <cmath>
+#include <condition_variable>
 #include <cstdio>
 #include <cstdlib>
 #include <cstring>
+#include <fstream>
+#include <mutex>
+#include <sstream>
 #include <stdexcept>
+#include <thread>
 #include <unordered_map>
 #include <vector>

+#if defined(__linux__)
+#include <unistd.h>
+#elif defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>
+#include <io.h>
+#endif
+
 namespace {

 // ClassLRU: one LRU list per frequency class, over the experts of a group of layers
@@ -322,6 +340,379 @@ static bool llama_moe_cache_is_host_weight(const ggml_tensor * t) {
         ggml_backend_buffer_is_host(t->buffer);
 }

+// memory the page cache of the model files can use: MemAvailable, or less under a cgroup memory limit, 0 if unknown
+static size_t llama_moe_cache_mem_available() {
+#if defined(__linux__)
+    size_t avail = 0;
+    {
+        std::ifstream f("/proc/meminfo");
+        std::string key;
+        size_t kib;
+        std::string unit;
+        while (f >> key >> kib) {
+            std::getline(f, unit);
+            if (key == "MemAvailable:") {
+                avail = kib*1024;
+                break;
+            }
+        }
+    }
+    std::string cg;
+    {
+        std::ifstream f("/proc/self/cgroup");
+        std::string line;
+        while (std::getline(f, line)) {
+            if (line.rfind("0::", 0) == 0) {
+                cg = line.substr(3);
+            }
+        }
+    }
+    auto read_file = [](const std::string & path) {
+        std::ifstream f(path);
+        std::stringstream ss;
+        ss << f.rdbuf();
+        return ss.str();
+    };
+    // the limits of the cgroup and of its parents, the file pages charged to them can be reclaimed
+    while (!cg.empty()) {
+        const std::string dir = "/sys/fs/cgroup" + cg;
+        const std::string max = read_file(dir + "/memory.max");
+        if (!max.empty() && max.rfind("max", 0) != 0) {
+            const size_t limit   = std::strtoull(max.c_str(), nullptr, 10);
+            const size_t current = std::strtoull(read_file(dir + "/memory.current").c_str(), nullptr, 10);
+            size_t file = 0;
+            std::istringstream stat(read_file(dir + "/memory.stat"));
+            std::string key;
+            size_t val;
+            while (stat >> key >> val) {
+                if (key == "file") {
+                    file = val;
+                    break;
+                }
+            }
+            const size_t used     = current > file ? current - file : 0;
+            const size_t cg_avail = limit > used ? limit - used : 0;
+            avail = avail == 0 ? cg_avail : std::min(avail, cg_avail);
+        }
+        const size_t pos = cg.find_last_of('/');
+        cg = pos == std::string::npos || pos == 0 ? "" : cg.substr(0, pos);
+    }
+    return avail;
+#elif defined(_WIN32)
+    MEMORYSTATUSEX st;
+    st.dwLength = sizeof(st);
+    return GlobalMemoryStatusEx(&st) ? (size_t) st.ullAvailPhys : 0;
+#else
+    return 0;
+#endif
+}
+
+// reads host experts from the mmap'd model files with O_DIRECT into a ring of pinned slots, and uploads each slot as soon as its read is done
+// when the model does not fit in RAM, an upload from mmap reads the missing pages one fault at a time, and faults from more threads wait on the page cache lock of the file
+struct moe_cache_reader {
+    struct range {
+        ggml_tensor   * dst;
+        size_t          offs; // in dst
+        const uint8_t * src;  // in a mapping
+        size_t          size;
+    };
+
+    static constexpr int32_t n_threads = 8;
+    static constexpr size_t  slot_size = 2ull*1024*1024; // per read
+    static constexpr int32_t n_slots   = 4*n_threads;    // per device, so that the reads run ahead of the uploads
+
+#ifdef _WIN32
+    using native_file = HANDLE; // opened for overlapped I/O, so that the reads of the threads run concurrently
+#else
+    using native_file = int;
+#endif
+
+    struct file {
+        const uint8_t * addr;
+        size_t size;
+        size_t align;
+        std::unique_ptr<llama_file> f;
+        native_file fd;
+    };
+
+    // a read into a slot and the upload from it
+    struct piece {
+        native_file     fd;
+        size_t          offs;   // aligned
+        size_t          size;   // aligned
+        size_t          n_need; // bytes that must be read, less than size at the end of the file
+        size_t          align;
+        uint8_t       * buf;    // the slot, nullptr if the piece is uploaded from src
+        ggml_tensor   * dst;
+        size_t          dst_offs;
+        const uint8_t * src;
+        size_t          skew;   // of src in buf
+        size_t          n;      // bytes uploaded
+    };
+
+    struct slot {
+        uint8_t            * data;
+        ggml_backend_event_t event; // recorded after the upload from the slot, nullptr if the device has no events
+        bool                 busy;
+    };
+
+    struct stage {
+        ggml_backend_buffer_ptr buf;
+        std::vector<slot> slots;
+        size_t next = 0; // slot of the next piece
+    };
+
+    std::vector<file> files;
+    std::unordered_map<ggml_backend_t, stage> stages;
+    bool   ok    = true; // false after a failed read, then the uploads read through mmap
+    size_t bytes = 0;    // read with direct I/O
+
+    // the workers read pieces[n_taken, n_ready), the calling thread uploads them in order
+    std::vector<std::thread> workers;
+    std::mutex mutex;
+    std::condition_variable cv_work;
+    std::condition_variable cv_done;
+    std::vector<piece>   pieces;
+    std::vector<uint8_t> state; // of each piece: 0 = pending, 1 = read, 2 = failed
+    size_t n_ready = 0;
+    size_t n_taken = 0;
+    bool   stop    = false;
+
+    moe_cache_reader(const llama_model & model, const std::vector<ggml_backend_t> & backends) {
+#if defined(__linux__) || defined(_WIN32)
+        size_t align_max = 1;
+        for (const auto & m : model.get_mappings()) {
+            auto f = std::make_unique<llama_file>(m.path.c_str(), "rb", true);
+            const size_t align = f->read_alignment();
+            if (!f->has_direct_io() || f->size() != m.size || align == 0 || (align & (align - 1)) != 0 || align > slot_size) {
+                LLAMA_LOG_WARN("%s: no direct I/O for %s, its experts are read through mmap\n", __func__, m.path.c_str());
+                continue;
+            }
+#ifdef _WIN32
+            const HANDLE fd = ReOpenFile((HANDLE) _get_osfhandle(f->file_id()), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED);
+            if (fd == INVALID_HANDLE_VALUE) {
+                LLAMA_LOG_WARN("%s: no direct I/O for %s, its experts are read through mmap\n", __func__, m.path.c_str());
+                continue;
+            }
+#else
+            const int fd = f->file_id();
+#endif
+            align_max = std::max(align_max, align);
+            files.push_back({ (const uint8_t *) m.addr, m.size, align, std::move(f), fd });
+        }
+        if (files.empty()) {
+            LLAMA_LOG_WARN("%s: the experts are not mmap'd from the model files, direct I/O is not used\n", __func__);
+            return;
+        }
+        for (ggml_backend_t backend : backends) {
+            ggml_backend_dev_t dev = ggml_backend_get_device(backend);
+            ggml_backend_buffer_type_t buft = ggml_backend_dev_host_buffer_type(dev);
+            ggml_backend_buffer_ptr buf(buft ? ggml_backend_buft_alloc_buffer(buft, n_slots*slot_size) : nullptr);
+            uint8_t * base = buf ? (uint8_t *) ggml_backend_buffer_get_base(buf.get()) : nullptr;
+            if (base == nullptr || (uintptr_t) base % align_max != 0) {
+                LLAMA_LOG_WARN("%s: no pinned buffer for %s, its experts are read through mmap\n", __func__, ggml_backend_name(backend));
+                continue;
+            }
+            stage & st = stages[backend];
+            st.buf = std::move(buf);
+            for (int32_t i = 0; i < n_slots; ++i) {
+                st.slots.push_back({ base + i*slot_size, ggml_backend_event_new(dev), false });
+            }
+        }
+        for (int32_t i = 0; i < n_threads; ++i) {
+            workers.emplace_back([this] { worker(); });
+        }
+        LLAMA_LOG_INFO("%s: reading the uploaded experts with direct I/O, %d threads, %d pinned slots of %zu MiB per device\n", __func__, n_threads, n_slots, slot_size/1024/1024);
+#else
+        GGML_UNUSED(model);
+        GGML_UNUSED(backends);
+        GGML_UNUSED(n_slots);
+        LLAMA_LOG_WARN("%s: direct I/O is not supported on this platform, the experts are read through mmap\n", __func__);
+#endif
+    }
+
+    ~moe_cache_reader() {
+        {
+            std::lock_guard<std::mutex> lock(mutex);
+            stop = true;
+        }
+        cv_work.notify_all();
+        for (auto & t : workers) {
+            t.join();
+        }
+        // the backends may already be freed, the events belong to the devices
+        for (auto & [backend, st] : stages) {
+            for (slot & s : st.slots) {
+                if (s.event) {
+                    if (s.busy) {
+                        ggml_backend_event_synchronize(s.event);
+                    }
+                    ggml_backend_event_free(s.event);
+                }
+            }
+        }
+#ifdef _WIN32
+        for (const file & f : files) {
+            CloseHandle(f.fd);
+        }
+#endif
+    }
+
+    const file * find(const uint8_t * p, size_t size) const {
+        for (const file & f : files) {
+            if (p >= f.addr && p + size <= f.addr + f.size) {
+                return &f;
+            }
+        }
+        return nullptr;
+    }
+
+    // a short read continues at an aligned offset
+    static bool read_piece(const piece & p) {
+#if defined(__linux__) || defined(_WIN32)
+        size_t done = 0;
+        while (done < p.n_need) {
+#ifdef _WIN32
+            const uint64_t offs = p.offs + done;
+            OVERLAPPED ov = {};
+            ov.Offset     = (DWORD) offs;
+            ov.OffsetHigh = (DWORD) (offs >> 32);
+            ov.hEvent     = CreateEventW(nullptr, TRUE, FALSE, nullptr);
+            if (ov.hEvent == nullptr) {
+                return false;
+            }
+            DWORD n = 0;
+            const bool res = (ReadFile(p.fd, p.buf + done, (DWORD) (p.size - done), nullptr, &ov) || GetLastError() == ERROR_IO_PENDING) &&
+                GetOverlappedResult(p.fd, &ov, &n, TRUE);
+            CloseHandle(ov.hEvent);
+            if (!res || n == 0) {
+                return false;
+            }
+#else
+            const ssize_t n = pread(p.fd, p.buf + done, p.size - done, (off_t) (p.offs + done));
+            if (n < 0 && errno == EINTR) {
+                continue;
+            }
+            if (n <= 0) {
+                return false;
+            }
+#endif
+            if (done + (size_t) n >= p.n_need) {
+                break;
+            }
+            const size_t next = (done + (size_t) n) & ~(p.align - 1);
+            if (next <= done) {
+                return false;
+            }
+            done = next;
+        }
+        return true;
+#else
+        GGML_UNUSED(p);
+        return false;
+#endif
+    }
+
+    void worker() {
+        std::unique_lock<std::mutex> lock(mutex);
+        for (;;) {
+            cv_work.wait(lock, [this] { return stop || n_taken < n_ready; });
+            if (stop) {
+                return;
+            }
+            const size_t i = n_taken++;
+            const piece p = pieces[i];
+            lock.unlock();
+            const bool res = read_piece(p);
+            lock.lock();
+            state[i] = res ? 1 : 2;
+            cv_done.notify_all();
+        }
+    }
+
+    // the ranges outside of the mappings with direct I/O are uploaded from their source
+    void upload(ggml_backend_t backend, const std::vector<range> & ranges) {
+        const auto it = stages.find(backend);
+        if (!ok || it == stages.end()) {
+            for (const range & r : ranges) {
+                ggml_backend_tensor_set_async(backend, r.dst, r.src, r.offs, r.size);
+            }
+            return;
+        }
+        stage & st = it->second;
+
+        // the workers are idle between uploads
+        pieces.clear();
+        for (const range & r : ranges) {
+            const file * f = find(r.src, r.size);
+            if (f == nullptr) {
+                ggml_backend_tensor_set_async(backend, r.dst, r.src, r.offs, r.size);
+                continue;
+            }
+            for (size_t done = 0; done < r.size; ) {
+                const size_t offs   = (r.src - f->addr) + done;
+                const size_t skew   = offs & (f->align - 1);
+                const size_t n      = std::min(r.size - done, slot_size - skew);
+                const size_t n_read = GGML_PAD(skew + n, f->align);
+                const size_t start  = offs - skew;
+                pieces.push_back({ f->fd, start, n_read, std::min(n_read, f->size - start), f->align, nullptr, r.dst, r.offs + done, r.src + done, skew, n });
+                done += n;
+            }
+        }
+        {
+            std::lock_guard<std::mutex> lock(mutex);
+            state.assign(pieces.size(), 0);
+            n_ready = 0;
+            n_taken = 0;
+        }
+
+        // keep up to n_slots reads in flight, a slot is reused once the upload from it is done
+        size_t n_disp = 0;
+        for (size_t i = 0; i < pieces.size(); ++i) {
+            while (ok && n_disp < pieces.size() && n_disp < i + st.slots.size()) {
+                slot & s = st.slots[(st.next + n_disp) % st.slots.size()];
+                if (s.busy) {
+                    if (s.event) {
+                        ggml_backend_event_synchronize(s.event);
+                    } else {
+                        ggml_backend_synchronize(backend);
+                    }
+                    s.busy = false;
+                }
+                pieces[n_disp].buf = s.data;
+                {
+                    std::lock_guard<std::mutex> lock(mutex);
+                    n_ready = ++n_disp;
+                }
+                cv_work.notify_one();
+            }
+
+            const piece & p = pieces[i];
+            if (p.buf != nullptr) {
+                std::unique_lock<std::mutex> lock(mutex);
+                cv_done.wait(lock, [&] { return state[i] != 0; });
+                if (state[i] == 2 && ok) {
+                    LLAMA_LOG_WARN("%s: direct I/O read failed, reading the experts through mmap from now on\n", __func__);
+                    ok = false;
+                }
+            }
+            if (p.buf != nullptr && state[i] == 1) {
+                ggml_backend_tensor_set_async(backend, p.dst, p.buf + p.skew, p.dst_offs, p.n);
+                slot & s = st.slots[(st.next + i) % st.slots.size()];
+                if (s.event) {
+                    ggml_backend_event_record(s.event, backend);
+                }
+                s.busy = true;
+                bytes += p.n;
+            } else {
+                ggml_backend_tensor_set_async(backend, p.dst, p.src, p.dst_offs, p.n);
+            }
+        }
+
+        st.next = (st.next + n_disp) % st.slots.size();
+    }
+};
+
 }

 struct llama_moe_cache::impl {
@@ -400,6 +791,9 @@ struct llama_moe_cache::impl {
     uint32_t cpu_share_q = 0; // cpu_share in 1/65536, integer so that a simulator can reproduce the rounding
     int32_t  n_zero    = 0; // zero slots per group

+    std::unique_ptr<moe_cache_reader> reader;
+    std::vector<moe_cache_reader::range> uploads;
+
     // LLAMA_MOE_CACHE_TRACE: the selected experts of each slot lookup, for a simulator of the cache
     FILE * trace = nullptr;

@@ -712,6 +1106,48 @@ struct llama_moe_cache::impl {
         }
         ggml_backend_buffer_set_usage(buf_host.get(), GGML_BACKEND_BUFFER_USAGE_WEIGHTS);

+        // when the mmap'd experts do not fit in the page cache, read the uploaded experts with direct I/O
+        // close to the limit the page cache still serves most of the misses after the first batches, so mmap stays faster in decode
+        // LLAMA_MOE_CACHE_DIRECT_IO=0/1 turns it off/on
+        size_t mapped = 0;
+        {
+            const auto mappings = model.get_mappings();
+            for (const layer & l : layers) {
+                for (const ggml_tensor * t : l.experts) {
+                    const uint8_t * data = (const uint8_t *) t->data;
+                    for (const auto & m : mappings) {
+                        if (data >= (const uint8_t *) m.addr && data + ggml_nbytes(t) <= (const uint8_t *) m.addr + m.size) {
+                            mapped += ggml_nbytes(t);
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        const char * env_direct_io = getenv("LLAMA_MOE_CACHE_DIRECT_IO");
+        const size_t mem_avail     = mapped > 0 ? llama_moe_cache_mem_available() : 0;
+        bool direct_io = mem_avail > 0 && (double) mapped > 1.2*(double) mem_avail;
+        if (env_direct_io != nullptr && *env_direct_io != '\0') {
+            direct_io = atoi(env_direct_io) != 0;
+        }
+        if (mapped > 0 && !no_alloc) {
+            LLAMA_LOG_INFO("%s: %.2f GiB of mmap'd host experts, %.2f GiB of memory available, direct I/O %s%s\n", __func__,
+                mapped/1024.0/1024.0/1024.0, mem_avail/1024.0/1024.0/1024.0, direct_io ? "on" : "off",
+                env_direct_io != nullptr && *env_direct_io != '\0' ? " (LLAMA_MOE_CACHE_DIRECT_IO)" : "");
+        }
+        if (direct_io && mapped > 0 && !no_alloc) {
+            std::vector<ggml_backend_t> cache_backends;
+            for (const device & d : devices) {
+                if (d.host_bytes > 0) {
+                    cache_backends.push_back(d.backend);
+                }
+            }
+            reader = std::make_unique<moe_cache_reader>(model, cache_backends);
+            if (reader->stages.empty()) {
+                reader.reset();
+            }
+        }
+
         for (size_t id = 0; id < devices.size(); ++id) {
             const device & d = devices[id];
             if (d.host_bytes == 0) {
@@ -944,7 +1380,12 @@ struct llama_moe_cache::impl {
                 while (i + n < fills.size() && fills[i + n].expert == fills[i].expert + (int32_t) n && fills[i + n].slot == fills[i].slot + (int32_t) n) {
                     n++;
                 }
-                ggml_backend_tensor_set_async(backend, bank, (const uint8_t *) w->data + fills[i].expert*expert_size, fills[i].slot*expert_size, n*expert_size);
+                const uint8_t * src = (const uint8_t *) w->data + fills[i].expert*expert_size;
+                if (reader) {
+                    uploads.push_back({ bank, fills[i].slot*expert_size, src, n*expert_size });
+                } else {
+                    ggml_backend_tensor_set_async(backend, bank, src, fills[i].slot*expert_size, n*expert_size);
+                }
                 bytes += n*expert_size;
                 for (int k = 0; k < LLAMA_MOE_CACHE_SCALE_COUNT; ++k) {
                     if (ggml_tensor * scale_bank = g.scale_banks[ip][k]) {
@@ -958,6 +1399,11 @@ struct llama_moe_cache::impl {
             }
         }

+        if (!uploads.empty()) {
+            reader->upload(backend, uploads);
+            uploads.clear();
+        }
+
         stats & st = ids.size() <= (size_t) 8*n_expert_used ? stats_small : stats_large;
         st.hits   += n_hit;
         st.misses += fills.size() + cpu.size();
@@ -984,6 +1430,9 @@ struct llama_moe_cache::impl {
         if (stats_copy.hits > 0) {
             LLAMA_LOG_INFO("llama_moe_cache: large batches: %zu experts copied from the cache, %.2f MiB\n", stats_copy.hits, stats_copy.bytes/1024.0/1024.0);
         }
+        if (reader) {
+            LLAMA_LOG_INFO("llama_moe_cache: direct I/O: %.2f MiB read%s\n", reader->bytes/1024.0/1024.0, reader->ok ? "" : ", disabled after a failed read");
+        }
     }
 };

@@ -1087,6 +1536,21 @@ int64_t llama_moe_cache::copy_experts(ggml_backend_t backend, const ggml_tensor
     return pimpl->copy_experts(backend, w, dst, e, last);
 }

+bool llama_moe_cache::upload_experts(const ggml_tensor * w, ggml_tensor * dst, size_t offset, size_t size) {
+    if (!pimpl->reader) {
+        return false;
+    }
+    pimpl->uploads.push_back({ dst, offset, (const uint8_t *) w->data + offset, size });
+    return true;
+}
+
+void llama_moe_cache::flush_uploads(ggml_backend_t backend) {
+    if (!pimpl->uploads.empty()) {
+        pimpl->reader->upload(backend, pimpl->uploads);
+        pimpl->uploads.clear();
+    }
+}
+
 std::map<ggml_backend_buffer_type_t, size_t> llama_moe_cache::memory_breakdown() const {
     std::map<ggml_backend_buffer_type_t, size_t> res;
     for (const auto & d : pimpl->devices) {
@@ -1097,5 +1561,10 @@ std::map<ggml_backend_buffer_type_t, size_t> llama_moe_cache::memory_breakdown()
     if (pimpl->buf_host) {
         res[ggml_backend_buffer_get_type(pimpl->buf_host.get())] += pimpl->buf_host_size;
     }
+    if (pimpl->reader) {
+        for (const auto & [backend, st] : pimpl->reader->stages) {
+            res[ggml_backend_buffer_get_type(st.buf.get())] += ggml_backend_buffer_get_size(st.buf.get());
+        }
+    }
     return res;
 }
diff --git a/src/llama-moe-cache.h b/src/llama-moe-cache.h
index e2e9adad5..85e49d47d 100644
--- a/src/llama-moe-cache.h
+++ b/src/llama-moe-cache.h
@@ -42,6 +42,7 @@ class llama_moe_cache {
 public:
     // backends are all the backends of the context, each GPU gets its own cache of the given size for the layers assigned to it
     // cpu_share is the share of the misses computed on the CPU instead of uploaded
+    // when the mmap'd experts do not fit in the RAM, the uploaded experts are read from the model files with direct I/O instead of through mmap
     llama_moe_cache(const llama_model & model, bool no_alloc, const std::vector<ggml_backend_t> & backends, const std::vector<ggml_backend_buffer_type_t> & bufts, size_t size, float cpu_share);
     ~llama_moe_cache();

@@ -69,6 +70,13 @@ public:
     // returns the number of experts copied, 0 if expert e is not in the cache
     int64_t copy_experts(ggml_backend_t backend, const ggml_tensor * w, ggml_tensor * dst, int64_t e, int64_t last);

+    // for large batches: queue an upload of size bytes at offset of the host experts w to the copy dst of w with direct I/O
+    // returns false if direct I/O is not enabled
+    bool upload_experts(const ggml_tensor * w, ggml_tensor * dst, size_t offset, size_t size);
+
+    // issue the queued uploads, so that the reads of all of them are pipelined with their uploads
+    void flush_uploads(ggml_backend_t backend);
+
     std::map<ggml_backend_buffer_type_t, size_t> memory_breakdown() const;

 private: