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
52 changes: 52 additions & 0 deletions app/gguf_meta.h
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,56 @@ inline long long gguf_int(const std::string& path, const std::string& key) {
return -1;
}

// How many tensors of ggml type `type` (GGML_TYPE_Q4_0 = 2, ...) a GGUF holds, or -1 when the file
// is not a GGUF or its header cannot be read. Reads the key/value section and the tensor infos only.
inline long long gguf_tensor_type_count(const std::string& path, uint32_t type) {
std::ifstream f(path, std::ios::binary);
auto rd = [&](void* p, size_t n) { return static_cast<bool>(f.read(static_cast<char*>(p), n)); };
uint32_t magic = 0, version = 0;
uint64_t n_tensors = 0, n_kv = 0;
if (!rd(&magic, 4) || magic != 0x46554747u || !rd(&version, 4) || version < 2 || !rd(&n_tensors, 8) || !rd(&n_kv, 8))
return -1;
auto skip_str = [&]() {
uint64_t n = 0;
if (!rd(&n, 8) || n > (1u << 20)) return false;
return static_cast<bool>(f.seekg(static_cast<std::streamoff>(n), std::ios::cur));
};
static const int size[] = {1, 1, 2, 2, 4, 4, 4, 1, 0, 0, 8, 8, 8};
auto scalar = [](uint32_t t) -> int { return t < 13 ? size[t] : -1; };
for (uint64_t i = 0; i < n_kv; ++i) {
uint32_t t = 0;
if (!skip_str() || !rd(&t, 4)) return -1;
if (t == 8) {
if (!skip_str()) return -1;
} else if (t == 9) {
uint32_t et = 0;
uint64_t n = 0;
if (!rd(&et, 4) || !rd(&n, 8)) return -1;
if (et == 8) {
for (uint64_t j = 0; j < n; ++j)
if (!skip_str()) return -1;
} else if (scalar(et) > 0) {
f.seekg(static_cast<std::streamoff>(n * scalar(et)), std::ios::cur);
} else {
return -1;
}
} else if (scalar(t) > 0) {
f.seekg(scalar(t), std::ios::cur);
} else {
return -1;
}
if (!f) return -1;
}
long long count = 0;
for (uint64_t i = 0; i < n_tensors; ++i) {
uint32_t n_dims = 0, t = 0;
uint64_t offset = 0;
if (!skip_str() || !rd(&n_dims, 4) || n_dims > 8) return -1;
f.seekg(static_cast<std::streamoff>(8 * n_dims), std::ios::cur);
if (!rd(&t, 4) || !rd(&offset, 8)) return -1;
count += t == type;
}
return count;
}

} // namespace onebit
8 changes: 8 additions & 0 deletions app/serve.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,14 @@ Launch launch_for(const Options& o, const std::string& device, int child_port) {
// A value set in the environment wins (GGML_W4A4_TENSORS= keeps exact int8).
if (device != "rocm") throw std::runtime_error(o.model + " is Hadamard-rotated: it runs on --device rocm only");
if (!std::getenv("GGML_Q4_0_HADAMARD")) env.push_back("GGML_Q4_0_HADAMARD=1");
// the rotation applies to every Q4_0 matmul in the backend, the drafter's too: a drafter
// or MTP head with unrotated Q4_0 tensors would read its activations rotated and accept
// nothing (a Q4_0 DFlash2 drafter did exactly that)
for (const std::string& draft : {o.dflash, o.mtp}) {
if (!draft.empty() && gguf_tensor_type_count(draft, 2) > 0 && !hadamard_q4_0(draft))
throw std::runtime_error(draft + " has Q4_0 tensors that are not Hadamard-rotated, and " + o.model +
" rotates every Q4_0 activation in its backend: use a Q8_0 or Q4_K drafter");
}
if (!std::getenv("GGML_W4A4_TENSORS")) env.push_back("GGML_W4A4_TENSORS=all");
// micro-batch size: recipe rotated-moe-ub1024 (config/recipes.json)
}
Expand Down
4 changes: 3 additions & 1 deletion docs/serve.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,9 @@ kept only when the model agrees, so the output is the model's own.
processing and DFlash2 decode from one server, 518 t/s prompt and 46.0 / 28.4 / 17.6 tok/s decode
([lean.md](lean.md#hadamard-rotated-q4_0-w4a4-prompt-processing)). `--dflash` gets
`--spec-draft-p-min` from a [recipe](recipes.md) (0.4 on rocm, 0 elsewhere) unless `--mtp-p-min` is given, and without `--mtp-max` drafts the
drafter's block minus one (its `dflash.block_size`; 16 when the file does not say).
drafter's block minus one (its `dflash.block_size`; 16 when the file does not say). Next to a
Hadamard-rotated file a drafter must not hold plain Q4_0 tensors: the rotation applies to every Q4_0
matmul in the backend, so serve refuses one (a Q8_0 or Q4_K drafter works).

## Recipes (`--recipes`, `--no-recipes`)

Expand Down
19 changes: 16 additions & 3 deletions tests/hadamard_route.sh
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
# - an unstamped file with --device auto still goes to Vulkan with neither variable,
# - --dflash on a rotated file adds the DFlash drafter (p-min 0.4 from its rocm recipe, n-max = the
# drafter's dflash.block_size - 1, or 16 when the file does not say): one ROCm server, W4A4
# prompt processing and DFlash2 decode.
# prompt processing and DFlash2 decode,
# - a drafter with unrotated Q4_0 tensors is refused next to a rotated file (the rotation is
# process-wide), one with Q8_0 tensors is not.
#
# usage: tests/hadamard_route.sh path/to/1bit
set -uo pipefail
Expand All @@ -37,20 +39,24 @@ check() { if eval "$2"; then echo "ok $1"; else echo "FAIL $1"; fail=1; fi; }

python3 - "$scratch" <<'PY'
import struct, sys
def gguf(path, stamp, arch="llama", ints={}):
def gguf(path, stamp, arch="llama", ints={}, tensors=()):
kv = []
def s(x): b = x.encode(); return struct.pack("<Q", len(b)) + b
kv.append(s("general.architecture") + struct.pack("<I", 8) + s(arch))
if stamp:
kv.append(s("onebit.hadamard_q4_0") + struct.pack("<I", 5) + struct.pack("<i", 32))
for k, v in ints.items():
kv.append(s(k) + struct.pack("<I", 4) + struct.pack("<I", v))
open(path, "wb").write(b"GGUF" + struct.pack("<IQQ", 3, 0, len(kv)) + b"".join(kv))
ti = b"".join(s(name) + struct.pack("<I", 1) + struct.pack("<Q", 32) + struct.pack("<I", t) + struct.pack("<Q", 0)
for name, t in tensors)
open(path, "wb").write(b"GGUF" + struct.pack("<IQQ", 3, len(tensors), len(kv)) + b"".join(kv) + ti)
gguf(sys.argv[1] + "/h32.gguf", True)
gguf(sys.argv[1] + "/h32moe.gguf", True, "qwen3moe", {"qwen3moe.expert_count": 128})
gguf(sys.argv[1] + "/plain.gguf", False)
gguf(sys.argv[1] + "/draft.gguf", False)
gguf(sys.argv[1] + "/draft8.gguf", False, "dflash", {"dflash.block_size": 8})
gguf(sys.argv[1] + "/draftq4.gguf", False, "dflash", {"dflash.block_size": 8}, [("blk.0.ffn_up.weight", 2)])
gguf(sys.argv[1] + "/draftq8.gguf", False, "dflash", {"dflash.block_size": 8}, [("blk.0.ffn_up.weight", 8)])
PY

# a backend that records how it was started, then answers /health
Expand Down Expand Up @@ -109,5 +115,12 @@ check " and the Hadamard W4A4 environment" '[ "$(field "$scratch/df.json" "r[\"
run "$scratch/h32.gguf" "$scratch/df8.json" --dflash "$scratch/draft8.gguf"
check "--dflash with a block-8 drafter drafts 7" '[ "$(field "$scratch/df8.json" "r[\"argv\"][r[\"argv\"].index(\"--spec-draft-n-max\")+1]")" = 7 ]'

port=$(python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
q4=$(timeout 20 "$bin" serve -m "$scratch/h32.gguf" --device auto --port "$port" --llama-server "$scratch/backend.py" \
--dflash "$scratch/draftq4.gguf" 2>&1)
check "a Q4_0 drafter next to a rotated file is refused" '[[ "$q4" == *"not Hadamard-rotated"* ]]'
run "$scratch/h32.gguf" "$scratch/dfq8.json" --dflash "$scratch/draftq8.gguf"
check " a Q8_0 drafter is not" '[ "$(field "$scratch/dfq8.json" "r[\"argv\"][r[\"argv\"].index(\"-md\")+1]")" = "$scratch/draftq8.gguf" ]'

if [ $fail -ne 0 ]; then for f in "$scratch"/*.log; do echo "--- $f"; cat "$f"; done; echo FAIL; exit 1; fi
echo PASS
Loading