diff --git a/.crumb b/.crumb index 512b532..07979e9 100644 --- a/.crumb +++ b/.crumb @@ -3,14 +3,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-28T21:30:36Z", + "compiled_at": "2026-10-31T11:52:56Z", "compiler": "crumb-compile/1", - "digest": "sha256:5548a938f2ecd175b05a22120f2b83e38af934c4e390f81af88e463b4a391b19", + "digest": "sha256:fea0cf2d6ff42f7c811e170c031673eb828096be3c56e9a38b986aafd78986cd", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 4, - "generated_at_commit": "d45f6366550b29574664b45ab4156bb25f537593", - "source_tree": "sha256:83c69364fafbedd9e55b699f36ff06ca171d1bc8587287979704fe68d881094c" + "files": 33, + "generated_at_commit": "db86d1a2dfc0613294d27f984b99a48bb97dd27a", + "source_tree": "sha256:a1cc3ba49a6a73e337af7110817528b19800b746513a33822fc61f0e87735f23" } }, "invariants": [ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1748df4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,78 @@ +name: ggml-omega +on: + push: + pull_request: + workflow_dispatch: +permissions: + contents: read +defaults: + run: + shell: bash # bash -eo pipefail: a failing test before `| tee` fails the step +env: + OMEGA_MV_REF: e5b32567a7aff3ce594e3254a622a846a6cd190b # omc sha256 2c824805… (pinned in build.sh) + OMEGA_BRIDGE_REF: d06ec808de7da583acbadf0cb4bb3ba48797e729 # src/native.om sha256 901684b2… (pinned in build.sh) + LLAMA_REF: 7aca0d2ea8d92b56911233b822db01f9fbb1ae50 # pinned in build.sh + MODEL_URL: https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/9217f5db79a29953eb74d5343926648285ec7e67/qwen2.5-0.5b-instruct-q8_0.gguf + MODEL_SHA256: ca59ca7f13d0e15a8cfa77bd17e65d24f6844b554a7b6c12e07a5f89ff76844e +jobs: + test: + runs-on: ubuntu-24.04-arm + timeout-minutes: 300 + steps: + - uses: actions/checkout@v4 + - name: pinned sources + run: | + set -eu + mkdir -p deps && cd deps + curl -fsSL -o omc "https://raw.githubusercontent.com/aien-dev/omega-mv/$OMEGA_MV_REF/seed/out/omc" && chmod +x omc + for r in omega-bridge:$OMEGA_BRIDGE_REF llama.cpp:$LLAMA_REF; do + n=${r%%:*}; s=${r#*:}; u=https://github.com/aien-dev/omega-bridge; [ "$n" = llama.cpp ] && u=https://github.com/ggml-org/llama.cpp + git init -q "$n" && git -C "$n" fetch -q --depth 1 "$u" "$s" && git -C "$n" checkout -q FETCH_HEAD + done + - name: llama.cpp (CPU backend, test-backend-ops) + run: | + cmake -S deps/llama.cpp -B deps/llama.cpp/build -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON \ + -DLLAMA_BUILD_TESTS=ON -DLLAMA_CURL=OFF -DGGML_NATIVE=ON -DGGML_OPENMP=OFF > /dev/null + cmake --build deps/llama.cpp/build -j"$(nproc)" --target test-backend-ops llama > /dev/null + - name: build libggml-omega.so and its two mutants (bin-add, math-exp) + run: | + export OMEGA_GGML_OMC=$PWD/deps/omc OMEGA_BRIDGE=$PWD/deps/omega-bridge GGML_SRC=$PWD/deps/llama.cpp GGML_LIB=$PWD/deps/llama.cpp/build/bin + ./build.sh + OMEGA_GGML_OUT=$PWD/build-mut OMEGA_GGML_MUTANT=bin-add ./build.sh + OMEGA_GGML_OUT=$PWD/build-exp OMEGA_GGML_MUTANT=math-exp ./build.sh + - name: Omega math units against libm and _Float16 + run: | + cc -std=gnu11 -O2 -ffp-contract=off -Wall -Wextra -Werror -o build/test-kernels tests/kernels.c build/omega_ggml_kernels.o -lm + ./build/test-kernels | tee build/kernels.txt + cc -std=gnu11 -O2 -ffp-contract=off -o build/test-kernels-exp tests/kernels.c build-exp/omega_ggml_kernels.o -lm + if ./build/test-kernels-exp > build/kernels-mutant.txt; then echo "math-exp mutant NOT caught" >&2; exit 1; fi + echo "math-exp mutant CAUGHT: $(grep -c ' FAIL$' build/kernels-mutant.txt) failing checks" | tee -a build/kernels-mutant.txt + - name: test-backend-ops, Omega vs CPU, per op + run: tests/backend-ops.sh deps/llama.cpp/build/bin/test-backend-ops "$PWD/build/libggml-omega.so" "$PWD/build-mut/libggml-omega.so" | tee build/backend-ops.tsv + - name: end to end, Qwen2.5-0.5B q8_0, CPU vs Omega + if: always() + run: | + set -eu + L=deps/llama.cpp + cc -std=gnu11 -O2 -Wall -Wextra -Werror -I$L/include -I$L/ggml/include -o build/e2e tests/e2e.c -L$L/build/bin -lllama -lggml -lggml-base -Wl,-rpath,$PWD/$L/build/bin + cc -std=gnu11 -O2 -Wall -Wextra -Werror -o build/cmp tests/cmp.c -lm + curl -fsSL -o model.gguf "$MODEL_URL" + echo "$MODEL_SHA256 model.gguf" | sha256sum -c + N=${E2E_TOKENS:-16} + ./build/e2e model.gguf $N build/cpu.logits 2 > build/e2e-cpu.jsonl + GGML_BACKEND_PATH=$PWD/build/libggml-omega.so ./build/e2e model.gguf $N build/omega.logits 2 > build/e2e-omega.jsonl 2> build/e2e-omega.err + cat build/e2e-omega.err + NV=$(tail -n1 build/e2e-cpu.jsonl | sed 's/.*"n_vocab":\([0-9]*\).*/\1/') + ./build/cmp "$NV" build/cpu.logits build/omega.logits | tee build/e2e-cmp.json + cat build/e2e-cpu.jsonl build/e2e-omega.jsonl + - uses: actions/upload-artifact@v4 + if: always() + with: + name: ggml-omega-logs + path: | + build/*.txt + build/*.tsv + build/*.json + build/*.jsonl + build/*.err + build/backend-ops/ diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..3dd6e17 --- /dev/null +++ b/build.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# Build libggml-omega.so: a ggml backend (llama.cpp backend API v3) whose op kernels are seeded-Omega +# units (kernels/*.om) bound through the omega-bridge native call ABI (src/native.om, docs/NATIVE-ABI.md). +# OMEGA_GGML_OMC the seeded compiler, sha256 pinned below (omega-mv seed/out/omc at e5b32567) +# OMEGA_BRIDGE an aien-dev/omega-bridge checkout; its src/native.om must match the pinned sha256 +# GGML_SRC a llama.cpp checkout at the pinned commit (headers: ggml/include, ggml/src) +# GGML_LIB the folder holding that checkout's libggml-base.so and libggml-cpu.so +# OMEGA_GGML_OUT output folder (default build) +# OMEGA_GGML_MUTANT negative controls: bin-add (the add lane of bin.om computes x - y; test-backend-ops +# must fail) or math-exp (math.om's e^x series keeps 4 terms instead of 13; tests/kernels.c +# must fail) +set -eu +PIN=2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f +LLAMA_PIN=7aca0d2ea8d92b56911233b822db01f9fbb1ae50 +ROOT=$(cd "$(dirname "$0")" && pwd) +K=$ROOT/kernels +NATIVE_PIN=901684b2dc7cd148eb6bb2fe74dd43a6bce857ff014308b00ebaa9d18029158d +BR=${OMEGA_BRIDGE:?set OMEGA_BRIDGE to an omega-bridge checkout (src/native.om sha256 $NATIVE_PIN)} +OMC=${OMEGA_GGML_OMC:?set OMEGA_GGML_OMC to the seeded omc (sha256 $PIN)} +SRC=${GGML_SRC:?set GGML_SRC to a llama.cpp checkout at $LLAMA_PIN} +LIB=${GGML_LIB:?set GGML_LIB to the folder with libggml-base.so and libggml-cpu.so} +O=${OMEGA_GGML_OUT:-$ROOT/build} +got=$(sha256sum < "$OMC" | cut -d' ' -f1) +[ "$got" = "$PIN" ] || { echo "FAIL omc sha256 $got, pinned $PIN" >&2; exit 1; } +got=$(sha256sum < "$BR/src/native.om" | cut -d' ' -f1) +[ "$got" = "$NATIVE_PIN" ] || { echo "FAIL omega-bridge src/native.om sha256 $got, pinned $NATIVE_PIN" >&2; exit 1; } +head=$(git -C "$SRC" rev-parse HEAD) +[ "$head" = "$LLAMA_PIN" ] || { echo "FAIL llama.cpp at $head, pinned $LLAMA_PIN" >&2; exit 1; } +rm -rf "$O"; mkdir -p "$O/units" +"$OMC" < "$BR/src/native.om" > "$O/native"; chmod +x "$O/native" +# file:tile instances. T is the f32/f16 lane count; dq8 takes blocks (B), bytes (W) and floats (X). +INST="bin:32 bin:1 sq:32 sq:1 rmsc:0 scl:32 scl:1 smw:32 smw:1 smwh:32 smwh:1 vmax:32 vmax:1 +sexp:32 sexp:1 rcp:0 rtsc:0 rope:0 df32:256 df32:32 df32:1 dh16:256 dh16:32 dh16:1 dq8:8 dq8:1 +dq8r:0 h2fv:32 h2fv:1 f2hv:32 f2hv:1 cpy:32 cpy:1 cpyh:32 cpyh:1 swi:32 swi:1 silu:32 silu:1" +: > "$O/units.in" +for it in $INST; do + f=${it%%:*}; t=${it#*:}; u=$f; [ "$t" = 0 ] || u=${f}_$t + { cat "$K/math.om" + sed -e "s/@T@/$t/g; s/@B@/$t/g; s/@W@/$((34 * t))/g; s/@X@/$((32 * t))/g" "$K/$f.om"; } > "$O/units/$u.om" + if [ "${OMEGA_GGML_MUTANT:-}" = bin-add ] && [ "$f" = bin ]; then + sed -i 's/^put d i add x y$/put d i sub x y/' "$O/units/$u.om" + grep -q '^put d i sub x y$' "$O/units/$u.om" || { echo "FAIL mutant not applied to $u" >&2; exit 1; } + fi + if [ "${OMEGA_GGML_MUTANT:-}" = math-exp ]; then + sed -i 's/^for i ulong 13$/for i ulong 4/; s/^n = f64 sub 13 i$/n = f64 sub 4 i/' "$O/units/$u.om" + grep -q '^for i ulong 4$' "$O/units/$u.om" || { echo "FAIL mutant not applied to $u" >&2; exit 1; } + fi + "$OMC" < "$O/units/$u.om" > "$O/units/$u.bin" || { echo "FAIL omc $u" >&2; exit 1; } + { cat "$O/units/$u.om"; printf '\0'; printf '%08d' "$(wc -c < "$O/units/$u.bin")"; cat "$O/units/$u.bin"; } >> "$O/units.in" +done +"$O/native" < "$O/units.in" > "$O/omega_ggml_kernels.c" +cc -std=gnu11 -O2 -Wall -Wextra -Werror -fPIC -c -o "$O/omega_ggml_kernels.o" "$O/omega_ggml_kernels.c" +cc -std=gnu11 -O2 -Wall -Wextra -Werror -fPIC -pthread -I"$SRC/ggml/include" -I"$SRC/ggml/src" -I"$O" \ + -c -o "$O/ggml-omega.o" "$ROOT/ggml-omega.c" +cc -shared -pthread -o "$O/libggml-omega.so" "$O/ggml-omega.o" "$O/omega_ggml_kernels.o" \ + -L"$LIB" -lggml-base -lggml-cpu -Wl,-rpath,"$LIB" +echo "BUILT $O/libggml-omega.so ($(echo $INST | wc -w) Omega units, omc $(echo $PIN | cut -c1-12), llama.cpp $(echo $LLAMA_PIN | cut -c1-12))" diff --git a/ggml-omega.c b/ggml-omega.c new file mode 100644 index 0000000..6815d32 --- /dev/null +++ b/ggml-omega.c @@ -0,0 +1,532 @@ +// ggml-omega: a ggml backend (llama.cpp backend API v3) whose op arithmetic runs in seeded-Omega units. +// +// INTERIM HOST GLUE. This C file only registers the backend, decides which ops it takes, walks tensor +// strides, slices rows into fixed-length tiles, stages tiles through a scratch buffer and moves bits. +// Every arithmetic step, every type conversion (f16, q8_0, int32 positions) and every libm-style +// function (exp, log, pow, sin, cos, sqrt) is computed by the Omega units in kernels/*.om, called +// through the omega-bridge native ABI (docs/NATIVE-ABI.md). Its .om successor is the Omega native +// loadable-object ABI (aien-dev/omega-mv #636 / #637): once Omega can export the ggml backend +// tables itself, this file is replaced by a .om unit. +// +// Device type ACCEL with the CPU buffer type, as ggml-blas: weights stay in CPU buffers (no copies), +// llama.cpp places ACCEL backends ahead of CPU, and the scheduler leaves every op this backend does +// not claim in supports_op on the CPU backend. + +#include "ggml-backend-impl.h" +#include "ggml.h" + +#include +#include +#include +#include +#include + +// --- Omega units (generated by omega-bridge src/native.om from kernels/*.om; see build.sh) --------- +#define ARR(p) const void *p, uint64_t p##_n +#define OUT(p) void *p, uint64_t p##_n +uint32_t omega_bin_32(uint64_t *r, uint64_t op, ARR(a), ARR(b), OUT(d)); +uint32_t omega_bin_1(uint64_t *r, uint64_t op, ARR(a), ARR(b), OUT(d)); +uint32_t omega_sq_32(uint64_t *r, uint64_t acc, ARR(x)); +uint32_t omega_sq_1(uint64_t *r, uint64_t acc, ARR(x)); +uint32_t omega_rmsc(uint64_t *r, uint64_t acc, uint64_t n, uint64_t eps); +uint32_t omega_scl_32(uint64_t *r, ARR(x), OUT(d), uint64_t s, uint64_t b); +uint32_t omega_scl_1(uint64_t *r, ARR(x), OUT(d), uint64_t s, uint64_t b); +uint32_t omega_smw_32(uint64_t *r, ARR(x), ARR(m), OUT(d), uint64_t sc); +uint32_t omega_smw_1(uint64_t *r, ARR(x), ARR(m), OUT(d), uint64_t sc); +uint32_t omega_smwh_32(uint64_t *r, ARR(x), ARR(m), OUT(d), uint64_t sc); +uint32_t omega_smwh_1(uint64_t *r, ARR(x), ARR(m), OUT(d), uint64_t sc); +uint32_t omega_vmax_32(uint64_t *r, uint64_t acc, ARR(x)); +uint32_t omega_vmax_1(uint64_t *r, uint64_t acc, ARR(x)); +uint32_t omega_sexp_32(uint64_t *r, uint64_t acc, OUT(w), uint64_t mx); +uint32_t omega_sexp_1(uint64_t *r, uint64_t acc, OUT(w), uint64_t mx); +uint32_t omega_rcp(uint64_t *r, uint64_t acc); +uint32_t omega_rtsc(uint64_t *r, uint64_t base, uint64_t nd); +uint32_t omega_rope(uint64_t *r, uint64_t xy, uint64_t pos, uint64_t i, uint64_t ts, uint64_t fa); +uint32_t omega_df32_256(uint64_t *r, uint64_t acc, ARR(w), ARR(x), uint64_t fin); +uint32_t omega_df32_32(uint64_t *r, uint64_t acc, ARR(w), ARR(x), uint64_t fin); +uint32_t omega_df32_1(uint64_t *r, uint64_t acc, ARR(w), ARR(x), uint64_t fin); +uint32_t omega_dh16_256(uint64_t *r, uint64_t acc, ARR(w), ARR(x), uint64_t fin); +uint32_t omega_dh16_32(uint64_t *r, uint64_t acc, ARR(w), ARR(x), uint64_t fin); +uint32_t omega_dh16_1(uint64_t *r, uint64_t acc, ARR(w), ARR(x), uint64_t fin); +uint32_t omega_dq8_8(uint64_t *r, uint64_t acc, ARR(w), ARR(x), uint64_t fin); +uint32_t omega_dq8_1(uint64_t *r, uint64_t acc, ARR(w), ARR(x), uint64_t fin); +uint32_t omega_dq8r(uint64_t *r, ARR(w), OUT(y)); +uint32_t omega_h2fv_32(uint64_t *r, ARR(s), OUT(d)); +uint32_t omega_h2fv_1(uint64_t *r, ARR(s), OUT(d)); +uint32_t omega_f2hv_32(uint64_t *r, ARR(s), OUT(d)); +uint32_t omega_f2hv_1(uint64_t *r, ARR(s), OUT(d)); +uint32_t omega_cpy_32(uint64_t *r, ARR(s), OUT(d)); +uint32_t omega_cpy_1(uint64_t *r, ARR(s), OUT(d)); +uint32_t omega_cpyh_32(uint64_t *r, ARR(s), OUT(d)); +uint32_t omega_cpyh_1(uint64_t *r, ARR(s), OUT(d)); +uint32_t omega_swi_32(uint64_t *r, ARR(a), ARR(b), OUT(d)); +uint32_t omega_swi_1(uint64_t *r, ARR(a), ARR(b), OUT(d)); +uint32_t omega_silu_32(uint64_t *r, ARR(a), OUT(d)); +uint32_t omega_silu_1(uint64_t *r, ARR(a), OUT(d)); + +// A non-zero status (trap, refused argument, runtime failure) is never ignored. +#define OK(call) \ + do { \ + uint32_t st_ = (call); \ + if (st_ != 0) GGML_ABORT("ggml-omega: %s returned Omega status %u", #call, st_); \ + } while (0) + +#define TILE 32 + +static int32_t ggml_get_op_params_i32(const struct ggml_tensor *t, uint32_t i) { int32_t v; memcpy(&v, (const char *) t->op_params + 4 * i, 4); return v; } +static float ggml_get_op_params_f32(const struct ggml_tensor *t, uint32_t i) { float v; memcpy(&v, (const char *) t->op_params + 4 * i, 4); return v; } + +static uint64_t bits_f32(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } +static float f32_bits(uint64_t v) { uint32_t u = (uint32_t) v; float f; memcpy(&f, &u, 4); return f; } + +static char *at(const struct ggml_tensor *t, int64_t i1, int64_t i2, int64_t i3) { + return (char *) t->data + i1 * t->nb[1] + i2 * t->nb[2] + i3 * t->nb[3]; +} + +// --- row kernels: tiles of 32 lanes, then single lanes; outputs staged through t[] ------------- + +static void row_bin(uint64_t op, const float *a, const float *b, float *d, int64_t n) { + float t[TILE]; uint64_t r; int64_t i = 0; + for (; i + TILE <= n; i += TILE) { OK(omega_bin_32(&r, op, a + i, TILE, b + i, TILE, t, TILE)); memcpy(d + i, t, sizeof t); } + for (; i < n; i++) { OK(omega_bin_1(&r, op, a + i, 1, b + i, 1, t, 1)); d[i] = t[0]; } +} + +static void row_scl(const float *x, float *d, int64_t n, uint64_t s, uint64_t b) { + float t[TILE]; uint64_t r; int64_t i = 0; + for (; i + TILE <= n; i += TILE) { OK(omega_scl_32(&r, x + i, TILE, t, TILE, s, b)); memcpy(d + i, t, sizeof t); } + for (; i < n; i++) { OK(omega_scl_1(&r, x + i, 1, t, 1, s, b)); d[i] = t[0]; } +} + +// one row of src (f32, f16 or q8_0) to f32 or f16 at d +static void row_cvt(enum ggml_type st, const void *s, enum ggml_type dt, void *d, int64_t n) { + uint64_t r; int64_t i = 0; + if (st == GGML_TYPE_Q8_0) { + float t[32]; + for (; i < n / 32; i++) { OK(omega_dq8r(&r, (const char *) s + 34 * i, 34, t, 32)); memcpy((float *) d + 32 * i, t, sizeof t); } + return; + } + if (dt == GGML_TYPE_F32) { + float t[TILE]; float *df = d; + if (st == GGML_TYPE_F32) { + const float *sf = s; + for (; i + TILE <= n; i += TILE) { OK(omega_cpy_32(&r, sf + i, TILE, t, TILE)); memcpy(df + i, t, sizeof t); } + for (; i < n; i++) { OK(omega_cpy_1(&r, sf + i, 1, t, 1)); df[i] = t[0]; } + } else { + const uint16_t *sh = s; + for (; i + TILE <= n; i += TILE) { OK(omega_h2fv_32(&r, sh + i, TILE, t, TILE)); memcpy(df + i, t, sizeof t); } + for (; i < n; i++) { OK(omega_h2fv_1(&r, sh + i, 1, t, 1)); df[i] = t[0]; } + } + } else { + uint16_t t[TILE]; uint16_t *dh = d; + if (st == GGML_TYPE_F32) { + const float *sf = s; + for (; i + TILE <= n; i += TILE) { OK(omega_f2hv_32(&r, sf + i, TILE, t, TILE)); memcpy(dh + i, t, sizeof t); } + for (; i < n; i++) { OK(omega_f2hv_1(&r, sf + i, 1, t, 1)); dh[i] = t[0]; } + } else { + const uint16_t *sh = s; + for (; i + TILE <= n; i += TILE) { OK(omega_cpyh_32(&r, sh + i, TILE, t, TILE)); memcpy(dh + i, t, sizeof t); } + for (; i < n; i++) { OK(omega_cpyh_1(&r, sh + i, 1, t, 1)); dh[i] = t[0]; } + } + } +} + +// dot of one weight row (f32, f16 or q8_0) with one f32 row of k elements +static float row_dot(enum ggml_type wt, const void *w, const float *x, int64_t k) { + uint64_t acc = 0; int64_t i = 0; + if (wt == GGML_TYPE_Q8_0) { + const char *wb = w; const int64_t nb = k / 32; + while (i < nb) { + if (nb - i >= 8) { OK(omega_dq8_8(&acc, acc, wb + 34 * i, 272, x + 32 * i, 256, nb - i == 8)); i += 8; } + else { OK(omega_dq8_1(&acc, acc, wb + 34 * i, 34, x + 32 * i, 32, nb - i == 1)); i += 1; } + } + } else if (wt == GGML_TYPE_F16) { + const uint16_t *wh = w; + while (i < k) { + if (k - i >= 256) { OK(omega_dh16_256(&acc, acc, wh + i, 256, x + i, 256, k - i == 256)); i += 256; } + else if (k - i >= 32) { OK(omega_dh16_32(&acc, acc, wh + i, 32, x + i, 32, k - i == 32)); i += 32; } + else { OK(omega_dh16_1(&acc, acc, wh + i, 1, x + i, 1, k - i == 1)); i += 1; } + } + } else { + const float *wf = w; + while (i < k) { + if (k - i >= 256) { OK(omega_df32_256(&acc, acc, wf + i, 256, x + i, 256, k - i == 256)); i += 256; } + else if (k - i >= 32) { OK(omega_df32_32(&acc, acc, wf + i, 32, x + i, 32, k - i == 32)); i += 32; } + else { OK(omega_df32_1(&acc, acc, wf + i, 1, x + i, 1, k - i == 1)); i += 1; } + } + } + return f32_bits(acc); +} + +// --- ops ------------------------------------------------------------------------------------------ + +static void op_bin(struct ggml_tensor *dst, uint64_t code) { + const struct ggml_tensor *a = dst->src[0], *b = dst->src[1]; + for (int64_t i3 = 0; i3 < dst->ne[3]; i3++) + for (int64_t i2 = 0; i2 < dst->ne[2]; i2++) + for (int64_t i1 = 0; i1 < dst->ne[1]; i1++) + row_bin(code, (const float *) at(a, i1, i2, i3), + (const float *) at(b, i1 % b->ne[1], i2 % b->ne[2], i3 % b->ne[3]), + (float *) at(dst, i1, i2, i3), dst->ne[0]); +} + +static void op_rms_norm(struct ggml_tensor *dst) { + const struct ggml_tensor *x = dst->src[0]; + const uint64_t eps = bits_f32(ggml_get_op_params_f32(dst, 0)); + const int64_t n = x->ne[0]; + for (int64_t i3 = 0; i3 < x->ne[3]; i3++) + for (int64_t i2 = 0; i2 < x->ne[2]; i2++) + for (int64_t i1 = 0; i1 < x->ne[1]; i1++) { + const float *xr = (const float *) at(x, i1, i2, i3); + uint64_t acc = 0, sc; int64_t i = 0; + for (; i + TILE <= n; i += TILE) OK(omega_sq_32(&acc, acc, xr + i, TILE)); + for (; i < n; i++) OK(omega_sq_1(&acc, acc, xr + i, 1)); + OK(omega_rmsc(&sc, acc, (uint64_t) n, eps)); + row_scl(xr, (float *) at(dst, i1, i2, i3), n, sc, 0); + } +} + +static void op_scale(struct ggml_tensor *dst) { + const struct ggml_tensor *x = dst->src[0]; + const uint64_t s = bits_f32(ggml_get_op_params_f32(dst, 0)), b = bits_f32(ggml_get_op_params_f32(dst, 1)); + for (int64_t i3 = 0; i3 < x->ne[3]; i3++) + for (int64_t i2 = 0; i2 < x->ne[2]; i2++) + for (int64_t i1 = 0; i1 < x->ne[1]; i1++) + row_scl((const float *) at(x, i1, i2, i3), (float *) at(dst, i1, i2, i3), x->ne[0], s, b); +} + +static void op_soft_max(struct ggml_tensor *dst) { + const struct ggml_tensor *x = dst->src[0], *m = dst->src[1]; + const uint64_t sc = bits_f32(ggml_get_op_params_f32(dst, 0)); + const int64_t n = x->ne[0]; + float t[TILE]; uint64_t r; + for (int64_t i3 = 0; i3 < x->ne[3]; i3++) + for (int64_t i2 = 0; i2 < x->ne[2]; i2++) + for (int64_t i1 = 0; i1 < x->ne[1]; i1++) { + const float *xr = (const float *) at(x, i1, i2, i3); + float *dr = (float *) at(dst, i1, i2, i3); + int64_t i = 0; + if (!m) { + row_scl(xr, dr, n, sc, 0); + } else { + const char *mr = at(m, i1, i2 % m->ne[2], i3 % m->ne[3]); + if (m->type == GGML_TYPE_F32) { + const float *mf = (const float *) mr; + for (; i + TILE <= n; i += TILE) { OK(omega_smw_32(&r, xr + i, TILE, mf + i, TILE, t, TILE, sc)); memcpy(dr + i, t, sizeof t); } + for (; i < n; i++) { OK(omega_smw_1(&r, xr + i, 1, mf + i, 1, t, 1, sc)); dr[i] = t[0]; } + } else { + const uint16_t *mh = (const uint16_t *) mr; + for (; i + TILE <= n; i += TILE) { OK(omega_smwh_32(&r, xr + i, TILE, mh + i, TILE, t, TILE, sc)); memcpy(dr + i, t, sizeof t); } + for (; i < n; i++) { OK(omega_smwh_1(&r, xr + i, 1, mh + i, 1, t, 1, sc)); dr[i] = t[0]; } + } + } + uint64_t mx = bits_f32(-INFINITY), sum = 0, rs; + for (i = 0; i + TILE <= n; i += TILE) OK(omega_vmax_32(&mx, mx, dr + i, TILE)); + for (; i < n; i++) OK(omega_vmax_1(&mx, mx, dr + i, 1)); + for (i = 0; i + TILE <= n; i += TILE) OK(omega_sexp_32(&sum, sum, dr + i, TILE, mx)); + for (; i < n; i++) OK(omega_sexp_1(&sum, sum, dr + i, 1, mx)); + OK(omega_rcp(&rs, sum)); + row_scl(dr, dr, n, rs, 0); + } +} + +static void op_rope(struct ggml_tensor *dst) { + const struct ggml_tensor *x = dst->src[0], *p = dst->src[1]; + const int n_dims = ggml_get_op_params_i32(dst, 1), mode = ggml_get_op_params_i32(dst, 2); + const int n_offs = ggml_get_op_params_i32(dst, 15); + const uint64_t fs = bits_f32(ggml_get_op_params_f32(dst, 6)), af = bits_f32(ggml_get_op_params_f32(dst, 8)); + const uint64_t fa = fs | (af << 32); + uint64_t ts; + OK(omega_rtsc(&ts, bits_f32(ggml_get_op_params_f32(dst, 5)), (uint64_t) n_dims)); + const int64_t half = n_dims / 2, step = mode == GGML_ROPE_TYPE_NEOX ? half : 1; + const int32_t *pos = (const int32_t *) p->data; + for (int64_t i3 = 0; i3 < x->ne[3]; i3++) + for (int64_t i2 = 0; i2 < x->ne[2]; i2++) + for (int64_t i1 = 0; i1 < x->ne[1]; i1++) { + const float *s = (const float *) at(x, i1, i2, i3); + float *d = (float *) at(dst, i1, i2, i3); + float tail[TILE]; + for (int64_t k = 0; k < half; k++) { + const int64_t c = n_offs + (mode == GGML_ROPE_TYPE_NEOX ? k : 2 * k); + const uint64_t xy = bits_f32(s[c]) | (bits_f32(s[c + step]) << 32); + uint64_t o; + OK(omega_rope(&o, xy, (uint32_t) pos[i2], (uint64_t) k, ts, fa)); + const float o0 = f32_bits(o), o1 = f32_bits(o >> 32); + d[c] = o0; d[c + step] = o1; + } + // channels outside [n_offs, n_offs + n_dims) are copied (Omega cpy tiles) + for (int64_t i0 = 0; i0 < x->ne[0];) { + if (i0 == n_offs) { i0 += n_dims; continue; } + const int64_t end = i0 < n_offs ? n_offs : x->ne[0]; + for (; i0 < end; i0++) { uint64_t r; OK(omega_cpy_1(&r, s + i0, 1, tail, 1)); d[i0] = tail[0]; } + } + } +} + +static void op_get_rows(struct ggml_tensor *dst) { + const struct ggml_tensor *w = dst->src[0], *ix = dst->src[1]; + for (int64_t i12 = 0; i12 < ix->ne[2]; i12++) + for (int64_t i11 = 0; i11 < ix->ne[1]; i11++) + for (int64_t i10 = 0; i10 < ix->ne[0]; i10++) { + const int64_t r = *(const int32_t *) ((const char *) ix->data + i10 * ix->nb[0] + i11 * ix->nb[1] + i12 * ix->nb[2]); + GGML_ASSERT(r >= 0 && r < w->ne[1]); + row_cvt(w->type, at(w, r, i11, i12), dst->type, at(dst, i10, i11, i12), w->ne[0]); + } +} + +static void op_set_rows(struct ggml_tensor *dst) { + const struct ggml_tensor *s = dst->src[0], *ix = dst->src[1]; + for (int64_t i03 = 0; i03 < s->ne[3]; i03++) + for (int64_t i02 = 0; i02 < s->ne[2]; i02++) + for (int64_t i = 0; i < s->ne[1]; i++) { + const char *ip = (const char *) ix->data + i * ix->nb[0] + (i02 % ix->ne[1]) * ix->nb[1] + (i03 % ix->ne[2]) * ix->nb[2]; + const int64_t r = ix->type == GGML_TYPE_I64 ? *(const int64_t *) ip : *(const int32_t *) ip; + GGML_ASSERT(r >= 0 && r < dst->ne[1]); + row_cvt(s->type, at(s, i, i02, i03), dst->type, at(dst, r, i02, i03), s->ne[0]); + } +} + +static void op_cpy(struct ggml_tensor *dst) { + const struct ggml_tensor *s = dst->src[0]; + if (ggml_are_same_shape(s, dst)) { + for (int64_t i3 = 0; i3 < s->ne[3]; i3++) + for (int64_t i2 = 0; i2 < s->ne[2]; i2++) + for (int64_t i1 = 0; i1 < s->ne[1]; i1++) + row_cvt(s->type, at(s, i1, i2, i3), dst->type, at(dst, i1, i2, i3), s->ne[0]); + } else { // both contiguous (checked in supports_op): one flat row + row_cvt(s->type, s->data, dst->type, dst->data, ggml_nelements(s)); + } +} + +static void op_swiglu(struct ggml_tensor *dst) { + const struct ggml_tensor *a = dst->src[0], *b = dst->src[1]; + const int64_t nc = dst->ne[0]; + const int swapped = ggml_get_op_params_i32(dst, 1); + float t[TILE]; uint64_t r; + for (int64_t i3 = 0; i3 < dst->ne[3]; i3++) + for (int64_t i2 = 0; i2 < dst->ne[2]; i2++) + for (int64_t i1 = 0; i1 < dst->ne[1]; i1++) { + const float *ap = (const float *) at(a, i1, i2, i3); + const float *bp = b ? (const float *) at(b, i1, i2, i3) : ap; + if (!b) { ap += swapped ? nc : 0; bp += swapped ? 0 : nc; } + float *d = (float *) at(dst, i1, i2, i3); + int64_t i = 0; + for (; i + TILE <= nc; i += TILE) { OK(omega_swi_32(&r, ap + i, TILE, bp + i, TILE, t, TILE)); memcpy(d + i, t, sizeof t); } + for (; i < nc; i++) { OK(omega_swi_1(&r, ap + i, 1, bp + i, 1, t, 1)); d[i] = t[0]; } + } +} + +static void op_silu(struct ggml_tensor *dst) { + const struct ggml_tensor *a = dst->src[0]; + float t[TILE]; uint64_t r; + for (int64_t i3 = 0; i3 < dst->ne[3]; i3++) + for (int64_t i2 = 0; i2 < dst->ne[2]; i2++) + for (int64_t i1 = 0; i1 < dst->ne[1]; i1++) { + const float *ap = (const float *) at(a, i1, i2, i3); + float *d = (float *) at(dst, i1, i2, i3); + int64_t i = 0; + for (; i + TILE <= dst->ne[0]; i += TILE) { OK(omega_silu_32(&r, ap + i, TILE, t, TILE)); memcpy(d + i, t, sizeof t); } + for (; i < dst->ne[0]; i++) { OK(omega_silu_1(&r, ap + i, 1, t, 1)); d[i] = t[0]; } + } +} + +// MUL_MAT: dst[i01, col] = dot(src0 row i01, src1 col). Weight rows are split across threads. +struct mm_job { struct ggml_tensor *dst; int64_t r0, r1; }; + +static void *mm_run(void *arg) { + const struct mm_job *j = arg; + struct ggml_tensor *dst = j->dst; + const struct ggml_tensor *w = dst->src[0], *x = dst->src[1]; + const int64_t r2 = x->ne[2] / w->ne[2], r3 = x->ne[3] / w->ne[3]; + for (int64_t i13 = 0; i13 < x->ne[3]; i13++) + for (int64_t i12 = 0; i12 < x->ne[2]; i12++) + for (int64_t i11 = 0; i11 < x->ne[1]; i11++) { + const float *xc = (const float *) at(x, i11, i12, i13); + char *dc = at(dst, i11, i12, i13); + for (int64_t i01 = j->r0; i01 < j->r1; i01++) { + const float v = row_dot(w->type, at(w, i01, i12 / r2, i13 / r3), xc, w->ne[0]); + memcpy(dc + i01 * dst->nb[0], &v, 4); + } + } + return NULL; +} + +static void op_mul_mat(struct ggml_tensor *dst, int n_threads) { + const int64_t rows = dst->src[0]->ne[1]; + int nt = n_threads < 1 ? 1 : n_threads > 64 ? 64 : n_threads; + if (rows < 2 * nt) nt = 1; + struct mm_job jobs[64]; pthread_t th[64]; + for (int t = 0; t < nt; t++) jobs[t] = (struct mm_job) { dst, rows * t / nt, rows * (t + 1) / nt }; + for (int t = 1; t < nt; t++) if (pthread_create(&th[t], NULL, mm_run, &jobs[t]) != 0) GGML_ABORT("ggml-omega: pthread_create"); + mm_run(&jobs[0]); + for (int t = 1; t < nt; t++) pthread_join(th[t], NULL); +} + +// --- backend ---------------------------------------------------------------------------------------- + +struct omega_ctx { int n_threads; }; + +static const char *omega_name(ggml_backend_t b) { (void) b; return "Omega"; } +static void omega_free(ggml_backend_t b) { free(b->context); free(b); } + +static enum ggml_status omega_graph_compute(ggml_backend_t backend, struct ggml_cgraph *g) { + const struct omega_ctx *ctx = backend->context; + for (int i = 0; i < ggml_graph_n_nodes(g); i++) { + struct ggml_tensor *n = ggml_graph_node(g, i); + if ((n->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) continue; + switch (n->op) { + case GGML_OP_NONE: case GGML_OP_RESHAPE: case GGML_OP_VIEW: case GGML_OP_PERMUTE: case GGML_OP_TRANSPOSE: break; + case GGML_OP_ADD: op_bin(n, 0); break; + case GGML_OP_SUB: op_bin(n, 1); break; + case GGML_OP_MUL: op_bin(n, 2); break; + case GGML_OP_DIV: op_bin(n, 3); break; + case GGML_OP_RMS_NORM: op_rms_norm(n); break; + case GGML_OP_SCALE: op_scale(n); break; + case GGML_OP_SOFT_MAX: op_soft_max(n); break; + case GGML_OP_ROPE: op_rope(n); break; + case GGML_OP_GET_ROWS: op_get_rows(n); break; + case GGML_OP_SET_ROWS: op_set_rows(n); break; + case GGML_OP_CPY: case GGML_OP_CONT: case GGML_OP_DUP: op_cpy(n); break; + case GGML_OP_GLU: op_swiglu(n); break; + case GGML_OP_UNARY: op_silu(n); break; + case GGML_OP_MUL_MAT: op_mul_mat(n, ctx->n_threads); break; + default: GGML_ABORT("ggml-omega: op %s reached graph_compute without support", ggml_op_name(n->op)); + } + } + return GGML_STATUS_SUCCESS; +} + +static const struct ggml_backend_i omega_backend_i = { + .get_name = omega_name, + .free = omega_free, + .graph_compute = omega_graph_compute, +}; + +static ggml_guid_t omega_guid(void) { + static ggml_guid guid = { 0x4f, 0x6d, 0x65, 0x67, 0x61, 0x2d, 0x67, 0x67, 0x6d, 0x6c, 0x2d, 0x62, 0x72, 0x69, 0x64, 0x67 }; + return &guid; +} + +static void omega_set_n_threads(ggml_backend_t b, int n) { + GGML_ASSERT(b && ggml_guid_matches(b->guid, omega_guid())); + ((struct omega_ctx *) b->context)->n_threads = n; +} + +static ggml_backend_reg_t omega_reg(void); + +static const char *dev_name(ggml_backend_dev_t d) { (void) d; return "Omega"; } +static const char *dev_desc(ggml_backend_dev_t d) { (void) d; return "seeded-Omega kernels via omega-bridge (host)"; } +static void dev_memory(ggml_backend_dev_t d, size_t *free_, size_t *total) { (void) d; *free_ = 0; *total = 0; } +static enum ggml_backend_dev_type dev_type(ggml_backend_dev_t d) { (void) d; return GGML_BACKEND_DEVICE_TYPE_ACCEL; } + +static void dev_props(ggml_backend_dev_t d, struct ggml_backend_dev_props *p) { + p->name = dev_name(d); p->description = dev_desc(d); p->type = dev_type(d); p->device_id = NULL; + dev_memory(d, &p->memory_free, &p->memory_total); + p->caps = (struct ggml_backend_dev_caps) { .async = false, .host_buffer = false, .buffer_from_host_ptr = true, .events = false, .mmap_support = true }; +} + +static ggml_backend_t dev_init(ggml_backend_dev_t d, const char *params) { + (void) params; + struct omega_ctx *ctx = malloc(sizeof *ctx); + ggml_backend_t b = malloc(sizeof *b); + if (!ctx || !b) { free(ctx); free(b); return NULL; } + ctx->n_threads = 1; + *b = (struct ggml_backend) { .guid = omega_guid(), .iface = omega_backend_i, .device = d, .context = ctx }; + return b; +} + +static ggml_backend_buffer_type_t dev_buft(ggml_backend_dev_t d) { (void) d; return ggml_backend_cpu_buffer_type(); } +static ggml_backend_buffer_t dev_from_ptr(ggml_backend_dev_t d, void *ptr, size_t size, size_t max) { + (void) d; (void) max; return ggml_backend_cpu_buffer_from_ptr(ptr, size); +} +static bool dev_supports_buft(ggml_backend_dev_t d, ggml_backend_buffer_type_t b) { (void) d; return ggml_backend_buft_is_host(b); } + +static bool f32(const struct ggml_tensor *t) { return t && t->type == GGML_TYPE_F32; } +static bool rows1(const struct ggml_tensor *t) { return t->nb[0] == ggml_type_size(t->type); } // contiguous within a row +static bool fh(const struct ggml_tensor *t) { return t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_F16; } + +static bool dev_supports_op(ggml_backend_dev_t d, const struct ggml_tensor *op) { + (void) d; + const struct ggml_tensor *s0 = op->src[0], *s1 = op->src[1]; + switch (op->op) { + case GGML_OP_NONE: case GGML_OP_RESHAPE: case GGML_OP_VIEW: case GGML_OP_PERMUTE: case GGML_OP_TRANSPOSE: + return true; + case GGML_OP_ADD: case GGML_OP_SUB: case GGML_OP_MUL: case GGML_OP_DIV: + return f32(op) && f32(s0) && f32(s1) && rows1(op) && rows1(s0) && rows1(s1) && + ggml_are_same_shape(op, s0) && s1->ne[0] == s0->ne[0] && ggml_can_repeat(s1, s0); + case GGML_OP_RMS_NORM: case GGML_OP_SCALE: + return f32(op) && f32(s0) && rows1(op) && rows1(s0); + case GGML_OP_SOFT_MAX: + return f32(op) && f32(s0) && rows1(op) && rows1(s0) && op->src[2] == NULL && + ggml_get_op_params_f32(op, 1) == 0.0f && + (!s1 || ((s1->type == GGML_TYPE_F32 || s1->type == GGML_TYPE_F16) && rows1(s1) && s1->ne[0] == s0->ne[0] && + s1->ne[1] >= s0->ne[1] && s0->ne[2] % s1->ne[2] == 0 && s0->ne[3] % s1->ne[3] == 0)); + case GGML_OP_ROPE: { + const int mode = ggml_get_op_params_i32(op, 2); + return f32(op) && f32(s0) && rows1(op) && rows1(s0) && s1->type == GGML_TYPE_I32 && op->src[2] == NULL && + (mode == GGML_ROPE_TYPE_NORMAL || mode == GGML_ROPE_TYPE_NEOX) && + ggml_get_op_params_f32(op, 7) == 0.0f && ggml_get_op_params_i32(op, 1) % 2 == 0; + } + case GGML_OP_GET_ROWS: + return f32(op) && rows1(op) && s1->type == GGML_TYPE_I32 && + (s0->type == GGML_TYPE_F32 || s0->type == GGML_TYPE_F16 || s0->type == GGML_TYPE_Q8_0) && rows1(s0); + case GGML_OP_SET_ROWS: + return f32(s0) && fh(op) && rows1(op) && rows1(s0) && (s1->type == GGML_TYPE_I64 || s1->type == GGML_TYPE_I32); + case GGML_OP_CPY: case GGML_OP_CONT: case GGML_OP_DUP: { + const struct ggml_tensor *dst = op; + return fh(s0) && fh(dst) && rows1(s0) && rows1(dst) && + (ggml_are_same_shape(s0, dst) || (ggml_is_contiguous(s0) && ggml_is_contiguous(dst))); + } + case GGML_OP_GLU: + return ggml_get_glu_op(op) == GGML_GLU_OP_SWIGLU && f32(op) && f32(s0) && (!s1 || f32(s1)) && + ggml_is_contiguous_1(s0) && ggml_is_contiguous_1(op) && (!s1 || ggml_is_contiguous_1(s1)); + case GGML_OP_UNARY: + return ggml_get_unary_op(op) == GGML_UNARY_OP_SILU && f32(op) && f32(s0) && rows1(op) && rows1(s0); + case GGML_OP_MUL_MAT: + return f32(op) && f32(s1) && rows1(op) && rows1(s1) && rows1(s0) && + (s0->type == GGML_TYPE_F32 || s0->type == GGML_TYPE_F16 || s0->type == GGML_TYPE_Q8_0) && + s1->ne[2] % s0->ne[2] == 0 && s1->ne[3] % s0->ne[3] == 0 && + ggml_get_op_params_i32(op, 1) != GGML_HINT_SRC0_IS_HADAMARD; + default: + return false; + } +} + +static const struct ggml_backend_device_i omega_dev_i = { + .get_name = dev_name, + .get_description = dev_desc, + .get_memory = dev_memory, + .get_type = dev_type, + .get_props = dev_props, + .init_backend = dev_init, + .get_buffer_type = dev_buft, + .buffer_from_host_ptr = dev_from_ptr, + .supports_op = dev_supports_op, + .supports_buft = dev_supports_buft, +}; + +static const char *reg_name(ggml_backend_reg_t r) { (void) r; return "Omega"; } +static size_t reg_count(ggml_backend_reg_t r) { (void) r; return 1; } +static ggml_backend_dev_t reg_dev(ggml_backend_reg_t r, size_t i) { + static struct ggml_backend_device dev = { .iface = omega_dev_i, .context = NULL }; + GGML_ASSERT(i == 0); + dev.reg = r; + return &dev; +} +static void *reg_proc(ggml_backend_reg_t r, const char *name) { + (void) r; + if (strcmp(name, "ggml_backend_set_n_threads") == 0) return (void *) omega_set_n_threads; + return NULL; +} + +static const struct ggml_backend_reg_i omega_reg_i = { + .get_name = reg_name, .get_device_count = reg_count, .get_device = reg_dev, .get_proc_address = reg_proc, +}; + +static ggml_backend_reg_t omega_reg(void) { + static struct ggml_backend_reg reg = { .api_version = GGML_BACKEND_API_VERSION, .iface = omega_reg_i, .context = NULL }; + return ® +} + +// dynamic-load entry point read by ggml_backend_load (GGML_BACKEND_PATH) +__attribute__((visibility("default"))) ggml_backend_reg_t ggml_backend_init(void); +ggml_backend_reg_t ggml_backend_init(void) { return omega_reg(); } diff --git a/kernels/bin.om b/kernels/bin.om new file mode 100644 index 0000000..c2beb4d --- /dev/null +++ b/kernels/bin.om @@ -0,0 +1,20 @@ +note bin_@T@: d = a op b on @T@ f32 lanes; op 0 add, 1 sub, 2 mul, 3 div (one rounding each, as ggml-cpu). +fn bin_@T@ op ulong a view f32 @T@ b view f32 @T@ d edit f32 @T@ to void +for i ulong @T@ +x = get a i +y = get b i +if eq op 0 +put d i add x y +else +if eq op 1 +put d i sub x y +else +if eq op 2 +put d i mul x y +else +put d i div x y +end +end +end +end +end diff --git a/kernels/cpy.om b/kernels/cpy.om new file mode 100644 index 0000000..4b5eb09 --- /dev/null +++ b/kernels/cpy.om @@ -0,0 +1,6 @@ +note cpy_@T@: f32 copy on @T@ lanes. +fn cpy_@T@ s view f32 @T@ d edit f32 @T@ to void +for i ulong @T@ +put d i get s i +end +end diff --git a/kernels/cpyh.om b/kernels/cpyh.om new file mode 100644 index 0000000..994cc62 --- /dev/null +++ b/kernels/cpyh.om @@ -0,0 +1,6 @@ +note cpyh_@T@: f16 copy on @T@ lanes. +fn cpyh_@T@ s view ushort @T@ d edit ushort @T@ to void +for i ulong @T@ +put d i get s i +end +end diff --git a/kernels/df32.om b/kernels/df32.om new file mode 100644 index 0000000..6c8523c --- /dev/null +++ b/kernels/df32.om @@ -0,0 +1,11 @@ +note df32_@T@: acc (f64 bits) + sum of f64(w*x) over @T@ lanes; fin 1 returns the f32 bits of the total. +fn df32_@T@ acc ulong w view f32 @T@ x view f32 @T@ fin ulong to ulong +s = bitcast f64 acc +for i ulong @T@ +s = add s f64 mul get w i get x i +end +if eq fin 1 +ret ulong bitcast uint f32 s +end +ret bitcast ulong s +end diff --git a/kernels/dh16.om b/kernels/dh16.om new file mode 100644 index 0000000..7691669 --- /dev/null +++ b/kernels/dh16.om @@ -0,0 +1,11 @@ +note dh16_@T@: as df32 with f16 weights, converted in Omega (h2f). +fn dh16_@T@ acc ulong w view ushort @T@ x view f32 @T@ fin ulong to ulong +s = bitcast f64 acc +for i ulong @T@ +s = add s f64 mul h2f get w i get x i +end +if eq fin 1 +ret ulong bitcast uint f32 s +end +ret bitcast ulong s +end diff --git a/kernels/dq8.om b/kernels/dq8.om new file mode 100644 index 0000000..cc84969 --- /dev/null +++ b/kernels/dq8.om @@ -0,0 +1,28 @@ +note dq8_@B@: q8_0 dot over @B@ blocks of 34 bytes (f16 scale d, 32 signed bytes q) against f32 x: +note acc (f64 bits) + sum over blocks of f64(d * sum_j f32(q_j)*x_j); fin 1 returns the f32 total. +fn q8s u uchar to f32 +q = long u +if ge q 128 +q = sub q 256 +end +ret f32 q +end +fn q8d w view uchar @W@ o ulong to f32 +ret h2f ushort or ulong get w o shl ulong get w add o 1 8 +end +fn dq8_@B@ acc ulong w view uchar @W@ x view f32 @X@ fin ulong to ulong +s = bitcast f64 acc +for b ulong @B@ +o = mul b 34 +xo = mul b 32 +bs = f32 0.0 +for j ulong 32 +bs = add bs mul q8s get w add add o 2 j get x add xo j +end +s = add s f64 mul q8d view w o bs +end +if eq fin 1 +ret ulong bitcast uint f32 s +end +ret bitcast ulong s +end diff --git a/kernels/dq8r.om b/kernels/dq8r.om new file mode 100644 index 0000000..422aef1 --- /dev/null +++ b/kernels/dq8r.om @@ -0,0 +1,11 @@ +note dq8r: one q8_0 block (34 bytes) dequantised to 32 f32: y = f32(q) * d, as ggml-cpu dequantize_row_q8_0. +fn dq8r w view uchar 34 y edit f32 32 to void +d = h2f ushort or ulong get w 0 shl ulong get w 1 8 +for j ulong 32 +q = long get w add 2 j +if ge q 128 +q = sub q 256 +end +put y j mul f32 q d +end +end diff --git a/kernels/f2hv.om b/kernels/f2hv.om new file mode 100644 index 0000000..b41475b --- /dev/null +++ b/kernels/f2hv.om @@ -0,0 +1,6 @@ +note f2hv_@T@: f32 -> f16 on @T@ lanes, round to nearest even. +fn f2hv_@T@ s view f32 @T@ d edit ushort @T@ to void +for i ulong @T@ +put d i f2h get s i +end +end diff --git a/kernels/h2fv.om b/kernels/h2fv.om new file mode 100644 index 0000000..1287c65 --- /dev/null +++ b/kernels/h2fv.om @@ -0,0 +1,6 @@ +note h2fv_@T@: f16 -> f32 on @T@ lanes. +fn h2fv_@T@ s view ushort @T@ d edit f32 @T@ to void +for i ulong @T@ +put d i h2f get s i +end +end diff --git a/kernels/math.om b/kernels/math.om new file mode 100644 index 0000000..8e14673 --- /dev/null +++ b/kernels/math.om @@ -0,0 +1,157 @@ +note math.om: private f64/f16 helpers prepended to the ggml-omega kernel units that need them +note (exp, log, pow, sin, cos, f16 <-> f32). Constants are binary64 bit patterns checked in Wolfram +note Language (ImportByteArray of the bits, difference to Log[2], 1/Log[2], Pi/2, 2/Pi, Sqrt[2]): +note ln2 hi+lo -1.2e-26, pio2 1+2+3 -8.5e-32; the hi parts end in >= 21 zero bits, so k*hi is exact for |k| < 2^21. +const cln2h ulong 4604418534311723008 +const cln2l ulong 4461442080421002358 +const civln2 ulong 4609176140021203710 +const cpio21 ulong 4609753056924401664 +const cpio22 ulong 4454258360616747008 +const cpio23 ulong 4297306550709518336 +const civpio2 ulong 4603909380684499075 +const csqrt2 ulong 4609047870845172685 +note rnd: x rounded to the nearest whole number (halves away from zero), as long. +fn rnd x f64 to long +if lt x 0.0 +ret long sub x 0.5 +end +ret long add x 0.5 +end +note ex64: e^x. Inputs below -200 give 0 (every f32 result there is 0), above 709 are clamped (f32 inf). +fn ex64 x f64 to f64 +if ne x x +ret x +end +if lt x -200.0 +ret 0.0 +end +y = x +if gt y 709.0 +y = 709.0 +end +k = rnd mul y bitcast f64 civln2 +kf = f64 k +r = sub sub y mul kf bitcast f64 cln2h mul kf bitcast f64 cln2l +p = f64 1.0 +for i ulong 13 +n = f64 sub 13 i +p = add 1.0 div mul r p n +end +sc = bitcast f64 shl ulong add k 1023 52 +ret mul p sc +end +note ln64: natural log of a positive normal x. +fn ln64 x f64 to f64 +b = bitcast ulong x +e = sub long shr b 52 1023 +m = bitcast f64 or and b 4503599627370495 shl ulong 1023 52 +if gt m bitcast f64 csqrt2 +m = div m 2.0 +e = add e 1 +end +s = div sub m 1.0 add m 1.0 +s2 = mul s s +t = f64 0.0 +for i ulong 12 +n = f64 add mul 2 sub 11 i 1 +t = add div 1.0 n mul s2 t +end +ef = f64 e +ret add mul ef bitcast f64 cln2h add mul ef bitcast f64 cln2l mul mul 2.0 s t +end +note sinr / cosr: Taylor series on |r| <= pi/4. +fn sinr r f64 to f64 +r2 = mul r r +t = f64 1.0 +for i ulong 9 +n = f64 sub 9 i +t = sub 1.0 div mul r2 t mul mul 2.0 n add mul 2.0 n 1.0 +end +ret mul r t +end +fn cosr r f64 to f64 +r2 = mul r r +t = f64 1.0 +for i ulong 10 +n = f64 sub 10 i +t = sub 1.0 div mul r2 t mul sub mul 2.0 n 1.0 mul 2.0 n +end +ret t +end +note sc64: sin (c 0) or cos (c 1) of x, reduced by k * pi/2 in three parts. +fn sc64 x f64 c ulong to f64 +if ne x x +ret x +end +k = rnd mul x bitcast f64 civpio2 +kf = f64 k +r = sub sub sub x mul kf bitcast f64 cpio21 mul kf bitcast f64 cpio22 mul kf bitcast f64 cpio23 +q = add ulong and k 3 c +q = and q 3 +if eq q 0 +ret sinr r +end +if eq q 1 +ret cosr r +end +if eq q 2 +ret neg sinr r +end +ret neg cosr r +end +note h2f: binary16 bits to f32. +fn h2f h ushort to f32 +v = uint h +s = shl and shr v 15 1 31 +e = and shr v 10 31 +m = and v 1023 +if eq e 0 +z = mul f32 m 0.000000059604644775390625f32 +if eq s 0 +ret z +end +ret neg z +end +if eq e 31 +ret bitcast f32 or or s 2139095040 shl m 13 +end +ret bitcast f32 or or s shl add e 112 23 shl m 13 +end +note rne: v >> sh (sh 1 .. 31) rounded to nearest, ties to even. +fn rne v uint sh uint to uint +r = shr v sh +hf = shl uint 1 sub sh 1 +rm = and v sub shl hf 1 1 +up = gt rm hf +if and eq rm hf eq and r 1 1 +up = true +end +if up +ret add r 1 +end +ret r +end +note f2h: f32 to binary16 bits, round to nearest even (as FCVT). +fn f2h x f32 to ushort +b = bitcast uint x +s = and shr b 16 32768 +e = long and shr b 23 255 +m = and b 8388607 +if eq e 255 +if eq m 0 +ret ushort or s 31744 +end +ret ushort or or s 32256 shr m 13 +end +ee = sub e 112 +if ge ee 31 +ret ushort or s 31744 +end +if le ee 0 +if lt ee -10 +ret ushort s +end +ret ushort or s rne or m 8388608 uint sub 14 ee +end +ret ushort or s rne or shl uint ee 23 m 13 +end diff --git a/kernels/rcp.om b/kernels/rcp.om new file mode 100644 index 0000000..750b4eb --- /dev/null +++ b/kernels/rcp.om @@ -0,0 +1,4 @@ +note rcp: f32(1.0/sum) as f32 bits, sum f64 bits: the soft_max normaliser of ggml-cpu. +fn rcp acc ulong to ulong +ret ulong bitcast uint f32 div f64 1.0 bitcast f64 acc +end diff --git a/kernels/rmsc.om b/kernels/rmsc.om new file mode 100644 index 0000000..85d27fe --- /dev/null +++ b/kernels/rmsc.om @@ -0,0 +1,7 @@ +note rmsc: the rms_norm row scale 1/sqrt(f32(sum/n) + eps) as f32 bits; sum is f64 bits, eps f32 bits. +fn rmsc acc ulong n ulong eps ulong to ulong +mean = f32 div bitcast f64 acc f64 n +e = bitcast f32 uint eps +r = div f32 1.0 fsqrt add mean e +ret ulong bitcast uint r +end diff --git a/kernels/rope.om b/kernels/rope.om new file mode 100644 index 0000000..d0dfbce --- /dev/null +++ b/kernels/rope.om @@ -0,0 +1,31 @@ +note rope: one rotated pair. theta = pos * ts^i (f32, multiplied i times as ggml_rope_cache_init), +note times freq_scale; out0 = x0*c - x1*s, out1 = x0*s + x1*c with c, s = cos, sin(theta)*attn_factor. +note xy packs x0 (low 32 bits) and x1; fa packs freq_scale (low) and attn_factor. Returns the packed pair. +fn lo32 v ulong to f32 +ret bitcast f32 uint and v 4294967295 +end +fn hi32 v ulong to f32 +ret bitcast f32 uint shr v 32 +end +fn rth pos ulong i ulong ts ulong fs f32 to f64 +t = f32 bitcast int uint pos +tsf = bitcast f32 uint ts +for k ulong i +t = mul t tsf +end +ret f64 mul fs t +end +fn pack a f32 b f32 to ulong +ret or ulong bitcast uint a shl ulong bitcast uint b 32 +end +fn rope xy ulong pos ulong i ulong ts ulong fa ulong to ulong +th = rth pos i ts lo32 fa +af = hi32 fa +c = mul f32 sc64 th 1 af +s = mul f32 sc64 th 0 af +x0 = lo32 xy +x1 = hi32 xy +o0 = sub mul x0 c mul x1 s +o1 = add mul x0 s mul x1 c +ret pack o0 o1 +end diff --git a/kernels/rtsc.om b/kernels/rtsc.om new file mode 100644 index 0000000..c48269d --- /dev/null +++ b/kernels/rtsc.om @@ -0,0 +1,6 @@ +note rtsc: the rope theta scale powf(base, -2/n_dims) as f32 bits (base f32 bits). +fn rtsc base ulong nd ulong to ulong +b = bitcast f32 uint base +ex = div f32 -2.0 f32 nd +ret ulong bitcast uint f32 ex64 mul f64 ex ln64 f64 b +end diff --git a/kernels/scl.om b/kernels/scl.om new file mode 100644 index 0000000..2387aa2 --- /dev/null +++ b/kernels/scl.om @@ -0,0 +1,12 @@ +note scl_@T@: d = x*s + b on @T@ f32 lanes (s, b f32 bits); b 0 gives the plain x*s of ggml_vec_scale_f32. +fn scl_@T@ x view f32 @T@ d edit f32 @T@ s ulong b ulong to void +sf = bitcast f32 uint s +bf = bitcast f32 uint b +for i ulong @T@ +v = mul get x i sf +if ne b 0 +v = add v bf +end +put d i v +end +end diff --git a/kernels/sexp.om b/kernels/sexp.om new file mode 100644 index 0000000..c96340a --- /dev/null +++ b/kernels/sexp.om @@ -0,0 +1,11 @@ +note sexp_@T@: w[i] = f32 exp(w[i] - max) in place; returns acc (f64 bits) + the sum of the new w[i]. +fn sexp_@T@ acc ulong w edit f32 @T@ mx ulong to ulong +s = bitcast f64 acc +mf = bitcast f32 uint mx +for i ulong @T@ +v = f32 ex64 f64 sub get w i mf +put w i v +s = add s f64 v +end +ret bitcast ulong s +end diff --git a/kernels/silu.om b/kernels/silu.om new file mode 100644 index 0000000..f1c5eb0 --- /dev/null +++ b/kernels/silu.om @@ -0,0 +1,8 @@ +note silu_@T@: d = x/(1 + expf(-x)) in f32, as ggml_silu_f32. +fn silu_@T@ a view f32 @T@ d edit f32 @T@ to void +for i ulong @T@ +x = get a i +e = f32 ex64 f64 neg x +put d i div x add f32 1.0 e +end +end diff --git a/kernels/smw.om b/kernels/smw.om new file mode 100644 index 0000000..5502eb0 --- /dev/null +++ b/kernels/smw.om @@ -0,0 +1,7 @@ +note smw_@T@: the soft_max input w = x*scale + mask (f32 mask), on @T@ lanes. +fn smw_@T@ x view f32 @T@ m view f32 @T@ d edit f32 @T@ sc ulong to void +sf = bitcast f32 uint sc +for i ulong @T@ +put d i add mul get x i sf get m i +end +end diff --git a/kernels/smwh.om b/kernels/smwh.om new file mode 100644 index 0000000..dd2cf9d --- /dev/null +++ b/kernels/smwh.om @@ -0,0 +1,7 @@ +note smwh_@T@: the soft_max input w = x*scale + mask with an f16 mask, on @T@ lanes. +fn smwh_@T@ x view f32 @T@ m view ushort @T@ d edit f32 @T@ sc ulong to void +sf = bitcast f32 uint sc +for i ulong @T@ +put d i add mul get x i sf h2f get m i +end +end diff --git a/kernels/sq.om b/kernels/sq.om new file mode 100644 index 0000000..1ca24f4 --- /dev/null +++ b/kernels/sq.om @@ -0,0 +1,9 @@ +note sq_@T@: acc (f64 bits) + the sum over @T@ lanes of f64(x*x), the rms_norm sum of ggml-cpu. +fn sq_@T@ acc ulong x view f32 @T@ to ulong +s = bitcast f64 acc +for i ulong @T@ +v = get x i +s = add s f64 mul v v +end +ret bitcast ulong s +end diff --git a/kernels/swi.om b/kernels/swi.om new file mode 100644 index 0000000..a4e5803 --- /dev/null +++ b/kernels/swi.om @@ -0,0 +1,8 @@ +note swi_@T@: swiglu d = silu(a) * b with silu(x) = x/(1 + expf(-x)) in f32, as ggml_vec_swiglu_f32. +fn swi_@T@ a view f32 @T@ b view f32 @T@ d edit f32 @T@ to void +for i ulong @T@ +x = get a i +e = f32 ex64 f64 neg x +put d i mul div x add f32 1.0 e get b i +end +end diff --git a/kernels/vmax.om b/kernels/vmax.om new file mode 100644 index 0000000..83a140e --- /dev/null +++ b/kernels/vmax.om @@ -0,0 +1,11 @@ +note vmax_@T@: running maximum (f32 bits) over @T@ lanes, as ggml_vec_max_f32 (MAX(max, x)). +fn vmax_@T@ acc ulong x view f32 @T@ to ulong +m = bitcast f32 uint acc +for i ulong @T@ +v = get x i +if gt v m +m = v +end +end +ret ulong bitcast uint m +end diff --git a/tests/backend-ops.sh b/tests/backend-ops.sh new file mode 100755 index 0000000..8691920 --- /dev/null +++ b/tests/backend-ops.sh @@ -0,0 +1,30 @@ +#!/bin/sh +# tests/backend-ops.sh: llama.cpp test-backend-ops, Omega backend against ggml's CPU backend, per op. +# usage: backend-ops.sh TEST_BACKEND_OPS LIBGGML_OMEGA [MUTANT_LIB] +# stdout: one tab-separated row per op: op, cases passed, cases failed, cases not supported (CPU fallback), verdict. +# An op with 0 Omega cases is NOT_RUN, never PASS. With MUTANT_LIB (built OMEGA_GGML_MUTANT=bin-add), ADD +# must fail against it. Full logs: $OUT (default build/backend-ops). Exit 1 on any FAIL or uncaught mutant. +set -u +TBO=$1; LIB=$2; MUT=${3:-} +OUT=${OUT:-build/backend-ops} +mkdir -p "$OUT" +OPS="ADD SUB MUL DIV SCALE RMS_NORM SOFT_MAX ROPE GET_ROWS SET_ROWS CPY CONT DUP SWIGLU SILU MUL_MAT" +fails=0 +printf 'op\tpass\tfail\tnot_supported\tverdict\n' +for op in $OPS; do + GGML_BACKEND_PATH=$LIB "$TBO" test -b Omega -o "$op" > "$OUT/$op.log" 2>&1 + rc=$? + cases() { grep -a " $op(" "$OUT/$op.log" | grep -ac "$1"; } + p=$(cases '1;32mOK'); f=$(cases '1;31mFAIL'); n=$(cases 'not supported') + if [ "$f" -gt 0 ] || [ $rc -ne 0 ]; then v=FAIL; fails=$((fails + 1)) + elif [ "$p" -eq 0 ]; then v=NOT_RUN + else v=PASS; fi + printf '%s\t%s\t%s\t%s\t%s\n' "$op" "$p" "$f" "$n" "$v" +done +if [ -n "$MUT" ]; then + GGML_BACKEND_PATH=$MUT "$TBO" test -b Omega -o ADD > "$OUT/mutant-ADD.log" 2>&1 + f=$(grep -a ' ADD(' "$OUT/mutant-ADD.log" | grep -ac '1;31mFAIL') + if [ "$f" -gt 0 ]; then printf 'mutant-bin-add\t-\t%s\t-\tCAUGHT\n' "$f" + else printf 'mutant-bin-add\t-\t0\t-\tNOT_CAUGHT\n'; fails=$((fails + 1)); fi +fi +[ $fails -eq 0 ] diff --git a/tests/cmp.c b/tests/cmp.c new file mode 100644 index 0000000..d76da2c --- /dev/null +++ b/tests/cmp.c @@ -0,0 +1,37 @@ +// tests/cmp.c: test infrastructure (not shipped). Compares two e2e logits files (n_vocab f32 per step). +// usage: cmp N_VOCAB A.logits B.logits +// stdout, one JSON line: steps, top1_agree (argmax equal per step), first_divergence (-1 if none), +// max_abs_diff over steps before the first divergence (same context in both runs), and its step. +// Exit 0 when the files have the same step count, 1 otherwise or on read errors. +#include +#include +#include + +int main(int argc, char **argv) { + if (argc != 4) { fprintf(stderr, "usage: cmp N_VOCAB A.logits B.logits\n"); return 2; } + long nv = atol(argv[1]); + FILE *a = fopen(argv[2], "rb"), *b = fopen(argv[3], "rb"); + if (!a || !b || nv <= 0) { fprintf(stderr, "cannot open inputs\n"); return 1; } + float *x = malloc(sizeof(float) * nv), *y = malloc(sizeof(float) * nv); + long steps = 0, agree = 0, first_div = -1, worst_step = -1; + double worst = 0; + for (;;) { + size_t ra = fread(x, sizeof(float), nv, a), rb = fread(y, sizeof(float), nv, b); + if (ra == 0 && rb == 0) break; + if (ra != (size_t) nv || rb != (size_t) nv) { fprintf(stderr, "step %ld: length mismatch\n", steps); return 1; } + long ia = 0, ib = 0; + for (long v = 1; v < nv; v++) { if (x[v] > x[ia]) ia = v; if (y[v] > y[ib]) ib = v; } + if (ia == ib) agree++; + if (first_div < 0) { + for (long v = 0; v < nv; v++) { + double d = fabs((double) x[v] - (double) y[v]); + if (!(d <= worst)) { worst = d; worst_step = steps; } + } + if (ia != ib) first_div = steps; + } + steps++; + } + printf("{\"steps\":%ld,\"top1_agree\":%ld,\"first_divergence\":%ld,\"max_abs_diff\":%.9g,\"max_abs_diff_step\":%ld}\n", + steps, agree, first_div, worst, worst_step); + return 0; +} diff --git a/tests/e2e.c b/tests/e2e.c new file mode 100644 index 0000000..7fa01e4 --- /dev/null +++ b/tests/e2e.c @@ -0,0 +1,62 @@ +// tests/e2e.c: test infrastructure (not shipped). Greedy decode of a fixed prompt through llama.cpp's public +// API with whatever backends ggml_backend_load_all() finds (GGML_BACKEND_PATH=libggml-omega.so adds Omega). +// usage: e2e MODEL N_TOKENS LOGITS_OUT [THREADS] +// stdout: one JSON line per generated step {"step":i,"token":t}, then {"tok_per_s":x,"prompt_tokens":p}. +// LOGITS_OUT: n_vocab f32 values per step, raw, for tests/cmp.c. Diagnostics on stderr. Exit 0 on success. +#include "llama.h" +#include "ggml-backend.h" +#include +#include +#include +#include + +static const char *PROMPT = "The three primary colors of light are"; + +static double now(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec + t.tv_nsec * 1e-9; } +static void quiet(enum ggml_log_level l, const char *s, void *u) { (void) u; if (l >= GGML_LOG_LEVEL_WARN) fputs(s, stderr); } + +int main(int argc, char **argv) { + if (argc < 4) { fprintf(stderr, "usage: e2e MODEL N_TOKENS LOGITS_OUT [THREADS]\n"); return 2; } + int n_gen = atoi(argv[2]), threads = argc > 4 ? atoi(argv[4]) : 2; + llama_log_set(quiet, NULL); + ggml_backend_load_all(); + for (size_t i = 0; i < ggml_backend_dev_count(); i++) + fprintf(stderr, "device %zu: %s\n", i, ggml_backend_dev_name(ggml_backend_dev_get(i))); + struct llama_model_params mp = llama_model_default_params(); + mp.n_gpu_layers = 0; + struct llama_model *model = llama_model_load_from_file(argv[1], mp); + if (!model) { fprintf(stderr, "model load failed\n"); return 1; } + const struct llama_vocab *vocab = llama_model_get_vocab(model); + int n_vocab = llama_vocab_n_tokens(vocab); + struct llama_context_params cp = llama_context_default_params(); + cp.n_ctx = 256; cp.n_batch = 64; cp.n_ubatch = 64; cp.n_threads = threads; cp.n_threads_batch = threads; + cp.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED; + cp.no_perf = true; + struct llama_context *ctx = llama_init_from_model(model, cp); + if (!ctx) { fprintf(stderr, "context failed\n"); return 1; } + llama_token toks[64]; + int n_p = llama_tokenize(vocab, PROMPT, (int) strlen(PROMPT), toks, 64, true, false); + if (n_p <= 0) { fprintf(stderr, "tokenize failed\n"); return 1; } + FILE *lf = fopen(argv[3], "wb"); + if (!lf) { perror(argv[3]); return 1; } + struct llama_batch b = llama_batch_get_one(toks, n_p); + double t0 = now(), t_first = 0; + llama_token cur; + for (int i = 0; i < n_gen; i++) { + if (llama_decode(ctx, b) != 0) { fprintf(stderr, "decode failed at step %d\n", i); return 1; } + if (i == 0) t_first = now(); + const float *lg = llama_get_logits_ith(ctx, -1); + if (fwrite(lg, sizeof(float), (size_t) n_vocab, lf) != (size_t) n_vocab) { perror("write"); return 1; } + cur = 0; + for (int v = 1; v < n_vocab; v++) if (lg[v] > lg[cur]) cur = v; + printf("{\"step\":%d,\"token\":%d}\n", i, cur); + b = llama_batch_get_one(&cur, 1); + } + double t1 = now(); + fclose(lf); + // decode rate over the single-token steps (prompt step excluded) + printf("{\"n_vocab\":%d,\"prompt_tokens\":%d,\"prompt_s\":%.6f,\"gen_steps\":%d,\"gen_s\":%.6f,\"threads\":%d}\n", n_vocab, n_p, t_first - t0, n_gen - 1, t1 - t_first, threads); + llama_free(ctx); + llama_model_free(model); + return 0; +} diff --git a/tests/kernels.c b/tests/kernels.c new file mode 100644 index 0000000..2e3754c --- /dev/null +++ b/tests/kernels.c @@ -0,0 +1,127 @@ +// tests/kernels.c: test infrastructure (not shipped). Checks the Omega math units against independent +// oracles on this host: the C compiler's _Float16 conversions (AArch64 FCVT), glibc libm in double +// precision, and plain C reference loops. Prints one line per check; exit 1 on any failure. +#include +#include +#include +#include + +#define ARR(p) const void *p, uint64_t p##_n +#define OUT(p) void *p, uint64_t p##_n +uint32_t omega_h2fv_1(uint64_t *r, ARR(s), OUT(d)); +uint32_t omega_f2hv_1(uint64_t *r, ARR(s), OUT(d)); +uint32_t omega_sexp_1(uint64_t *r, uint64_t acc, OUT(w), uint64_t mx); +uint32_t omega_rtsc(uint64_t *r, uint64_t base, uint64_t nd); +uint32_t omega_rope(uint64_t *r, uint64_t xy, uint64_t pos, uint64_t i, uint64_t ts, uint64_t fa); +uint32_t omega_silu_1(uint64_t *r, ARR(a), OUT(d)); +uint32_t omega_rmsc(uint64_t *r, uint64_t acc, uint64_t n, uint64_t eps); +uint32_t omega_dq8_1(uint64_t *r, uint64_t acc, ARR(w), ARR(x), uint64_t fin); + +static int fails; +static uint32_t fb(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } +static float bf(uint32_t u) { float f; memcpy(&f, &u, 4); return f; } +// distance in f32 ulps (ordered integer line), NaN only matches NaN +static int64_t ulps(float a, float b) { + if (isnan(a) || isnan(b)) return isnan(a) && isnan(b) ? 0 : INT64_MAX; + int64_t x = (int32_t) fb(a), y = (int32_t) fb(b); + if (x < 0) x = INT32_MIN - x; + if (y < 0) y = INT32_MIN - y; + return x > y ? x - y : y - x; +} +static void report(const char *name, long n, long bad, int64_t worst, int64_t limit) { + printf("%-28s n=%-9ld bad=%-6ld worst_ulp=%lld limit=%lld %s\n", name, n, bad, (long long) worst, (long long) limit, + bad ? "FAIL" : "PASS"); + if (bad) fails++; +} +#define OK(c) do { if ((c) != 0) { printf("status fail: %s\n", #c); return 1; } } while (0) + +int main(void) { + uint64_t r; + long n = 0, bad = 0; int64_t worst = 0; + // f16 -> f32, all 65536 inputs, exact + for (uint32_t h = 0; h < 65536; h++) { + uint16_t hv = (uint16_t) h; _Float16 hf; memcpy(&hf, &hv, 2); + float o; OK(omega_h2fv_1(&r, &hv, 1, &o, 1)); + float want = (float) hf; n++; + if (!(isnan(want) ? isnan(o) : fb(o) == fb(want))) bad++; + } + report("h2f all f16", n, bad, 0, 0); + // f32 -> f16 (round to nearest even), every 1021st f32 bit pattern plus all specials, exact (NaN: any NaN) + n = bad = 0; + for (uint64_t u = 0; u < 4294967296ull; u += 1021) { + float x = bf((uint32_t) u); uint16_t o; OK(omega_f2hv_1(&r, &x, 1, &o, 1)); + _Float16 w = (_Float16) x; uint16_t wv; memcpy(&wv, &w, 2); n++; + if (isnan(x) ? ((o & 0x7c00) != 0x7c00 || (o & 0x3ff) == 0) : o != wv) bad++; + } + report("f2h f32 stride 1021", n, bad, 0, 0); + // exp: the sexp unit returns f32(exp(x - 0)); oracle double exp rounded to f32 + n = bad = 0; worst = 0; + for (float x = -110.0f; x < 89.0f; x += 0.00731f) { + float w = x; uint64_t s = 0; OK(omega_sexp_1(&s, 0, &w, 1, 0)); + float want = (float) exp((double) x); int64_t d = ulps(w, want); n++; + if (d > worst) worst = d; + if (d > 1) bad++; + } + report("exp vs libm (f32 ulp)", n, bad, worst, 1); + // powf(base, -2/nd) for rope theta scale + n = bad = 0; worst = 0; + const float bases[] = { 10000.0f, 1000000.0f, 500000.0f, 10.0f, 1.5f }; + for (int b = 0; b < 5; b++) + for (uint64_t nd = 2; nd <= 512; nd += 2) { + uint64_t ts; OK(omega_rtsc(&ts, fb(bases[b]), nd)); + float want = (float) pow((double) bases[b], (double) (-2.0f / (float) nd)); + int64_t d = ulps(bf((uint32_t) ts), want); n++; + if (d > worst) worst = d; + if (d > 1) bad++; + } + report("pow vs libm (f32 ulp)", n, bad, worst, 1); + // rope pair: oracle = same f32 theta recurrence, double cos/sin rounded to f32 + n = bad = 0; worst = 0; + const float ts = 0.8659643f, fs = 1.0f, af = 1.0f, x0 = 0.75f, x1 = -1.25f; + for (int32_t pos = -3; pos < 4100; pos += 7) + for (uint64_t i = 0; i < 64; i++) { + float t = (float) pos; + for (uint64_t k = 0; k < i; k++) t *= ts; + t *= fs; + float c = (float) cos((double) t) * af, s = (float) sin((double) t) * af; + float w0 = x0 * c - x1 * s, w1 = x0 * s + x1 * c; + uint64_t o; OK(omega_rope(&o, fb(x0) | ((uint64_t) fb(x1) << 32), (uint32_t) pos, i, fb(ts), fb(fs) | ((uint64_t) fb(af) << 32))); + int64_t d0 = ulps(bf((uint32_t) o), w0), d1 = ulps(bf((uint32_t) (o >> 32)), w1); + int64_t d = d0 > d1 ? d0 : d1; n++; + if (d > worst) worst = d; + if (d > 0) bad++; + } + report("rope vs libm sin/cos", n, bad, worst, 0); + // silu: x/(1+expf(-x)) with libm-exact expf + n = bad = 0; worst = 0; + for (float x = -90.0f; x < 90.0f; x += 0.0137f) { + float o; OK(omega_silu_1(&r, &x, 1, &o, 1)); + float want = x / (1.0f + (float) exp(-(double) x)); int64_t d = ulps(o, want); n++; + if (d > worst) worst = d; + if (d > 1) bad++; + } + report("silu vs libm", n, bad, worst, 1); + // rms scale: 1/sqrtf(f32(sum/n) + eps) + n = bad = 0; + for (int k = 1; k < 5000; k++) { + double sum = k * 0.37; uint64_t sb; memcpy(&sb, &sum, 8); uint64_t o; + OK(omega_rmsc(&o, sb, 896, fb(1e-6f))); + float want = 1.0f / sqrtf((float) (sum / 896) + 1e-6f); n++; + if (fb(bf((uint32_t) o)) != fb(want)) bad++; + } + report("rms scale exact", n, bad, 0, 0); + // q8_0 dot: one block, reference f64 accumulation of f32(q)*x then times f16 d + n = bad = 0; + for (int t = 0; t < 2000; t++) { + unsigned char blk[34]; float x[32]; uint32_t seed = 2654435761u * (uint32_t) (t + 1); + _Float16 d = (_Float16) (0.001f * (float) (t % 97 + 1)); memcpy(blk, &d, 2); + for (int j = 0; j < 32; j++) { seed = seed * 1103515245u + 12345u; blk[2 + j] = (unsigned char) (seed >> 16); x[j] = (float) ((int) (seed >> 8) % 2001 - 1000) / 333.0f; } + float bs = 0.0f; for (int j = 0; j < 32; j++) bs += (float) (int8_t) blk[2 + j] * x[j]; + float want = (float) (double) ((float) d * bs); + uint64_t o; OK(omega_dq8_1(&o, 0, blk, 34, x, 32, 1)); n++; + if (fb(bf((uint32_t) o)) != fb(want)) bad++; + } + report("q8_0 block dot exact", n, bad, 0, 0); + printf("%s\n", fails ? "KERNELS FAIL" : "KERNELS PASS"); + return fails ? 1 : 0; +}