#!/usr/bin/env bash
# Bonsai 2 27B PTQ1_0-MTP on RTX 4070 12GB — optimized PR #221 source build
#
# Model: Ternary-Bonsai-2-27B-PTQ1_0-mtp-lean.gguf (6.30 GB), Bonsai 2's
# original PTQ1_0 weights plus the Qwen 3.8 MTP head; the optimized
# runtime includes the Hadamard inverse needed by this lean graft.
# Runtime: professorpalmer/llama.cpp-ada-ternary, bonsai-combo at pinned
# commit 09b6cce98ff63b1104e3d62cd0188f47d6757692 (includes the
# PR #221 integration stack); CUDA arch 89 for Ada / RTX 4070.
# Build: requires git, CMake >=3.24, nvcc, a CUDA-compatible C++ compiler,
# and the NVIDIA driver. The source checkout/build are kept in vendor/.
#
# RTX 4070 12GB reported benchmarks on this runtime family:
# * ~93.5 tok/s for the Qwen teacher MTP graft used here at fresh context
# (three-prompt mean); the separate on-policy Q8 MTP graft scored 96.8.
# * ~100.7 tok/s for the on-policy head with the thinking budget off.
# * ~47.6 tok/s at 32K depth and ~36.9 tok/s at 64K depth with draft cutoff.
# These are upstream measurements, not a guarantee for this host. GPU clocks,
# power limit, thermals, context depth, and concurrent GPU memory use matter.
# The default 96K/q8_0 recipe is the measured 12GB quality/speed compromise;
# MTP draft decoding stops at 24K because it is slower at deep context.
# Validated on NixOS unstable / RTX 4070 12GB (local run):
# * CTX=110000 is the maximum safe context window; anything higher risks
# CUDA out-of-memory / paging errors on the 12GB card.
# * ~91 tokens/second decode was observed at CTX=110000 (see benchmark
# target line printed at launch). Initial speed was 91 tokens/second, but
# as session progressed and more questions were answered, the speed went down
# to around 60 tokens/second
# Sources: https://github.com/PrismML-Eng/llama.cpp/pull/221
# https://github.com/professorpalmer/bonsai-ada-surgery
# https://github.com/professorpalmer/llama.cpp-ada-ternary/tree/bonsai-combo
#
# Canonical NixOS unstable launch (provides nvcc + CUDA-compatible c++):
# NIXPKGS_ALLOW_UNFREE=1 nix shell --impure nixpkgs#cudaPackages.cudatoolkit nixpkgs#gcc14 --command bash -c 'export CUDAHOSTCXX="$(command -v c++)"; PORT=18081 CTX=110000 BUILD_JOBS=4 bash ./huggingface-bonsai-mtp-rtx4070.bash'
# Expected output on an RTX 4070 (server then listens on 127.0.0.1:18081):
# -> optimized llama-server already built; skipping compilation.
# -> model present; verifying SHA-256 ...
# === Bonsai 2 27B PTQ1_0-MTP / RTX 4070 / ctx=110000 / KV=q8_0 / MTP n-max=2 ===
# model: /tmp/llm/models/Ternary-Bonsai-2-27B-PTQ1_0-mtp-lean.gguf
# runtime: 09b6cce98ff63b1104e3d62cd0188f47d6757692 (version: ...)
# build: CUDA sm_89; ctx=110000; KV=q8_0; draft cutoff=24576; backend sampling=1
# benchmark target: >91 tokens/second was observed on RTX 4070 at context
# window of 110000 (110kB), not guaranteed at depth or on every host
# log: /tmp/llama-4070-mtp.log
# server pid <pid>
# ... llama.cpp server log lines, ending with:
# ... listening on http://127.0.0.1:18081
#
# Usage:
# bash ./huggingface-bonsai-mtp-rtx4070.bash
#
# Env overrides:
# PORT=18081 serve on another port (default 8080)
# CTX=110000 context tokens (default 98304, max 110000 on RTX 4070 12GB; higher OOMs)
# KV_TYPE=q4_0 K/V cache type (default q8_0)
# SPEC_NMAX=2 MTP draft count (default 2)
# SPEC_DEPTH_MAX=0 0 disables the 24K draft cutoff
# CUDA_ARCH=89 CUDA arch for the build (default 89 / RTX 4070)
# BUILD_JOBS=8 parallel compile jobs (default 4)
# FORCE_MODEL=1 replace and re-download the lean MTP model
# BACKEND_SAMPLING=0 disable CUDA/backend sampling optimization
# REASONING_EFFORT=medium reasoning template effort (default medium)
set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODEL="$DIR/models/Ternary-Bonsai-2-27B-PTQ1_0-mtp-lean.gguf"
MODEL_URL="https://huggingface.co/sudoingx/Ternary-Bonsai-2-27B-PTQ1_0-MTP-GGUF/resolve/main/Ternary-Bonsai-2-27B-PTQ1_0-mtp-lean.gguf"
MODEL_SIZE=6297658848
MODEL_SHA256="1e33c571a5ce7a9a3e42474d66192923d5a6d77da7fb3a22986dc809522b5685"
RUNTIME_REPO="https://github.com/professorpalmer/llama.cpp-ada-ternary.git"
RUNTIME_COMMIT="09b6cce98ff63b1104e3d62cd0188f47d6757692"
SRC_DIR="$DIR/vendor/llama.cpp-bonsai-combo-$RUNTIME_COMMIT"
PORT="${PORT:-18081}"
CTX="${CTX:-110000}"
KV_TYPE="${KV_TYPE:-q8_0}"
SPEC_NMAX="${SPEC_NMAX:-2}"
SPEC_DEPTH_MAX="${SPEC_DEPTH_MAX:-24576}"
CUDA_ARCH="${CUDA_ARCH:-89}"
BUILD_DIR="$DIR/vendor/llama.cpp-build-rtx4070-$RUNTIME_COMMIT-$CUDA_ARCH"
BIN="$BUILD_DIR/bin/llama-server"
BUILD_JOBS="${BUILD_JOBS:-4}"
BACKEND_SAMPLING="${BACKEND_SAMPLING:-1}"
REASONING_EFFORT="${REASONING_EFFORT:-medium}"
LOG="${LOG:-/tmp/llama-4070-mtp.log}"
require_command() {
command -v "$1" >/dev/null 2>&1 || {
echo "ERROR: required command '$1' is missing." >&2
return 1
}
}
for cmd in git cmake nvcc c++ curl sha256sum stat pkill setsid; do
require_command "$cmd"
done
cmake_version="$(cmake --version | awk 'NR == 1 { print $3 }')"
if [[ ! "$cmake_version" =~ ^([0-9]+)\.([0-9]+) ]]; then
echo "ERROR: unable to parse CMake version: $cmake_version" >&2
exit 1
fi
if (( BASH_REMATCH[1] < 3 || (BASH_REMATCH[1] == 3 && BASH_REMATCH[2] < 24) )); then
echo "ERROR: CMake >= 3.24 is required; found $cmake_version." >&2
exit 1
fi
if [[ ! "$PORT" =~ ^[0-9]{1,5}$ ]] || (( PORT < 1 || PORT > 65535 )); then
echo "ERROR: PORT must be an integer from 1 to 65535." >&2
exit 1
fi
[[ "$CTX" =~ ^[1-9][0-9]*$ ]] || { echo "ERROR: CTX must be a positive integer." >&2; exit 1; }
if (( CTX > 110000 )); then
echo "WARNING: CTX=$CTX exceeds the validated RTX 4070 12GB maximum of 110000;" >&2
echo "WARNING: expect CUDA out-of-memory / paging errors. Use CTX<=110000." >&2
fi
[[ "$SPEC_NMAX" =~ ^[1-9][0-9]*$ ]] || { echo "ERROR: SPEC_NMAX must be a positive integer." >&2; exit 1; }
[[ "$SPEC_DEPTH_MAX" =~ ^[0-9]+$ ]] || { echo "ERROR: SPEC_DEPTH_MAX must be zero or a positive integer." >&2; exit 1; }
[[ "$BUILD_JOBS" =~ ^[1-9][0-9]*$ ]] || { echo "ERROR: BUILD_JOBS must be a positive integer." >&2; exit 1; }
[[ "$CUDA_ARCH" =~ ^[0-9]+$ ]] || { echo "ERROR: CUDA_ARCH must be a numeric CUDA architecture (e.g. 89)." >&2; exit 1; }
[[ "$BACKEND_SAMPLING" == 0 || "$BACKEND_SAMPLING" == 1 ]] || {
echo "ERROR: BACKEND_SAMPLING must be 0 or 1." >&2
exit 1
}
[[ "$KV_TYPE" == q4_0 || "$KV_TYPE" == q8_0 ]] || {
echo "ERROR: KV_TYPE must be q4_0 or q8_0." >&2
exit 1
}
[[ "${FORCE_MODEL:-0}" == 0 || "${FORCE_MODEL:-0}" == 1 ]] || {
echo "ERROR: FORCE_MODEL must be 0 or 1." >&2
exit 1
}
[[ "$REASONING_EFFORT" == medium || "$REASONING_EFFORT" == xhigh || "$REASONING_EFFORT" == low ]] || {
echo "ERROR: REASONING_EFFORT must be medium, low, or xhigh." >&2
exit 1
}
mkdir -p "$DIR/vendor" "$DIR/models"
# ---- Step 1: fetch the exact optimized runtime source and build llama-server ----
if [[ ! -d "$SRC_DIR/.git" ]]; then
if [[ -e "$SRC_DIR" ]]; then
echo "ERROR: $SRC_DIR exists but is not a Git checkout; leaving it untouched." >&2
exit 1
fi
echo "-> fetching optimized Bonsai runtime at $RUNTIME_COMMIT ..."
stage="$(mktemp -d "$DIR/vendor/.bonsai-runtime.XXXXXX")"
trap 'rm -rf -- "$stage"' EXIT
git -C "$stage" init -q
git -C "$stage" remote add origin "$RUNTIME_REPO"
git -C "$stage" fetch --depth 1 origin "$RUNTIME_COMMIT"
git -C "$stage" checkout --detach FETCH_HEAD
mv "$stage" "$SRC_DIR"
trap - EXIT
fi
actual_commit="$(git -C "$SRC_DIR" rev-parse HEAD)"
if [[ "$actual_commit" != "$RUNTIME_COMMIT" ]]; then
echo "ERROR: runtime checkout is $actual_commit, expected pinned $RUNTIME_COMMIT." >&2
echo " Leaving the checkout untouched; remove or rename it yourself to rebuild." >&2
exit 1
fi
if [[ -n "$(git -C "$SRC_DIR" status --porcelain --untracked-files=all)" ]]; then
echo "ERROR: runtime checkout has local or untracked modifications; refusing to build it." >&2
exit 1
fi
if [[ ! -x "$BIN" ]]; then
echo "-> building optimized llama-server for CUDA sm_$CUDA_ARCH ($BUILD_JOBS jobs) ..."
CMAKE_CUDA_ARGS=()
nvcc_path="$(command -v nvcc)"
cuda_root="${CUDAToolkit_ROOT:-${CUDA_HOME:-$(dirname "$(dirname "$nvcc_path")")}}"
if [[ -f "$cuda_root/include/cuda_runtime.h" ]]; then
# NixOS splits nvcc from the merged toolkit headers; CMake's compiler-ID
# probe invokes nvcc directly and otherwise misses cuda_runtime.h.
CMAKE_CUDA_ARGS+=("-DCUDAToolkit_ROOT=$cuda_root" "-DCMAKE_CUDA_FLAGS=-I$cuda_root/include")
fi
cuda_host_compiler="${CUDAHOSTCXX:-${CMAKE_CUDA_HOST_COMPILER:-}}"
if [[ -n "$cuda_host_compiler" ]]; then
CMAKE_CUDA_ARGS+=("-DCMAKE_CUDA_HOST_COMPILER=$cuda_host_compiler")
fi
cmake -S "$SRC_DIR" -B "$BUILD_DIR" \
-DGGML_CUDA=ON \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CUDA_ARCHITECTURES="$CUDA_ARCH" \
"${CMAKE_CUDA_ARGS[@]}"
cmake --build "$BUILD_DIR" --target llama-server -j "$BUILD_JOBS"
else
echo "-> optimized llama-server already built; skipping compilation."
fi
[ -x "$BIN" ] || { echo "ERROR: build did not produce $BIN." >&2; exit 1; }
# ---- Step 2: download and verify the smaller MTP graft ----
if [[ "${FORCE_MODEL:-0}" == 1 ]]; then
rm -f "$MODEL"
fi
if [[ -f "$MODEL" && "$(stat -c %s "$MODEL")" == "$MODEL_SIZE" ]]; then
echo "-> model present; verifying SHA-256 ..."
else
echo "-> downloading lean MTP model (resume-safe, ~6.30 GB) ..."
curl -L --fail --retry 3 --continue-at - --progress-bar "$MODEL_URL" -o "$MODEL"
fi
actual_size="$(stat -c %s "$MODEL")"
if [[ "$actual_size" != "$MODEL_SIZE" ]]; then
echo "ERROR: model size mismatch: got $actual_size bytes, expected $MODEL_SIZE." >&2
exit 1
fi
actual_sha256="$(sha256sum "$MODEL" | cut -d' ' -f1)"
if [[ "$actual_sha256" != "$MODEL_SHA256" ]]; then
echo "ERROR: model SHA-256 mismatch: got $actual_sha256, expected $MODEL_SHA256." >&2
echo " The file will not be served; inspect it and re-download with FORCE_MODEL=1." >&2
exit 1
fi
# ---- Step 3: NixOS library wiring ----
# The NixOS driver is host-provided. The CUDA toolkit supplies build-time CUDA
# libraries; include common NixOS runtime paths and store CUDA libraries when present.
NIXLD=/run/current-system/sw/share/nix-ld/lib
export LD_LIBRARY_PATH="$NIXLD:/run/opengl-driver/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
for d in /nix/store/*cudart*/lib /nix/store/*cublas*lib/lib; do
[ -f "$d/libcudart.so.12" ] && case ":$LD_LIBRARY_PATH:" in *":$d:"*) ;; *) export LD_LIBRARY_PATH="$d:$LD_LIBRARY_PATH";; esac
[ -f "$d/libcublas.so.12" ] && case ":$LD_LIBRARY_PATH:" in *":$d:"*) ;; *) export LD_LIBRARY_PATH="$d:$LD_LIBRARY_PATH";; esac
done
pkill -f "llama-server.*$PORT" || true
rm -f "$LOG"
SPEC_DEPTH_ARGS=()
if (( SPEC_DEPTH_MAX > 0 )); then
SPEC_DEPTH_ARGS=(--spec-draft-depth-max "$SPEC_DEPTH_MAX")
fi
SAMPLING_ARGS=()
if [[ "$BACKEND_SAMPLING" == 1 ]]; then
SAMPLING_ARGS=(--backend-sampling)
fi
# Draft cache uses the same quantization as the target cache. On the measured
# 12GB profile, 96K + q8_0 leaves room for the lean MTP head without paging.
# CTX=110000 is the validated maximum on RTX 4070 12GB; higher values OOM.
echo "=== Bonsai 2 27B PTQ1_0-MTP / RTX 4070 / ctx=$CTX / KV=$KV_TYPE / MTP n-max=$SPEC_NMAX ==="
echo "model: $MODEL"
echo "runtime: $RUNTIME_COMMIT ($("$BIN" --version 2>&1 | head -1))"
echo "build: CUDA sm_$CUDA_ARCH; ctx=$CTX; KV=$KV_TYPE; draft cutoff=$SPEC_DEPTH_MAX; backend sampling=$BACKEND_SAMPLING"
echo "benchmark target: >91 tokens/second was observed on RTX 4070 at context window of 110000 (110kB), not guaranteed at depth or on every host"
echo "log: $LOG"
export GGML_CUDA_BATCH_INVARIANT=1
setsid "$BIN" \
-m "$MODEL" \
--host 127.0.0.1 --port "$PORT" \
-ngl 99 -fa on -c "$CTX" \
-ctk "$KV_TYPE" -ctv "$KV_TYPE" \
-ctkd "$KV_TYPE" -ctvd "$KV_TYPE" \
-np 1 -b 2048 -ub 512 \
--spec-type draft-mtp --spec-draft-n-max "$SPEC_NMAX" \
"${SPEC_DEPTH_ARGS[@]}" \
"${SAMPLING_ARGS[@]}" \
--reasoning-effort "$REASONING_EFFORT" \
--temp 1.0 --top-p 0.95 --top-k 20 \
--jinja > "$LOG" 2>&1 < /dev/null &
echo "server pid $!"
sleep 10
tail -40 "$LOG" || true
echo "--- health ---"
curl -s "http://127.0.0.1:$PORT/health" || echo "not up yet, check $LOG"