Skip to content
RemoteMedia-SDKPublic

About

llama.cpp GGUF inference nodes (generation, embedding, activation extraction, steering) — RemoteMedia SDK Path 3 loadable plugin

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

15 Commits

Folders and files

Repository files navigation

llama-cpp — GGUF inference node family

Standalone Path 3 Rust cdylib that registers the four LlamaCpp* streaming nodes into the RemoteMedia SDK streaming pipeline registry.

This plugin wraps the llama.cpp C library through the safe llama-cpp-4 Rust bindings, providing in-process GGUF inference for text generation, embeddings, hidden-state extraction, and steering.

Build-time CUDA requirement

This plugin links llama-cpp-sys-4 with the cuda feature enabled. At build time you need the CUDA toolkit installed and visible to nvcc. First build takes 15–30 minutes because the underlying llama-cpp-sys-4 C++/CUDA layer compiles ~180 template-instance kernels (fattn-mma-f16-*, mmq-instance-*).

The plugin itself (libllama_cpp_plugin.so) is ~2.3 MiB because llama-cpp-sys-4 uses dynamic linking for the heavy GGML backends. The companion shared libraries — built into the same output directory — are:

Library Size Purpose
libllama.so.0 ~1.5 MiB Top-level llama.cpp surface
libggml.so.0 ~60 KiB GGML loader
libggml-base.so.0 ~870 KiB GGML base
libggml-cpu.so.0 ~880 KiB CPU backend
libggml-cuda.so.0 ~500 MiB CUDA backend (heavy)
libggml-blas.so.0 varies BLAS backend
libllama-common.so.0 small Internal common helpers
libmtmd.so.0 small Multi-modal extensions

Consumers need all of these reachable via $LD_LIBRARY_PATH or in the same directory as the plugin .so. The release pipeline packages them together.

If you don't have a CUDA-capable build environment:

  1. Build without CUDA: clone this repo, edit Cargo.toml to drop the features = ["cuda"] from both llama-cpp-4 and llama-cpp-sys-4, then cargo build --release. The resulting plugin runs on CPU only; consumers pass gpu_offload: "none".
  2. Use a prebuilt release asset: the GitHub release pipeline (.github/workflows/release.yml) cross-builds platform-specific binaries that ship via release-manifest.json.

At runtime the loaded .so finds CUDA dynamically (libcuda.so.1, libcudart.so) — consumers on a CUDA host don't need the toolkit, just a current NVIDIA driver.

Use from a manifest

{
  "version": "v1",
  "plugins": ["llama-cpp@v0.2.0"],
  "nodes": [
    {
      "id": "llm",
      "node_type": "LlamaCppGenerationNode",
      "params": {
        "model_path": "/models/Qwen3.5-9B-MLX-4bit.gguf",
        "context_size": 4096,
        "max_tokens": 256,
        "temperature": 0.8,
        "system_prompt": "You are a helpful voice assistant.",
        "backend": { "gpu_offload": "all", "flash_attention": true }
      }
    }
  ]
}

The SDK resolver expands llama-cpp@v0.2.0 to github.com/RemoteMedia-SDK/llama-cpp, fetches plugin.toml, then falls through to release-manifest.json for the platform-specific prebuilt .so / .dylib / .dll asset.

Build the cdylib locally

git clone https://github.com/RemoteMedia-SDK/llama-cpp
cd llama-cpp
cargo build --release
# → target/release/libllama_cpp_plugin.so  (~200 MiB)

First build takes 5–10 minutes because llama-cpp-sys-4 compiles several hundred MB of C/C++ + CUDA kernels.

Windows (MSVC + CUDA)

Use scripts\build-windows.bat (arguments go straight to cargo):

scripts\build-windows.bat build --release

It enters a VS 2022 developer environment (CUDA 13.0's nvcc rejects VS 2026) and pins libclang, nvcc and CMake to the system LLVM, CUDA and CMake installs so an Anaconda PATH (clang 5, its own nvcc) can't break bindgen or the CUDA configure step. Paths are overridable via VS2022_VCVARS, LLAMA_CUDA_PATH, LLVM_BIN and CMAKE. A cold build takes ~1 h, mostly ggml-cuda/argsort.cu (CUB) under MSVC.

llama-cpp-4 0.12.0 does not compile on MSVC as published (its fit.rs matches bindgen enum constants as u32; MSVC bindgen emits c_int). vendor/llama-cpp-4 carries a two-line fix and is wired in via [patch.crates-io] — drop both once upstream ships a fix.

LFM3-Audio smoke test

examples/lfm3_smoke.rs loads an LFM3-Audio GGUF plus its mmproj and runs a text turn and an ASR turn:

scripts\build-windows.bat run --release --example lfm3_smoke -- ^
  LFM3-Audio-2B-Q4_K_M.gguf mmproj-LFM3-Audio-2B-Q8_0.gguf speech.wav

Releasing a new version

GitHub Actions cannot cut releases for this plugin. The standard build-plugin.yml reusable workflow runs on ubuntu-latest / macos-latest / windows-latest, none of which ship the CUDA toolkit. Even with CUDA available, the dynamic-linked layout (cdylib + ~8 companion libggml-*.so.0 libraries) doesn't fit the upstream workflow's single-binary upload contract. The tag-triggered .github/workflows/release.yml is intentionally a tripwire that fails with a pointer to this section.

Releases are cut locally on a CUDA-equipped host via the helper script:

# 1. Bump the version
$EDITOR plugin.toml Cargo.toml   # version = "0.X.Y" in both
cargo update -p llama-cpp-plugin
git commit -am "release: v0.X.Y"

# 2. Tag and run the script
git tag v0.X.Y
scripts/release-local.sh v0.X.Y                  # builds + uploads
scripts/release-local.sh v0.X.Y --dry-run        # builds + stages locally, no upload
scripts/release-local.sh v0.X.Y --platform aarch64-linux   # other platforms

The script:

  1. Verifies the tag matches plugin.toml / Cargo.toml.
  2. Runs cargo build --release.
  3. Locates the SONAME-versioned companion libraries (libllama.so.0, libggml-{base,cpu,cuda,blas}.so.0, libllama-common.so.0, libmtmd.so.0) in target/llama-cmake-cache/<hash>/lib/.
  4. Stages them into a tarball named lib{plugin}-{platform}-companions.tar.gz.
  5. Renames the cdylib to lib{plugin}-{platform}.{ext} per the resolver's current_platform() lookup.
  6. SHA256-hashes both, writes .sha256 sidecars.
  7. Generates release-manifest.json with file, sha256, companions, companions_sha256 keys per platform. Multi-platform releases accrete by re-running the script against the same tag on each host — the script downloads the existing manifest and merges the new platform entry.
  8. Pushes the tag and runs gh release create (or gh release upload --clobber if the release already exists).

Consumers fetch the cdylib from the manifest's file entry and the companion tarball from companions, extract the tarball next to the cdylib (or anywhere on LD_LIBRARY_PATH), and dlopen the cdylib.

What it exports

Node type Input Output
LlamaCppGenerationNode Text / Json prompt Streamed Text chunks + Tensor (activation taps) + tool envelopes
LlamaCppEmbeddingNode Text / Json Tensor (dense embedding vector)
LlamaCppActivationNode Text / Json Tensor (one per requested layer, pooled per pooling)
LlamaCppSteerNode Tensor / Text / Json Text chunks + Json (steering delta metadata)

Configuration highlights

Generation

  • Activation tap: capture hidden-state snapshots at any layer via activation_tap: { layer: 15, every_n_tokens: 32 }. Emits Tensor envelopes with metadata.kind = "activation_tap" alongside text chunks. Used by emotion-driven face nodes.
  • Tool calls: built-in say / show tools plus arbitrary user-defined entries in tools: [...]. The streaming output is parsed for <tool_call>{...}</tool_call> blocks (Qwen3 / Hermes / DeepSeek format); each block is stripped from the text stream and dispatched.
  • Chat templates: the GGUF's embedded Jinja chat template is rendered via minijinja with tools, tool_choice, and enable_thinking=false kwargs so Qwen3-style templates produce the # Tools system block. HF {% generation %} tags are stripped first (minijinja has no such tag), so templates like LFM3's compile instead of falling back to llama.cpp's built-in renderer, which drops tools.

Audio in / speech out (LFM3-Audio)

Point mmproj_path at the model's multimodal projector and LlamaCppGenerationNode accepts RuntimeData::Audio and can answer in speech:

{
  "model_path": "LFM3-Audio-2B-Q4_K_M.gguf",
  "mmproj_path": "mmproj-LFM3-Audio-2B-Q8_0.gguf",
  "backend": { "gpu_offload": "all" },
  "response_mode": "mixed",
  "temperature": 0.0
}
  • Input: with audio_turns: "clip" (default) each Audio envelope is one complete user utterance (put a VAD / segmenter upstream); with "stream" see Streamed audio turns below. Any rate / channel count; it is downmixed and resampled to the encoder rate (16 kHz). The clip's PCM stays in the session history, so follow-ups can refer to it.
  • response_mode:
    • text (default): text reply. On LFM3 the audio-switch tokens are biased out; with no system prompt the reply is prefilled with <think></think> (the model card's text-chat recipe).
    • mixed: voice chat — interleaved text and speech; the text stream is the transcript of what is spoken. Uses the card's "Respond with interleaved text and audio." system prompt (tool variant when tools are advertised) unless system_prompt is set.
    • audio: speech only. auto: the model chooses per turn.
    • tts: speak the input text verbatim via the model's "tts" template (tts_language, e.g. en / en-gb / fr; tts_voice: female | male). No history.
    • live_asr: streaming transcription — see below.
  • Output: speech streams as mono RuntimeData::Audio (metadata.kind = "llm_speech", 24 kHz for LFM3-Audio) as frames are decoded — first audio ~250 ms after the request on an RTX 4090, ~5x faster than real time. process() (non-streaming) returns text, or the whole utterance in tts mode.
  • Knobs: audio_temperature (default: the model's, 1.0), max_audio_steps (text tokens + audio frames per spoken reply, default 2048). Text sampling follows the usual fields; the card recommends temperature: 0.
  • The activation tap is text-mode only.

examples/lfm3_voice_chat.rs drives the node end to end (ASR, voice chat with a follow-up turn, tools, TTS) and transcribes its own speech back as a check.

Streaming transcription (response_mode: "live_asr")

Feeds the audio encoder as audio arrives (llama.cpp's experimental mtmd_audio_stream_* API, opened with the model's "asr" template), so no VAD is needed to cut utterances and text streams out mid-sentence:

  • Input: RuntimeData::Audio frames of any size / rate / channel count (resampled with a stateful resampler, so frame boundaries are seamless), plus JSON controls: {"kind": "audio_stream_flush"} — a pause: transcribe everything so far, stream stays open; {"kind": "audio_stream_end"} — end the stream (the next frame opens a new one).
  • Output: transcript text deltas as RuntimeData::Text while audio is still arriving (LFM3 transcribes in 0.96 s chunks), and after each flush / end a RuntimeData::Json {"kind": "asr_final", "text": …, "end": bool, "audio_ms": …, "elapsed_ms": …} holding the text since the previous final.
  • Behaviour: greedy decoding under the stream's logit bias; the model restarts its context every 30 s of audio by itself (tested past it). stream_step_ms overrides the encoder step for models that honour it. process() treats one envelope as a whole clip (stream + end) and returns the text.
  • Limits: one live stream per session (up to max_sessions at once, each on its own KV sequence). Changing the input rate / channels mid-stream is an error; end the stream first.
  • Measured on an RTX 4090 with 20 ms real-time frames: first words ~1 s into the audio, a pause's final ~10 ms after the flush, the closing final ~30–130 ms after the last frame; 35 s of audio fed as fast as possible transcribes in 2.5–4 s.

examples/lfm3_live_asr.rs runs these cases (real-time with a pause, a 35 s stream, one-shot).

Sessions, cache reuse and barge-in

Each conversation (session_id) keeps its own KV sequence across turns — up to max_sessions (default 4) at once; the context holds context_size tokens per session. A turn decodes only what is new since the session's last checkpoint (on LFM3-Audio a follow-up prefills in ~10–20 ms instead of re-decoding the history). The least recently used session is evicted when all are taken; its history is kept and re-decoded (audio re-encoded from its PCM) on its next turn. Replies stay in the cache as generated — for spoken replies that is LFM3's own audio, which it attends to on later turns.

Hybrid models like LFM3 (recurrent + sliding-window attention) can't trim their state back past the last batch, so rollback points snapshot that state (llama_state_seq_* with PARTIAL_ONLY, < 1 MiB, ~4 ms) and are restored before trimming the attention cache — verified bit-exact against an uninterrupted decode. Anything that doesn't match a checkpoint (history edits, set_context, eviction) falls back to a rebuild from history.

Barge-in (request_cancel, finalize_turn(interrupted), or a {"kind": "barge_in", "heard_ms": N} control that waits until applied):

  • The reply stops at its next step. The user's turn is always kept.
  • If less than barge_in_keep_min_ms (default 2000) of the reply was heard, it is rolled back — cache and history.
  • Otherwise it is kept up to what was heard: rollback points are taken every barge_in_checkpoint_ms (default 1000) of spoken audio, and the reply is cut back to the last one within the heard audio (cache and transcript). "Heard" is estimated as the time since the first audio was emitted, capped at the audio generated; heard_ms overrides it. The kept transcript can lead the kept audio by up to one text block (LFM3 writes ~6 text tokens before speaking them).

{"kind": "get_history"} returns the session's messages (audio as durations) for inspection.

Streamed audio turns (audio_turns: "stream")

Audio envelopes are frames of the user's turn: the first one brings the cache to the start of the user's message, then each frame is encoded and decoded as it arrives (an MtmdAudioStream in chat-turn mode). {"kind": "audio_stream_end"} (e.g. from a VAD) ends the turn — the rest of the message is decoded and the reply streams back on that call. On a 7 s utterance 88 of 89 audio rows are decoded while the user speaks, so the turn's remaining prefill drops from ~110 ms (clip) to ~70 ms on an RTX 4090 — more for longer utterances. End-to-end first-audio latency did not improve in our runs (median 273 ms vs 194 ms for clip turns): after seconds of near-idle streaming the first reply steps run 3–8x slower (30–60 ms vs ~7 ms per step) and settle within ~150 ms, consistent with GPU clock ramp-up; with the GPU kept at performance clocks (busy server, or the driver's "prefer maximum performance") that gap should disappear, but this is not verified. Text input while a turn is open is an error.

examples/lfm3_sessions.rs runs it all: interleaved sessions, eviction, streamed vs clip turns (7 trials), and barge-in before / after a reply finished. Run it with RUST_LOG=llama_cpp_plugin=info to see per-turn n_decoded / n_reused / prefill_ms / first_output_ms.

Multi-Token Prediction (Qwen3.6 MTP)

Since v0.2.0 the plugin links llama-cpp-4 v0.3.0, which carries the upstream MTP support merged in ggml-org/llama.cpp#22673. Loading a Qwen3.6 MTP GGUF (e.g. Qwen3.6-27B-Q4_K_M-mtp.gguf, Qwen3.6-27B-IQ2_M-mtp.gguf) works out of the box — the MTP head is autodetected from GGUF metadata.

What you get today:

  • Drop-in load of MTP-flavored Qwen3.6 GGUFs through LlamaCppGenerationNode / LlamaCppEmbeddingNode / LlamaCppActivationNode. Normal next-token generation runs against the base head; the MTP head is simply present in the file.

What is not yet wired through the plugin params:

  • LlamaContextType::Mtp / LlamaContextParams::with_ctx_type for speculative-decoding draft contexts.
  • The llama_cpp_4::mtp::MtpSession draft loop (would need a new mtp: { enabled: true, n_max: 1, n_min: 0, p_min: 0.0 } block on LlamaCppGenerationNode params and a second model handle).

Speculative-decoding throughput gains (≈+6–10% on Qwen3.6-27B per upstream benchmarks) therefore require either (a) using the llama-cpp-4 API directly until the plugin exposes those params or (b) opening an issue for the MTP draft-loop wiring.

Embedding

  • Pooling modes: mean (default), last_token, first_token, cls.
  • L2 normalization on by default; turn off with l2_normalize: false.

Activation extraction

  • Captures any number of layers at once via layers: [15, 21].
  • Pooling modes: last_token (default), mean, first_token.
  • Per-layer raw-norm metadata included on each Tensor envelope.

Steering

  • Accepts pre-extracted steering vectors as RuntimeData::Tensor envelopes labelled via metadata.emotion / metadata.label.
  • Coefficients updated at runtime via Json {"coefficients": {...}}.
  • Metadata mode only: the underlying KV-cache injection is not yet implemented (mirrors the in-tree implementation status). Text output passes through without hidden-state modification; steering delta + per-vector coefficients are surfaced in the output Json envelope.

Plugin-side differences from the in-tree node

This is a mechanical port. Two structural changes worth calling out:

  1. No per-session typed ChatState. The in-tree LlamaCppGenerationNode uses the host's make_session_state / try_state mechanism to keep multi-turn conversation history per session. That surface isn't reachable from the Path-3 FFI boundary, so the plugin constructs a fresh ChatState on every generate() call (still picks up system_prompt). Multi-turn coordination should happen outside the plugin — typically the consumer batches history into the prompt itself.
  2. No CancelGate integration. The in-tree dispatcher takes a ProtectGuard whenever a cancelable: false tool dispatches so subsequent barge_in envelopes are suppressed for the rest of the turn. The plugin doesn't have access to CancelGate (it's a host-internal type), so the dispatcher just calls the tool dispatcher directly and relies on the universal future-drop cancellation pathway.

<think>...</think> stripping, <tool_call> parsing + dispatch, the activation-tap side channel, the embedded-Jinja chat template render path, and the <|text_end|> sentinel all behave identically.

License

See LICENSE.md. Governed by the RemoteMedia SDK Community License 1.0.

About

llama.cpp GGUF inference nodes (generation, embedding, activation extraction, steering) — RemoteMedia SDK Path 3 loadable plugin

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages