From b816bcac56602c4c8443272ad2abcec7e9e6a319 Mon Sep 17 00:00:00 2001 From: rafasmour <54501936+rafasmour@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:34:21 +0000 Subject: [PATCH] spec : reduced draft LM head from a token id list (port of upstream PR 31031), opt-in --spec-draft-vocab FILE (env LLAMA_ARG_SPEC_DRAFT_VOCAB, default off) makes the draft context multiply by a byte copy of the listed rows of its LM head (same quant type) and scatter the result into -inf logits, so no id map is needed downstream (greedy, top-k and p-min selection are unchanged). The target verifies every token, so output is unchanged; unlisted ids are practically never drafted. Covers every head that goes through build_lora_mm(): model.output, MTP nextn.shared_head_head (qwen35, qwen35moe, qwen4exp MTP) and the target head shared with DFlash/DSpark drafters via ctx_other. Cherry-picked from ggml-org/llama.cpp PR 31031 (6 commits squashed), plus: - accept heads with more rows than the vocabulary (padded shared head of DFlash) - test-llama-archs --draft-vocab: listed logits equal the full head, others -inf, for llama, qwen35, qwen35moe, qwen4exp (CPU) - tools/rdna3-w2/spec-trimmed-draft-vocab/mkvocab.py: 16k/32k/64k lists (python only, CPU llama-tokenize), tokenizer fingerprint of GGUF files - docs notes (VRAM of the copy, tokenizer sharing) Assisted-by: Claude Sonnet 5.5 --- ci/run.sh | 2 +- common/arg.cpp | 8 + common/common.h | 2 + common/speculative.cpp | 45 +++ docs/speculative.md | 22 ++ include/llama.h | 4 + scripts/build-draft-vocab.py | 130 ++++++++ src/llama-context.cpp | 145 +++++++++ src/llama-context.h | 7 + src/llama-graph.cpp | 22 +- src/llama-graph.h | 11 + tests/CMakeLists.txt | 1 + tests/test-draft-vocab.cpp | 173 ++++++++++ tests/test-llama-archs.cpp | 157 +++++++++ tools/cli/README.md | 1 + .../spec-trimmed-draft-vocab/mkvocab.py | 306 ++++++++++++++++++ tools/server/README.md | 1 + 17 files changed, 1035 insertions(+), 2 deletions(-) create mode 100755 scripts/build-draft-vocab.py create mode 100644 tests/test-draft-vocab.cpp create mode 100644 tools/rdna3-w2/spec-trimmed-draft-vocab/mkvocab.py diff --git a/ci/run.sh b/ci/run.sh index 5ea5f52ab120..11fbe0773e86 100755 --- a/ci/run.sh +++ b/ci/run.sh @@ -196,7 +196,7 @@ if [ ! -z ${GG_BUILD_OPENVINO} ]; then CMAKE_EXTRA="${CMAKE_EXTRA} -DGGML_OPENVINO=ON" # TODO: fix failing tests on OpenVINO backend - CTEST_EXTRA="-E test-llama-archs|test-llama-context|test-fp8-kv" + CTEST_EXTRA="-E test-llama-archs|test-llama-context|test-fp8-kv|test-draft-vocab" fi ## helpers diff --git a/common/arg.cpp b/common/arg.cpp index 7b9db4263b73..e4ab4d35cf20 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -4293,6 +4293,14 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.speculative.draft.p_min = std::stof(value); } ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_P_MIN")); + add_opt(common_arg( + {"--spec-draft-vocab"}, "FNAME", + "draft LM head computes only the token ids in FNAME (JSON array or one id per line) and the end-of-generation ids, " + "build the list with scripts/build-draft-vocab.py (default: full LM head)", + [](common_params & params, const std::string & value) { + params.speculative.draft.vocab_file = value; + } + ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_VOCAB")); add_opt(common_arg( {"--spec-draft-backend-sampling"}, {"--no-spec-draft-backend-sampling"}, diff --git a/common/common.h b/common/common.h index aa454944c98b..ea36f953fd24 100644 --- a/common/common.h +++ b/common/common.h @@ -349,6 +349,8 @@ struct common_params_speculative_draft { float p_split = 0.1f; // speculative decoding split probability float p_min = 0.0f; // minimum speculative decoding probability (greedy) + std::string vocab_file; // token ids the draft LM head computes, see --spec-draft-vocab (empty = full LM head) + bool backend_sampling = true; // offload draft sampling to the backend (default: on) bool probabilistic = false; // sample the draft and verify by rejection, instead of argmax and match diff --git a/common/speculative.cpp b/common/speculative.cpp index 60ed79d22803..c358faeccf69 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #define SPC_DBG(fmt, ...) LOG_DBG("spec %12.*s: " fmt, 12, __func__, __VA_ARGS__) @@ -3300,6 +3301,38 @@ struct common_speculative_init_result::impl { llama_context_ptr context; }; +// token ids of --spec-draft-vocab: a JSON array of integers or one id per line, range checks are done by the context +static bool common_speculative_load_vocab(const std::string & path, std::vector & ids, std::string & err) { + std::ifstream f(path); + if (!f) { + err = "cannot open the file"; + return false; + } + std::string text((std::istreambuf_iterator(f)), std::istreambuf_iterator()); + for (char & c : text) { + if (c == '[' || c == ']' || c == ',') { + c = ' '; + } + } + + std::istringstream ss(text); + std::string tok; + while (ss >> tok) { + char * end = nullptr; + const long v = std::strtol(tok.c_str(), &end, 10); + if (end == tok.c_str() || *end != '\0' || v < 0 || v > INT32_MAX) { + err = "'" + tok + "' is not a token id"; + return false; + } + ids.push_back((llama_token) v); + } + if (ids.empty()) { + err = "the list is empty"; + return false; + } + return true; +} + common_speculative_init_result::common_speculative_init_result( common_params & params, llama_model * model_tgt, @@ -3325,6 +3358,18 @@ common_speculative_init_result::common_speculative_init_result( cparams.n_rs_seq = 0; cparams.ctx_other = ctx_tgt; + // ids for --spec-draft-vocab, only read while the draft context is created + std::vector vocab_ids; + if (!params.speculative.draft.vocab_file.empty()) { + std::string err; + if (!common_speculative_load_vocab(params.speculative.draft.vocab_file, vocab_ids, err)) { + LOG_ERR("%s: --spec-draft-vocab '%s': %s\n", __func__, params.speculative.draft.vocab_file.c_str(), err.c_str()); + return; + } + cparams.vocab_subset = vocab_ids.data(); + cparams.n_vocab_subset = vocab_ids.size(); + } + std::string model_path; if (has_draft) { model_path = params.speculative.draft.mparams.path; diff --git a/docs/speculative.md b/docs/speculative.md index 3cd77046dca2..b3e3a77b72a0 100644 --- a/docs/speculative.md +++ b/docs/speculative.md @@ -284,6 +284,25 @@ Use exactly one of these options: - `--spec-synth-rates P0,P1,...` sets unconditional per-position acceptance probabilities. Entry `i` is the probability that the first `i+1` draft tokens are all accepted. The number of entries must match the effective maximum draft length. Values must be finite, within `[0, 1]`, and monotonically non-increasing. - `--spec-synth-len L` sets the target mean acceptance length, including the target token. For `K` maximum draft tokens, `L` must be within `[1, K+1]`. The server finds a constant conditional probability `p` such that `p + p^2 + ... + p^K = L - 1`, then uses unconditional rates `[p, p^2, ..., p^K]`. +### Reduced Draft Vocabulary + +`--spec-draft-vocab FNAME` makes the draft compute only the token ids in `FNAME` (JSON array or one id per line) and the end-of-generation ids. Their LM head rows are copied at load, so each draft token reads a smaller head. Unlisted ids get -inf logits (the softcap floor in drafts that softcap their logits), so they are practically never drafted; the target still verifies every token, so the output distribution does not change. A draft whose LM head cannot be reduced ignores the option with a warning. + +Build the list from text like the expected requests, ideally the target model's own outputs: + +```bash +python scripts/build-draft-vocab.py -m model.gguf --tokenize build/bin/llama-tokenize \ + --text-file outputs.jsonl --num-tokens 32768 -o draft-vocab.json + +llama-server -m model.gguf --spec-type draft-mtp --spec-draft-vocab draft-vocab.json +``` + +Notes for this fork: + +- The copy of the rows is a byte copy in the quant type of the head, so a 32k list of a 417 MB Q6_K head costs about 54 MB of extra VRAM (the copy is made in the buffer of the head). A head that is shared with the target (MTP in the same model, DFlash/DSpark without an own head) is copied once per head, the target keeps its full head. +- The draft must use the vocabulary of the list: one list serves every model with the same tokenizer (`mkvocab.py info` prints a token hash; Qwen3.8 and Qwen4 match, Gemma-4 and Nemotron-Bolt match). Drafts with their own reduced vocabulary (d2t) ignore the list. +- `tools/rdna3-w2/spec-trimmed-draft-vocab/mkvocab.py` builds 16k/32k/64k lists with only python and a CPU `llama-tokenize`. + ### General Speculative Parameters ``` @@ -319,6 +338,9 @@ Use exactly one of these options: --spec-draft-p-min, --draft-p-min P minimum speculative decoding probability (greedy) (default: 0.00) (env: LLAMA_ARG_SPEC_DRAFT_P_MIN) +--spec-draft-vocab FNAME + draft LM head computes only the token ids in FNAME (JSON array or one id per line) and the end-of-generation ids, build the list with scripts/build-draft-vocab.py (default: full LM head) + (env: LLAMA_ARG_SPEC_DRAFT_VOCAB) --spec-draft-ngl, -ngld, --gpu-layers-draft, --n-gpu-layers-draft N max. number of draft model layers to store in VRAM, either an exact number, 'auto', or 'all' (default: auto) (env: LLAMA_ARG_N_GPU_LAYERS_DRAFT) diff --git a/include/llama.h b/include/llama.h index 477049638d69..cbaa82b92b95 100644 --- a/include/llama.h +++ b/include/llama.h @@ -436,6 +436,10 @@ extern "C" { // a source/target/parent context // can be utilized in various ways, for example by sharing results or llama_memory between 2 contexts struct llama_context * ctx_other; + + // [EXPERIMENTAL] draft contexts: LM head computes only these ids and the end-of-generation ids, others get -inf before any final logit softcap (read at creation only) + const llama_token * vocab_subset; + size_t n_vocab_subset; }; struct llama_model_tensor_override { diff --git a/scripts/build-draft-vocab.py b/scripts/build-draft-vocab.py new file mode 100755 index 000000000000..c6d8f19259f8 --- /dev/null +++ b/scripts/build-draft-vocab.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys +import tempfile +from collections import Counter +from pathlib import Path + +if 'NO_LOCAL_GGUF' not in os.environ: + sys.path.insert(1, str(Path(__file__).parent.parent / 'gguf-py')) +import gguf # noqa: E402 + +DESCRIPTION = """ +Build the token id list for --spec-draft-vocab: the control and user-defined ids, the ids below --id-floor, then the +most frequent ids of the corpus (ideally text the target model generated), then the lowest unused ids. +An evenly spread --holdout of each file is left out of the counts to report the coverage of unseen text. + +Example: + python scripts/build-draft-vocab.py -m model.gguf --tokenize build/bin/llama-tokenize \\ + --text-file outputs.jsonl --num-tokens 32768 -o draft-vocab.json + + llama-server -m model.gguf --spec-type draft-mtp --spec-draft-vocab draft-vocab.json +""" + +KEEP_TYPES = {gguf.TokenType.CONTROL, gguf.TokenType.USER_DEFINED} + + +def read_docs(path: str) -> list[str]: + # .jsonl: one document per line, a string or an object ("text", chat "messages"/"conversations", else its strings) + if not path.endswith(".jsonl"): + return [Path(path).read_text(encoding="utf-8")] + docs = [] + with open(path, encoding="utf-8") as f: + for line in f: + if not line.strip(): + continue + row = json.loads(line) + if isinstance(row, dict): + turns = row.get("messages") or row.get("conversations") + if isinstance(row.get("text"), str): + row = row["text"] + elif isinstance(turns, list): + row = "\n".join(str(m.get("content") or m.get("value") or "") for m in turns) + else: + row = "\n".join(v for v in row.values() if isinstance(v, str)) + docs.append(row) + return docs + + +def tokenize(exe: str, model: str, docs: list[str]) -> list[int]: + if not docs: + return [] + with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="\n", suffix=".txt", delete=False) as f: + f.write("\n".join(docs)) + try: + res = subprocess.run([exe, "-m", model, "-f", f.name, "--ids", "--no-bos", "--no-escape", "--log-disable"], + capture_output=True, text=True, check=True) + finally: + os.unlink(f.name) + m = re.search(r"\[([0-9,\s]*)\]", res.stdout) + if m is None: + raise RuntimeError(f"no token ids in the output of {exe}") + return [int(x) for x in m.group(1).split(",") if x.strip()] + + +def main() -> None: + parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("-m", "--model", required=True, help="a GGUF of the target model (only the vocabulary is read)") + parser.add_argument("--tokenize", required=True, help="path to llama-tokenize") + parser.add_argument("--text-file", action="append", required=True, + help="plain text (one document) or .jsonl (one document per line), may be repeated") + parser.add_argument("--num-tokens", type=int, default=32768, help="number of ids in the list (default: 32768)") + parser.add_argument("--id-floor", type=int, default=0, help="always keep the ids below this value (default: 0)") + parser.add_argument("--holdout", type=float, default=0.05, help="fraction of each file left out of the counts, every 1/holdout-th document (default: 0.05)") + parser.add_argument("-o", "--output", required=True, help="output JSON file, ids sorted") + args = parser.parse_args() + + reader = gguf.GGUFReader(args.model, "r") + types = [int(t) for t in reader.fields["tokenizer.ggml.token_type"].contents()] + n_vocab = len(types) + if not 0 < args.num_tokens < n_vocab: + parser.error(f"--num-tokens must be in 1..{n_vocab - 1}") + + counts: Counter[int] = Counter() + held: dict[str, list[int]] = {} + n_docs = 0 + # every k-th document is held out, so a file sorted by language or source is sampled evenly + k = round(1 / args.holdout) if args.holdout > 0 else 0 + for path in args.text_file: + docs = read_docs(path) + is_held = [k > 0 and i % k == k - 1 for i in range(len(docs))] + train = tokenize(args.tokenize, args.model, [d for d, h in zip(docs, is_held) if not h]) + held[path] = tokenize(args.tokenize, args.model, [d for d, h in zip(docs, is_held) if h]) + counts.update(train) + n_docs += len(docs) - sum(is_held) + print(f"{path}: {len(docs) - sum(is_held)} documents, {len(train)} tokens, {sum(is_held)} documents held out") # noqa: NP100 + + keep = set(range(min(args.id_floor, n_vocab))) + keep.update(i for i, t in enumerate(types) if t in KEEP_TYPES) + n_fixed = len(keep) + if n_fixed > args.num_tokens: + parser.error(f"{n_fixed} ids are always kept, more than --num-tokens {args.num_tokens}") + for i in sorted(counts, key=lambda i: (-counts[i], i)): + if len(keep) >= args.num_tokens: + break + keep.add(i) + n_counted = len(keep) - n_fixed + for i in range(n_vocab): + if len(keep) >= args.num_tokens: + break + keep.add(i) + ids = sorted(keep) + + with open(args.output, "w") as f: + json.dump(ids, f) + + print(f"wrote {len(ids)} of {n_vocab} ids to {args.output}: {n_fixed} control/user-defined/floor, {n_counted} by frequency " # noqa: NP100 + f"({len(counts)} distinct ids in {sum(counts.values())} tokens of {n_docs} documents), {len(ids) - n_fixed - n_counted} lowest unused") + for path, toks in held.items(): + if toks: + print(f"held-out coverage of {path}: {100 * sum(t in keep for t in toks) / len(toks):.2f}% of {len(toks)} tokens") # noqa: NP100 + + +if __name__ == "__main__": + main() diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 787c8029587b..ef581c8cbe72 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -534,6 +534,19 @@ llama_context::llama_context( memory.reset(model.create_memory(params_mem, cparams)); } + // reduced LM head, must exist before the graph is reserved + if (!hparams.vocab_only && params.vocab_subset != nullptr && params.n_vocab_subset > 0) { + try { + vocab_subset_init(params.vocab_subset, params.n_vocab_subset); + } catch (const std::exception & e) { + // e.g. out of memory or an id outside the vocabulary, the draft still works with the full head + LLAMA_LOG_WARN("%s: vocab_subset: %s, using the full LM head\n", __func__, e.what()); + vocab_subset.reset(); + vocab_subset_bufs.clear(); + vocab_subset_ctxs.clear(); + } + } + // init backends if (!hparams.vocab_only) { LLAMA_LOG_DEBUG("%s: enumerating backends\n", __func__); @@ -2962,6 +2975,11 @@ uint32_t llama_context::graph_max_nodes() const { res += llama_sampler_backend_n_nodes(sampler) * cparams.n_outputs_max_per_seq; } + // build_lora_mm() adds up to 8 entries per reduced head to the scheduler's hash set (sized by max_nodes, holds nodes and leafs): 5 nodes (ggml_fill, ggml_set_rows, three reshapes) and up to 3 leafs (ggml_fill's shape tensor, the ids, and the row copy when the head is also the token embedding) + if (vocab_subset) { + res += 8*(uint32_t) vocab_subset->heads.size(); + } + if (cparams.training) { res *= 4; } @@ -3143,6 +3161,7 @@ llm_graph_params llama_context::graph_params( /*.n_outputs =*/ n_outputs, /*.cb =*/ graph_get_cb(), /*.res =*/ res, + /*.vocab_subset =*/ vocab_subset.get(), }; } @@ -3165,6 +3184,130 @@ void llama_context::sched_graph_realloc(ggml_backend_sched_t sched, ggml_cgraph lctx->n_reallocs_same, lctx->n_reallocs_diff); } +// reduced draft LM head: the listed ids get exact logits from a copy of their rows of the head, every other id gets -inf +void llama_context::vocab_subset_init(const llama_token * list, size_t n_list) { + // the list holds target ids, which need not match the head rows of a draft that maps its own vocabulary with d2t + if (model.d2t != nullptr) { + LLAMA_LOG_WARN("%s: the draft maps its own vocabulary with d2t, the list is ignored\n", __func__); + return; + } + + const int64_t t_start_us = ggml_time_us(); + + const int64_t n_vocab = model.vocab.n_tokens(); + + // the listed ids and every end-of-generation id, sorted and unique + std::vector ids; + ids.reserve(n_list); + for (size_t i = 0; i < n_list; ++i) { + if (list[i] < 0 || list[i] >= n_vocab) { + throw std::runtime_error(format("token id %d is outside the vocabulary of %" PRId64 " tokens", list[i], n_vocab)); + } + ids.push_back(list[i]); + } + for (llama_token id = 0; id < (llama_token) n_vocab; ++id) { + if (model.vocab.is_eog(id)) { + ids.push_back(id); + } + } + std::sort(ids.begin(), ids.end()); + ids.erase(std::unique(ids.begin(), ids.end()), ids.end()); + + if ((int64_t) ids.size() >= n_vocab) { + LLAMA_LOG_WARN("%s: the list covers all %" PRId64 " ids, using the full LM head\n", __func__, n_vocab); + return; + } + + // the model's head, the MTP heads, and the target's head for drafters without one + std::vector cands = { model.output }; + for (const auto & layer : model.layers) { + cands.push_back(layer.nextn.shared_head_head); + } + if (model.output == nullptr && cparams.ctx_other != nullptr) { + cands.push_back(llama_get_model(cparams.ctx_other)->output); + } + + vocab_subset = std::make_unique(); + + for (ggml_tensor * w : cands) { + if (w == nullptr || vocab_subset->heads.count(w) || ggml_n_dims(w) != 2 || w->ne[1] < n_vocab || !ggml_is_contiguous(w) || w->buffer == nullptr) { + continue; + } + + // a head with more rows than the vocabulary (padded, e.g. the target head shared by DFlash) keeps its shape, the extra rows get -inf + // the rows are read by byte offset, so skip repacked, row-split and tensor-parallel (meta device) weights + ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(w->buffer); + ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft); + if ((!ggml_backend_buft_is_host(buft) && (dev == nullptr || ggml_backend_dev_buffer_type(dev) != buft)) || + (dev != nullptr && ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_META)) { + LLAMA_LOG_WARN("%s: %s is in buffer type %s, not supported\n", __func__, w->name, ggml_backend_buft_name(buft)); + continue; + } + + // the rows are copied without their per-row weight scale, so such heads keep the full head (same lookup as get_weight_scale) + const ggml_tensor * w_s = model.w_scales.get(w); + if (w_s == nullptr && cparams.ctx_other != nullptr) { + w_s = llama_get_model(cparams.ctx_other)->w_scales.get(w); + } + if (w_s != nullptr && !ggml_is_scalar(w_s)) { + LLAMA_LOG_WARN("%s: %s has a per-row weight scale, not supported\n", __func__, w->name); + continue; + } + + ggml_init_params ip = { + /*.mem_size =*/ 2*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context * ctx = ggml_init(ip); + vocab_subset_ctxs.emplace_back(ctx); + + // the listed rows, in the type of the head + ggml_tensor * rows = ggml_new_tensor_2d(ctx, w->type, w->ne[0], ids.size()); + + // the ids are stored next to the first head + const bool with_ids = vocab_subset->ids == nullptr; + if (with_ids) { + vocab_subset->ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, ids.size()); + } + + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft); + if (buf == nullptr) { + throw std::runtime_error("failed to allocate the reduced LM head"); + } + ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS); + vocab_subset_bufs.emplace_back(buf); + + if (with_ids) { + ggml_backend_tensor_set(vocab_subset->ids, ids.data(), 0, ids.size()*sizeof(int32_t)); + } + + // one read per run of consecutive ids + const size_t row_size = w->nb[1]; + std::vector data(ids.size()*row_size); + for (size_t i = 0; i < ids.size(); ) { + size_t j = i + 1; + while (j < ids.size() && ids[j] == ids[j - 1] + 1) { + ++j; + } + ggml_backend_tensor_get(w, data.data() + i*row_size, (size_t) ids[i]*row_size, (j - i)*row_size); + i = j; + } + ggml_backend_tensor_set(rows, data.data(), 0, data.size()); + + vocab_subset->heads[w] = rows; + } + + if (vocab_subset->heads.empty()) { + LLAMA_LOG_WARN("%s: no supported LM head with a row for every token id, the list is ignored\n", __func__); + vocab_subset.reset(); + return; + } + + LLAMA_LOG_INFO("%s: %zu of %" PRId64 " ids (the list plus the end-of-generation ids), %zu LM head(s), %.2f s\n", + __func__, ids.size(), n_vocab, vocab_subset->heads.size(), (ggml_time_us() - t_start_us)/1e6); +} + ggml_status llama_context::graph_compute( ggml_cgraph * gf, bool batched) { @@ -4516,6 +4659,8 @@ llama_context_params llama_context_default_params() { /*.sampler =*/ nullptr, /*.n_sampler =*/ 0, /*.ctx_other =*/ nullptr, + /*.vocab_subset =*/ nullptr, + /*.n_vocab_subset =*/ 0, }; return result; diff --git a/src/llama-context.h b/src/llama-context.h index 9153cd244a0d..84e46d6457b6 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -320,6 +320,8 @@ struct llama_context { // ggml_backend_sched realloc callback, counts and traces the graph reallocations of this context static void sched_graph_realloc(ggml_backend_sched_t sched, ggml_cgraph * gf, bool backend_ids_changed, bool graph_size_changed, void * user_data); + void vocab_subset_init(const llama_token * list, size_t n_list); + // disable auto fused ops (Flash Attention, Gated Delta Net) whose op lands on a device // that differs from the layer it belongs to (usually due to missing backend support) void resolve_fused_ops(const llama_memory_context_i * mctx, uint32_t n_seqs); @@ -511,6 +513,11 @@ struct llama_context { bool ev_h_nextn_written_recorded = false; bool ev_h_nextn_read_recorded = false; + // reduced draft LM head, nullptr = full LM head + std::unique_ptr vocab_subset; + std::vector vocab_subset_ctxs; + std::vector vocab_subset_bufs; + // keep copies of the per-sequence memory on the device std::map mem_storage; diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 7a5411d17a4a..2249e0108955 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1781,6 +1781,7 @@ llm_graph_context::llm_graph_context(const llm_graph_params & params) : samplers (params.samplers), cb_func (params.cb), res (params.res), + vocab_subset (params.vocab_subset), ctx0 (res->get_ctx()), gf (res->get_gf()) { res->set_params(params); @@ -1885,7 +1886,16 @@ ggml_tensor * llm_graph_context::build_lora_mm( ggml_tensor * cur) const { // a Hadamard-folded weight reads the transformed input; a LoRA delta lives in the primal basis and reads `cur` ggml_tensor * cur_mm = build_hadamard_input(w, cur); - ggml_tensor * res = ggml_mul_mat_ext(ctx0, w, cur_mm, get_weight_scale(w), get_input_scale(w)); + + // reduced draft LM head, not with a LoRA on the head: multiply by the copy of the listed rows, then scatter into -inf logits + ggml_tensor * rows = nullptr; + if (vocab_subset != nullptr && ggml_n_dims(cur_mm) <= 2 && cur_mm->ne[1] > 0 && + std::none_of(loras->begin(), loras->end(), [w](const auto & lora) { return lora.first->get_weight(w) != nullptr; })) { + const auto it = vocab_subset->heads.find(w); + rows = it != vocab_subset->heads.end() ? it->second : nullptr; + } + + ggml_tensor * res = ggml_mul_mat_ext(ctx0, rows ? rows : w, cur_mm, get_weight_scale(w), get_input_scale(w)); if (w->type == GGML_TYPE_NVFP4) { ggml_prec_set_acc(res, GGML_PREC_BF16); @@ -1893,6 +1903,16 @@ ggml_tensor * llm_graph_context::build_lora_mm( prec_policy.apply(res, w); + if (rows != nullptr) { + const int64_t n_vocab = w->ne[1]; + const int64_t n_ids = rows->ne[1]; + const int64_t n_outputs = res->ne[1]; + + ggml_tensor * logits = ggml_fill(ctx0, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 1, n_vocab, n_outputs), -INFINITY); + logits = ggml_set_rows(ctx0, logits, ggml_reshape_3d(ctx0, res, 1, n_ids, n_outputs), ggml_reshape_3d(ctx0, vocab_subset->ids, n_ids, 1, 1)); + return ggml_reshape_2d(ctx0, logits, n_vocab, n_outputs); + } + for (const auto & lora : *loras) { llama_adapter_lora_weight * lw = lora.first->get_weight(w); if (lw == nullptr) { diff --git a/src/llama-graph.h b/src/llama-graph.h index c386ea7ff53b..566bc2dc4980 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -871,6 +871,13 @@ using llm_graph_cb = std::function heads; // head -> copy of its listed rows, in the type of the head + + ggml_tensor * ids = nullptr; // I32 listed and end-of-generation ids, sorted +}; + struct llm_graph_params { const llama_model * model = nullptr; @@ -918,6 +925,8 @@ struct llm_graph_params { llm_graph_result * res; + const llama_vocab_subset * vocab_subset = nullptr; + // return true if the "other" params would result in a graph with the same topology as with the current params // having the same topology allows us to reuse the graph in some cases bool allow_reuse(const llm_graph_params & other) const { @@ -1179,6 +1188,8 @@ struct llm_graph_context { llm_graph_result * res; + const llama_vocab_subset * vocab_subset; + ggml_context * ctx0 = nullptr; ggml_cgraph * gf = nullptr; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 531f34c1f28d..57c836be1587 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -319,6 +319,7 @@ llama_build_and_test(test-chat-template.cpp LABEL behavior) # debug tool for chat template differential analysis (not registered as a test, run it manually) llama_build(test-chat-analysis.cpp) llama_build_and_test(test-log.cpp LABEL behavior) +llama_build_and_test(test-draft-vocab.cpp LABEL "main behavior backend" LINK llama) llama_build_and_test( test-peg-parser.cpp peg-parser/simple-tokenize.cpp diff --git a/tests/test-draft-vocab.cpp b/tests/test-draft-vocab.cpp new file mode 100644 index 000000000000..072b810a1731 --- /dev/null +++ b/tests/test-draft-vocab.cpp @@ -0,0 +1,173 @@ +// tests the reduced draft LM head (llama_context_params::vocab_subset) against the full head on a small random model + +#include "ggml-backend.h" +#include "gguf.h" +#include "llama.h" +#include "llama-cpp.h" + +#include +#include +#include +#include +#include +#include +#include + +static const int32_t n_vocab = 40960; +static const int32_t n_embd = 64; +static const int32_t eos = n_vocab - 1; // not in the lists, so it has to be added on its own + +static void set_tensor_data(ggml_tensor * tensor, void * /*userdata*/) { + std::mt19937 gen(std::hash{}(tensor->name)); + std::normal_distribution dis(0.0f, 0.1f); + + std::vector data(ggml_nelements(tensor)); + for (float & v : data) { + v = dis(gen); + } + ggml_backend_tensor_set(tensor, data.data(), 0, ggml_nbytes(tensor)); +} + +static gguf_context * make_metadata() { + gguf_context * meta = gguf_init_empty(); + + gguf_set_val_str(meta, "general.architecture", "llama"); + gguf_set_val_u32(meta, "llama.vocab_size", n_vocab); + gguf_set_val_u32(meta, "llama.context_length", 256); + gguf_set_val_u32(meta, "llama.embedding_length", n_embd); + gguf_set_val_u32(meta, "llama.feed_forward_length", 128); + gguf_set_val_u32(meta, "llama.block_count", 1); + gguf_set_val_u32(meta, "llama.attention.head_count", 2); + gguf_set_val_u32(meta, "llama.attention.head_count_kv", 2); + gguf_set_val_f32(meta, "llama.attention.layer_norm_rms_epsilon", 1e-5f); + + std::vector tokens(n_vocab); + std::vector token_ptrs(n_vocab); + std::vector scores(n_vocab, 0.0f); + for (int32_t i = 0; i < n_vocab; ++i) { + tokens[i] = "tok_" + std::to_string(i); + token_ptrs[i] = tokens[i].c_str(); + } + gguf_set_val_str (meta, "tokenizer.ggml.model", "test"); + gguf_set_arr_str (meta, "tokenizer.ggml.tokens", token_ptrs.data(), n_vocab); + gguf_set_arr_data(meta, "tokenizer.ggml.scores", GGUF_TYPE_FLOAT32, scores.data(), n_vocab); + gguf_set_val_u32 (meta, "tokenizer.ggml.eos_token_id", eos); + + return meta; +} + +// returns the number of logits that differ from the full head; computed = ids expected to get logits, empty = all (full head fallback) +static int run(llama_model * model, const char * name, const std::vector & list, const std::set & computed) { + llama_context_params cparams = llama_context_default_params(); + cparams.n_ctx = 256; + cparams.n_batch = 64; + cparams.n_ubatch = 64; + cparams.n_threads = 4; + cparams.n_threads_batch = 4; + + llama_context * ctx_full = llama_init_from_model(model, cparams); + cparams.vocab_subset = list.data(); + cparams.n_vocab_subset = list.size(); + llama_context * ctx_list = llama_init_from_model(model, cparams); + if (ctx_full == nullptr || ctx_list == nullptr) { + fprintf(stderr, "%s: %s: failed to create the contexts\n", __func__, name); + return 1; + } + + int n_fail = 0; + + // a batch with no outputs, a batch with several outputs and a batch with one output + const std::vector> steps = { + std::vector(8, false), + std::vector(16, true), + { true }, + }; + + llama_pos pos = 0; + for (const auto & outputs : steps) { + llama_batch_ext_ptr batch_full(llama_batch_ext_init(ctx_full)); + llama_batch_ext_ptr batch_list(llama_batch_ext_init(ctx_list)); + for (size_t i = 0; i < outputs.size(); ++i) { + for (llama_batch_ext * batch : { batch_full.get(), batch_list.get() }) { + const int32_t idx = llama_batch_ext_add_token(batch, 0, (llama_token) ((7919*pos + 13) % n_vocab)); + llama_batch_ext_set_pos(batch, idx, &pos); + llama_batch_ext_set_output_logits(batch, idx, outputs[i]); + } + pos++; + } + + if (llama_process(ctx_full, LLAMA_PROCESS_TYPE_DECODE, batch_full.get()) != 0 || + llama_process(ctx_list, LLAMA_PROCESS_TYPE_DECODE, batch_list.get()) != 0) { + fprintf(stderr, "%s: %s: decode failed\n", __func__, name); + return n_fail + 1; + } + + for (size_t i = 0; i < outputs.size(); ++i) { + if (!outputs[i]) { + continue; + } + const float * full = llama_get_logits_ith(ctx_full, (int32_t) i); + const float * part = llama_get_logits_ith(ctx_list, (int32_t) i); + + for (int32_t t = 0; t < n_vocab; ++t) { + // listed ids match the full head, the others are exactly -inf + const bool want = computed.empty() || computed.count(t); + const bool ok = want ? std::fabs(part[t] - full[t]) <= 1e-3f*(1.0f + std::fabs(full[t])) : part[t] == -INFINITY; + if (!ok) { + fprintf(stderr, "%s: %s: token %d (%s): logit %f, full head %f\n", __func__, name, t, want ? "listed" : "not listed", part[t], full[t]); + n_fail++; + } + } + } + } + + llama_free(ctx_list); + llama_free(ctx_full); + + return n_fail; +} + +int main(void) { + llama_backend_init(); + + gguf_context * meta = make_metadata(); + llama_model * model = llama_model_init_from_user(meta, set_tensor_data, nullptr, llama_model_default_params()); + if (model == nullptr) { + fprintf(stderr, "%s: failed to create the model\n", __func__); + return 1; + } + + // scattered ids and a run of consecutive ids, given unsorted and with duplicates + std::vector list; + for (int32_t id = 0; id < 20000; id += 5) { + list.push_back(id); + } + for (int32_t id = 30999; id >= 30000; --id) { + list.push_back(id); + } + list.push_back(100); + + std::set computed(list.begin(), list.end()); + computed.insert(eos); + + std::vector bad = list; + bad.push_back(n_vocab); + + std::vector all(n_vocab); + for (int32_t id = 0; id < n_vocab; ++id) { + all[id] = id; + } + + int n_fail = 0; + n_fail += run(model, "list", list, computed); + n_fail += run(model, "id outside the vocab", bad, {}); // falls back to the full head + n_fail += run(model, "every id", all, {}); // falls back to the full head + + llama_model_free(model); + gguf_free(meta); + llama_backend_free(); + + printf("%s: %s\n", __func__, n_fail == 0 ? "OK" : "FAILED"); + + return n_fail == 0 ? 0 : 1; +} diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index dc4eeaba4d7c..7ee98044e2bb 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -179,6 +180,7 @@ static void usage(char ** argv) { LOG(" -b, --backend Run only on the given backend device\n"); LOG(" --rpc Add RPC servers (comma-separated host:port), must precede -b\n"); LOG(" --kv-shift Check K-shift against a decode at the shifted positions (CPU only)\n"); + LOG(" --draft-vocab Check the reduced draft LM head (vocab_subset) against the full head (CPU only)\n"); LOG(" -h, --help Show this help message\n\n"); LOG("Examples:\n"); LOG(" %s\n", argv[0]); @@ -1996,6 +1998,155 @@ static int test_kv_shift(const std::string & arch_filter, const size_t seed, con return n_failed == 0 ? 0 : 1; } +// reduced draft LM head (llama_context_params::vocab_subset): a context with a token id list must give the logits of the +// full head on the listed ids (and the end-of-generation ids) and -inf on every other id (CPU only) +static int test_draft_vocab(const std::string & arch_filter, const size_t seed, const float stdev, const int verbosity) { + struct user_data_t { + struct { + ggml_log_callback callback; + void * user_data; + } log_old; + + int verbosity; + + user_data_t(int verbosity) : verbosity(verbosity) { + llama_log_get(&log_old.callback, &log_old.user_data); + } + }; + user_data_t ud(verbosity); + + llama_log_set([](ggml_log_level level, const char * text, void * user_data) { + const user_data_t * ud = (const user_data_t *) user_data; + int verbosity = common_log_get_verbosity(level); + if (verbosity <= ud->verbosity) { + ud->log_old.callback(level, text, ud->log_old.user_data); + } + }, &ud); + + // the default selection is the archs whose draft/MTP heads go through build_lora_mm() + const std::string filter = arch_filter.empty() ? "^(llama|qwen35|qwen35moe|qwen4exp)$" : arch_filter; + + const uint32_t n_tokens = 24; + + size_t max_arch_name_length = 0; + for (const llm_arch & arch : llama_arch_all()) { + max_arch_name_length = std::max(max_arch_name_length, strlen(llama_arch_name(arch))); + } + const std::string template_row = "|%" + std::to_string(max_arch_name_length) + "s|%6s|%s\n"; + + size_t n_tests = 0; + size_t n_failed = 0; + common_log_flush(common_log_main()); + LOG(template_row.c_str(), "Model arch.", "Config", "Status"); + + for (const llm_arch & arch : llama_arch_all()) { + if (arch == LLM_ARCH_UNKNOWN || !arch_matches(filter, arch) || !arch_supported(arch)) { + continue; + } + const bool encode = arch == LLM_ARCH_T5 || arch == LLM_ARCH_DREAM || arch == LLM_ARCH_LLADA || arch == LLM_ARCH_LLADA_MOE || arch == LLM_ARCH_RND1; + if (encode || arch == LLM_ARCH_EAGLE3 || arch == LLM_ARCH_DFLASH || arch == LLM_ARCH_GEMMA4_ASSISTANT) { + continue; + } + for (bool moe : {false, true}) { + if (moe && !moe_implemented(arch)) { + continue; + } + if (!moe && moe_mandatory(arch)) { + continue; + } + n_tests++; + LOG("|%*s|%6s|", (int) max_arch_name_length, llama_arch_name(arch), moe ? "MoE" : "Dense"); + + std::string status; + try { + gguf_context_ptr gguf_ctx = get_gguf_ctx(arch, moe, 4); + if (arch == LLM_ARCH_BAILINGMOE3) { + GGML_ASSERT(gguf_remove_key(gguf_ctx.get(), "bailingmoe3.kda.safe_gate") >= 0); + } + llama_model_ptr model = get_model(gguf_ctx.get(), nullptr, seed, stdev, {}); + + const llama_vocab * vocab = llama_model_get_vocab(model.get()); + const int32_t n_vocab = llama_vocab_n_tokens(vocab); + + // unsorted, with a duplicate; ids 0 and every third id up to n_vocab/2 are listed, the upper half is not + std::vector list; + for (int32_t id = (n_vocab/2 / 3)*3; id >= 0; id -= 3) { + list.push_back(id); + } + list.push_back(0); + + std::set computed(list.begin(), list.end()); + for (int32_t id = 0; id < n_vocab; ++id) { + if (llama_vocab_is_eog(vocab, id)) { + computed.insert(id); + } + } + + llama_context_params cparams = llama_context_default_params(); + cparams.n_ctx = 0; + cparams.n_ubatch = 64; + cparams.n_threads = 4; + cparams.n_threads_batch = 4; + llama_context_ptr ctx_full(llama_init_from_model(model.get(), cparams)); + cparams.vocab_subset = list.data(); + cparams.n_vocab_subset = list.size(); + llama_context_ptr ctx_list(llama_init_from_model(model.get(), cparams)); + if (!ctx_full || !ctx_list) { + throw std::runtime_error("failed to create the contexts"); + } + + const std::vector tokens = get_tokens(n_tokens, n_vocab, seed); + const std::vector full = get_logits(model.get(), ctx_full.get(), tokens); + const std::vector part = get_logits(model.get(), ctx_list.get(), tokens); + + size_t n_bad = 0; + size_t n_inf = 0; + double worst = 0.0; + for (uint32_t i = 0; i < n_tokens; ++i) { + for (int32_t t = 0; t < n_vocab; ++t) { + const float f = full[(size_t) i*n_vocab + t]; + const float p = part[(size_t) i*n_vocab + t]; + if (computed.count(t)) { + // a listed id gets exact logits: same weights (a byte copy of the rows), same kernel + const double d = std::fabs((double) p - f)/(1.0 + std::fabs((double) f)); + worst = std::max(worst, d); + n_bad += d > 1e-4; + } else { + n_inf += p == -INFINITY; + n_bad += p != -INFINITY && p != f; // p == f: the head was not reduced (full head fallback) + } + } + } + char buf[96]; + if (n_bad > 0) { + n_failed++; + snprintf(buf, sizeof(buf), "\033[1;31mFAIL\033[0m (%zu logits differ, worst listed %.2e)", n_bad, worst); + } else if (n_inf == 0) { + snprintf(buf, sizeof(buf), "\033[1;33mSKIP\033[0m (no reducible head, full head used)"); + } else { + snprintf(buf, sizeof(buf), "\033[1;32mOK\033[0m (listed %zu of %d ids, worst %.2e)", computed.size(), n_vocab, worst); + } + status = buf; + } catch (const std::exception & err) { + n_failed++; + status = std::string("\033[1;31mERROR\033[0m (") + err.what() + ")"; + } + LOG("%s\n", status.c_str()); + } + } + + if (n_tests == 0) { + LOG("Summary: no tests executed\n"); + } else if (n_failed == 0) { + LOG("Summary: all %zu test(s) passed\n", n_tests); + } else { + LOG("Summary: %zu test(s) executed, %zu failed\n", n_tests, n_failed); + } + + llama_log_set(ud.log_old.callback, ud.log_old.user_data); + return n_failed == 0 ? 0 : 1; +} + static bool add_rpc_devices(const std::string & endpoints) { ggml_backend_reg_t rpc_reg = ggml_backend_reg_by_name("RPC"); if (rpc_reg == nullptr) { @@ -2035,6 +2186,7 @@ int main(int argc, char ** argv) { std::string out; const char * target_backend = nullptr; bool kv_shift = false; + bool draft_vocab = false; int verbosity = LOG_LEVEL_ERROR; @@ -2114,6 +2266,8 @@ int main(int argc, char ** argv) { } } else if (strcmp(argv[i], "--kv-shift") == 0) { kv_shift = true; + } else if (strcmp(argv[i], "--draft-vocab") == 0) { + draft_vocab = true; } else { LOG_ERR("%s: unknown argument: %s\n", __func__, argv[i]); usage(argv); @@ -2135,6 +2289,9 @@ int main(int argc, char ** argv) { if (kv_shift) { return test_kv_shift(arch_filter, seed, stdev, verbosity); } + if (draft_vocab) { + return test_draft_vocab(arch_filter, seed, stdev, verbosity); + } return test_backends(arch_filter, seed, stdev, verbosity, target_backend); } catch (const std::exception & err) { fprintf(stderr, "encountered runtime error: %s\n", err.what()); diff --git a/tools/cli/README.md b/tools/cli/README.md index 1dc83ee81e2e..54a23369e20e 100644 --- a/tools/cli/README.md +++ b/tools/cli/README.md @@ -206,6 +206,7 @@ | `--spec-synth-rates P0,P1,...` | comma-separated unconditional per-position synthetic acceptance probabilities (benchmarking only)
(env: LLAMA_ARG_SPEC_SYNTH_RATES) | | `--spec-draft-p-split, --draft-p-split P` | speculative decoding split probability (default: 0.10)
(env: LLAMA_ARG_SPEC_DRAFT_P_SPLIT) | | `--spec-draft-p-min, --draft-p-min P` | minimum speculative decoding probability (greedy) (default: 0.00)
(env: LLAMA_ARG_SPEC_DRAFT_P_MIN) | +| `--spec-draft-vocab FNAME` | draft LM head computes only the token ids in FNAME (JSON array or one id per line) and the end-of-generation ids, build the list with scripts/build-draft-vocab.py (default: full LM head)
(env: LLAMA_ARG_SPEC_DRAFT_VOCAB) | | `--spec-draft-backend-sampling, --no-spec-draft-backend-sampling` | offload draft sampling to the backend (default: enabled)
(env: LLAMA_ARG_SPEC_DRAFT_BACKEND_SAMPLING) | | `--spec-draft-sampling {greedy,probabilistic}` | how the draft is sampled: greedy takes its argmax, probabilistic samples it and has the target verify by rejection sampling (default: greedy)
(env: LLAMA_ARG_SPEC_DRAFT_SAMPLING) | | `--spec-draft-device, -devd, --device-draft ` | comma-separated list of devices to use for offloading the draft model (none = don't offload, default: follows --device)
use --list-devices to see a list of available devices | diff --git a/tools/rdna3-w2/spec-trimmed-draft-vocab/mkvocab.py b/tools/rdna3-w2/spec-trimmed-draft-vocab/mkvocab.py new file mode 100644 index 000000000000..b64a69170f00 --- /dev/null +++ b/tools/rdna3-w2/spec-trimmed-draft-vocab/mkvocab.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +""" +Token id lists for --spec-draft-vocab (reduced draft LM head). + +Pure python, no numpy / gguf-py needed: it reads only the metadata of a GGUF (tokenizer + tensor table) and calls a +CPU llama-tokenize (vocab only, never opens a GPU) for the frequency counts. + + mkvocab.py info FILE.gguf [...] tokenizer fingerprint + LM head tensors (decides which list fits which model) + mkvocab.py build -m FILE.gguf --tokenize llama-tokenize --text PATH [--text PATH ...] --prefix qwen --outdir DIR + +build writes DIR/-16k.txt, -32k.txt, -64k.txt (one id per line; the server also accepts JSON arrays). +A list always contains + * every token whose type is not NORMAL (control, user defined, byte, unknown), unused tokens excluded, + * every token that decodes to a single byte (the byte alphabet, so any UTF-8 text stays representable), + * every whitespace-only token (spaces, newlines, tabs, indentation runs), +then the ids ranked by frequency over the --text corpora (files or directories; every 20th document/chunk is held out +and used only for the coverage report), then, if the corpus has fewer distinct ids than the list size, the lowest unused +ids (BPE and sentencepiece vocabularies are roughly ordered from frequent to rare, so low ids are the best blind guess). +The end-of-generation ids are added by the runtime itself. +""" +import argparse +import hashlib +import os +import re +import struct +import subprocess +import sys +import tempfile +from collections import Counter + +# ---------------------------------------------------------------- minimal GGUF metadata reader + +GGML_TYPES = {0: "F32", 1: "F16", 2: "Q4_0", 3: "Q4_1", 6: "Q5_0", 7: "Q5_1", 8: "Q8_0", 9: "Q8_1", 10: "Q2_K", 11: "Q3_K", + 12: "Q4_K", 13: "Q5_K", 14: "Q6_K", 15: "Q8_K", 16: "IQ2_XXS", 17: "IQ2_XS", 18: "IQ3_XXS", 19: "IQ1_S", + 20: "IQ4_NL", 21: "IQ3_S", 22: "IQ2_S", 23: "IQ4_XS", 24: "I8", 25: "I16", 26: "I32", 27: "I64", 28: "F64", + 29: "IQ1_M", 30: "BF16"} +# (block elements, bytes per block) for the types that are used for LM heads +BLOCK = {"F32": (1, 4), "F16": (1, 2), "BF16": (1, 2), "Q4_0": (32, 18), "Q4_1": (32, 20), "Q5_0": (32, 22), "Q5_1": (32, 24), + "Q8_0": (32, 34), "Q2_K": (256, 84), "Q3_K": (256, 110), "Q4_K": (256, 144), "Q5_K": (256, 176), "Q6_K": (256, 210), + "IQ4_NL": (32, 18), "IQ4_XS": (256, 136), "IQ3_XXS": (256, 98), "IQ3_S": (256, 110), "IQ2_XXS": (256, 66)} +SCALAR = {0: " bytes it stands for (best effort, only used to find byte and whitespace tokens)""" + if ttype == TT_BYTE: + m = re.fullmatch(r"<0x([0-9A-Fa-f]{2})>", tok) + return bytes([int(m.group(1), 16)]) if m else tok.encode() + if model == "gpt2": + inv = {v: k for k, v in bytes_to_unicode().items()} + try: + return bytes(inv[c] for c in tok) + except KeyError: + return tok.encode() + return tok.replace("▁", " ").encode() + + +def fixed_ids(kv): + toks = kv["tokenizer.ggml.tokens"] + types = kv.get("tokenizer.ggml.token_type") or [TT_NORMAL] * len(toks) + model = kv.get("tokenizer.ggml.model", "") + inv = {v: k for k, v in bytes_to_unicode().items()} + keep, why = set(), Counter() + for i, (tok, tt) in enumerate(zip(toks, types)): + if tt == TT_UNUSED: + continue + if tt != TT_NORMAL: + keep.add(i) + why["non-normal type"] += 1 + continue + if model == "gpt2": + try: + raw = bytes(inv[c] for c in tok) + except KeyError: + raw = tok.encode() + else: + raw = tok.replace("▁", " ").encode() + if len(raw) == 1: + keep.add(i) + why["single byte"] += 1 + elif raw and not raw.strip(): + keep.add(i) + why["whitespace only"] += 1 + return keep, why, types + + +def fingerprint(kv): + toks = kv.get("tokenizer.ggml.tokens") or [] + return len(toks), hashlib.sha1("\n".join(toks).encode("utf-8", "replace")).hexdigest()[:12] + + +def head_info(tensors): + out = [] + for name, tt, shape in tensors: + if name in ("output.weight", "token_embd.weight") or "shared_head" in name or name.endswith("lm_head.weight"): + ne, nb = BLOCK.get(tt, (1, 0)) + size = shape[0] // ne * nb * shape[1] if len(shape) == 2 else 0 + out.append("%s %s %s %.0f MB" % (name, tt, "x".join(map(str, shape)), size / 1e6)) + return out + + +def cmd_info(args): + for p in args.files: + kv, tensors = read_gguf(p, TOK_KEYS) + n, h = fingerprint(kv) + print("%s\n arch=%s tokenizer=%s/%s n_tokens=%d token-hash=%s" % ( + p, kv.get("general.architecture"), kv.get("tokenizer.ggml.model"), kv.get("tokenizer.ggml.pre"), n, h)) + for line in head_info(tensors): + print(" head:", line) + + +# ---------------------------------------------------------------- corpus + tokenization + +def read_corpus(paths, exts=(".txt", ".md", ".py", ".cpp", ".h", ".cu", ".cuh", ".c", ".sh", ".json", ".jsonl", ".cmake", ".ini")): + """documents: one per file; files over 64 KB are cut into chunks so that the hold-out is spread evenly""" + docs = [] + files = [] + for p in paths: + if os.path.isdir(p): + for root, _, names in os.walk(p): + files += [os.path.join(root, n) for n in sorted(names) if n.lower().endswith(exts)] + else: + files.append(p) + for fn in sorted(files): + try: + text = open(fn, encoding="utf-8", errors="replace").read() + except OSError: + continue + for i in range(0, len(text), 65536): + docs.append(text[i:i + 65536]) + return docs + + +def tokenize(exe, model, docs): + if not docs: + return [] + ids = [] + # one call per batch of documents keeps the command line and the memory small + batch, size = [], 0 + for d in docs + [None]: + if d is not None: + batch.append(d) + size += len(d) + if batch and (d is None or size > 1_000_000): + with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="\n", suffix=".txt", delete=False) as f: + f.write("\n".join(batch)) + try: + res = subprocess.run([exe, "-m", model, "-f", f.name, "--ids", "--no-bos", "--no-escape", "--log-disable"], + capture_output=True, text=True, check=True) + finally: + os.unlink(f.name) + m = re.search(r"\[([0-9,\s]*)\]", res.stdout) + if m is None: + raise RuntimeError("no token ids in the output of %s" % exe) + ids += [int(x) for x in m.group(1).split(",") if x.strip()] + batch, size = [], 0 + return ids + + +def cmd_build(args): + kv, _ = read_gguf(args.model, TOK_KEYS) + toks = kv["tokenizer.ggml.tokens"] + n_vocab = len(toks) + keep0, why, types = fixed_ids(kv) + unused = {i for i, t in enumerate(types) if t == TT_UNUSED} + + docs = read_corpus(args.text) + k = args.holdout_every + train = [d for i, d in enumerate(docs) if i % k != k - 1] + held = [d for i, d in enumerate(docs) if i % k == k - 1] + ids_train = tokenize(args.tokenize, args.model, train) + ids_held = tokenize(args.tokenize, args.model, held) + counts = Counter(ids_train) + print("corpus: %d docs (%d held out), %d training tokens, %d distinct ids, %d held-out tokens" % ( + len(docs), len(held), len(ids_train), len(counts), len(ids_held))) + print("always kept: %d ids (%s)" % (len(keep0), ", ".join("%s %d" % kv_ for kv_ in why.items()))) + + os.makedirs(args.outdir, exist_ok=True) + ranked = [i for i, _ in sorted(counts.items(), key=lambda x: (-x[1], x[0])) if i not in unused and i < n_vocab] + for size in args.sizes: + keep = set(keep0) + if len(keep) > size: + sys.exit("%d ids are always kept, more than %d" % (len(keep), size)) + for i in ranked: + if len(keep) >= size: + break + keep.add(i) + n_counted = len(keep) - len(keep0) + for i in range(n_vocab): + if len(keep) >= size: + break + if i not in unused: + keep.add(i) + name = "%s-%dk.txt" % (args.prefix, size // 1024) if size % 1024 == 0 else "%s-%d.txt" % (args.prefix, size) + path = os.path.join(args.outdir, name) + with open(path, "w") as f: + f.write("\n".join(str(i) for i in sorted(keep)) + "\n") + cov = 100.0 * sum(t in keep for t in ids_held) / max(1, len(ids_held)) + cov_tr = 100.0 * sum(t in keep for t in ids_train) / max(1, len(ids_train)) + print("%s: %d of %d ids (%d fixed, %d by frequency, %d lowest-unused); coverage train %.2f%% held-out %.2f%%" % ( + path, len(keep), n_vocab, len(keep0), n_counted, len(keep) - len(keep0) - n_counted, cov_tr, cov)) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("info", help="tokenizer fingerprint and LM head tensors of GGUF files") + p.add_argument("files", nargs="+") + p.set_defaults(fn=cmd_info) + p = sub.add_parser("build", help="write the 16k/32k/64k lists") + p.add_argument("-m", "--model", required=True, help="GGUF of the target model (only its vocabulary is loaded)") + p.add_argument("--tokenize", required=True, help="CPU llama-tokenize binary") + p.add_argument("--text", action="append", required=True, help="text file or directory, may be repeated") + p.add_argument("--prefix", required=True) + p.add_argument("--outdir", required=True) + p.add_argument("--sizes", type=lambda s: [int(x) for x in s.split(",")], default=[16384, 32768, 65536]) + p.add_argument("--holdout-every", type=int, default=20) + p.set_defaults(fn=cmd_build) + args = ap.parse_args() + args.fn(args) + + +if __name__ == "__main__": + main() diff --git a/tools/server/README.md b/tools/server/README.md index f690d7c04843..6fa0f5eae503 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -274,6 +274,7 @@ For the full list of features, please refer to [server's changelog](https://gith | `--spec-synth-rates P0,P1,...` | comma-separated unconditional per-position synthetic acceptance probabilities (benchmarking only)
(env: LLAMA_ARG_SPEC_SYNTH_RATES) | | `--spec-draft-p-split, --draft-p-split P` | speculative decoding split probability (default: 0.10)
(env: LLAMA_ARG_SPEC_DRAFT_P_SPLIT) | | `--spec-draft-p-min, --draft-p-min P` | minimum speculative decoding probability (greedy) (default: 0.00)
(env: LLAMA_ARG_SPEC_DRAFT_P_MIN) | +| `--spec-draft-vocab FNAME` | draft LM head computes only the token ids in FNAME (JSON array or one id per line) and the end-of-generation ids, build the list with scripts/build-draft-vocab.py (default: full LM head)
(env: LLAMA_ARG_SPEC_DRAFT_VOCAB) | | `--spec-draft-backend-sampling, --no-spec-draft-backend-sampling` | offload draft sampling to the backend (default: enabled)
(env: LLAMA_ARG_SPEC_DRAFT_BACKEND_SAMPLING) | | `--spec-draft-sampling {greedy,probabilistic}` | how the draft is sampled: greedy takes its argmax, probabilistic samples it and has the target verify by rejection sampling (default: greedy)
(env: LLAMA_ARG_SPEC_DRAFT_SAMPLING) | | `--spec-draft-device, -devd, --device-draft ` | comma-separated list of devices to use for offloading the draft model (none = don't offload, default: follows --device)
use --list-devices to see a list of available devices |