8000 llama.cpp: build every ggml CPU variant and pick one at run time by bryan-minimal · Pull Request #1559 · gominimal/pkgs · GitHub
[go: up one dir, main page]

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
30 changes: 29 additions & 1 deletion packages/llama.cpp/build.ncl
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ let version = "b12359" in
# CVE-2023-45663: upstream stb's TGA/HDR fix (nothings/stb cd44845) for the
# vendored stb_image 2.30. See build.sh.
{ file = "stb-cve-2023-45663.patch" } | Local,
# The CPU backends are dlopen()ed: search only GGML_BACKEND_DIR, never the
# executable's or the current directory. See build.sh.
{ file = "ggml-backend-dir-only.patch" } | Local,
# The x86 CPU variant scorer checks CPUID only: also require the OS to have
# enabled the register state (XCR0). See build.sh.
{ file = "ggml-cpu-feats-xcr0.patch" } | Local,
# License texts and NOTICEs of everything compiled into the embedded web UI
# (pkgs#994), generated from this version's tools/ui/package-lock.json by
# gen-ui-notices.py. The build doesn't run it: rerun it on every bump.
Expand Down Expand Up @@ -64,6 +70,9 @@ let version = "b12359" in
llama-cli = { glob = "usr/bin/llama-cli" } | OutputBin,

libs = { glob = "usr/lib/*" } | OutputLib,
# One CPU backend per microarchitecture, dlopen()ed from GGML_BACKEND_DIR
# (/usr/lib/ggml) at run time; the loader keeps the best one for the host.
cpu-backends = { glob = "usr/lib/ggml/libggml-cpu-*.so*" } | OutputLib,
# ui-THIRD-PARTY-NOTICES: the web UI's third-party license texts (pkgs#994).
licenses = { glob = "usr/share/licenses/llama.cpp/*" } | OutputData,
},
Expand Down Expand Up @@ -101,14 +110,33 @@ let version = "b12359" in
owner = "ggml-org",
repo = "llama.cpp",
},
build_cost_multiple = 3,
# ggml-cpu is compiled once per CPU variant: 8 on arm64, 14 on x86_64.
build_cost_multiple = 5,
} | Attrs,

# No test_deps: base would mask a missing library. Both binaries exited 127
# (libllama.so.0 etc. not shipped) before build.sh kept the SONAME links.
tests = {
llama-cli = standaloneTest "/usr/bin/llama-cli --version",
llama-server = standaloneTest "/usr/bin/llama-server --version",
# The CPU backend is not linked in: it is loaded from /usr/lib/ggml at run
# time, and --version never loads it. `-ot x=CPU` loads every backend and
# throws "unknown buffer type" (exit 1) unless a CPU backend loaded and
# registered its "CPU" buffer type; --list-devices then exits 0 with no
# model. (--list-devices alone lists only non-CPU devices, so it passes with
# no CPU backend at all.)
cpu-backend-cli =
{
class = 'Standalone,
test_deps = [],
cmds = [["/usr/bin/llama-cli", "-ot", "x=CPU", "--list-devices"]],
} | Test,
cpu-backend-server =
{
class = 'Standalone,
test_deps = [],
cmds = [["/usr/bin/llama-server", "-ot", "x=CPU", "--list-devices"]],
} | Test,
# The web UI's notices ship, for this UI version, with the texts that must
# travel: svelte (MIT), dompurify (MPL-2.0 OR Apache-2.0, both texts) and
# pdfjs-dist (Apache-2.0; its npm package has no NOTICE, which is recorded).
Expand Down
108 changes: 99 additions & 9 deletions packages/llama.cpp/build.sh
Original file line number Diff line number Diff line change
@@ -1,10 +1,32 @@
#!/bin/sh
set -e

# The CPU kernels (ggml-cpu) are built once per microarchitecture and the best one
# for the host is picked at run time (GGML_BACKEND_DL + GGML_CPU_ALL_VARIANTS,
# below), so CFLAGS carry only each arch's baseline, the gcc default spelled out.
# Each variant appends its own -march (arm64, which overrides this one) or -m flags
# (x86, which add to it). A higher floor here leaks into every variant and into the
# feature probe that scores them: with the old -march=x86-64-v3 the "x64" and "sse42"
# variants would carry AVX2 and the probe itself could SIGILL on a pre-AVX2 CPU. The
# rest (libllama, ggml-base, the server) builds at the baseline too, as upstream's
# release builds do; the hot loops are in ggml-cpu.
#
# VARIANTS is the exact set ggml/src/CMakeLists.txt defines for Linux at this
# version. build.sh checks the build produced exactly these, so a bump that adds,
# renames or drops one fails here instead of shipping a different set.
case $(uname -m) in
x86_64) MARCH="-march=x86-64-v3" ;;
aarch64) MARCH="-march=armv8-a" ;;
*) MARCH="" ;;
x86_64)
MARCH="-march=x86-64"
VARIANTS="x64 sse42 sandybridge ivybridge piledriver haswell skylakex cannonlake cascadelake icelake cooperlake zen4 alderlake sapphirerapids"
;;
aarch64)
MARCH="-march=armv8-a"
VARIANTS="armv8.0_1 armv8.2_1 armv8.2_2 armv8.2_3 armv8.6_1 armv8.6_2 armv9.2_1 armv9.2_2"
;;
*)
echo "ERROR: no ggml CPU variant list for $(uname -m)" >&2
exit 1
;;
esac
export CFLAGS="$MARCH -O2 -pipe -gno-record-gcc-switches -ffile-prefix-map=$(pwd)=/builddir"
export LDFLAGS="-Wl,--build-id=none"
Expand Down Expand Up @@ -54,19 +76,87 @@ echo "594c2fe35d49488b4382dbfaec8f98366defca819d916ac95becf3e75f4200b3 vendor/s
patch -Np1 -i ./stb-cve-2023-45663.patch
echo "a604136650368a391554f4a4b45f285d4c8fe94c7bf28a414b37edd28407899e vendor/stb/stb_image.h" | sha256sum -c -

# GGML_NATIVE=OFF is a guard: ggml already defaults it OFF when SOURCE_DATE_EPOCH is
# set (the sandbox sets it), and -march=native would make the code follow the build
# host's CPU instead of the explicit $MARCH in CFLAGS.
cmake -B build -DGGML_NATIVE=OFF -DLLAMA_BUILD_UI=OFF -DLLAMA_USE_PREBUILT_UI=OFF
# With GGML_BACKEND_DL, ggml_backend_load_best() searches GGML_BACKEND_DIR, then the
# executable's directory, then the CURRENT directory, and dlopen()s every
# libggml-<name>-*.so it finds there before scoring them (constructors run on load).
# Starting llama-server/llama-cli in a directory someone else can write (a downloaded
# model folder, a cloned repo) would run a planted library. The static build never
# did this. The patch makes an installed build (GGML_BACKEND_DIR set) search only
# /usr/lib/ggml; GGML_BACKEND_PATH, an explicit opt-in, still works. Both hashes are
# checked: a changed loader fails here instead of patching blind.
echo "0a23a627cec97926fb1fbb2b1bf4fa7fed4900aa21b0215302eced797231578b ggml/src/ggml-backend-reg.cpp" | sha256sum -c -
patch -Np1 -i ./ggml-backend-dir-only.patch
echo "607514a82eb47dbf21994914ea3c6abe7c8c5aca1a48d5d620f74f6c7d1f7815 ggml/src/ggml-backend-reg.cpp" | sha256sum -c -

# The x86 variant scorer (ggml_backend_cpu_x86_score) reads CPUID feature bits only;
# upstream marks it "FIXME: this does not check for OS support"
# (ggml/src/ggml-cpu/arch/x86/cpu-feats.cpp:264 at b12359, unchanged on master). A
# host whose CPU has AVX-512 (or AVX/AVX2, or AMX) while the OS or hypervisor leaves
# that register state off in XCR0 would load skylakex (etc.) and SIGILL, where
# haswell runs. The patch reads XCR0 (XGETBV, only when CPUID.1:ECX.OSXSAVE is set)
# and counts AVX/AVX2/FMA/F16C/AVX-VNNI only with XCR0[2:1], AVX-512 only with
# XCR0[7:5] too, and AMX only with XCR0[18:17]; amx.cpp's arch_prctl request is
# untouched. Scores are otherwise unchanged. Upstream has open, unmerged PRs for this
# (ggml-org/llama.cpp#19514, #20940); drop the patch when one lands.
# https://github.com/gominimal/pkgs/pull/1559#discussion_r4621978298
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit · This line links to a review thread on this same pull request. The paragraph above it already gives the reason and the upstream PR numbers. The link records how the change came about, not what the code does. Remove it. No other build script in packages/ links a review thread.

echo "b0f6aaaeb0b12a4f3e15ceec14d0c2031633f91e864a6c15954a001d6390f6d4 ggml/src/ggml-cpu/arch/x86/cpu-feats.cpp" | sha256sum -c -
patch -Np1 -i ./ggml-cpu-feats-xcr0.patch
echo "33c17ca73a60a7fb30eb399a4f8e6562062b82b3ea02907e0156765df111a080 ggml/src/ggml-cpu/arch/x86/cpu-feats.cpp" | sha256sum -c -

# GGML_NATIVE=OFF: ggml already defaults it OFF when SOURCE_DATE_EPOCH is set (the
# sandbox sets it), and it must be: -march=native would follow the build host's CPU,
# and ggml refuses GGML_NATIVE with GGML_BACKEND_DL.
#
# GGML_BACKEND_DL + GGML_CPU_ALL_VARIANTS: one libggml-cpu-<variant>.so per entry in
# $VARIANTS, dlopen()ed at run time. ggml_backend_load_all() loads each candidate,
# asks its ggml_backend_score() (a feature probe compiled without the variant's
# flags), and keeps the highest-scoring one. On arm64 that brings in the DOTPROD,
# FP16, SVE, i8mm, SVE2 and SME kernels plain armv8-a left out (pkgs#975); on x86 it
# runs on pre-AVX2 CPUs and uses AVX-512/VNNI/AMX where present. The set is fixed by
# these options, not the build host, so the output is the same on every builder.
# armv9.2 (+sme) needs gcc >= 14.
#
# GGML_BACKEND_DIR: where the loader looks first. Its other places are the
# executable's own directory (resolved through /proc/self/exe, which need not be
# /usr/bin) and the current directory. The variants are plugins, not libraries
# anything links, so they get their own directory instead of the linker's path.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

low · This comment says the loader also searches the executable's directory and the current directory. ggml-backend-dir-only.patch, applied at line 74, removes both when GGML_BACKEND_DIR is set. The comment at lines 65-72 and the one in build.ncl:22-23 say the opposite of this one. The next reader cannot tell which is true, and the wrong one hides a library-planting surface. Rewrite it to say that /usr/lib/ggml is the only directory searched. This is the only place in the package with the stale description.

#
# Tests and examples are not shipped; skipping them offsets part of the cost of
# building ggml-cpu 8 (arm64) or 14 (x86_64) times.
cmake -B build \
-DGGML_NATIVE=OFF \
-DGGML_BACKEND_DL=ON \
-DGGML_CPU_ALL_VARIANTS=ON \
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
-DGGML_BACKEND_DIR=/usr/lib/ggml \
-DLLAMA_BUILD_TESTS=OFF \
-DLLAMA_BUILD_EXAMPLES=OFF \
-DLLAMA_BUILD_UI=OFF \
-DLLAMA_USE_PREBUILT_UI=OFF
cmake --build build --config Release -j $(nproc)

mkdir -pv $OUTPUT_DIR/usr/{bin,lib}
# Exactly the expected variants, and no single non-variant CPU backend.
built=$(cd build/bin && ls libggml-cpu-*.so | sed 's/^libggml-cpu-//; s/\.so$//' | sort | tr '\n' ' ')
want=$(printf '%s\n' $VARIANTS | sort | tr '\n' ' ')
if [ "$built" != "$want" ]; then
echo "ERROR: ggml CPU variants differ from VARIANTS" >&2
echo " built: $built" >&2
echo " want: $want" >&2
exit 1
fi
if [ -e build/bin/libggml-cpu.so ]; then
echo "ERROR: build/bin/libggml-cpu.so exists: GGML_CPU_ALL_VARIANTS was not applied" >&2
exit 1
fi

mkdir -pv $OUTPUT_DIR/usr/{bin,lib} $OUTPUT_DIR/usr/lib/ggml

# The shared libraries ship as built: lib*.so -> lib*.so.0 -> lib*.so.0.x.y.
# `install build/bin/*.so` followed each link and wrote the library under its
# unversioned name only, so the binaries' DT_NEEDED (the SONAME, libllama.so.0
# etc.) was never shipped and llama-cli/llama-server exited 127 at startup.
cp -av build/bin/*.so* $OUTPUT_DIR/usr/lib/
# The CPU variants go where GGML_BACKEND_DIR points.
mv -v $OUTPUT_DIR/usr/lib/libggml-cpu-*.so* $OUTPUT_DIR/usr/lib/ggml/
install -vm755 build/bin/llama-{cli,server} $OUTPUT_DIR/usr/bin/
install -Dvm644 "$notices" $OUTPUT_DIR/usr/share/licenses/llama.cpp/ui-THIRD-PARTY-NOTICES

Expand All @@ -76,7 +166,7 @@ install -Dvm644 "$notices" $OUTPUT_DIR/usr/share/licenses/llama.cpp/ui-THIRD-PAR
command -v readelf >/dev/null
missing=0
found=0
for f in $OUTPUT_DIR/usr/bin/* $OUTPUT_DIR/usr/lib/*.so*; do
for f in $OUTPUT_DIR/usr/bin/* $OUTPUT_DIR/usr/lib/*.so* $OUTPUT_DIR/usr/lib/ggml/*.so*; do
[ -L "$f" ] && continue
for lib in $(readelf -d "$f" | sed -n 's/.*(NEEDED).*\[\(.*\)\]/\1/p'); do
[ -e "build/bin/$lib" ] || continue
Expand Dow 8BD0 n
26 changes: 26 additions & 0 deletions packages/llama.cpp/ggml-backend-dir-only.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
diff --git a/ggml/src/ggml-backend-reg.cpp b/ggml/src/ggml-backend-reg.cpp
index c3bc926..f752ae9 100644
--- a/ggml/src/ggml-backend-reg.cpp
+++ b/ggml/src/ggml-backend-reg.cpp
@@ -486,8 +486,12 @@ static ggml_backend_reg_t ggml_backend_load_best(const char * name, bool silent,
std::vector<fs::path> search_paths;
if (user_search_path == nullptr) {
#ifdef GGML_BACKEND_DIR
+ // minimal (pkgs#975): an installed build searches ONLY its backend directory.
+ // Every matching file found is dlopen()ed (constructors run) before scoring,
+ // so searching the executable's directory or the current directory would run
+ // any libggml-*.so planted where llama-server/llama-cli is started.
search_paths.push_back(fs::u8path(GGML_BACKEND_DIR));
-#endif
+#else
// default search paths: executable directory, current directory
search_paths.push_back(get_executable_path());
std::error_code cwd_ec;
@@ -497,6 +501,7 @@ static ggml_backend_reg_t ggml_backend_load_best(const char * name, bool silent,
} else {
search_paths.push_back(cwd);
}
+#endif
} else {
search_paths.push_back(fs::u8path(user_search_path));
}
115 changes: 115 additions & 0 deletions packages/llama.cpp/ggml-cpu-feats-xcr0.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
diff --git a/ggml/src/ggml-cpu/arch/x86/cpu-feats.cpp b/ggml/src/ggml-cpu/arch/x86/cpu-feats.cpp
--- a/ggml/src/ggml-cpu/arch/x86/cpu-feats.cpp
+++ b/ggml/src/ggml-cpu/arch/x86/cpu-feats.cpp
@@ -6,6 +6,7 @@
#include <intrin.h>
#endif

+#include <cstdint>
#include <cstring>
#include <vector>
#include <bitset>
@@ -87,7 +88,22 @@
bool AMX_FP16(void) { return f_7_1_eax[21]; }
bool AMX_BF16(void) { return f_7_edx[22]; }

+ // The CPUID bits above say what the CPU implements. Using a register set
+ // also needs the OS to save and restore it, which it reports in XCR0, read
+ // with XGETBV. XGETBV is only valid when CPUID.1:ECX.OSXSAVE[27] is set.
+ uint64_t xcr0(void) { return OSXSAVE() ? xgetbv(0) : 0; }
+ // XCR0[2:1]: SSE + AVX state (YMM). AVX, AVX2, FMA, F16C, AVX-VNNI.
+ bool OS_YMM(void) { return (xcr0() & 0x6) == 0x6; }
+ // + XCR0[7:5]: opmask, ZMM_Hi256, Hi16_ZMM. Every AVX-512 feature.
+ bool OS_ZMM(void) { return (xcr0() & 0xe6) == 0xe6; }
+ // XCR0[18:17]: XTILECFG, XTILEDATA. AMX. (On Linux the process must still
+ // request XTILEDATA with arch_prctl(ARCH_REQ_XCOMP_PERM): amx.cpp does.)
+ bool OS_AMX(void) { return (xcr0() & 0x60000) == 0x60000; }
+
#ifdef _MSC_VER
+ static uint64_t xgetbv(unsigned int xcr) {
+ return _xgetbv(xcr);
+ }
static void cpuid(int cpu_info[4], int eax) {
__cpuid(cpu_info, eax);
}
@@ -95,6 +111,11 @@
__cpuidex(cpu_info, eax, ecx);
}
#else
+ static uint64_t xgetbv(unsigned int xcr) {
+ uint32_t eax, edx;
+ __asm__ __volatile__("xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr));
+ return ((uint64_t)edx << 32) | eax;
+ }
static void cpuid(int cpu_info[4], int eax) {
__asm__ __volatile__(
"cpuid"
@@ -261,17 +282,18 @@
#endif

static int ggml_backend_cpu_x86_score() {
- // FIXME: this does not check for OS support
+ // A feature counts only when the CPU has it (CPUID) and the OS has enabled
+ // its register state (XCR0); otherwise the variant would load and SIGILL.

int score = 1;
cpuid_x86 is;

#ifdef GGML_FMA
- if (!is.FMA()) { return 0; }
+ if (!is.FMA() || !is.OS_YMM()) { return 0; }
score += 1;
#endif
#ifdef GGML_F16C
- if (!is.F16C()) { return 0; }
+ if (!is.F16C() || !is.OS_YMM()) { return 0; }
score += 1<<1;
#endif
#ifdef GGML_SSE42
@@ -283,18 +305,19 @@
score += 1<<3;
#endif
#ifdef GGML_AVX
- if (!is.AVX()) { return 0; }
+ if (!is.AVX() || !is.OS_YMM()) { return 0; }
score += 1<<4;
#endif
#ifdef GGML_AVX2
- if (!is.AVX2()) { return 0; }
+ if (!is.AVX2() || !is.OS_YMM()) { return 0; }
score += 1<<5;
#endif
#ifdef GGML_AVX_VNNI
- if (!is.AVX_VNNI()) { return 0; }
+ if (!is.AVX_VNNI() || !is.OS_YMM()) { return 0; }
score += 1<<6;
#endif
#ifdef GGML_AVX512
+ if (!is.OS_ZMM()) { return 0; }
if (!is.AVX512F()) { return 0; }
if (!is.AVX512CD()) { return 0; }
if (!is.AVX512VL()) { return 0; }
@@ -303,19 +326,19 @@
score += 1<<7;
#endif
#ifdef GGML_AVX512_VBMI
- if (!is.AVX512_VBMI()) { return 0; }
+ if (!is.AVX512_VBMI() || !is.OS_ZMM()) { return 0; }
score += 1<<8;
#endif
#ifdef GGML_AVX512_BF16
- if (!is.AVX512_BF16()) { return 0; }
+ if (!is.AVX512_BF16() || !is.OS_ZMM()) { return 0; }
score += 1<<9;
#endif
#ifdef GGML_AVX512_VNNI
- if (!is.AVX512_VNNI()) { return 0; }
+ if (!is.AVX512_VNNI() || !is.OS_ZMM()) { return 0; }
score += 1<<10;
#endif
#ifdef GGML_AMX_INT8
- if (!is.AMX_INT8()) { return 0; }
+ if (!is.AMX_INT8() || !is.OS_AMX()) { return 0; }
score += 1<<11;
#endif

Loading
0