From b5c1f7bcd10da9d3ff3f490922b1f1415d8a41de Mon Sep 17 00:00:00 2001 From: Helldez <74499579+Helldez@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:06:05 +0100 Subject: [PATCH] llama : compute the experts missing from the MoE cache on the CPU (experimental) With moe_cache_cpu >= 0, a batch served by the MoE cache no longer uploads every selected expert the cache does not hold. The experts are built twice: on the device from the cache, and on the CPU from the host weights. Each pass is weighted by the router only for the experts it holds (dev_mask, cpu_mask), so each row of their sum is exactly one of the two, and the CPU pass selects the cached experts with id -1, which ggml-cpu's mul_mat_id now treats as no expert (a zero row) instead of reading their host weights. At most moe_cache_cpu missing experts per layer and batch are still uploaded, the best scored first, so the cache keeps learning; those are read from the cache by the same batch. The copy callback plans the layer once per batch, on the first of its maps to be copied, and writes the maps after the plan: the slot map gives slot 0 to the experts computed on the CPU, cpu_ids gives -1 to the others. The maps are looked up on the device like the slot map, so they are read after the plan. llama_moe_cache_slots returns the cache's own slots, which tell a caller the experts whose host weights the batch does not read. -1, the default, keeps the upload of every missing expert. Llama 4 weights the input of the experts, so it keeps the uploads. The scheduler runs the CPU pass after the device pass, not alongside it. LLAMA_HAS_MOE_CACHE_CPU lets a caller build against a llama.cpp without it. --- ggml/src/ggml-cpu/ggml-cpu.c | 8 ++- include/llama.h | 2 + src/llama-context.cpp | 4 +- src/llama-cparams.h | 1 + src/llama-graph.cpp | 66 +++++++++++++++++--- src/llama-graph.h | 15 ++++- src/llama-moe-cache.cpp | 115 +++++++++++++++++++++++++++++------ src/llama-moe-cache.h | 8 ++- 8 files changed, 187 insertions(+), 32 deletions(-) diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index 56bdbcf54e97..73307bca820c 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -1663,7 +1663,13 @@ static void ggml_compute_forward_mul_mat_id( for (int id = 0; id < n_ids; ++id) { const int32_t i02 = *(const int32_t *) ((const char *) ids->data + iid1*ids->nb[1] + id*ids->nb[0]); - assert(i02 >= 0 && i02 < n_as); + // a negative id selects no expert, its row is zero (the other experts are computed elsewhere) + if (i02 < 0) { + memset((char *) dst->data + id*nb1 + iid1*nb2, 0, ne0*sizeof(float)); + continue; + } + + assert(i02 < n_as); MMID_MATRIX_ROW(i02, matrix_row_counts[i02]) = (struct mmid_row_mapping) {id, iid1}; matrix_row_counts[i02] += 1; diff --git a/include/llama.h b/include/llama.h index f79b4d0e0bad..6b3aac6baabc 100644 --- a/include/llama.h +++ b/include/llama.h @@ -397,6 +397,7 @@ extern "C" { enum ggml_type type_v; // data type for V cache [EXPERIMENTAL] size_t moe_cache_size; // device cache in bytes for the experts kept in host memory, split among the devices like the layers, 0 = disabled [EXPERIMENTAL] + int32_t moe_cache_cpu; // experts missing from the MoE cache: -1 = uploaded, N >= 0 = computed on the CPU, at most N of them per layer and batch still uploaded for later batches [EXPERIMENTAL] // Abort callback // if it returns true, execution of llama_decode() will be aborted @@ -1175,6 +1176,7 @@ extern "C" { // an expert the batch selects that has a slot then is not evicted by that layer's uploads, so its host weights // are not read for this batch. The map changes as later layers upload their experts. #define LLAMA_HAS_MOE_CACHE_SLOTS 1 + #define LLAMA_HAS_MOE_CACHE_CPU 1 // llama_context_params::moe_cache_cpu LLAMA_API const int32_t * llama_moe_cache_slots(struct llama_context * ctx, int32_t il, int64_t n_tokens, int64_t n_expert_used); // diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 10b8a36494ab..a9d0e609d807 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -369,6 +369,7 @@ llama_context::llama_context( cparams.op_offload = params.op_offload; cparams.kv_unified = params.kv_unified; cparams.moe_cache_size = params.moe_cache_size; + cparams.moe_cache_cpu = params.moe_cache_cpu; // initialized later cparams.pipeline_parallel = false; @@ -559,7 +560,7 @@ llama_context::llama_context( } if (cparams.moe_cache_size > 0) { - moe_cache = std::make_unique(model, backend_ptrs, backend_buft, cparams.moe_cache_size); + moe_cache = std::make_unique(model, backend_ptrs, backend_buft, cparams.moe_cache_size, cparams.moe_cache_cpu); } sched_reserve(); @@ -4022,6 +4023,7 @@ llama_context_params llama_context_default_params() { /*.type_k =*/ GGML_TYPE_F16, /*.type_v =*/ GGML_TYPE_F16, /*.moe_cache_size =*/ 0, + /*.moe_cache_cpu =*/ -1, /*.abort_callback =*/ nullptr, /*.abort_callback_data =*/ nullptr, /*.embeddings =*/ false, diff --git a/src/llama-cparams.h b/src/llama-cparams.h index 0c260f7b6285..d4feeeab145b 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -58,6 +58,7 @@ struct llama_cparams { bool training; // set by llama_opt_init() size_t moe_cache_size; + int32_t moe_cache_cpu; std::vector embeddings_layer_inp; // [n_layer()] extract input embeddings for layer diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 415dff33e9d3..ad1ec0b89d78 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1709,13 +1709,17 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( ggml_tensor * cur, // ggml_tensor * b ggml_tensor * ids, ggml_tensor * w_s, - ggml_tensor * slots) const { + ggml_tensor * slots, + ggml_backend_t backend) const { // as in build_lora_mm: the folded weight reads the transformed input, the LoRA delta reads `cur` ggml_tensor * cur_mm = build_hadamard_input(w, cur); // the experts in the MoE cache are selected by their slots ggml_tensor * res = slots == nullptr ? ggml_mul_mat_id(ctx0, w, cur_mm, ids) : ggml_mul_mat_id(ctx0, moe_cache->get_experts(w), cur_mm, slots); + if (backend) { + ggml_backend_sched_set_tensor_backend(sched, res, backend); + } if (prec_policy) { prec_policy->apply(res); @@ -2355,7 +2359,8 @@ ggml_tensor * llm_graph_context::build_moe_ffn( ggml_build_forward_expand(gf, weights); // the experts of host-resident layers may be read from the MoE cache - ggml_tensor * slots = build_moe_cache_slots(selected_experts, up_exps, gate_exps, down_exps, gate_up_exps, il); + moe_cache_cpu cache_cpu; + ggml_tensor * slots = build_moe_cache_slots(selected_experts, up_exps, gate_exps, down_exps, gate_up_exps, il, weight_before_ffn ? nullptr : &cache_cpu); cur = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); @@ -2366,12 +2371,26 @@ ggml_tensor * llm_graph_context::build_moe_ffn( cb(cur, "ffn_moe_weighted", il); } - ggml_tensor * up = nullptr; ggml_tensor * experts = nullptr; + // with the missing experts of the MoE cache on the CPU, the experts are built twice: on the device from the cache and on the CPU + // from the host weights, each weighted by the router only for the experts it holds, so each row of the sum comes from one of them + // the body of the loop is not indented, to keep this change small + ggml_tensor * const cur_in = cur; + ggml_tensor * experts_sum = nullptr; + const int n_pass = cache_cpu.cpu_ids ? 2 : 1; + for (int pass = 0; pass < n_pass; ++pass) { + ggml_tensor * const mm_ids = pass == 0 ? selected_experts : cache_cpu.cpu_ids; + ggml_tensor * const mm_slots = pass == 0 ? slots : nullptr; + ggml_backend_t const mm_backend = pass == 0 ? nullptr : backend_cpu; + ggml_tensor * const mm_weights = n_pass == 1 ? weights : ggml_mul(ctx0, weights, pass == 0 ? cache_cpu.dev_mask : cache_cpu.cpu_mask); + cur = cur_in; + + ggml_tensor * up = nullptr; + if (gate_up_exps) { // merged gate_up path: one mul_mat_id, then split into gate and up views - ggml_tensor * gate_up = build_lora_mm_id(gate_up_exps, cur, selected_experts, up_exps_s, slots); // [n_ff*2, n_expert_used, n_tokens] + ggml_tensor * gate_up = build_lora_mm_id(gate_up_exps, cur, mm_ids, up_exps_s, mm_slots, mm_backend); // [n_ff*2, n_expert_used, n_tokens] cb(gate_up, "ffn_moe_gate_up", il); if (up_exps_s) { @@ -2390,7 +2409,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( cb(up, "ffn_moe_up", il); } else { // separate gate and up path - up = build_lora_mm_id(up_exps, cur, selected_experts, up_exps_s, slots); // [n_ff, n_expert_used, n_tokens] + up = build_lora_mm_id(up_exps, cur, mm_ids, up_exps_s, mm_slots, mm_backend); // [n_ff, n_expert_used, n_tokens] cb(up, "ffn_moe_up", il); if (up_exps_s) { @@ -2403,7 +2422,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( } if (gate_exps) { - cur = build_lora_mm_id(gate_exps, cur, selected_experts, gate_exps_s, slots); // [n_ff, n_expert_used, n_tokens] + cur = build_lora_mm_id(gate_exps, cur, mm_ids, gate_exps_s, mm_slots, mm_backend); // [n_ff, n_expert_used, n_tokens] cb(cur, "ffn_moe_gate", il); } else { cur = up; @@ -2515,7 +2534,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( cur = amax_src1.res; } - experts = build_lora_mm_id(down_exps, cur, selected_experts, down_exps_s, slots); // [n_embd, n_expert_used, n_tokens] + experts = build_lora_mm_id(down_exps, cur, mm_ids, down_exps_s, mm_slots, mm_backend); // [n_embd, n_expert_used, n_tokens] //ggml_prec_set_src(experts, GGML_PREC_BF16, 1); // (see TODO above) cb(experts, "ffn_moe_down", il); @@ -2541,10 +2560,14 @@ ggml_tensor * llm_graph_context::build_moe_ffn( } if (!weight_before_ffn) { - experts = ggml_mul(ctx0, experts, weights); + experts = ggml_mul(ctx0, experts, mm_weights); cb(experts, "ffn_moe_weighted", il); } + experts_sum = experts_sum ? ggml_add(ctx0, experts_sum, experts) : experts; + } + experts = experts_sum; + ggml_build_forward_expand(gf, experts); ggml_tensor * cur_experts[LLAMA_MAX_EXPERTS] = { nullptr }; @@ -2587,7 +2610,8 @@ ggml_tensor * llm_graph_context::build_moe_cache_slots( ggml_tensor * gate_exps, ggml_tensor * down_exps, ggml_tensor * gate_up_exps, - int il) const { + int il, + moe_cache_cpu * cpu) const { if (moe_cache == nullptr) { return nullptr; } @@ -2617,6 +2641,30 @@ ggml_tensor * llm_graph_context::build_moe_cache_slots( ggml_backend_sched_set_tensor_backend(sched, slots, moe_cache->backend(il)); cb(slots, "ffn_moe_slots", il); + // the missing experts on the CPU: the maps are looked up on the device like the slot map, so the copy callback plans before they are read + ggml_tensor * maps[3]; + if (moe_cache->get_cpu_maps(il, &maps[0], &maps[1], &maps[2])) { + if (cpu == nullptr) { + return nullptr; + } + // all or none: a lookup in the graph makes the copy callback plan the layer + ggml_tensor * lookups[3]; + for (int i = 0; i < 3; ++i) { + lookups[i] = ggml_get_rows(ctx0, maps[i], ids); // [1, n_expert_used*n_tokens] + if (!ggml_backend_supports_op(moe_cache->backend(il), lookups[i])) { + return nullptr; + } + } + for (ggml_tensor * lookup : lookups) { + ggml_backend_sched_set_tensor_backend(sched, lookup, moe_cache->backend(il)); + ggml_build_forward_expand(gf, lookup); + } + cpu->cpu_ids = ggml_reshape_2d(ctx0, lookups[0], selected_experts->ne[0], selected_experts->ne[1]); + cpu->dev_mask = ggml_reshape_3d(ctx0, lookups[1], 1, selected_experts->ne[0], selected_experts->ne[1]); + cpu->cpu_mask = ggml_reshape_3d(ctx0, lookups[2], 1, selected_experts->ne[0], selected_experts->ne[1]); + cb(lookups[0], "ffn_moe_cpu_ids", il); + } + // add the lookup now: the transform of a Hadamard-folded expert reads host weights and would start its split first ggml_build_forward_expand(gf, slots); diff --git a/src/llama-graph.h b/src/llama-graph.h index a49f5432d2b9..5d33990019d2 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1114,12 +1114,14 @@ struct llm_graph_context { // do mat_mul_id, while optionally apply lora and per-expert scale // if slots is set, the experts are read from the MoE cache at these slots (see build_moe_cache_slots) + // if backend is set, the mat_mul_id runs on it ggml_tensor * build_lora_mm_id( ggml_tensor * w, // ggml_tensor * as ggml_tensor * cur, // ggml_tensor * b ggml_tensor * ids, ggml_tensor * w_s = nullptr, - ggml_tensor * slots = nullptr) const; + ggml_tensor * slots = nullptr, + ggml_backend_t backend = nullptr) const; // rescale `cur` (the src1 of a matmul) by a power of two, computed from its maximum absolute // keep both individual values and Q8 activation block sums within F16 range @@ -1225,14 +1227,23 @@ struct llm_graph_context { ggml_tensor * post_exp_norm = nullptr, float post_exp_norm_eps = 1e-5f) const; + // the experts missing from the MoE cache, computed on the CPU (see llama_moe_cache::get_cpu_maps) + struct moe_cache_cpu { + ggml_tensor * cpu_ids = nullptr; // [n_expert_used, n_tokens], -1 for the experts in the cache + ggml_tensor * dev_mask = nullptr; // [1, n_expert_used, n_tokens] + ggml_tensor * cpu_mask = nullptr; // [1, n_expert_used, n_tokens] + }; + // the slots of the selected experts in the MoE cache, nullptr if the experts of the layer are not read from the cache + // if the cache computes its missing experts on the CPU, cpu receives their lookups, or the cache is not used if cpu is nullptr ggml_tensor * build_moe_cache_slots( ggml_tensor * selected_experts, ggml_tensor * up_exps, ggml_tensor * gate_exps, ggml_tensor * down_exps, ggml_tensor * gate_up_exps, - int il) const; + int il, + moe_cache_cpu * cpu) const; // // inputs diff --git a/src/llama-moe-cache.cpp b/src/llama-moe-cache.cpp index 53f505283c5e..b190d6b3c870 100644 --- a/src/llama-moe-cache.cpp +++ b/src/llama-moe-cache.cpp @@ -31,6 +31,7 @@ struct moe_cache_slru { std::vector seen; // [n_expert] uint32_t seen_gen = 0; std::vector uniq; + size_t n_uniq = 0; // distinct experts of the last plan void init(int32_t n_layer, int32_t n_expert, int32_t n_slots) { this->n_expert = n_expert; @@ -103,9 +104,9 @@ struct moe_cache_slru { int32_t slot; }; - // give a slot to each expert selected by ids in layer il, evicting from probation first + // give a slot to each expert selected by ids in layer il, or to the first max_fills missing ones if max_fills >= 0, evicting from probation first // returns false if the ids select more distinct experts than there are slots - bool plan(int32_t il, const int32_t * ids, size_t n_ids, std::vector & fills, size_t & n_hit) { + bool plan(int32_t il, const int32_t * ids, size_t n_ids, std::vector & fills, size_t & n_hit, int32_t max_fills = -1) { fills.clear(); n_hit = 0; @@ -124,6 +125,7 @@ struct moe_cache_slru { if (uniq.size() > (size_t) n_slots) { return false; } + n_uniq = uniq.size(); int32_t * slots = slot_map[il]; @@ -134,6 +136,11 @@ struct moe_cache_slru { n_hit++; } } + // the ids of a token come by score, so the limit keeps the best scored misses of the first tokens + if (max_fills >= 0) { + uniq.erase(std::remove_if(uniq.begin(), uniq.end(), [&](int32_t e) { return slots[e] >= 0; }), uniq.end()); + uniq.resize(std::min(uniq.size(), (size_t) max_fills)); + } // sorted misses usually get consecutive slots, so the uploads can be merged std::sort(uniq.begin(), uniq.end()); for (int32_t e : uniq) { @@ -213,6 +220,14 @@ struct llama_moe_cache::impl { int32_t ig = -1; // -1 if the layer is not cached ggml_tensor * slot_map = nullptr; // I32 [1, n_expert] in host memory std::vector experts; // host expert tensors, in the order of the banks + + // with the missing experts on the CPU: the maps looked up with the slot map, all in host memory + // the slot map then holds what the device reads, and slots what the cache holds + ggml_tensor * cpu_ids = nullptr; // I32 [1, n_expert] + ggml_tensor * dev_mask = nullptr; // F32 [1, n_expert] + ggml_tensor * cpu_mask = nullptr; // F32 [1, n_expert] + std::vector slots; + uint32_t copied = 0; // the maps copied for the current batch, one bit each }; struct binding { @@ -225,11 +240,13 @@ struct llama_moe_cache::impl { size_t hits = 0; size_t misses = 0; size_t bytes = 0; + size_t cpu = 0; // misses computed on the CPU and not uploaded }; static constexpr int64_t max_batch = 32; int32_t n_expert_used; + int32_t cpu; // -1, or the uploads per layer and batch when the missing experts are computed on the CPU stats stats_small; // up to 8 tokens per ubatch stats stats_large; @@ -255,8 +272,8 @@ struct llama_moe_cache::impl { // the lookup that get_slots checks with the backend mutable std::vector lookup_mem; - impl(const llama_model & model, const std::vector & backends, const std::vector & bufts, size_t size) : - n_expert_used(model.hparams.n_expert_used_max()), layers(model.layers.size()) { + impl(const llama_model & model, const std::vector & backends, const std::vector & bufts, size_t size, int32_t cpu) : + n_expert_used(model.hparams.n_expert_used_max()), cpu(cpu), layers(model.layers.size()) { for (size_t i = 0; i < backends.size(); ++i) { const auto dev_type = ggml_backend_dev_type(ggml_backend_get_device(backends[i])); if (dev_type == GGML_BACKEND_DEVICE_TYPE_GPU || dev_type == GGML_BACKEND_DEVICE_TYPE_IGPU) { @@ -274,6 +291,11 @@ struct llama_moe_cache::impl { if (model.hparams.n_expert == 0 || n_expert_used == 0) { throw std::runtime_error("MoE cache requires a MoE model"); } + if (this->cpu >= 0 && model.arch == LLM_ARCH_LLAMA4) { + // the router weights scale the input of the experts, so they cannot drop the experts of the other device + LLAMA_LOG_WARN("%s: the missing experts of this model cannot be computed on the CPU, they are uploaded\n", __func__); + this->cpu = -1; + } // only cache layers that keep all of their experts in host memory, on the device the layer is assigned to for (size_t il = 0; il < model.layers.size(); ++il) { @@ -362,7 +384,7 @@ struct llama_moe_cache::impl { } g.slru.init(model.layers.size(), n_expert, g.n_slots); n_tensors[g.id] += g.ref.size()*(1 + g.layers.size()); - n_tensors_host += g.layers.size(); + n_tensors_host += g.layers.size()*(cpu >= 0 ? 4 : 1); } if (n_tensors_host == 0) { throw std::runtime_error("MoE cache is too small to hold the experts of one token"); @@ -417,6 +439,19 @@ struct llama_moe_cache::impl { ggml_format_name(l.slot_map, "moe_cache.slot_map-%d", il); layer_of[l.slot_map] = il; buf_host_size += GGML_PAD(ggml_nbytes(l.slot_map), alignment_host); + if (cpu >= 0) { + l.cpu_ids = ggml_new_tensor_2d(ctx_host.get(), GGML_TYPE_I32, 1, g.ref[0]->ne[2]); + l.dev_mask = ggml_new_tensor_2d(ctx_host.get(), GGML_TYPE_F32, 1, g.ref[0]->ne[2]); + l.cpu_mask = ggml_new_tensor_2d(ctx_host.get(), GGML_TYPE_F32, 1, g.ref[0]->ne[2]); + ggml_format_name(l.cpu_ids, "moe_cache.cpu_ids-%d", il); + ggml_format_name(l.dev_mask, "moe_cache.dev_mask-%d", il); + ggml_format_name(l.cpu_mask, "moe_cache.cpu_mask-%d", il); + for (ggml_tensor * t : { l.cpu_ids, l.dev_mask, l.cpu_mask }) { + layer_of[t] = il; + buf_host_size += GGML_PAD(ggml_nbytes(t), alignment_host); + } + l.slots.assign(g.ref[0]->ne[2], -1); + } } devices[g.id].buf_size += alloc_size(g, g.n_slots); } @@ -458,7 +493,7 @@ struct llama_moe_cache::impl { for (group & g : groups) { for (int32_t il : g.layers) { if (layers[il].slot_map != nullptr) { - g.slru.slot_map[il] = (int32_t *) layers[il].slot_map->data; + g.slru.slot_map[il] = cpu >= 0 ? layers[il].slots.data() : (int32_t *) layers[il].slot_map->data; } } } @@ -515,21 +550,32 @@ struct llama_moe_cache::impl { if (slot_map == nullptr) { return nullptr; } - lookup_mem.resize(2*ggml_tensor_overhead()); + lookup_mem.resize(5*ggml_tensor_overhead()); ggml_init_params params = { /*.mem_size =*/ lookup_mem.size(), /*.mem_buffer =*/ lookup_mem.data(), /*.no_alloc =*/ true, }; ggml_context_ptr ctx(ggml_init(params)); - ggml_tensor * ids = ggml_new_tensor_1d(ctx.get(), GGML_TYPE_I32, n_tokens*n_expert_used); - ggml_tensor * slots = ggml_get_rows(ctx.get(), slot_map, ids); - if (!ggml_backend_supports_op(backend(il), slots)) { - return nullptr; + ggml_tensor * ids = ggml_new_tensor_1d(ctx.get(), GGML_TYPE_I32, n_tokens*n_expert_used); + for (ggml_tensor * map : { slot_map, layers[il].cpu_ids, layers[il].dev_mask, layers[il].cpu_mask }) { + if (map != nullptr && !ggml_backend_supports_op(backend(il), ggml_get_rows(ctx.get(), map, ids))) { + return nullptr; + } } return groups[layers[il].ig].slru.slot_map[il]; } + bool get_cpu_maps(int32_t il, ggml_tensor ** cpu_ids, ggml_tensor ** dev_mask, ggml_tensor ** cpu_mask) const { + if (cpu < 0 || il < 0 || il >= (int32_t) layers.size() || layers[il].ig < 0) { + return false; + } + *cpu_ids = layers[il].cpu_ids; + *dev_mask = layers[il].dev_mask; + *cpu_mask = layers[il].cpu_mask; + return true; + } + ggml_tensor * get_experts(const ggml_tensor * w) const { const auto it = bindings.find(w); return it != bindings.end() ? it->second.cached : nullptr; @@ -576,11 +622,25 @@ struct llama_moe_cache::impl { return false; } const int32_t il = it->second; - const layer & l = layers[il]; + layer & l = layers[il]; group & g = groups[l.ig]; GGML_ASSERT(backend == devices[g.id].backend); + // the maps of a layer are planned once per batch, by the first of them to be copied + if (cpu >= 0) { + const uint32_t bit = src == l.slot_map ? 1 : src == l.cpu_ids ? 2 : src == l.dev_mask ? 4 : 8; + if (l.copied & bit) { + l.copied = 0; + } + const bool planned = l.copied != 0; + l.copied |= bit; + if (planned) { + ggml_backend_tensor_set_async(backend, dst, src->data, 0, ggml_nbytes(src)); + return true; + } + } + // the get_rows that looks up the slots of the selected experts const int n_nodes = ggml_graph_n_nodes(graph); const ggml_tensor * lookup = nullptr; @@ -608,9 +668,23 @@ struct llama_moe_cache::impl { ggml_backend_synchronize(backend); size_t n_hit = 0; - if (!g.slru.plan(il, ids.data(), ids.size(), fills, n_hit)) { + if (!g.slru.plan(il, ids.data(), ids.size(), fills, n_hit, cpu)) { GGML_ABORT("the MoE cache is too small for the experts selected in layer %d", il); } + const size_t n_cpu = cpu >= 0 ? g.slru.n_uniq - n_hit - fills.size() : 0; + + // after the plan, as the experts uploaded now are read from the cache by this batch too + // a hit keeps its slot through the plan, so the device computes the experts that were in the cache or are uploaded now + if (cpu >= 0) { + const int32_t * slots = g.slru.slot_map[il]; + for (int32_t e : ids) { + const bool hit = slots[e] >= 0; + ((int32_t *) l.slot_map->data)[e] = hit ? slots[e] : 0; + ((int32_t *) l.cpu_ids->data)[e] = hit ? -1 : e; + ((float *) l.dev_mask->data)[e] = hit ? 1.0f : 0.0f; + ((float *) l.cpu_mask->data)[e] = hit ? 0.0f : 1.0f; + } + } // upload the missing experts, consecutive experts going to consecutive slots are uploaded together size_t bytes = 0; @@ -632,6 +706,7 @@ struct llama_moe_cache::impl { stats & st = ids.size() <= (size_t) 8*n_expert_used ? stats_small : stats_large; st.hits += n_hit; st.misses += fills.size(); + st.cpu += n_cpu; st.bytes += bytes; // the next copy synchronizes the backend before it changes the slot map again @@ -642,12 +717,12 @@ struct llama_moe_cache::impl { void log_stats() const { auto log = [](const char * name, const stats & st) { - const size_t n = st.hits + st.misses; + const size_t n = st.hits + st.misses + st.cpu; if (n == 0) { return; } - LLAMA_LOG_INFO("llama_moe_cache: %s: hits = %zu, misses = %zu, hit rate = %.2f%%, uploaded = %.2f MiB\n", - name, st.hits, st.misses, 100.0*st.hits/n, st.bytes/1024.0/1024.0); + LLAMA_LOG_INFO("llama_moe_cache: %s: hits = %zu, misses = %zu, hit rate = %.2f%%, uploaded = %.2f MiB, computed on the CPU = %zu\n", + name, st.hits, st.misses + st.cpu, 100.0*st.hits/n, st.bytes/1024.0/1024.0, st.cpu); }; log("ubatch <= 8", stats_small); log("ubatch > 8", stats_large); @@ -657,8 +732,8 @@ struct llama_moe_cache::impl { } }; -llama_moe_cache::llama_moe_cache(const llama_model & model, const std::vector & backends, const std::vector & bufts, size_t size) : - pimpl(new impl(model, backends, bufts, size)) { +llama_moe_cache::llama_moe_cache(const llama_model & model, const std::vector & backends, const std::vector & bufts, size_t size, int32_t cpu) : + pimpl(new impl(model, backends, bufts, size, cpu)) { } llama_moe_cache::~llama_moe_cache() = default; @@ -675,6 +750,10 @@ const int32_t * llama_moe_cache::get_slots(int32_t il, int64_t n_tokens, int64_t return pimpl->get_slots(il, n_tokens, n_expert_used); } +bool llama_moe_cache::get_cpu_maps(int32_t il, ggml_tensor ** cpu_ids, ggml_tensor ** dev_mask, ggml_tensor ** cpu_mask) const { + return pimpl->get_cpu_maps(il, cpu_ids, dev_mask, cpu_mask); +} + ggml_tensor * llama_moe_cache::get_experts(const ggml_tensor * w) const { return pimpl->get_experts(w); } diff --git a/src/llama-moe-cache.h b/src/llama-moe-cache.h index cbe2c6e8e9d5..274a0ffd7c3a 100644 --- a/src/llama-moe-cache.h +++ b/src/llama-moe-cache.h @@ -13,7 +13,8 @@ struct llama_model; 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 - llama_moe_cache(const llama_model & model, const std::vector & backends, const std::vector & bufts, size_t size); + // cpu >= 0 computes the missing experts on the CPU and uploads at most cpu of them per layer and batch, see get_cpu_maps + llama_moe_cache(const llama_model & model, const std::vector & backends, const std::vector & bufts, size_t size, int32_t cpu = -1); ~llama_moe_cache(); // the device that caches layer il @@ -26,6 +27,11 @@ class llama_moe_cache { // an expert selected by the batch that has a slot here when the layer's lookup starts keeps it through that layer's plan const int32_t * get_slots(int32_t il, int64_t n_tokens, int64_t n_expert_used) const; + // if the missing experts are computed on the CPU, the maps of layer il, looked up like the slot map: + // I32 cpu_ids (the expert, -1 if it is in the cache), F32 dev_mask (1 if it is in the cache) and cpu_mask (1 - dev_mask) + // the slot map then gives slot 0 to the missing experts, so the device computes them with any weights and dev_mask drops them + bool get_cpu_maps(int32_t il, ggml_tensor ** cpu_ids, ggml_tensor ** dev_mask, ggml_tensor ** cpu_mask) const; + // the experts of w in the cache, nullptr if w is not cached ggml_tensor * get_experts(const ggml_tensor * w) const;