Author SHA1 Message Date
Owen Qwen d5458aa44e Add portable CPU longhaul support 2026-07-30 16:59:40 -05:00
20 changed files with 304 additions and 1308 deletions
+1 -1
View File
@@ -2631,7 +2631,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
).set_env("LLAMA_ARG_LOAD_MODE")); ).set_env("LLAMA_ARG_LOAD_MODE"));
add_opt(common_arg( add_opt(common_arg(
{"--longhaul"}, {"--longhaul"},
"stream routed Qwen3.5 MoE experts through a bounded Metal cache", "stream routed Qwen3.5 MoE or Laguna experts through a bounded CPU or Metal cache",
[](common_params & params) { [](common_params & params) {
params.load_mode = LLAMA_LOAD_MODE_LONGHAUL; params.load_mode = LLAMA_LOAD_MODE_LONGHAUL;
} }
+29 -43
View File
@@ -11,45 +11,16 @@ llama-cli \
--model /path/to/model.gguf \ --model /path/to/model.gguf \
--longhaul \ --longhaul \
--longhaul-cache 2 \ --longhaul-cache 2 \
--n-gpu-layers 99 --n-gpu-layers 0
``` ```
`--longhaul-cache` is the expert cache budget in GiB. It is required when `--longhaul` is used. The same options are accepted by `llama-server`. `--longhaul-cache` is the expert cache budget in GiB. It is required when `--longhaul` is used. The same options are accepted by `llama-server`.
## RPC mode The command above runs every repeating layer on CPU and is supported on macOS,
Linux, and Windows. On macOS, the existing all-Metal mode remains available by
RPC longhaul keeps the paging loop on the accelerator host so expert payloads do using `--n-gpu-layers 99` instead. Longhaul does not silently change device
not cross the network during generation. Build both hosts with `-DGGML_RPC=ON`. placement: an unsupported GPU or mixed CPU/GPU repeating-layer placement fails
Place the same GGUF shard files on both hosts, preserving their basenames, then with guidance to use `--n-gpu-layers 0`.
start the Metal host with the directory containing those shards:
```sh
ggml-rpc-server \
--device MTL0 \
--longhaul-root /path/to/model-directory \
--host 192.168.1.20
```
Start the client normally:
```sh
llama-server \
--model /local/path/model.gguf \
--rpc 192.168.1.20:50052 \
--longhaul \
--longhaul-cache 2 \
--n-gpu-layers 99
```
RPC longhaul currently requires all repeating layers on one remote Metal device.
The server validates each shard basename, size, GGUF metadata layout digest, and
every registered expert range before decoding. An older server, a server without
`--longhaul-root`, or a shard mismatch is a fatal model-load error; the client
does not fall back to sending expert slices over RPC.
`--longhaul-root` grants connected RPC clients read access to registered byte
ranges in files in that directory. The RPC server remains experimental and
insecure and must not be exposed to an untrusted network.
Longhaul may reduce `--ubatch-size` so that every expert selected by one graph segment can be present in the cache at the same time. The effective value is logged during context creation. If one token selects more experts than the cache has slots, the routed MoE computation is split into multiple stages and the partial results are summed. This permits smaller caches at the cost of additional graph work. Longhaul may reduce `--ubatch-size` so that every expert selected by one graph segment can be present in the cache at the same time. The effective value is logged during context creation. If one token selects more experts than the cache has slots, the routed MoE computation is split into multiple stages and the partial results are summed. This permits smaller caches at the cost of additional graph work.
@@ -59,23 +30,38 @@ The normal startup warmup is skipped automatically in longhaul mode. Routed expe
Longhaul currently requires: Longhaul currently requires:
- the Metal backend, either local on macOS or on one RPC host - all repeating layers on CPU, or all repeating layers on Metal
- Qwen3.5 MoE or Laguna architecture - Qwen3.5 MoE or Laguna architecture
- all repeating model layers assigned to local Metal or one RPC Metal device
- text generation without embeddings or LoRA adapters - text generation without embeddings or LoRA adapters
Longhaul does not restrict the GGUF quantization type. Individual tensor types must still be supported by Metal. CPU mode is available wherever the CPU backend is supported. Metal mode requires
macOS. Longhaul does not restrict the GGUF quantization type; individual tensor
types must still be supported by the selected compute backend.
MTP/speculative decoding, tensor validation during loading, vocabulary-only loading, and CPU or mixed CPU/Metal layer placement are not supported. Both single-file and split GGUF models are supported; routed expert tensors are read from the shard that owns each tensor. MTP/speculative decoding, tensor validation during loading, vocabulary-only
loading, and mixed CPU/GPU repeating-layer placement are not supported. Both
single-file and split GGUF models are supported; routed expert tensors are read
from the shard that owns each tensor.
The cache budget covers the compact routed-expert tensors. It does not include dense weights, attention weights, the KV cache, graph allocations, or the temporary buffer used for one expert read. Disk reads bypass the macOS unified file cache where supported, avoiding a second long-lived copy of streamed weights in system RAM. The cache budget covers the compact routed-expert tensors. It does not include
dense weights, attention weights, the KV cache, graph allocations, or temporary
staging buffers. CPU expert caches use the standard directly writable tensor
layout so individual slots can be replaced; optimized CPU buffer selection
continues to apply to all non-streamed weights.
File-cache control is best effort and is outside the explicit cache budget.
macOS disables caching for streamed files where supported, and Linux advises the
kernel to discard completed reads. Windows may retain file data in its system
cache. Windows reads from one GGUF shard are serialized to preserve positional
read correctness, while POSIX systems retain concurrent `pread` operations.
This implementation synchronizes at each routed MoE layer to discover the selected experts, populate missing cache slots, and continue execution with cache-local expert IDs. Storage speed and expert reuse therefore have a large effect on generation speed. This implementation synchronizes at each routed MoE layer to discover the selected experts, populate missing cache slots, and continue execution with cache-local expert IDs. Storage speed and expert reuse therefore have a large effect on generation speed.
Expert IDs are planned as a batch at each synchronization point. Experts already Expert IDs are planned as a batch at each synchronization point. Experts already
needed by that batch are protected from eviction, duplicate IDs are loaded only needed by that batch are protected from eviction, duplicate IDs are loaded only
once, and independent expert slices are read concurrently on shared-memory Metal once, and independent expert slices are read concurrently where the platform
devices. Private Metal buffers use a staged fallback. supports positional reads. CPU and shared Metal buffers are populated directly;
private Metal buffers use a staged fallback.
## Benchmarking prompt processing ## Benchmarking prompt processing
@@ -86,7 +72,7 @@ llama-bench \
--model /path/to/model.gguf \ --model /path/to/model.gguf \
--load-mode longhaul \ --load-mode longhaul \
--longhaul-cache 2 \ --longhaul-cache 2 \
--n-gpu-layers 99 \ --n-gpu-layers 0 \
--n-prompt 2048 \ --n-prompt 2048 \
--n-gen 0 --n-gen 0
``` ```
+1 -44
View File
@@ -8,7 +8,7 @@ extern "C" {
#define RPC_PROTO_MAJOR_VERSION 4 #define RPC_PROTO_MAJOR_VERSION 4
#define RPC_PROTO_MINOR_VERSION 0 #define RPC_PROTO_MINOR_VERSION 0
#define RPC_PROTO_PATCH_VERSION 4 #define RPC_PROTO_PATCH_VERSION 3
#ifdef __cplusplus #ifdef __cplusplus
static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION");
@@ -27,49 +27,6 @@ GGML_BACKEND_API void ggml_backend_rpc_get_device_memory(const char * endpoint,
GGML_BACKEND_API void ggml_backend_rpc_start_server(const char * endpoint, const char * cache_dir, GGML_BACKEND_API void ggml_backend_rpc_start_server(const char * endpoint, const char * cache_dir,
size_t n_threads, size_t n_devices, ggml_backend_dev_t * devices); size_t n_threads, size_t n_devices, ggml_backend_dev_t * devices);
struct ggml_backend_rpc_longhaul_shard {
const char * name;
uint64_t size;
uint64_t metadata_size;
uint8_t metadata_sha256[32];
};
struct ggml_backend_rpc_longhaul_source {
struct ggml_tensor * tensor;
uint32_t shard;
uint64_t offset;
uint64_t expert_size;
int32_t layer;
};
struct ggml_backend_rpc_longhaul_params {
uint32_t n_layers;
uint32_t n_experts;
uint32_t n_slots;
size_t n_shards;
const struct ggml_backend_rpc_longhaul_shard * shards;
size_t n_sources;
const struct ggml_backend_rpc_longhaul_source * sources;
};
GGML_BACKEND_API bool ggml_backend_rpc_longhaul_register(
const struct ggml_backend_rpc_longhaul_params * params,
uint64_t * registration_id,
char * error,
size_t error_size);
GGML_BACKEND_API void ggml_backend_rpc_longhaul_unregister(
struct ggml_tensor * tensor,
uint64_t registration_id);
GGML_BACKEND_API void ggml_backend_rpc_start_server_with_options(
const char * endpoint,
const char * cache_dir,
const char * longhaul_root,
size_t n_threads,
size_t n_devices,
ggml_backend_dev_t * devices);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_rpc_reg(void); GGML_BACKEND_API ggml_backend_reg_t ggml_backend_rpc_reg(void);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_rpc_add_server(const char * endpoint); GGML_BACKEND_API ggml_backend_reg_t ggml_backend_rpc_add_server(const char * endpoint);
File diff suppressed because it is too large Load Diff
+3 -5
View File
@@ -1359,12 +1359,10 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll
res->reset(); res->reset();
ggml_backend_sched_reset(sched.get()); ggml_backend_sched_reset(sched.get());
auto * longhaul = model.longhaul_cache();
const bool local_longhaul = longhaul && !longhaul->is_remote();
ggml_backend_sched_set_eval_callback( ggml_backend_sched_set_eval_callback(
sched.get(), sched.get(),
local_longhaul ? longhaul_eval_callback : cparams.cb_eval, model.longhaul_cache() ? longhaul_eval_callback : cparams.cb_eval,
local_longhaul ? this : cparams.cb_eval_user_data); model.longhaul_cache() ? this : cparams.cb_eval_user_data);
//const auto t_start_us = ggml_time_us(); //const auto t_start_us = ggml_time_us();
@@ -2463,7 +2461,7 @@ llm_graph_params llama_context::graph_params(
bool llama_context::longhaul_eval_callback(ggml_tensor * tensor, bool ask, void * user_data) { bool llama_context::longhaul_eval_callback(ggml_tensor * tensor, bool ask, void * user_data) {
auto * ctx = static_cast<llama_context *>(user_data); auto * ctx = static_cast<llama_context *>(user_data);
auto * cache = ctx->model.longhaul_cache(); auto * cache = ctx->model.longhaul_cache();
GGML_ASSERT(cache != nullptr && !cache->is_remote()); GGML_ASSERT(cache != nullptr);
int layer = -1; int layer = -1;
const bool remap = sscanf(tensor->name, "longhaul.remap.%d", &layer) == 1; const bool remap = sscanf(tensor->name, "longhaul.remap.%d", &layer) == 1;
+2 -102
View File
@@ -1,108 +1,23 @@
#include "llama-longhaul.h" #include "llama-longhaul.h"
#include "llama-impl.h" #include "llama-impl.h"
#include "llama-token-cache.h"
#include "ggml-rpc.h"
#include <algorithm> #include <algorithm>
#include <array>
#include <cstring> #include <cstring>
#include <inttypes.h> #include <inttypes.h>
#include <stdexcept>
llama_longhaul_cache::llama_longhaul_cache( llama_longhaul_cache::llama_longhaul_cache(
llama_files files, llama_files files,
std::vector<llama_model_loader::longhaul_source> sources, std::vector<llama_model_loader::longhaul_source> sources,
std::vector<llama_model_loader::longhaul_shard> shards,
size_t n_slots, size_t n_slots,
uint32_t n_experts, uint32_t n_experts,
uint32_t n_layers, uint32_t n_layers) :
bool remote) :
files(std::move(files)), files(std::move(files)),
sources(std::move(sources)), sources(std::move(sources)),
shards(std::move(shards)),
sources_by_layer(n_layers), sources_by_layer(n_layers),
layers(n_layers), layers(n_layers),
n_slots(n_slots), n_slots(n_slots),
n_experts(n_experts), n_experts(n_experts) {
remote(remote) {
if (remote) {
if (this->shards.size() != this->files.size() || this->sources.empty()) {
throw std::runtime_error("RPC longhaul requires named GGUF shards");
}
std::vector<std::array<uint8_t, 32>> digests(this->shards.size());
std::vector<ggml_backend_rpc_longhaul_shard> rpc_shards(this->shards.size());
for (size_t i = 0; i < this->shards.size(); ++i) {
const auto & shard = this->shards[i];
if (shard.metadata_size > shard.size) {
throw std::runtime_error("invalid RPC longhaul shard metadata range");
}
std::vector<uint8_t> metadata(shard.metadata_size);
if (!metadata.empty()) {
this->files[i]->read_at(metadata.data(), metadata.size(), 0);
}
const std::string hex = llama_token_cache_hash(metadata.data(), metadata.size());
if (hex.size() != 64) {
throw std::runtime_error("failed to fingerprint RPC longhaul shard");
}
for (size_t j = 0; j < digests[i].size(); ++j) {
auto nibble = [](char c) -> uint8_t {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return 0xff;
};
const uint8_t hi = nibble(hex[2*j]);
const uint8_t lo = nibble(hex[2*j + 1]);
if (hi > 0x0f || lo > 0x0f) {
throw std::runtime_error("invalid RPC longhaul shard fingerprint");
}
digests[i][j] = (hi << 4) | lo;
}
rpc_shards[i] = {
shard.name.c_str(),
shard.size,
shard.metadata_size,
{},
};
memcpy(rpc_shards[i].metadata_sha256, digests[i].data(), digests[i].size());
}
std::vector<ggml_backend_rpc_longhaul_source> rpc_sources;
rpc_sources.reserve(this->sources.size());
for (const auto & source : this->sources) {
rpc_sources.push_back({
source.tensor,
source.file_idx,
source.offset,
source.expert_size,
source.layer,
});
}
ggml_backend_rpc_longhaul_params params = {
n_layers,
n_experts,
(uint32_t) n_slots,
rpc_shards.size(),
rpc_shards.data(),
rpc_sources.size(),
rpc_sources.data(),
};
ggml_backend_reg_t reg = ggml_backend_reg_by_name("RPC");
auto register_fn = reg ? (decltype(ggml_backend_rpc_longhaul_register) *)
ggml_backend_reg_get_proc_address(reg, "ggml_backend_rpc_longhaul_register") : nullptr;
if (!register_fn) {
throw std::runtime_error("RPC backend does not expose longhaul registration");
}
char error[256] = {};
if (!register_fn(&params, &remote_registration_id, error, sizeof(error))) {
throw std::runtime_error(error[0] ? error : "RPC longhaul registration failed");
}
this->files.clear();
return;
}
for (auto & file : this->files) { for (auto & file : this->files) {
file->set_no_cache(); file->set_no_cache();
} }
@@ -130,17 +45,6 @@ llama_longhaul_cache::llama_longhaul_cache(
} }
llama_longhaul_cache::~llama_longhaul_cache() { llama_longhaul_cache::~llama_longhaul_cache() {
if (remote) {
if (!sources.empty() && remote_registration_id != 0) {
ggml_backend_reg_t reg = ggml_backend_reg_by_name("RPC");
auto unregister_fn = reg ? (decltype(ggml_backend_rpc_longhaul_unregister) *)
ggml_backend_reg_get_proc_address(reg, "ggml_backend_rpc_longhaul_unregister") : nullptr;
if (unregister_fn) {
unregister_fn(sources.front().tensor, remote_registration_id);
}
}
return;
}
{ {
std::lock_guard<std::mutex> lock(io_mutex); std::lock_guard<std::mutex> lock(io_mutex);
io_stopping = true; io_stopping = true;
@@ -417,7 +321,3 @@ uint64_t llama_longhaul_cache::misses() const {
uint64_t llama_longhaul_cache::bytes_read_count() const { uint64_t llama_longhaul_cache::bytes_read_count() const {
return bytes_read; return bytes_read;
} }
bool llama_longhaul_cache::is_remote() const {
return remote;
}
+1 -7
View File
@@ -17,11 +17,9 @@ struct llama_longhaul_cache {
llama_longhaul_cache( llama_longhaul_cache(
llama_files files, llama_files files,
std::vector<llama_model_loader::longhaul_source> sources, std::vector<llama_model_loader::longhaul_source> sources,
std::vector<llama_model_loader::longhaul_shard> shards,
size_t n_slots, size_t n_slots,
uint32_t n_experts, uint32_t n_experts,
uint32_t n_layers, uint32_t n_layers);
bool remote);
~llama_longhaul_cache(); ~llama_longhaul_cache();
bool remap(int layer, ggml_tensor * ids); bool remap(int layer, ggml_tensor * ids);
@@ -33,7 +31,6 @@ struct llama_longhaul_cache {
bool failed() const; bool failed() const;
uint64_t misses() const; uint64_t misses() const;
uint64_t bytes_read_count() const; uint64_t bytes_read_count() const;
bool is_remote() const;
private: private:
struct layer_state { struct layer_state {
@@ -52,7 +49,6 @@ private:
llama_files files; llama_files files;
std::vector<llama_model_loader::longhaul_source> sources; std::vector<llama_model_loader::longhaul_source> sources;
std::vector<llama_model_loader::longhaul_shard> shards;
std::vector<std::vector<const llama_model_loader::longhaul_source *>> sources_by_layer; std::vector<std::vector<const llama_model_loader::longhaul_source *>> sources_by_layer;
std::vector<layer_state> layers; std::vector<layer_state> layers;
size_t n_slots; size_t n_slots;
@@ -88,8 +84,6 @@ private:
std::condition_variable io_done; std::condition_variable io_done;
size_t io_pending = 0; size_t io_pending = 0;
bool io_stopping = false; bool io_stopping = false;
bool remote = false;
uint64_t remote_registration_id = 0;
bool source_is_direct(const llama_model_loader::longhaul_source & source) const; bool source_is_direct(const llama_model_loader::longhaul_source & source) const;
bool load_plan_sources(); bool load_plan_sources();
+22
View File
@@ -9,6 +9,7 @@
#include <stdexcept> #include <stdexcept>
#include <cerrno> #include <cerrno>
#include <algorithm> #include <algorithm>
#include <mutex>
#ifdef __has_include #ifdef __has_include
#if __has_include(<unistd.h>) #if __has_include(<unistd.h>)
@@ -66,8 +67,12 @@ static std::string llama_format_win_err(DWORD err) {
// llama_file // llama_file
struct llama_file::impl { struct llama_file::impl {
bool no_cache = false;
#if defined(_WIN32) #if defined(_WIN32)
HANDLE fp_win32; HANDLE fp_win32;
std::mutex read_at_mutex;
std::string GetErrorMessageWin32(DWORD error_code) const { std::string GetErrorMessageWin32(DWORD error_code) const {
std::string ret; std::string ret;
LPSTR lpMsgBuf = NULL; LPSTR lpMsgBuf = NULL;
@@ -433,6 +438,10 @@ void llama_file::read_raw_unsafe(void * ptr, size_t len) { pimpl->read_raw_unsaf
void llama_file::read_at(void * ptr, size_t len, size_t offset) { void llama_file::read_at(void * ptr, size_t len, size_t offset) {
#ifdef _WIN32 #ifdef _WIN32
// The Windows FILE pointer is shared by all longhaul I/O workers. Keep the
// seek and read together so concurrent jobs cannot change each other's
// offsets. POSIX uses pread below and does not need this serialization.
std::lock_guard<std::mutex> lock(pimpl->read_at_mutex);
seek(offset, SEEK_SET); seek(offset, SEEK_SET);
read_raw(ptr, len); read_raw(ptr, len);
#else #else
@@ -448,6 +457,13 @@ void llama_file::read_at(void * ptr, size_t len, size_t offset) {
} }
n_read += result; n_read += result;
} }
#if defined(__linux__) && defined(POSIX_FADV_DONTNEED)
if (pimpl->no_cache) {
// Longhaul owns a bounded expert cache, so avoid retaining a second
// long-lived copy of completed reads in the kernel page cache.
(void) posix_fadvise(file_id(), (off_t) offset, (off_t) len, POSIX_FADV_DONTNEED);
}
#endif
#endif #endif
} }
@@ -456,6 +472,12 @@ void llama_file::set_no_cache() const {
if (fcntl(file_id(), F_NOCACHE, 1) != 0) { if (fcntl(file_id(), F_NOCACHE, 1) != 0) {
throw std::runtime_error(format("failed to disable file cache: %s", strerror(errno))); throw std::runtime_error(format("failed to disable file cache: %s", strerror(errno)));
} }
#elif defined(__linux__) && defined(POSIX_FADV_RANDOM)
pimpl->no_cache = true;
const int err = posix_fadvise(file_id(), 0, 0, POSIX_FADV_RANDOM);
if (err != 0) {
LLAMA_LOG_WARN("%s: failed to set random-access file advice: %s\n", __func__, strerror(err));
}
#endif #endif
} }
+21 -10
View File
@@ -594,11 +594,6 @@ llama_model_loader::llama_model_loader(
files.emplace_back(new llama_file(fname.c_str(), "rb", use_direct_io)); files.emplace_back(new llama_file(fname.c_str(), "rb", use_direct_io));
contexts.emplace_back(ctx); contexts.emplace_back(ctx);
longhaul_shards.push_back({
std::filesystem::path(fname).filename().string(),
files.back()->size(),
gguf_get_data_offset(metadata),
});
// Save tensors data offset of the main file. // Save tensors data offset of the main file.
// For subsidiary files, `meta` tensor data offset must not be used, // For subsidiary files, `meta` tensor data offset must not be used,
@@ -667,11 +662,6 @@ llama_model_loader::llama_model_loader(
files.emplace_back(new llama_file(fname_split, "rb", use_direct_io)); files.emplace_back(new llama_file(fname_split, "rb", use_direct_io));
contexts.emplace_back(ctx); contexts.emplace_back(ctx);
longhaul_shards.push_back({
std::filesystem::path(fname_split).filename().string(),
files.back()->size(),
gguf_get_data_offset(ctx_gguf.get()),
});
// Save tensors data offset info of the shard. // 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)) { for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
@@ -1230,6 +1220,7 @@ struct ggml_tensor * llama_model_loader::create_tensor(
} }
ggml_backend_buffer_type_t buft = nullptr; ggml_backend_buffer_type_t buft = nullptr;
ggml_backend_buffer_type_t requested_override = nullptr;
// check overrides // check overrides
if (tensor_buft_overrides) { if (tensor_buft_overrides) {
@@ -1237,6 +1228,7 @@ struct ggml_tensor * llama_model_loader::create_tensor(
for (const auto * overrides = tensor_buft_overrides; overrides->pattern != nullptr; ++overrides) { for (const auto * overrides = tensor_buft_overrides; overrides->pattern != nullptr; ++overrides) {
std::regex pattern(overrides->pattern); std::regex pattern(overrides->pattern);
if (std::regex_search(tensor_name, pattern)) { if (std::regex_search(tensor_name, pattern)) {
requested_override = overrides->buft;
if (overrides->buft == ggml_backend_cpu_buffer_type()) { if (overrides->buft == ggml_backend_cpu_buffer_type()) {
// when overriding to a CPU buffer, consider the extra buffer types // when overriding to a CPU buffer, consider the extra buffer types
buft = select_weight_buft(hparams, t_meta, op, buft_list_cpu); buft = select_weight_buft(hparams, t_meta, op, buft_list_cpu);
@@ -1266,6 +1258,25 @@ struct ggml_tensor * llama_model_loader::create_tensor(
} }
} }
// Streamed CPU experts are updated one expert slice at a time. CPU
// repack and accelerator buffers only accept whole-tensor updates, so
// keep these cache tensors in the standard, directly writable layout.
if ((flags & TENSOR_LONGHAUL) && buft_list == buft_list_cpu) {
auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
if (!cpu_dev) {
throw std::runtime_error("no CPU backend found");
}
ggml_backend_buffer_type_t cpu_buft = ggml_backend_dev_buffer_type(cpu_dev);
if (requested_override != nullptr &&
requested_override != ggml_backend_cpu_buffer_type() &&
requested_override != cpu_buft) {
throw std::runtime_error(format(
"longhaul CPU expert tensor '%s' has an incompatible buffer override",
tn.str().c_str()));
}
buft = cpu_buft;
}
// avoid using a host buffer when using mmap // avoid using a host buffer when using mmap
auto * buft_dev = ggml_backend_buft_get_device(buft); auto * buft_dev = ggml_backend_buft_get_device(buft);
if (use_mmap && buft_dev && buft == ggml_backend_dev_host_buffer_type(buft_dev)) { if (use_mmap && buft_dev && buft == ggml_backend_dev_host_buffer_type(buft_dev)) {
-8
View File
@@ -9,7 +9,6 @@
#include "ggml-cpp.h" #include "ggml-cpp.h"
#include <array>
#include <cstddef> #include <cstddef>
#include <cstring> #include <cstring>
#include <map> #include <map>
@@ -78,12 +77,6 @@ struct llama_model_loader {
int layer; int layer;
}; };
struct longhaul_shard {
std::string name;
uint64_t size;
uint64_t metadata_size;
};
int n_kv = 0; int n_kv = 0;
int n_tensors = 0; int n_tensors = 0;
int n_created = 0; int n_created = 0;
@@ -122,7 +115,6 @@ struct llama_model_loader {
std::vector<std::pair<size_t, size_t>> mmaps_used; std::vector<std::pair<size_t, size_t>> mmaps_used;
size_t longhaul_slots = 0; size_t longhaul_slots = 0;
std::vector<longhaul_source> longhaul_sources; std::vector<longhaul_source> longhaul_sources;
std::vector<longhaul_shard> longhaul_shards;
// define a comparator for the buft -> ctx map to ensure that the order is well-defined: // define a comparator for the buft -> ctx map to ensure that the order is well-defined:
struct ggml_backend_buft_comparator { struct ggml_backend_buft_comparator {
+12 -23
View File
@@ -1039,7 +1039,6 @@ struct llama_model::impl {
std::vector<float> tensor_split_owned; std::vector<float> tensor_split_owned;
std::unique_ptr<llama_longhaul_cache> longhaul; std::unique_ptr<llama_longhaul_cache> longhaul;
bool longhaul_remote = false;
}; };
llama_model::llama_model(const llama_model_params & params) : params(params), pimpl(std::make_unique<impl>()) { llama_model::llama_model(const llama_model_params & params) : params(params), pimpl(std::make_unique<impl>()) {
@@ -1366,36 +1365,27 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
if (params.check_tensors || params.no_alloc || params.vocab_only) { if (params.check_tensors || params.no_alloc || params.vocab_only) {
throw std::runtime_error("longhaul does not support check-tensors, no-alloc, or vocab-only loading"); throw std::runtime_error("longhaul does not support check-tensors, no-alloc, or vocab-only loading");
} }
bool all_cpu = true;
bool all_metal = true; bool all_metal = true;
bool all_rpc = true;
for (int il = 0; il < n_layer_all; ++il) { for (int il = 0; il < n_layer_all; ++il) {
ggml_backend_dev_t dev = pimpl->dev_layer[il].dev; ggml_backend_dev_t dev = pimpl->dev_layer[il].dev;
const char * reg_name = ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)); const char * backend = ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev));
all_cpu = all_cpu && ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU;
all_metal = all_metal && all_metal = all_metal &&
ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU && ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU &&
strcmp(reg_name, "MTL") == 0; strcmp(backend, "MTL") == 0;
all_rpc = all_rpc &&
ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU &&
strcmp(reg_name, "RPC") == 0;
} }
if (!all_metal && !all_rpc) { if (!all_cpu && !all_metal) {
throw std::runtime_error( throw std::runtime_error(
"longhaul requires all model layers on local Metal or one RPC device"); "longhaul requires every repeating model layer on CPU or Metal; "
"use --n-gpu-layers 0 for CPU mode");
} }
if (all_metal) {
#if !defined(__APPLE__) #if !defined(__APPLE__)
throw std::runtime_error("local longhaul is only supported on macOS"); if (all_metal) {
throw std::runtime_error("longhaul Metal mode is only supported on macOS");
}
#endif #endif
} else { LLAMA_LOG_INFO("%s: longhaul using %s expert cache\n", __func__, all_cpu ? "CPU" : "Metal");
ggml_backend_dev_t first = pimpl->dev_layer.front().dev;
for (int il = 1; il < n_layer_all; ++il) {
if (pimpl->dev_layer[il].dev != first) {
throw std::runtime_error(
"RPC longhaul v1 requires every model layer on one RPC device");
}
}
pimpl->longhaul_remote = true;
}
ml.configure_longhaul(params.longhaul_cache_bytes, n_expert, n_layer_all); ml.configure_longhaul(params.longhaul_cache_bytes, n_expert, n_layer_all);
if (ml.longhaul_slots < (size_t) n_expert_used) { if (ml.longhaul_slots < (size_t) n_expert_used) {
LLAMA_LOG_WARN("%s: longhaul cache has %zu slots for %lld selected experts; " LLAMA_LOG_WARN("%s: longhaul cache has %zu slots for %lld selected experts; "
@@ -1715,8 +1705,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
if (params.load_mode == LLAMA_LOAD_MODE_LONGHAUL) { if (params.load_mode == LLAMA_LOAD_MODE_LONGHAUL) {
pimpl->longhaul = std::make_unique<llama_longhaul_cache>( pimpl->longhaul = std::make_unique<llama_longhaul_cache>(
std::move(ml.files), std::move(ml.longhaul_sources), std::move(ml.longhaul_shards), std::move(ml.files), std::move(ml.longhaul_sources), ml.longhaul_slots, hparams.n_expert, hparams.n_layer_all);
ml.longhaul_slots, hparams.n_expert, hparams.n_layer_all, pimpl->longhaul_remote);
} }
return true; return true;
-5
View File
@@ -263,10 +263,6 @@ static bool llama_prepare_model_devices(const llama_model_params & params, llama
} }
} }
if (params.load_mode == LLAMA_LOAD_MODE_LONGHAUL && !rpc_servers.empty()) {
// RPC longhaul v1 keeps the entire paging domain on one remote device.
model->devices.push_back(rpc_servers.front());
} else {
// add RPC servers at the front of the list to minimize network transfers // add RPC servers at the front of the list to minimize network transfers
model->devices.insert(model->devices.begin(), rpc_servers.begin(), rpc_servers.end()); model->devices.insert(model->devices.begin(), rpc_servers.begin(), rpc_servers.end());
@@ -279,7 +275,6 @@ static bool llama_prepare_model_devices(const llama_model_params & params, llama
model->devices.insert(model->devices.end(), igpus.begin(), igpus.end()); model->devices.insert(model->devices.end(), igpus.begin(), igpus.end());
} }
} }
}
// if using single GPU mode, remove all except the main GPU // if using single GPU mode, remove all except the main GPU
if (params.split_mode == LLAMA_SPLIT_MODE_NONE && !model->devices.empty()) { if (params.split_mode == LLAMA_SPLIT_MODE_NONE && !model->devices.empty()) {
+16
View File
@@ -259,6 +259,22 @@ set_tests_properties(test-thread-safety PROPERTIES FIXTURES_REQUIRED test-downlo
llama_build_and_test(test-arg-parser.cpp) llama_build_and_test(test-arg-parser.cpp)
llama_build_and_test(test-longhaul.cpp) llama_build_and_test(test-longhaul.cpp)
llama_test(
test-longhaul
NAME test-longhaul-cpu-qwen35moe
ARGS --cpu-model "${MODEL_DIR}/qwen35moe-moe.gguf" 3145728
)
set_tests_properties(test-longhaul-cpu-qwen35moe PROPERTIES
FIXTURES_REQUIRED generate-models
)
llama_test(
test-longhaul
NAME test-longhaul-cpu-laguna
ARGS --cpu-model "${MODEL_DIR}/laguna-moe.gguf" 2097152
)
set_tests_properties(test-longhaul-cpu-laguna PROPERTIES
FIXTURES_REQUIRED generate-models
)
llama_build_and_test(test-token-cache.cpp) llama_build_and_test(test-token-cache.cpp)
target_include_directories(test-token-cache PRIVATE ${PROJECT_SOURCE_DIR}/src) target_include_directories(test-token-cache PRIVATE ${PROJECT_SOURCE_DIR}/src)
+17 -1
View File
@@ -9,6 +9,7 @@
// TODO: replace with #include "llama-ext.h" in the future // TODO: replace with #include "llama-ext.h" in the future
#include "../src/llama-arch.h" #include "../src/llama-arch.h"
#include "../src/llama-model.h"
#include "../src/llama-model-saver.h" #include "../src/llama-model-saver.h"
#include <cinttypes> #include <cinttypes>
@@ -476,7 +477,9 @@ static int save_models(const llm_arch target_arch, const size_t seed, const ggml
if (!moe && moe_mandatory(arch)) { if (!moe && moe_mandatory(arch)) {
continue; continue;
} }
if (!llama_model_saver_supports_arch(arch) || !arch_supported(arch)) { const bool can_save_fixture =
llama_model_saver_supports_arch(arch) || arch == LLM_ARCH_LAGUNA;
if (!can_save_fixture || !arch_supported(arch)) {
LOG_INF("%s: %s model (%s) is unsupported, skipping\n", __func__, llm_arch_name(arch), moe ? "MoE" : "dense"); LOG_INF("%s: %s model (%s) is unsupported, skipping\n", __func__, llm_arch_name(arch), moe ? "MoE" : "dense");
continue; continue;
} }
@@ -484,7 +487,20 @@ static int save_models(const llm_arch target_arch, const size_t seed, const ggml
auto model_and_ctx = get_model_and_ctx(gguf_ctx.get(), nullptr, seed, {}); auto model_and_ctx = get_model_and_ctx(gguf_ctx.get(), nullptr, seed, {});
const std::string path = dir + "/" + llm_arch_name(arch) + (moe ? "-moe.gguf" : "-dense.gguf"); const std::string path = dir + "/" + llm_arch_name(arch) + (moe ? "-moe.gguf" : "-dense.gguf");
LOG_INF("%s: Saving %s model (%s) to %s...\n", __func__, llm_arch_name(arch), moe ? "MoE" : "dense", path.c_str()); LOG_INF("%s: Saving %s model (%s) to %s...\n", __func__, llm_arch_name(arch), moe ? "MoE" : "dense", path.c_str());
if (llama_model_saver_supports_arch(arch)) {
llama_model_save_to_file(model_and_ctx.first.get(), path.c_str()); llama_model_save_to_file(model_and_ctx.first.get(), path.c_str());
} else {
// Laguna is not supported by the production model saver yet.
// Preserve the exact synthetic fixture metadata and attach the
// initialized model tensors so longhaul can be tested from a
// real file without broadening the saver API.
gguf_context_ptr fixture(gguf_init_empty());
gguf_set_kv(fixture.get(), gguf_ctx.get());
for (const auto & item : llama_internal_get_tensor_map(model_and_ctx.first.get())) {
gguf_add_tensor(fixture.get(), item.second);
}
gguf_write_to_file(fixture.get(), path.c_str(), false);
}
} }
} }
llama_log_set(ud.original_logger.callback, ud.original_logger.user_data); llama_log_set(ud.original_logger.callback, ud.original_logger.user_data);
+149 -3
View File
@@ -1,11 +1,16 @@
#include "testing.h" #include "testing.h"
#include "../src/llama-longhaul.h" #include "../src/llama-longhaul.h"
#include "../src/llama-model.h"
#include "ggml-backend.h" #include "ggml-backend.h"
#include "llama-cpp.h"
#include <cmath>
#include <cstdio> #include <cstdio>
#include <memory> #include <memory>
#include <stdexcept>
#include <string>
#include <vector> #include <vector>
struct longhaul_fixture { struct longhaul_fixture {
@@ -58,8 +63,7 @@ struct longhaul_fixture {
sources.push_back({ weights_b, 0, n_experts * expert_size, expert_size, 0 }); sources.push_back({ weights_b, 0, n_experts * expert_size, expert_size, 0 });
} }
cache = std::make_unique<llama_longhaul_cache>( cache = std::make_unique<llama_longhaul_cache>(
std::move(files), std::move(sources), std::vector<llama_model_loader::longhaul_shard>{}, std::move(files), std::move(sources), n_slots, n_experts, 1);
n_slots, n_experts, 1, false);
} }
~longhaul_fixture() { ~longhaul_fixture() {
@@ -129,6 +133,32 @@ static void test_multiple_sources(testing & t) {
t.assert_equal(uint8_t(34), fixture.slot_value(fixture.weights_b, remapped[1])); t.assert_equal(uint8_t(34), fixture.slot_value(fixture.weights_b, remapped[1]));
} }
static void test_concurrent_source_reads(testing & t) {
longhaul_fixture fixture(2, 4, true);
for (int iteration = 0; iteration < 64; ++iteration) {
const int32_t first = iteration % 2 == 0 ? 0 : 2;
const int32_t second = first + 1;
const auto remapped = fixture.remap({first, second});
if (!t.assert_equal(2u, remapped.size())) {
return;
}
t.assert_equal(
uint8_t(1 + first),
fixture.slot_value(fixture.weights_a, remapped[0]));
t.assert_equal(
uint8_t(33 + first),
fixture.slot_value(fixture.weights_b, remapped[0]));
t.assert_equal(
uint8_t(1 + second),
fixture.slot_value(fixture.weights_a, remapped[1]));
t.assert_equal(
uint8_t(33 + second),
fixture.slot_value(fixture.weights_b, remapped[1]));
}
}
static void test_invalid_ids(testing & t) { static void test_invalid_ids(testing & t) {
longhaul_fixture fixture(2, 4); longhaul_fixture fixture(2, 4);
@@ -153,8 +183,110 @@ static void test_read_failure_recovery(testing & t) {
t.assert_equal(uint8_t(1), fixture.slot_value(fixture.weights_a, remapped[0])); t.assert_equal(uint8_t(1), fixture.slot_value(fixture.weights_a, remapped[0]));
} }
struct cpu_decode_result {
std::vector<float> logits;
uint32_t capacity = 0;
uint64_t misses = 0;
uint64_t bytes_read = 0;
bool expert_buffer_is_host = false;
};
static cpu_decode_result decode_cpu_model(
const std::string & path,
llama_load_mode load_mode,
uint64_t cache_bytes) {
llama_model_params model_params = llama_model_default_params();
model_params.n_gpu_layers = 0;
model_params.load_mode = load_mode;
model_params.longhaul_cache_bytes = cache_bytes;
model_params.use_extra_bufts = true;
llama_model_ptr model(llama_model_load_from_file(path.c_str(), model_params));
if (!model) {
throw std::runtime_error("failed to load CPU model: " + path);
}
llama_context_params context_params = llama_context_default_params();
context_params.n_ctx = 32;
context_params.n_batch = 8;
context_params.n_ubatch = 8;
context_params.n_threads = 2;
context_params.n_threads_batch = 2;
llama_context_ptr context(llama_init_from_model(model.get(), context_params));
if (!context) {
throw std::runtime_error("failed to create CPU context: " + path);
}
std::vector<llama_token> tokens = {1, 2, 3, 4, 5, 6, 7, 8};
llama_batch batch = llama_batch_get_one(tokens.data(), tokens.size());
if (llama_decode(context.get(), batch) != 0) {
throw std::runtime_error("failed to decode CPU model: " + path);
}
const int32_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model.get()));
const float * logits = llama_get_logits_ith(context.get(), -1);
if (!logits) {
throw std::runtime_error("CPU model produced no logits: " + path);
}
cpu_decode_result result;
result.logits.assign(logits, logits + n_vocab);
if (load_mode == LLAMA_LOAD_MODE_LONGHAUL) {
llama_longhaul_cache * cache = model->longhaul_cache();
if (!cache) {
throw std::runtime_error("longhaul cache was not created: " + path);
}
result.capacity = cache->capacity();
result.misses = cache->misses();
result.bytes_read = cache->bytes_read_count();
for (const auto & item : llama_internal_get_tensor_map(model.get())) {
const std::string & name = item.first;
if (name.find("ffn_") != std::string::npos &&
name.find("_exps.weight") != std::string::npos &&
item.second->ne[2] == result.capacity) {
result.expert_buffer_is_host = ggml_backend_buffer_is_host(item.second->buffer);
break;
}
}
}
return result;
}
static void test_cpu_model(
testing & t,
const std::string & path,
uint64_t cache_bytes) {
const cpu_decode_result regular =
decode_cpu_model(path, LLAMA_LOAD_MODE_NONE, 0);
const cpu_decode_result longhaul =
decode_cpu_model(path, LLAMA_LOAD_MODE_LONGHAUL, cache_bytes);
t.assert_equal(1u, longhaul.capacity);
t.assert_true("longhaul loaded at least one expert", longhaul.misses > 0);
t.assert_true("longhaul read expert bytes", longhaul.bytes_read > 0);
t.assert_true("streamed experts use a directly writable host buffer", longhaul.expert_buffer_is_host);
t.assert_equal(regular.logits.size(), longhaul.logits.size());
double squared_error = 0.0;
double squared_reference = 0.0;
for (size_t i = 0; i < regular.logits.size(); ++i) {
const double delta = double(regular.logits[i]) - double(longhaul.logits[i]);
squared_error += delta * delta;
squared_reference += double(regular.logits[i]) * double(regular.logits[i]);
}
const double nmse = squared_reference > 0.0 ? squared_error / squared_reference : squared_error;
t.assert_true(
"longhaul CPU logits NMSE = " + std::to_string(nmse),
std::isfinite(nmse) && nmse <= 1e-6);
}
int main(int argc, char ** argv) { int main(int argc, char ** argv) {
testing t; testing t;
llama_backend_init();
const char * verbose = getenv("LLAMA_TEST_VERBOSE"); const char * verbose = getenv("LLAMA_TEST_VERBOSE");
if (verbose) { if (verbose) {
@@ -164,14 +296,28 @@ int main(int argc, char ** argv) {
llama_log_set([](ggml_log_level, const char *, void *) {}, nullptr); llama_log_set([](ggml_log_level, const char *, void *) {}, nullptr);
} }
if (argc == 4 && std::string(argv[1]) == "--cpu-model") {
const std::string path = argv[2];
const uint64_t cache_bytes = std::stoull(argv[3]);
t.test("cpu_model", [&](testing & current) {
test_cpu_model(current, path, cache_bytes);
});
const int result = t.summary();
llama_backend_free();
return result;
}
if (argc > 1) { if (argc > 1) {
t.set_filter(argv[1]); t.set_filter(argv[1]);
} }
t.test("batch_planning", test_batch_planning); t.test("batch_planning", test_batch_planning);
t.test("multiple_sources", test_multiple_sources); t.test("multiple_sources", test_multiple_sources);
t.test("concurrent_reads", test_concurrent_source_reads);
t.test("invalid_ids", test_invalid_ids); t.test("invalid_ids", test_invalid_ids);
t.test("read_failure", test_read_failure_recovery); t.test("read_failure", test_read_failure_recovery);
return t.summary(); const int result = t.summary();
llama_backend_free();
return result;
} }
+1 -1
View File
@@ -61,7 +61,7 @@
| `--mmap, --no-mmap` | DEPRECATED in favor of `--load-mode`: whether to memory-map model. (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>(env: LLAMA_ARG_MMAP) | | `--mmap, --no-mmap` | DEPRECATED in favor of `--load-mode`: whether to memory-map model. (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>(env: LLAMA_ARG_MMAP) |
| `-dio, --direct-io, -ndio, --no-direct-io` | DEPRECATED in favor of `--load-mode`: use DirectIO if available<br/>(env: LLAMA_ARG_DIO) | | `-dio, --direct-io, -ndio, --no-direct-io` | DEPRECATED in favor of `--load-mode`: use DirectIO if available<br/>(env: LLAMA_ARG_DIO) |
| `-lm, --load-mode MODE` | model loading mode (default: mmap)<br/>- none: no special loading mode<br/>- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>- mlock: force system to keep model in RAM rather than swapping or compressing<br/>- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing<br/>- dio: use DirectIO if available<br/>- longhaul: stream routed MoE experts through a bounded cache<br/><br/>(env: LLAMA_ARG_LOAD_MODE) | | `-lm, --load-mode MODE` | model loading mode (default: mmap)<br/>- none: no special loading mode<br/>- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>- mlock: force system to keep model in RAM rather than swapping or compressing<br/>- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing<br/>- dio: use DirectIO if available<br/>- longhaul: stream routed MoE experts through a bounded cache<br/><br/>(env: LLAMA_ARG_LOAD_MODE) |
| `--longhaul` | stream routed Qwen3.5 MoE experts through a bounded Metal cache<br/>(env: LLAMA_ARG_LONGHAUL) | | `--longhaul` | stream routed Qwen3.5 MoE or Laguna experts through a bounded CPU or Metal cache<br/>(env: LLAMA_ARG_LONGHAUL) |
| `--longhaul-cache N` | longhaul expert cache size in GiB<br/>(env: LLAMA_ARG_LONGHAUL_CACHE) | | `--longhaul-cache N` | longhaul expert cache size in GiB<br/>(env: LLAMA_ARG_LONGHAUL_CACHE) |
| `--numa TYPE` | attempt optimizations that help on some NUMA systems<br/>- distribute: spread execution evenly over all nodes<br/>- isolate: only spawn threads on CPUs on the node that execution started on<br/>- numactl: use the CPU map provided by numactl<br/>if run without this previously, it is recommended to drop the system page cache before using this<br/>see https://github.com/ggml-org/llama.cpp/issues/1437<br/>(env: LLAMA_ARG_NUMA) | | `--numa TYPE` | attempt optimizations that help on some NUMA systems<br/>- distribute: spread execution evenly over all nodes<br/>- isolate: only spawn threads on CPUs on the node that execution started on<br/>- numactl: use the CPU map provided by numactl<br/>if run without this previously, it is recommended to drop the system page cache before using this<br/>see https://github.com/ggml-org/llama.cpp/issues/1437<br/>(env: LLAMA_ARG_NUMA) |
| `-dev, --device <dev1,dev2,..>` | comma-separated list of devices to use for offloading (none = don't offload)<br/>use --list-devices to see a list of available devices<br/>(env: LLAMA_ARG_DEVICE) | | `-dev, --device <dev1,dev2,..>` | comma-separated list of devices to use for offloading (none = don't offload)<br/>use --list-devices to see a list of available devices<br/>(env: LLAMA_ARG_DEVICE) |
+1 -1
View File
@@ -144,7 +144,7 @@ llama-completion.exe -m models\gemma-1.1-7b-it.Q4_K_M.gguf --ignore-eos -n -1
| `--mmap, --no-mmap` | DEPRECATED in favor of `--load-mode`: whether to memory-map model. (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>(env: LLAMA_ARG_MMAP) | | `--mmap, --no-mmap` | DEPRECATED in favor of `--load-mode`: whether to memory-map model. (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>(env: LLAMA_ARG_MMAP) |
| `-dio, --direct-io, -ndio, --no-direct-io` | DEPRECATED in favor of `--load-mode`: use DirectIO if available<br/>(env: LLAMA_ARG_DIO) | | `-dio, --direct-io, -ndio, --no-direct-io` | DEPRECATED in favor of `--load-mode`: use DirectIO if available<br/>(env: LLAMA_ARG_DIO) |
| `-lm, --load-mode MODE` | model loading mode (default: mmap)<br/>- none: no special loading mode<br/>- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>- mlock: force system to keep model in RAM rather than swapping or compressing<br/>- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing<br/>- dio: use DirectIO if available<br/>- longhaul: stream routed MoE experts through a bounded cache<br/><br/>(env: LLAMA_ARG_LOAD_MODE) | | `-lm, --load-mode MODE` | model loading mode (default: mmap)<br/>- none: no special loading mode<br/>- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>- mlock: force system to keep model in RAM rather than swapping or compressing<br/>- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing<br/>- dio: use DirectIO if available<br/>- longhaul: stream routed MoE experts through a bounded cache<br/><br/>(env: LLAMA_ARG_LOAD_MODE) |
| `--longhaul` | stream routed Qwen3.5 MoE experts through a bounded Metal cache<br/>(env: LLAMA_ARG_LONGHAUL) | | `--longhaul` | stream routed Qwen3.5 MoE or Laguna experts through a bounded CPU or Metal cache<br/>(env: LLAMA_ARG_LONGHAUL) |
| `--longhaul-cache N` | longhaul expert cache size in GiB<br/>(env: LLAMA_ARG_LONGHAUL_CACHE) | | `--longhaul-cache N` | longhaul expert cache size in GiB<br/>(env: LLAMA_ARG_LONGHAUL_CACHE) |
| `--numa TYPE` | attempt optimizations that help on some NUMA systems<br/>- distribute: spread execution evenly over all nodes<br/>- isolate: only spawn threads on CPUs on the node that execution started on<br/>- numactl: use the CPU map provided by numactl<br/>if run without this previously, it is recommended to drop the system page cache before using this<br/>see https://github.com/ggml-org/llama.cpp/issues/1437<br/>(env: LLAMA_ARG_NUMA) | | `--numa TYPE` | attempt optimizations that help on some NUMA systems<br/>- distribute: spread execution evenly over all nodes<br/>- isolate: only spawn threads on CPUs on the node that execution started on<br/>- numactl: use the CPU map provided by numactl<br/>if run without this previously, it is recommended to drop the system page cache before using this<br/>see https://github.com/ggml-org/llama.cpp/issues/1437<br/>(env: LLAMA_ARG_NUMA) |
| `-dev, --device <dev1,dev2,..>` | comma-separated list of devices to use for offloading (none = don't offload)<br/>use --list-devices to see a list of available devices<br/>(env: LLAMA_ARG_DEVICE) | | `-dev, --device <dev1,dev2,..>` | comma-separated list of devices to use for offloading (none = don't offload)<br/>use --list-devices to see a list of available devices<br/>(env: LLAMA_ARG_DEVICE) |
+1 -11
View File
@@ -36,17 +36,6 @@ flowchart TD
By default, `ggml-rpc-server` exposes all available accelerator devices on the host. By default, `ggml-rpc-server` exposes all available accelerator devices on the host.
If there are no accelerators, it exposes a single `CPU` device. If there are no accelerators, it exposes a single `CPU` device.
For server-resident longhaul MoE paging, place the same GGUF shards on the RPC
host and point the server at their directory:
```sh
$ bin/ggml-rpc-server --device MTL0 --longhaul-root /path/to/model-directory
```
The client can then use `--rpc`, `--longhaul`, and `--longhaul-cache` together.
RPC longhaul v1 requires one remote Metal device. Expert cache misses are read
from the RPC host's local files rather than uploaded by the client.
## Usage ## Usage
### Remote hosts ### Remote hosts
@@ -118,3 +107,4 @@ Use the `GGML_RPC_DEBUG` environment variable to enable debug messages from `ggm
```bash ```bash
$ GGML_RPC_DEBUG=1 bin/ggml-rpc-server $ GGML_RPC_DEBUG=1 bin/ggml-rpc-server
``` ```
+3 -35
View File
@@ -13,7 +13,6 @@
#include <algorithm> #include <algorithm>
#include <clocale> #include <clocale>
#include <codecvt> #include <codecvt>
#include <cstring>
#include <filesystem> #include <filesystem>
#include <regex> #include <regex>
#include <stdio.h> #include <stdio.h>
@@ -174,7 +173,6 @@ struct rpc_server_params {
std::string host = "127.0.0.1"; std::string host = "127.0.0.1";
int port = 50052; int port = 50052;
bool use_cache = false; bool use_cache = false;
std::string longhaul_root;
int n_threads = std::max(1U, std::thread::hardware_concurrency()/2); int n_threads = std::max(1U, std::thread::hardware_concurrency()/2);
std::vector<std::string> devices; std::vector<std::string> devices;
}; };
@@ -188,7 +186,6 @@ static void print_usage(int /*argc*/, char ** argv, rpc_server_params params) {
fprintf(stderr, " -H, --host HOST host to bind to (default: %s)\n", params.host.c_str()); fprintf(stderr, " -H, --host HOST host to bind to (default: %s)\n", params.host.c_str());
fprintf(stderr, " -p, --port PORT port to bind to (default: %d)\n", params.port); fprintf(stderr, " -p, --port PORT port to bind to (default: %d)\n", params.port);
fprintf(stderr, " -c, --cache enable local file cache\n"); fprintf(stderr, " -c, --cache enable local file cache\n");
fprintf(stderr, " --longhaul-root PATH serve longhaul expert data from this model directory\n");
fprintf(stderr, "\n"); fprintf(stderr, "\n");
} }
@@ -236,11 +233,6 @@ static bool rpc_server_params_parse(int argc, char ** argv, rpc_server_params &
} }
} else if (arg == "-c" || arg == "--cache") { } else if (arg == "-c" || arg == "--cache") {
params.use_cache = true; params.use_cache = true;
} else if (arg == "--longhaul-root") {
if (++i >= argc) {
return false;
}
params.longhaul_root = argv[i];
} else if (arg == "-h" || arg == "--help") { } else if (arg == "-h" || arg == "--help") {
print_usage(argc, argv, params); print_usage(argc, argv, params);
exit(0); exit(0);
@@ -321,23 +313,6 @@ int main(int argc, char * argv[]) {
fprintf(stderr, "No devices found\n"); fprintf(stderr, "No devices found\n");
return 1; return 1;
} }
if (!params.longhaul_root.empty()) {
std::error_code ec;
const auto root = std::filesystem::canonical(params.longhaul_root, ec);
if (ec || !std::filesystem::is_directory(root, ec)) {
fprintf(stderr, "Invalid longhaul root: %s\n", params.longhaul_root.c_str());
return 1;
}
params.longhaul_root = root.string();
for (auto * dev : devices) {
auto * dev_reg = ggml_backend_dev_backend_reg(dev);
if (!dev_reg || strcmp(ggml_backend_reg_name(dev_reg), "MTL") != 0) {
fprintf(stderr, "--longhaul-root currently requires Metal devices\n");
return 1;
}
}
}
std::string endpoint = params.host + ":" + std::to_string(params.port); std::string endpoint = params.host + ":" + std::to_string(params.port);
const char * cache_dir = nullptr; const char * cache_dir = nullptr;
std::string cache_dir_str; std::string cache_dir_str;
@@ -356,19 +331,12 @@ int main(int argc, char * argv[]) {
return 1; return 1;
} }
auto start_server_fn = (decltype(ggml_backend_rpc_start_server_with_options)*) auto start_server_fn = (decltype(ggml_backend_rpc_start_server)*) ggml_backend_reg_get_proc_address(reg, "ggml_backend_rpc_start_server");
ggml_backend_reg_get_proc_address(reg, "ggml_backend_rpc_start_server_with_options");
if (!start_server_fn) { if (!start_server_fn) {
fprintf(stderr, "Failed to obtain RPC backend start server function with options\n"); fprintf(stderr, "Failed to obtain RPC backend start server function\n");
return 1; return 1;
} }
start_server_fn( start_server_fn(endpoint.c_str(), cache_dir, params.n_threads, devices.size(), devices.data());
endpoint.c_str(),
cache_dir,
params.longhaul_root.empty() ? nullptr : params.longhaul_root.c_str(),
params.n_threads,
devices.size(),
devices.data());
return 0; return 0;
} }
+1 -1
View File
@@ -78,7 +78,7 @@ For the full list of features, please refer to [server's changelog](https://gith
| `--mmap, --no-mmap` | DEPRECATED in favor of `--load-mode`: whether to memory-map model. (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>(env: LLAMA_ARG_MMAP) | | `--mmap, --no-mmap` | DEPRECATED in favor of `--load-mode`: whether to memory-map model. (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>(env: LLAMA_ARG_MMAP) |
| `-dio, --direct-io, -ndio, --no-direct-io` | DEPRECATED in favor of `--load-mode`: use DirectIO if available<br/>(env: LLAMA_ARG_DIO) | | `-dio, --direct-io, -ndio, --no-direct-io` | DEPRECATED in favor of `--load-mode`: use DirectIO if available<br/>(env: LLAMA_ARG_DIO) |
| `-lm, --load-mode MODE` | model loading mode (default: mmap)<br/>- none: no special loading mode<br/>- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>- mlock: force system to keep model in RAM rather than swapping or compressing<br/>- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing<br/>- dio: use DirectIO if available<br/>- longhaul: stream routed MoE experts through a bounded cache<br/><br/>(env: LLAMA_ARG_LOAD_MODE) | | `-lm, --load-mode MODE` | model loading mode (default: mmap)<br/>- none: no special loading mode<br/>- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>- mlock: force system to keep model in RAM rather than swapping or compressing<br/>- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing<br/>- dio: use DirectIO if available<br/>- longhaul: stream routed MoE experts through a bounded cache<br/><br/>(env: LLAMA_ARG_LOAD_MODE) |
| `--longhaul` | stream routed Qwen3.5 MoE experts through a bounded Metal cache<br/>(env: LLAMA_ARG_LONGHAUL) | | `--longhaul` | stream routed Qwen3.5 MoE or Laguna experts through a bounded CPU or Metal cache<br/>(env: LLAMA_ARG_LONGHAUL) |
| `--longhaul-cache N` | longhaul expert cache size in GiB<br/>(env: LLAMA_ARG_LONGHAUL_CACHE) | | `--longhaul-cache N` | longhaul expert cache size in GiB<br/>(env: LLAMA_ARG_LONGHAUL_CACHE) |
| `--numa TYPE` | attempt optimizations that help on some NUMA systems<br/>- distribute: spread execution evenly over all nodes<br/>- isolate: only spawn threads on CPUs on the node that execution started on<br/>- numactl: use the CPU map provided by numactl<br/>if run without this previously, it is recommended to drop the system page cache before using this<br/>see https://github.com/ggml-org/llama.cpp/issues/1437<br/>(env: LLAMA_ARG_NUMA) | | `--numa TYPE` | attempt optimizations that help on some NUMA systems<br/>- distribute: spread execution evenly over all nodes<br/>- isolate: only spawn threads on CPUs on the node that execution started on<br/>- numactl: use the CPU map provided by numactl<br/>if run without this previously, it is recommended to drop the system page cache before using this<br/>see https://github.com/ggml-org/llama.cpp/issues/1437<br/>(env: LLAMA_ARG_NUMA) |
| `-dev, --device <dev1,dev2,..>` | comma-separated list of devices to use for offloading (none = don't offload)<br/>use --list-devices to see a list of available devices<br/>(env: LLAMA_ARG_DEVICE) | | `-dev, --device <dev1,dev2,..>` | comma-separated list of devices to use for offloading (none = don't offload)<br/>use --list-devices to see a list of available devices<br/>(env: LLAMA_ARG_DEVICE) |