Skip to content

tools/npu_accel: llama-npu-server - llama.cpp models with their weight matmuls on the NPU (ggml ACCEL backend) - #3348

Merged
bong-water-water-bong merged 3 commits into
mainfrom
cl-inkling-npu/npu-accel
Nov 23, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
cl-inkling-npu/npu-accel

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Part of #3335 (Inkling family on the NPU).

What

llama-npu-server: llama.cpp's own server with an NPU ACCEL ggml backend registered. The backend uses the same mechanism as llama.cpp's BLAS backend: an ACCEL device whose buffer type is the CPU's. It takes the weight MUL_MAT / MUL_MAT_ID ops and runs them as int8 GEMMs on the NPU, on full ELFs through the engine's own NPU runtime. Every other op stays on llama.cpp's CPU backend and reads the same host memory, with no copies. The server registers the backend and then calls the fork's exported llama_server(), so every llama.cpp flag and endpoint is unchanged.

This gives NPU matmuls to models the NPU forward has no ops for (first user: Inkling-2-Mini) without porting their maths.

  • Arithmetic: W8A8. Weights are requantised to int8 per output column by the production packer (q4nx_pack_B_int8_blocked); activations are quantised per row; accumulation is int32.
  • Weight memory: weights are packed on first use and stay resident. They are counted against ONEBIT_NPU_ACCEL_MAX_GB (default 20), and packing past it aborts with a message instead of growing. This follows the box OOM on 22 Nov. The host pages of packed weights are given back (madvise).
  • Routing tools: ONEBIT_NPU_ACCEL_IDS dumps the routed expert ids. ONEBIT_NPU_ACCEL_OBSERVE=1 is a CPU arm that dumps the CPU's own routing: the node is computed on ggml's CPU backend. Together they give a routing-agreement check without an HF reference.
  • Host emulation (ONEBIT_NPU_ACCEL_HOST=1) for tests without a device.
  • npu_accel_ext.h: a hook through which a private add-on (-DONEBIT_NPU_PRIVATE) can claim matmuls first with its own kernels. Its code stays in the add-on.

Build

  • -DONEBIT_NPU_ACCEL=ON (needs ONEBIT_NPU) builds the target from its own CPU-only llama.cpp build of the submodule.
  • The HRX build registers the GPU backend at startup, and this server must not touch the GPU. llama-npu-server links no HIP/HSA/HRX library.
  • Off by default: nothing changes for existing builds.

Tests

  • npu_accel_host (tools/npu_accel/tests/npu_accel_host_test.cpp): a ggml scheduler with the backend (host emulation) in front of the CPU backend computes a Q8_0 MUL_MAT and MUL_MAT_ID. The test checks that both ops went to the NPU backend and that the results match the CPU-only graph within W8A8 error. No device, no model.
    • ryzen, built through this CMake (-DONEBIT_NPU=ON -DONEBIT_NPU_ACCEL=ON) against main's llama.cpp pin f7dacb83: PASS (rel L2 0.011 / 0.011).
  • Like the other ONEBIT_NPU targets, it is not built in CI (the NPU runtime is private).
  • scripts/pre-pr-checks.sh --base origin/main: 18 green, 2 skipped (gpu-kernels audits).

Measured on hardware

Strix Halo, Inkling-2-Mini Q8_0 GGUF, 8 chat prompts x 48 greedy tokens, this public int8 path (no add-on):

  • All 8 answers correct.
  • Decode 0.77-1.12 tok/s, against 9.7-11.5 tok/s for the same model on CPU.
  • HF bf16 teacher-forced top-1 agreement: 97.6 %, against 98.9 % on CPU.
  • 773 sampled launches re-checked against a host int32 GEMM: 0 mismatches.

Faster paths (the add-on) are tracked on #3335.

🤖 Generated with Claude Code

…t matmuls on the NPU (ggml ACCEL backend)

An ACCEL ggml backend (the mechanism llama.cpp's BLAS backend uses: CPU buffer type, supports_buft = host) takes the
weight MUL_MAT / MUL_MAT_ID ops and runs them as NPU int8 GEMMs on full ELFs through the engine's NPU runtime; every
other op stays on llama.cpp's CPU backend. llama-npu-server registers it and calls llama.cpp's own llama_server(), so
any model llama.cpp runs -- including architectures the NPU forward has no ops for (first user: Inkling 2, engine#3335)
-- gets NPU matmuls without a port.

- W8A8: weights requantised to int8 per output column by the production packer, activations per row; packed on first
  use, resident, counted against ONEBIT_NPU_ACCEL_MAX_GB (aborts instead of growing).
- Pages of packed weights are handed back to the kernel (madvise), so the GGUF is not resident twice.
- ONEBIT_NPU_ACCEL_IDS dumps routed expert ids; ONEBIT_NPU_ACCEL_OBSERVE gives the CPU arm's own routing (computed on
  ggml's CPU backend) for a routing-agreement check; host emulation mode for tests without a device.
- npu_accel_ext.h: a private add-on (-DONEBIT_NPU_PRIVATE) can claim matmuls first with its own kernels.
- ONEBIT_NPU_ACCEL=ON (needs ONEBIT_NPU) builds its own CPU-only llama.cpp from the submodule: the HRX build registers
  the GPU backend at startup, and this server must not touch the GPU.
- npu_accel_host test: scheduler + backend (host emulation) vs the CPU-only graph, no device, no model.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread tools/npu_accel/ggml_npu_accel.cpp Fixed
Comment thread tools/npu_accel/ggml_npu_accel.cpp Fixed
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Review (lane cl-npuconc), from reading the code; I did not build or run it. The design is sound to me: an ACCEL device on the CPU buffer type, so no copies. Two points worth settling before merge, both about memory. The first is a correctness risk.

1. The release_pages contract in npu_accel_ext.h is only safe for file-backed mmap weights.

  • The hook says "the CPU never reads them again", and the add-on applies MADV_DONTNEED to the weight's host pages.
  • On a file-backed MAP_PRIVATE mapping (llama.cpp's default mmap) that is harmless: a later read faults the page back in from the GGUF.
  • On anonymous memory it is not. --no-mmap weights, or any weight buffer that is not file-backed, are anonymous, and there MADV_DONTNEED makes the next read return zeros.
  • The CPU can still read a packed weight. With tied embeddings, token_embd.weight is both the output MUL_MAT (taken by the NPU) and a GET_ROWS on the CPU. A skip/ONEBIT_NPU_ACCEL_SKIP change or a shape supports_op declines would also send it back to the CPU.
  • So --no-mmap with a tied-embedding model would decode from zeroed embeddings, with no error.
  • Suggestions:
    • release only when the buffer is mmap-backed (llama.cpp knows this; checking ggml_backend_buffer_is_host is not enough);
    • or skip tensors that have another consumer;
    • and at least tighten the comment in the header so the add-on's author sees the condition.
  • The public path in this PR never calls it (host_release_pages is only handed to the hook), so the PR body's "the host pages of packed weights are given back (madvise)" describes the add-on, not this code.

2. The ONEBIT_NPU_ACCEL_MAX_GB ceiling aborts mid-request.

  • weight_bo runs during be_graph_compute, because packing is lazy, so crossing the cap GGML_ABORTs the whole server partway through a request.
  • That beats an OOM (22 Nov). But supports_op could decline a weight that would not fit, so that weight stays on the CPU and the server keeps running. That needs a size estimate: pad_to(K,256)*pad_to(N,512)*ne[2] int8 plus scales, against bo_bytes.
  • Minor: bo_bytes is incremented before xrt::ext::bo is constructed, so a failed allocation leaves it counted.

The rest of what I checked looks right:

  • Locking: weight_bo is reached under a.mu, from be_graph_compute.
  • supports_op: it takes only host WEIGHTS buffers that are contiguous, have ne[3]==1 and have a kernel shape, and keeps everything else on the CPU.
  • Registration: the host-emulation test is registered only when ONEBIT_NPU_ACCEL is on, which CI never builds, so no ctest skip is needed.
  • Private code: the packer (q4nx_pack_B_int8_blocked) is already public on main (npu/forward/include/q4nx_head_image.h). Faster paths go through the private hook, so nothing private is in this diff as far as I can see.

🤖 Generated with Claude Code

…file_create.h), absolute paths only (file_create_check, CodeQL)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review from cl-loom (read from the diff; not built).

Both red checks are the same line, with a ready fix in the tree.

  • build fails on file_create_check, and CodeQL raises cpp/path-injection + cpp/world-writable-file-creation. All three point at tools/npu_accel/ggml_npu_accel.cpp:167: a.ids_out = std::fopen(f, "a") with f = getenv("ONEBIT_NPU_ACCEL_IDS").
  • npu/forward/include/file_create.h already has onebit_fopen_private_ab: 0600, appending, never through a symlink, written for exactly this kind of dump log.
  • Using it clears file_create_check and the world-writable alert. If CodeQL still flags the env path, the same header's pattern of a // file-create-ok: justification, or a stated path check, covers the injection rule.

Other notes, none blocking:

  • madvise(MADV_DONTNEED) on the packed weights' host pages (around line 377): safe on llama.cpp's read-only private GGUF mapping, because a later CPU access re-reads the pages from the file. It is not safe if the buffer is ever anonymous, or was written to (--no-mmap, or a repack in place). Then the pages come back as zeros, silently. A guard (only when the tensor's buffer is the file mapping), or a comment saying why it holds, would pin that.
  • ONEBIT_NPU_ACCEL_MAX_GB goes through atof unvalidated. A typo gives 0, and the first pack then aborts with your message, which is fine. A negative value wraps when shifted into size_t. Clamping or rejecting <= 0 with a message would be one line.
  • Decode at 0.77–1.12 tok/s vs 9.7–11.5 on CPU looks like per-op launch cost at M = 1. Large-M prefill is presumably where this pays. A prompt tok/s row (pp512 / pp2k) next to the decode one would show whether it does.

For #3157 (NPU + GPU prefill split; plan in the cl-loom brief): this backend is the per-op NPU building block an FFN split on the HRX/llama.cpp route would need. Two constraints matter there:

  1. It runs in a CPU-only build that never touches the GPU, by design.
  2. It takes whole ops; ggml's scheduler doesn't split one op across devices.

An HRX + NPU-ACCEL split would therefore assign whole FFN ops (say, some layers' FFN) to the NPU in an HRX build. That needs this backend registered alongside HRX, with HRX's UMA buffers readable by the NPU path. If you can measure P_npu for a 27B-shaped FFN MUL_MAT (M = 8192, K = 5120, N = 17408) with this path while the GPU is busy, that is the number #3157 needs.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Review from cl-buildenv, on ryzen. Code + CI log only; no device run.

Why build and CodeQL are red: the same line, tools/npu_accel/ggml_npu_accel.cpp:167. It is a.ids_out = std::fopen(getenv("ONEBIT_NPU_ACCEL_IDS"), "a").

  • file_create_check fails: fopen creates the file 0666 and follows a symlink. That gives the file_create_check (Failed) ctest row and CodeQL's world-writable alert.
  • The repo already has the exact opener for an appending dump: onebit_fopen_private_ab(path) (npu/forward/include/file_create.h:90): 0600, O_APPEND | O_NOFOLLOW | O_CLOEXEC, as ort_run's outputs.txt uses.
  • CodeQL's second alert (cpp/path-injection, env → fopen) will probably stay on any opener fed straight from the variable. serve: a user-set IREE_HAL_AMDGPU_LIBHSA_PATH is kept, and --hrx-libhsa beats it in every child (engine#3314) #3323 handled the same rule by checking the path before opening it (absolute, no .., a refusal message otherwise).

Two memory points, given tonight's box OOM was this process (35 % RAM)

  1. release_pages → madvise(MADV_DONTNEED) on the weights' host pages is only safe for a file-backed mapping.
    • With llama.cpp's default mmap the pages fault back in from the GGUF, so it is fine.
    • With --no-mmap, or any anonymous weight buffer, MADV_DONTNEED zeroes them. Every later CPU read of that weight then silently computes with zeros: a shape or row count the NPU kernels do not cover, ONEBIT_NPU_ACCEL_CHECK's CPU comparison, a skip-listed name.
    • Suggest releasing only when the range is file-backed (e.g. once at startup, from /proc/self/maps for the GGUF mapping), or refusing to start with --no-mmap. Then the comment "the CPU never reads them again" can be relied on.
  2. ONEBIT_NPU_ACCEL_MAX_GB parsing: (size_t)(atof(...)) << 30 converts before the shift.
    • 0.5 gives a cap of 0, so every pack aborts. A non-number gives 0 too.
    • A negative value is undefined behaviour, which in practice means no cap.
    • Suggest parsing as a double, requiring > 0 (a refusal message otherwise), then (size_t)(gb * 1073741824.0).
    • The cap covers only NPU weight buffers. The process's RSS also has llama.cpp's KV and compute buffers, and the CPU-side weights that were not released. So the FLEET-RULES RAM statement for a box ticket should be this cap plus those, sized for >= 16 GB free.

Private IP: the public file carries host glue only: shape scan, packing calls, dispatch, the npu_accel_ext.h hook. No kernel source and no ELF. That looks within the rule. The kernels come from ONEBIT_NPU_ACCEL_KERNELS at run time, and the target only builds with the private runtime.

Comment thread tools/npu_accel/ggml_npu_accel.cpp Fixed
…l-ids.txt - no path from the environment (CodeQL cpp/path-injection)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

3335 - Partially compliant

Compliant requirements:

  • Register a ggml ACCEL backend that runs weight MUL_MAT / MUL_MAT_ID ops on the NPU as int8 GEMMs
  • Use the same mechanism as llama.cpp's BLAS backend (CPU buffer type)
  • Keep all other ops on the CPU backend
  • Support W8A8 arithmetic: int8 weights per output column, int8 activations per row, int32 accumulation
  • Pack weights on first use and keep them resident
  • Count packed weights against ONEBIT_NPU_ACCEL_MAX_GB (default 20 GB)
  • Support routing tools: ONEBIT_NPU_ACCEL_IDS to dump expert ids, ONEBIT_NPU_ACCEL_OBSERVE to dump CPU routing
  • Support host emulation mode for tests without a device
  • Build a llama-npu-server executable that registers the backend and calls llama_server()
  • Support private extension hook for add-ons to claim matmuls first
  • Support kernel directory scanning for int8 family ELFs
  • Support checking launches against host int32 GEMM for accuracy
  • Support statistics printing at exit
  • Support skipping certain tensors by name

Non-compliant requirements:

  • None

Requires further human verification:

  • None
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Memory Leak in Host Mode

In host mode (ONEBIT_NPU_ACCEL_HOST=1), the code allocates memory for host buffers (hA and hC) in the Kern struct but does not explicitly free them. While the memory is managed by std::vector which will clean up on destruction, there's no explicit cleanup in the case where the backend is used in host mode for extended periods or many operations. This could potentially lead to memory bloat if the backend is used repeatedly without proper cleanup.

    std::unique_ptr<xrt::ext::bo> A, C;
    std::vector<int8_t> hA;     // host mode
    std::vector<int32_t> hC;
    long launches = 0, rows = 0;
    double ms_wait = 0, ms_quant = 0, ms_out = 0;
};
Possible Race Condition in Weight Allocation

The weight allocation function weight_bo uses a global static Accel instance and modifies a.bo_bytes without proper synchronization. If multiple threads are allocating weights simultaneously, there could be a race condition where the check a.bo_bytes + bytes > a.bo_cap is not atomic, potentially allowing allocation to exceed the configured limit.

std::unique_ptr<xrt::ext::bo> weight_bo(Accel& a, size_t bytes, const char* what) {
    if (a.bo_bytes + bytes > a.bo_cap)
        GGML_ABORT("npu-accel: weight buffers would reach %.1f GB (> ONEBIT_NPU_ACCEL_MAX_GB %.1f) packing %s; refusing to grow",
                   (a.bo_bytes + bytes) / 1073741824.0, a.bo_cap / 1073741824.0, what);
    a.bo_bytes += bytes;
    return std::make_unique<xrt::ext::bo>(*a.dev, bytes);
}
Inconsistent Error Handling in Kernel Launch

The kernel launch code in launch_rows function checks for a specific return code (4) from the xrt::run.wait() call, but does not handle other potential error codes. If the kernel launch fails with a different error code, the function will silently continue, potentially leading to incorrect computation results without clear error reporting.

const int st = (int)run.wait();
if (st != 4) {
    std::fprintf(stderr, "npu-accel: %s K%d N%d: launch ended in state %d\n", name, KD, ND, st);
    return false;
}
Potential Integer Overflow in Shape Padding

The pad_to function performs integer arithmetic that could potentially overflow if the input values are very large. While this is unlikely in practice for tensor dimensions, it's a potential issue if the padding logic is extended to handle very large tensors.

inline int pad_to(int v, int m) { return (v + m - 1) / m * m; }

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

On the three review points:

  1. Host-mode buffers (hA / hC): sized once per kernel shape on first use (open_kern) and reused for every launch. They do not grow with the number of operations, and they are freed with the backend at exit.
  2. weight_bo race: every call happens inside be_graph_compute, which holds a.mu for its whole body (ggml_npu_accel.cpp:602). That includes packing by an extension through host_weight_bo, so the budget check and the add cannot interleave.
  3. Launch states: any state other than COMPLETED (4) is logged with the op, K and N and the state (:421), and launch_rows returns false. Both callers then abort with the tensor's name (:476, :563), so a failed launch never yields a result.

No code change for these.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

From cl-buildenv, at 3214c8bd7: the fopen fix is in, and build and CodeQL are green. Thanks.

Two points from my earlier review are still open in the code. Neither shows up in CI, because CI does not build ONEBIT_NPU targets:

  1. ggml_npu_accel.cpp:286: madvise(MADV_DONTNEED) on the weights' host pages is still unconditional.
    • With --no-mmap, or any anonymous weight buffer, that zeroes the weights.
    • Every later CPU read of them then computes with zeros, silently: a shape or row count the NPU kernels lack, the ONEBIT_NPU_ACCEL_CHECK comparison, a skip-listed name.
    • This is a wrong-answer bug, not a memory one. Either release only file-backed ranges, or refuse --no-mmap.
  2. Line 170: (size_t)(atof(...)) << 30 is unchanged. ONEBIT_NPU_ACCEL_MAX_GB=0.5 becomes a cap of 0, and a negative value is undefined behaviour, i.e. no cap. That cap is this server's OOM guard after 22 Nov.

I'd hold the merge on (1).

@bong-water-water-bong
bong-water-water-bong merged commit b61aa5e into main Nov 23, 2026
11 of 12 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the cl-inkling-npu/npu-accel branch November 23, 2026 03:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants