diff --git a/common/common.cpp b/common/common.cpp index 65aa77da2..a0fe213d0 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1292,12 +1292,12 @@ common_init_result::common_init_result(common_params & params, bool model_only) auto mparams = common_model_params_to_llama(params); auto cparams = common_context_params_to_llama(params); - // DFlash2/DSpark drafters rank their full draft vocabulary inside the graph (top_k / argmax - // on the lm_head output), which needs the lm_head (the target's when the draft has none) - // replicated on every device. The flag must be set before the model is loaded, since the - // tensor split state is fixed during load. + // DSpark's markov head reads the lm_head output in-graph (argmax over the full vocabulary), + // so it keeps the lm_head replicated on every device; DFlash2 ranks the vocabulary on the + // CPU instead and can use a split lm_head. The flag must be set before the model is loaded, + // since the tensor split state is fixed during load. if (params.split_mode == LLAMA_SPLIT_MODE_TENSOR && !params.speculative.draft.mparams.path.empty() && - common_speculative_draft_ranks_full_output(params.speculative.draft.mparams.path)) { + common_speculative_draft_replicated_lm_head(params.speculative.draft.mparams.path)) { mparams.output_replicated = true; } diff --git a/common/speculative.cpp b/common/speculative.cpp index 1489ce880..85d861025 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -928,6 +928,13 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { bool is_dflash2 = false; bool is_mrope = false; int32_t selector_top_k = 0; + int32_t selector_rank = 0; + + // DFlash2 CPU-side selector: the lm_head output may be split across devices, so the + // candidate lattice is built on the host from the gathered logits + std::vector sel_next; // [selector_rank, n_vocab] + std::vector sel_prev; // [selector_rank, n_vocab] + std::vector sel_hidden; // [n_embd_dec, selector_rank] // draft-dspark: the draft carries a Markov head and uses an anchor-first block layout const bool is_dspark; @@ -981,6 +988,12 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { is_dflash2 = selector_top_k > 0; mask_token_id = llama_vocab_mask(llama_model_get_vocab(model_dft)); + if (is_dflash2) { + // the candidate lattice is built on the CPU, so the raw lm_head output must be + // available after the decode; the hidden states ride the nextn output + load_dflash2_selector(); + } + if (is_dspark && this->params.p_min > 0.0f) { char buf[16] = {}; const bool has_conf = @@ -1052,6 +1065,112 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { llama_set_causal_attn(ctx_dft, causal_attn); // DFlash needs non-causal attention unless the model says otherwise } + // read the DFlash2 selector weights straight from the draft GGUF file (they are i8) + void load_dflash2_selector() { + struct gguf_init_params gguf_params = { + /* .no_alloc = */ true, + /* .ctx = */ nullptr, + }; + + gguf_context_ptr gguf_ctx(gguf_init_from_file(params.mparams.path.c_str(), gguf_params)); + GGML_ASSERT(gguf_ctx && "failed to open the draft GGUF for the DFlash2 selector"); + + const int64_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(params.ctx_dft))); + + auto load_i8 = [&](const char * name, std::vector & dst) { + const int64_t id = gguf_find_tensor(gguf_ctx.get(), name); + GGML_ASSERT(id >= 0 && "DFlash2 selector tensor missing"); + const enum ggml_type t = gguf_get_tensor_type(gguf_ctx.get(), id); + const struct ggml_type_traits * tt = ggml_get_type_traits(t); + GGML_ASSERT(tt && tt->to_float && "unsupported DFlash2 selector tensor type"); + + const size_t size = gguf_get_tensor_size(gguf_ctx.get(), id); + std::vector raw(size); + + std::unique_ptr f(ggml_fopen(params.mparams.path.c_str(), "rb"), fclose); + GGML_ASSERT(f && "failed to open the draft GGUF for the DFlash2 selector"); +#ifdef _WIN32 + const int rc = _fseeki64(f.get(), (int64_t) (gguf_get_data_offset(gguf_ctx.get()) + gguf_get_tensor_offset(gguf_ctx.get(), id)), SEEK_SET); +#else + const int rc = fseeko(f.get(), (off_t) (gguf_get_data_offset(gguf_ctx.get()) + gguf_get_tensor_offset(gguf_ctx.get(), id)), SEEK_SET); +#endif + GGML_ASSERT(rc == 0 && "failed to seek to the DFlash2 selector tensor"); + GGML_ASSERT(fread(raw.data(), 1, size, f.get()) == size && "failed to read the DFlash2 selector tensor"); + + // dequantize with the same conversion the GPU get_rows uses + const size_t n_elts = size / tt->type_size * tt->blck_size; + dst.resize(n_elts); + tt->to_float(raw.data(), dst.data(), (int64_t) n_elts); + }; + + load_i8("selector_successor.weight", sel_next); + load_i8("selector_predecessor.weight", sel_prev); + load_i8("selector_hidden.weight", sel_hidden); + + selector_rank = (int32_t) (sel_next.size() / n_vocab); + GGML_ASSERT((size_t) selector_rank * n_vocab == sel_next.size()); + GGML_ASSERT((size_t) selector_rank * n_vocab == sel_prev.size()); + GGML_ASSERT((size_t) n_embd_dec * selector_rank == sel_hidden.size()); + } + + // DFlash2 CPU-side selector: rank the (possibly split) lm_head output once per batch and + // return the per-position top-k candidate ids, unary scores and the selector gate + void build_dflash2_selector_cpu(std::vector & cand, std::vector & unary, std::vector & gate) { + auto & ctx_dft = params.ctx_dft; + + const int64_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx_dft))); + const int32_t n_tokens = batch.n_tokens; + const int32_t top_k = selector_top_k; + const int32_t rank = selector_rank; + + cand.resize((size_t) n_tokens * top_k); + unary.resize((size_t) n_tokens * top_k); + gate.resize((size_t) n_tokens * rank); + + const float * embd_all = llama_get_embeddings_nextn(ctx_dft); + GGML_ASSERT(embd_all && "DFlash2 CPU selector requires the decoder hidden states"); + for (int32_t i = 0; i < n_tokens; ++i) { + const float * logits = llama_get_logits_ith(ctx_dft, i); + const float * embd = embd_all + (size_t) i * n_embd_dec; + GGML_ASSERT(logits && "DFlash2 CPU selector requires the lm_head output"); + + int32_t * ci = cand.data() + (size_t) i * top_k; + float * ui = unary.data() + (size_t) i * top_k; + + // top-k scan keeping the largest values in descending order + std::vector ids(top_k, 0); + std::vector vals(top_k, -INFINITY); + for (int64_t t = 0; t < n_vocab; ++t) { + const float v = logits[t]; + if (v <= vals[top_k - 1]) { + continue; + } + int32_t pos = top_k - 1; + while (pos > 0 && v > vals[pos - 1]) { + vals[pos] = vals[pos - 1]; + ids[pos] = ids[pos - 1]; + pos--; + } + vals[pos] = v; + ids[pos] = (int32_t) t; + } + for (int32_t k = 0; k < top_k; ++k) { + ci[k] = ids[k]; + ui[k] = vals[k]; + } + + // gate = selector_hidden^T x hidden_state + float * gi = gate.data() + (size_t) i * rank; + for (int32_t k = 0; k < rank; ++k) { + float s = 0.0f; + for (int32_t d = 0; d < n_embd_dec; ++d) { + s += sel_hidden[(size_t) k * n_embd_dec + d] * embd[d]; + } + gi[k] = s; + } + } + } + ~common_speculative_impl_draft_dflash() override { auto * ctx_dft = this->params.ctx_dft; for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) backend_chains.size(); ++seq_id) { @@ -1205,7 +1324,8 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { i_block_beg[seq_id] = batch.n_tokens; n_block [seq_id] = n_block_tokens; for (int32_t i = 0; i < n_block_tokens; ++i) { - common_batch_add(batch, i == 0 ? dp.id_last : mask_token_id, n + i, { seq_id }, !is_dflash2); + // DFlash2 ranks the lm_head output on the CPU, so its block positions emit logits + common_batch_add(batch, i == 0 ? dp.id_last : mask_token_id, n + i, { seq_id }, true); } } @@ -1220,6 +1340,14 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { return; } + // DFlash2 ranks the (possibly split) lm_head output on the CPU once for the whole batch + std::vector cand; + std::vector unary; + std::vector gate; + if (is_dflash2) { + build_dflash2_selector_cpu(cand, unary, gate); + } + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { if (i_block_beg[seq_id] < 0) { continue; @@ -1234,16 +1362,34 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { auto & result = *dp.result; if (is_dflash2) { - const float * lattice = llama_get_embeddings_nextn(ctx_dft); - GGML_ASSERT(lattice && "DFlash2 selector produced no lattice"); - + // block walk over the CPU-computed candidates: the transition scores for the + // current predecessor are evaluated on the fly int32_t predecessor = 0; for (int32_t i = 1; i < n_block_tokens; ++i) { - const float * row = lattice + (size_t) (beg + i) * n_embd_dec; - const float * scores = row + selector_top_k + (size_t) predecessor * selector_top_k; + const int32_t pos = beg + i; - predecessor = (int32_t) std::distance(scores, - std::max_element(scores, scores + selector_top_k)); + const int32_t * ci = cand.data() + (size_t) pos * selector_top_k; + const float * ui = unary.data() + (size_t) pos * selector_top_k; + const float * gi = gate.data() + (size_t) pos * selector_rank; + + // the predecessor candidate id: the anchor for block position 1, else the + // previously chosen candidate + const int32_t pred_id = i == 1 + ? batch.token[beg] + : cand[(size_t) (pos - 1) * selector_top_k + predecessor]; + + std::vector scores(selector_top_k); + for (int32_t j = 0; j < selector_top_k; ++j) { + float s = ui[j]; + const int32_t cj = ci[j]; + for (int32_t k = 0; k < selector_rank; ++k) { + s += sel_next[(size_t) cj * selector_rank + k] * sel_prev[(size_t) pred_id * selector_rank + k] * gi[k]; + } + scores[j] = s; + } + + predecessor = (int32_t) std::distance(scores.begin(), + std::max_element(scores.begin(), scores.end())); if (params.p_min > 0.0f) { // softmax(scores) at the argmax, i.e. 1 / sum(exp(s_k - s_max)) float sum = 0.0f; @@ -1254,7 +1400,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { break; } } - result.push_back((llama_token) row[predecessor]); + result.push_back((llama_token) ci[predecessor]); } if (result.size() < (size_t) params.n_min) { @@ -2324,7 +2470,7 @@ std::vector common_speculative_types_from_gguf(const st return { type }; } -bool common_speculative_draft_ranks_full_output(const std::string & path) { +bool common_speculative_draft_replicated_lm_head(const std::string & path) { struct gguf_init_params gguf_params = { /* .no_alloc = */ true, /* .ctx = */ nullptr, @@ -2335,31 +2481,9 @@ bool common_speculative_draft_ranks_full_output(const std::string & path) { return false; } - const int64_t arch_id = gguf_find_key(gguf_ctx.get(), "general.architecture"); - if (arch_id < 0 || gguf_get_kv_type(gguf_ctx.get(), arch_id) != GGUF_TYPE_STRING) { - return false; - } - - const std::string arch = gguf_get_val_str(gguf_ctx.get(), arch_id); - if (arch != "dflash") { - return false; - } - - // DFlash2's candidate selector and DSpark's markov head rank the full draft - // vocabulary in-graph (top_k / argmax on the lm_head output) - bool ranks_full_output = false; - if (gguf_find_tensor(gguf_ctx.get(), "selector_hidden.weight") >= 0) { - ranks_full_output = true; // DFlash2 - } - if (gguf_find_tensor(gguf_ctx.get(), "markov_w1.weight") >= 0) { - ranks_full_output = true; // DSpark - } - if (!ranks_full_output) { - return false; - } - - // a draft with its own lm_head replicates it itself; only the shared target lm_head needs the flag - return gguf_find_tensor(gguf_ctx.get(), "output.weight") < 0; + // DSpark's markov head reads the lm_head output in-graph; DFlash2 ranks the + // vocabulary on the CPU instead and can use a split lm_head + return gguf_find_tensor(gguf_ctx.get(), "markov_w1.weight") >= 0; } static uint32_t common_get_enabled_speculative_configs(const std::vector & configs) { @@ -2592,8 +2716,8 @@ common_speculative_init_result::common_speculative_init_result( cparams.n_rs_seq = 0; cparams.ctx_other = ctx_tgt; - // DFlash2/DSpark rank the full target vocabulary inside the draft graph (top_k / argmax - // on the lm_head output), so the worst-case compute buffer grows with n_ubatch * n_vocab. + // DFlash2/DSpark rank the full target vocabulary (in-graph or on the CPU after the decode), + // so the lm_head output for every block position grows with n_ubatch * n_vocab. // Their largest decode batch is one noise block per sequence (n_max + 1 tokens), so cap the // ubatch to that; anything larger only inflates the reserved compute buffer. const bool has_block_draft = std::any_of( diff --git a/common/speculative.h b/common/speculative.h index 78c349591..3ef9203d7 100644 --- a/common/speculative.h +++ b/common/speculative.h @@ -17,10 +17,9 @@ std::vector common_speculative_types_from_names(co // infer the spec types from the GGUF metadata of a draft model; empty if unknown std::vector common_speculative_types_from_gguf(const std::string & path); -// returns true when the draft model ranks its full vocabulary inside the graph (DFlash2 -// candidate selector, DSpark markov head) and has no lm_head of its own, so the target's -// lm_head must be replicated on every device under tensor parallelism -bool common_speculative_draft_ranks_full_output(const std::string & path); +// returns true when the draft's in-graph logits consumer (DSpark markov head) requires the +// lm_head replicated on every device under tensor parallelism +bool common_speculative_draft_replicated_lm_head(const std::string & path); // convert string to type enum common_speculative_type common_speculative_type_from_name(const std::string & name); diff --git a/src/models/dflash.cpp b/src/models/dflash.cpp index bc992884f..3a3578d62 100644 --- a/src/models/dflash.cpp +++ b/src/models/dflash.cpp @@ -139,8 +139,10 @@ void llama_model_dflash::load_arch_tensors(llama_model_loader &) { throw std::runtime_error("DFlash2 hidden size is too small for the selector lattice"); } - dflash_selector_prev = create_tensor(tn(LLM_TENSOR_DFLASH_SELECTOR_PREV, "weight"), { rank, n_vocab }, 0); - dflash_selector_next = create_tensor(tn(LLM_TENSOR_DFLASH_SELECTOR_NEXT, "weight"), { rank, n_vocab }, 0); + // the successor/predecessor tables are consumed by the CPU-side selector straight + // from the GGUF file, so they are not loaded into device memory + dflash_selector_prev = create_tensor(tn(LLM_TENSOR_DFLASH_SELECTOR_PREV, "weight"), { rank, n_vocab }, TENSOR_SKIP); + dflash_selector_next = create_tensor(tn(LLM_TENSOR_DFLASH_SELECTOR_NEXT, "weight"), { rank, n_vocab }, TENSOR_SKIP); dflash_selector_hidden = create_tensor(tn(LLM_TENSOR_DFLASH_SELECTOR_HIDDEN, "weight"), { n_embd, rank }, 0); LLAMA_LOG_INFO("%s: DFlash2 conv kernel = %u, group = %u, selector rank = %u, top-k = %u\n", __func__, @@ -148,8 +150,8 @@ void llama_model_dflash::load_arch_tensors(llama_model_loader &) { hparams.dflash_selector_rank, hparams.dflash_selector_top_k); } - // DFlash2/DSpark rank the full draft vocabulary in-graph (top_k/argmax on the lm_head - // output), which requires the lm_head to be replicated on every device + // a draft with its own lm_head keeps it replicated under tensor parallelism, so the + // in-graph DSpark markov head sees the full vocabulary if (params.split_mode == LLAMA_SPLIT_MODE_TENSOR && (selector_meta || markov_meta)) { output_replicated = true; } @@ -461,99 +463,6 @@ static ggml_tensor * build_dflash2_conv( return result; } -// DFlash2 selector: top-k candidates per block position plus the pairwise -// transition scores, packed into the nextn output slot for the CPU-side walk. -static void build_dflash2_selector(llm_graph_context & g, const llama_model & model, ggml_tensor * tokens) { - ggml_context * ctx0 = g.ctx0; - auto & res = g.res; - - const auto & hparams = g.hparams; - const int64_t n_tokens = g.n_tokens; - const int64_t n_embd = g.n_embd; - - const int64_t top_k = hparams.dflash_selector_top_k; - const int64_t rank = hparams.dflash_selector_rank; - const int64_t n_blocks = g.ubatch.n_seqs_unq; - GGML_ASSERT(n_blocks > 0 && n_tokens % n_blocks == 0); - GGML_ASSERT(res->t_logits->ne[1] == n_tokens); - if (!tokens) { - return; - } - - const int64_t tokens_per_block = n_tokens / n_blocks; - const int64_t block_size = std::min(tokens_per_block, hparams.dflash_block_size); - const int64_t row_used = top_k + top_k * top_k; - - ggml_tensor * candidates = ggml_top_k(ctx0, res->t_logits, top_k); - ggml_tensor * logits_rows = ggml_reshape_3d(ctx0, res->t_logits, 1, res->t_logits->ne[0], n_tokens); - ggml_tensor * unary = ggml_reshape_2d(ctx0, - ggml_get_rows(ctx0, logits_rows, candidates), top_k, n_tokens); - ggml_tensor * gate = g.build_lora_mm(model.dflash_selector_hidden, res->t_embd); - - // Everything below indexes [.., tokens_per_block, n_blocks]: the block - // position varies fastest, sequences are the outer dimension. - ggml_tensor * cand_blk = ggml_reshape_3d(ctx0, candidates, top_k, tokens_per_block, n_blocks); - ggml_tensor * unary_blk = ggml_reshape_3d(ctx0, unary, top_k, tokens_per_block, n_blocks); - ggml_tensor * gate_blk = ggml_reshape_3d(ctx0, gate, rank, tokens_per_block, n_blocks); - - // a position's score reads only the candidate sets at pos-1 and pos, so a run - // of positions has no internal dependency and scores in one batched matmul - auto score_run = [&](int64_t beg_pos, int64_t n_pos, ggml_tensor * pred_ids) { - ggml_tensor * cand_run = ggml_cont(ctx0, ggml_view_3d(ctx0, cand_blk, top_k, n_pos, n_blocks, - cand_blk->nb[1], cand_blk->nb[2], beg_pos * cand_blk->nb[1])); - ggml_tensor * unary_run = ggml_cont(ctx0, ggml_view_3d(ctx0, unary_blk, top_k, n_pos, n_blocks, - unary_blk->nb[1], unary_blk->nb[2], beg_pos * unary_blk->nb[1])); - ggml_tensor * gate_run = ggml_cont(ctx0, ggml_view_3d(ctx0, gate_blk, rank, n_pos, n_blocks, - gate_blk->nb[1], gate_blk->nb[2], beg_pos * gate_blk->nb[1])); - - const int64_t n_pred = pred_ids->ne[0] / (n_pos * n_blocks); - - ggml_tensor * successor = ggml_reshape_4d(ctx0, - ggml_get_rows(ctx0, model.dflash_selector_next, ggml_reshape_1d(ctx0, cand_run, top_k * n_pos * n_blocks)), - rank, top_k, n_pos, n_blocks); - ggml_tensor * predecessor = ggml_reshape_4d(ctx0, - ggml_get_rows(ctx0, model.dflash_selector_prev, pred_ids), - rank, n_pred, n_pos, n_blocks); - - ggml_tensor * gate_bcast = ggml_reshape_4d(ctx0, gate_run, rank, 1, n_pos, n_blocks); - ggml_tensor * cond = ggml_mul(ctx0, predecessor, ggml_repeat(ctx0, gate_bcast, predecessor)); - ggml_tensor * score = ggml_mul_mat(ctx0, successor, cond); - if (n_pred == 1) { - score = ggml_repeat_4d(ctx0, score, top_k, top_k, n_pos, n_blocks); - } - ggml_tensor * unary_bcast = ggml_reshape_4d(ctx0, unary_run, top_k, 1, n_pos, n_blocks); - score = ggml_add(ctx0, score, ggml_repeat(ctx0, unary_bcast, score)); - - ggml_tensor * row = ggml_concat(ctx0, - ggml_cast(ctx0, cand_run, GGML_TYPE_F32), - ggml_reshape_3d(ctx0, score, top_k * top_k, n_pos, n_blocks), 0); - return ggml_pad(ctx0, row, n_embd - row_used, 0, 0, 0); - }; - - ggml_tensor * packed = ggml_fill(ctx0, - ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, 1, n_blocks), 0.0f); - - if (block_size > 1) { - // Position 1 alone: its predecessor is the anchor token, one id per - // sequence rather than a candidate set. - ggml_tensor * anchor_ids = ggml_cont_1d(ctx0, - ggml_view_2d(ctx0, tokens, 1, n_blocks, tokens_per_block * tokens->nb[0], 0), n_blocks); - packed = ggml_concat(ctx0, packed, score_run(1, 1, anchor_ids), 1); - } - if (block_size > 2) { - ggml_tensor * prev_ids = ggml_reshape_1d(ctx0, - ggml_cont(ctx0, ggml_view_3d(ctx0, cand_blk, top_k, block_size - 2, n_blocks, - cand_blk->nb[1], cand_blk->nb[2], cand_blk->nb[1])), - top_k * (block_size - 2) * n_blocks); - packed = ggml_concat(ctx0, packed, score_run(2, block_size - 2, prev_ids), 1); - } - - packed = ggml_reshape_2d(ctx0, packed, n_embd, block_size * n_blocks); - g.cb(packed, "dflash2_lattice", -1); - res->t_h_nextn = packed; - ggml_build_forward_expand(g.gf, packed); -} - // DFlash decoder, dual-mode by batch type: // * embd batch -> fused target features: project + inject K/V into the cache. // * token batch -> noise-block diffusion: attend over [committed, MASK...] to generate draft tokens @@ -760,6 +669,13 @@ llama_model_dflash::graph::graph(const llama_model & model, const llm_gra res->t_embd = cur; + // DFlash2's candidate lattice is built on the CPU by the speculative implementation from + // the lm_head output (which may be split across devices), so expose the decoder hidden + // states through the nextn slot that the implementation already reads + if (model.dflash_selector_hidden) { + res->t_h_nextn = cur; + } + // lm_head from the target model (shared via ctx_other) auto * output = model.output; auto * output_s = model.output_s; @@ -773,8 +689,8 @@ llama_model_dflash::graph::graph(const llama_model & model, const llm_gra cur = build_lora_mm(output, cur, output_s); - // DFlash2 feeds these logits to the selector, so they need the target's output - // transforms; DFlash1 and DSpark read them through the sampler instead + // DFlash2 feeds these logits to the CPU-side selector, so they need the target's + // output transforms; DFlash1 and DSpark read them through the sampler instead if (model.dflash_selector_hidden) { if (hparams.f_logit_scale != 0.0f) { cur = ggml_scale(ctx0, cur, hparams.f_logit_scale); @@ -810,10 +726,6 @@ llama_model_dflash::graph::graph(const llama_model & model, const llm_gra if (model.dspark_markov_w1) { build_dspark_markov_head(*this, model, inp_tokens); } - - if (model.dflash_selector_hidden) { - build_dflash2_selector(*this, model, inp_tokens); - } } // DSV4 DSpark decoder, dual-mode by batch type (see the DFlash decoder above):