Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ci/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions common/arg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand Down
2 changes: 2 additions & 0 deletions common/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
45 changes: 45 additions & 0 deletions common/speculative.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include <iomanip>
#include <map>
#include <random>
#include <sstream>
#include <cinttypes>

#define SPC_DBG(fmt, ...) LOG_DBG("spec %12.*s: " fmt, 12, __func__, __VA_ARGS__)
Expand Down Expand Up @@ -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<llama_token> & ids, std::string & err) {
std::ifstream f(path);
if (!f) {
err = "cannot open the file";
return false;
}
std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
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,
Expand All @@ -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<llama_token> 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;
Expand Down
22 changes: 22 additions & 0 deletions docs/speculative.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

```
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions include/llama.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
130 changes: 130 additions & 0 deletions scripts/build-draft-vocab.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading