Cider.Native
0.1.34
See the version list below for details.
dotnet add package Cider.Native --version 0.1.34
NuGet\Install-Package Cider.Native -Version 0.1.34
<PackageReference Include="Cider.Native" Version="0.1.34" />
<PackageVersion Include="Cider.Native" Version="0.1.34" />
<PackageReference Include="Cider.Native" />
paket add Cider.Native --version 0.1.34
#r "nuget: Cider.Native, 0.1.34"
#:package Cider.Native@0.1.34
#addin nuget:?package=Cider.Native&version=0.1.34
#tool nuget:?package=Cider.Native&version=0.1.34
Cider.Native
In-process GGUF v3 weight loader, selective $K$-row LM-head engine, and libllama CPU/GPU (Metal, Vulkan, CUDA) backend for Cider.NET.
Cider.Native runs System One decisions (Choice, Score, Noul) directly in-process from .gguf files or local Ollama model blobs (~/.ollama/models/blobs/) without requiring an external inference server.
Installation
dotnet add package Cider.Native
Key Components
LlamaCppBackend: Direct@DllImport("llama")P/Invoke backend with GPU offload (Metal on Apple silicon, Vulkan on Linux and Windows x64, CUDA when you supply it; see GPU backends) and CPU execution. Loads GGUF weights once and supports a configurable pool ofNindependent single-sequencellama_contextslots (maxConcurrency, default1) with prefix-affinity checkout, explicit per-context thread control (threads/threadsBatch, matching llama.cppn_threads/n_threads_batch, with automatic pool-budgeted defaults when0), and effective native thread reporting viaThreads,ThreadsBatch,Placement.Describe(), andDescribeDiagnostics(). ImplementsIModelIdentityProvider(GetModelHash/GetModelHashAsync) reusing its bound-handle SHA-256BoundModelFiles/BoundFileHasheridentity (including multi-shard split GGUFs, without allocating the embedding context) soCalibrationWorkflowandDecisionClient.LoadCalibrationverify exact loaded weights fail-closed (ADR-0018). Automatically detects the model family'sPromptLayout(chatml,llama3,gemma,phi3,mistral, orllama_chat_apply_templateprobe) from GGUFtokenizer.chat_template/general.architecture(DetectedPromptLayout), prevents duplicate BOS tokens on BOS-prefixed layouts, validates all candidate labels as single distinct tokens at the readout prefill boundary before decode (InvalidLabelTokenException), evaluates the sharedSystem + Stateprefix once onseq_id = 0, reuses/branches prefix KV and recurrent SSM states both within and across consecutive requests (llama_memory_seq_rmLCP truncation for pure-attention models and bounded LRUPrefixStateCachesnapshots viallama_state_seq_get/set_data_extfor hybrid/recurrent models), implementsITokenCountingBackend(ContextWindowTokens+ exactllama_tokenizecounting) with pre-decodeStateTooLargeExceptionguards, implementsIEmbeddingBackend(Embed/EmbedAsync) via a dedicated lazily allocatedllama_contextsharing the loaded model weights so embedding passes never disturb decision KV/SSM prefix caches (ADR-0007 / ADR-0017), and wires per-slot nativeabort_callbackflags with cancellable semaphore queuing so cancelling or timing out one decision or embedding call aborts cleanly without disturbing concurrent siblings.LlamaEmbedder: StandaloneIEmbeddingBackend&ITokenCountingBackendfor dedicated contrastive/encoder embedding GGUFs (e.g.,Qwen3-Embedding-0.6B,EmbeddingGemma-2, BERT/Nomic) or causal GGUFs, supportingAuto(model-native pooling orMeanfallback),Mean,Last, andClspooling, encoder-only (llama_encode) and decoder (llama_decode) models, L2 normalization, SHA-256ModelHashprovenance,LlamaDeviceOptions,ExplicitConfiguration,ICiderLogger, and native abort cancellation. Every result reports ordered per-row original/effective token counts (RowTokens). SettingEmbeddingOptions.MaxSequencesPerBatchabove1evaluates several independent rows in one native call (SupportsMultiSequenceEvaluation), with a per-row fallback for recurrent and hybrid models or backends that reject it (ADR-0019). Encoder-decoder models are not supported for embeddings.SelectiveLmHead: Projects the final normalized hidden state $h_{\text{last}} \in \mathbb{R}^d$ only against the $K \le 255$ permitted option token rows (F32,F16,BF16,Q8_0,Q4_0,Q4_K,Q6_K) rather than all151,936vocabulary rows (~38,000×output-head speedup).GgufFile&GgufTokenizer: Zero-dependency memory-mapped GGUF v2/v3 parser (withGetChatTemplate()/DetectPromptLayout()) and byte-level BPE tokenizer with multi-family special-token support (chatml,llama3,gemma,phi3,mistral) and readout-boundary single-token label validation.Qwen3ManagedBackend: Pure managed G# GGUF execution backend powered bySelectiveLmHead.LlamaSession/LlamaSampler/TokenGenerator: In-process token generation for constrained and checked decoding:- llama.cpp sampler chains (greedy, temperature, top-k, top-p, min-p, seed), GBNF grammars and a
TokenMask(allow, deny, bias) applied before sampling. - Tokenize and detokenize, with partial-UTF-8-safe streaming (
Utf8PieceDecoder). - KV snapshot and rollback (
seq_rmtruncation or a state copy). - A streaming loop whose per-step callback can stop, roll back to a checkpoint, or change the mask.
- llama.cpp sampler chains (greedy, temperature, top-k, top-p, min-p, seed), GBNF grammars and a
Quick Start (G#)
package Demo
import Cider
import Cider.Native
import System
// Resolves local Ollama GGUF blob for "qwen3:0.6b" automatically without needing `ollama serve`
using let backend = LlamaCppBackend("qwen3:0.6b", nGpuLayers: -1)
let client = DecisionClient(backend, "qwen3:0.6b")
let pRefund = client.DecideNoul(
"Returns are allowed within 30 days. Purchase was 12 days ago.",
"Is this purchase eligible for a return?"
)
Console.WriteLine("P(eligible) = $pRefund")
Generation Quick Start (G#)
using let session = LlamaSession("/models/qwen3-0.6b.gguf", nGpuLayers: -1)
using let sampler = session.CreateSampler(
SamplingOptions.Greedy().WithGrammar("root ::= \"let \" [a-z]+ \" = \" [0-9]+ \"\\n\"")
)
let gen = TokenGenerator(session, sampler)
var lineStart GenerationCheckpoint? = nil
let result = gen.Run(session.Tokenize(prompt, false, true), GenerationOptions(), step -> {
if step.TextDelta.Contains("\n") {
// Statement boundary: check the prefix, then keep it (checkpoint) or roll back and ban.
lineStart = step.Generator.Checkpoint()
}
StepAction.Continue
})
Console.WriteLine(result.Text)
GPU backends
Cider.Native.Runtime.<rid> bundles the official llama.cpp b12110 release libraries. llama.cpp loads each
backend module it finds next to libllama at startup and skips any whose driver is missing, so one package
runs on the CPU everywhere and on the GPU where it can:
| RID | Bundled backends |
|---|---|
linux-x64, win-x64 |
CPU (runtime-selected AVX/AVX2/AVX-512 variants), Vulkan (NVIDIA, AMD and Intel GPUs; needs the GPU driver's Vulkan loader, libvulkan.so.1 / vulkan-1.dll) |
linux-musl-x64, linux-musl-arm64 |
CPU (runtime-selected ISA variants, built from pinned b12110 source with GGML_OPENMP=OFF; runs on stock mcr.microsoft.com/dotnet/runtime:10.0-alpine with zero extra apk packages) |
osx-arm64 |
CPU, Metal, BLAS (Accelerate) |
osx-x64 |
CPU, BLAS (llama.cpp publishes no Metal build for Intel Macs) |
linux-arm64, win-arm64 |
CPU |
Choosing a device
LlamaCppBackend, LlamaSession (and so TokenGenerator) take nGpuLayers and an optional
device: LlamaDeviceOptions:
// Default: offload every layer to the best GPU (discrete before integrated; CUDA before Metal/ROCm
// before Vulkan for the same card), otherwise run on the CPU and say why.
using let auto = LlamaSession(path, nGpuLayers: -1)
Console.WriteLine(auto.Placement.Describe()) // "vulkan on Vulkan1 (NVIDIA GeForce RTX 4060 Laptop GPU), gpu layers all"
using let cpu = LlamaSession(path, device: LlamaDeviceOptions.Cpu())
using let vk = LlamaCppBackend(path, device: LlamaDeviceOptions.Gpu("vulkan"))
using let one = LlamaSession(path, device: LlamaDeviceOptions.Gpu("Vulkan1", gpuLayers: 20, requireGpu: true))
LlamaDeviceOptions.Backend:auto,cpu, or a ggml backend name (vulkan,cuda,metal, ...).Device: ggml device names, comma-separated (Vulkan1,CUDA0,CUDA1).GpuLayers:-1all,0none.RequireGpu: throw instead of falling back to the CPU.- With the defaults, the
CIDER_LLAMA_BACKENDandCIDER_LLAMA_DEVICEenvironment variables choose instead (for exampleCIDER_LLAMA_BACKEND=cpu). Placement(on both classes) reports the devices the model was given andFallbackReasonwhen a GPU was requested but the model runs on the CPU (no GPU device, an unknown backend or device, or a GPU load that failed and was retried on the CPU). Cider also writes each fallback reason to stderr once per process (CIDER_LLAMA_QUIET=1silences it).BackendName/Name()reportllamacpp-cpu,llamacpp-vulkan,llamacpp-cudaorllamacpp-metal.LlamaRuntime.Devices(),RegisteredBackends(),BackendLoadErrors()andDescribe()show what the process loaded, and why a bundled GPU module did not load.cider-server --list-devicesprints the same.
Explicit-configuration mode & logging hook
Embedding hosts that forbid ambient environment variables, implicit ~/.ollama/models discovery, silent GPU-to-CPU fallback, or stderr output can enable ExplicitConfiguration = true and attach an ICiderLogger (DelegateCiderLogger):
let logger = DelegateCiderLogger((level, category, msg) -> Console.WriteLine("[$level] $category: $msg"))
LlamaRuntime.Initialize(explicitConfiguration: true, logger: logger)
let opts = LlamaDeviceOptions.ExplicitCpu(logger)
using let backend = LlamaCppBackend("/abs/path/to/model.gguf", device: opts)
- Ignores
CIDER_LLAMA_BACKEND,CIDER_LLAMA_DEVICE,CIDER_LLAMA_QUIET,CIDER_LLAMA_LIB,NUGET_PACKAGES,GGML_BACKEND_PATH, andOLLAMA_MODELS(useLlamaDeviceOptions.NativeLibraryPath/ExtraBackendPathsfor explicit overrides). - Rejects Ollama tags (e.g.
qwen3:0.6b), relative paths, andmodelsRoot; requires an explicit absolute file path (Path.IsPathFullyQualified). - Never falls back silently from GPU to CPU (throws
InvalidOperationExceptionunless CPU was explicitly requested). - Routes native
llama.cpp/ggmllogs (llama_log_set+ggml_log_set, reassemblingGGML_LOG_LEVEL_CONTlines) andCider.Nativediagnostics exclusively throughICiderLogger, writing zero output tostderr.
Thread-count control
LlamaCppBackend accepts optional threads (llama.cpp n_threads) and threadsBatch (n_threads_batch), and
LlamaSession accepts nThreads and threadsBatch (both default to 0):
// Cap CPU threads per context slot so Cider does not starve sibling host workloads
using let backend = LlamaCppBackend(
path,
device: LlamaDeviceOptions.Cpu(),
maxConcurrency: 2,
threads: 2,
threadsBatch: 4
)
Console.WriteLine(backend.DescribeDiagnostics()) // "cpu, threads 2, threads_batch 4 (context pool: 2, n_ctx: 8192)"
(0, 0)(default): uses llama.cpp's default thread counts (fairly divided across pool slots whenmaxConcurrency > 1).(T > 0, 0): sets bothn_threadsandn_threads_batchtoT.(0, B > 0): keeps the defaultn_threads(respecting pool budget) and setsn_threads_batchtoB.(T > 0, B > 0): setsn_threads = Tandn_threads_batch = Bfor every context slot.- Effective native counts queried from
llama_n_threads/llama_n_threads_batchare exposed viaThreads,ThreadsBatch,Placement.Threads,Placement.ThreadsBatch,Placement.Describe(), andDescribeDiagnostics().
CUDA
CUDA is not bundled: llama.cpp's ggml-cuda module is 160–600 MB and needs NVIDIA's cuBLAS (another
~870 MB), which would exceed NuGet's package size limit and repeat in the Cider.Server tool. On NVIDIA
GPUs the bundled Vulkan backend works without the CUDA toolkit.
To use CUDA, download the CUDA module and matching CUDA runtime from the same ggml-org/llama.cpp release
(LlamaRuntime.ExpectedLlamaRelease == "b12110", LlamaRuntime.ExpectedGgmlBackendApiVersion == 3; modules from
mismatched builds such as Ollama fail with undefined symbols or an ABI version mismatch):
| Platform | ggml-cuda archive (b12110) |
Matching CUDA runtime archive (or installed toolkit) |
|---|---|---|
| Linux x64 (CUDA 12.8) | llama-b12110-bin-ubuntu-cuda-12.8-x64.tar.gz (libggml-cuda.so) |
cudart-llama-b12110-bin-ubuntu-cuda-12.8-x64.tar.gz (libcudart.so.12, libcublas.so.12, libcublasLt.so.12 on LD_LIBRARY_PATH) |
| Linux x64 (CUDA 13.4) | llama-b12110-bin-ubuntu-cuda-13.4-x64.tar.gz (libggml-cuda.so) |
cudart-llama-b12110-bin-ubuntu-cuda-13.4-x64.tar.gz |
| Linux ARM64 (CUDA 13.4) | llama-b12110-bin-ubuntu-cuda-13.4-arm64.tar.gz (libggml-cuda.so) |
cudart-llama-b12110-bin-ubuntu-cuda-13.4-arm64.tar.gz |
| Windows x64 (CUDA 12.4) | llama-b12110-bin-win-cuda-12.4-x64.zip (ggml-cuda.dll) |
cudart-llama-bin-win-cuda-12.4-x64.zip (cudart64_*.dll, cublas64_*.dll, cublasLt64_*.dll on PATH) |
| Windows x64 (CUDA 13.4) | llama-b12110-bin-win-cuda-13.4-x64.zip (ggml-cuda.dll) |
cudart-llama-bin-win-cuda-13.4-x64.zip |
| Windows ARM64 (CUDA 13.4) | llama-b12110-bin-win-cuda-13.4-arm64.zip (ggml-cuda.dll) |
cudart-llama-bin-win-cuda-13.4-arm64.zip |
Selecting CUDA explicitly through options (recommended — no GGML_BACKEND_PATH required)
Pass the module file path (or directory containing it) via LlamaDeviceOptions — works in both default mode and
ExplicitConfiguration = true mode (in explicit mode, the path must be absolute):
// Default mode: load explicit CUDA module (file or directory) and require CUDA offload
using let backend = LlamaCppBackend(
"/models/qwen3-0.6b.gguf",
device: LlamaDeviceOptions.Cuda("/opt/llama-b12110/libggml-cuda.so")
)
// Explicit-configuration mode (zero env vars, zero stderr, strict ABI check)
let opts = LlamaDeviceOptions.ExplicitCuda("/opt/llama-b12110/libggml-cuda.so", logger: logger)
using let explicitBackend = LlamaCppBackend("/models/qwen3-0.6b.gguf", device: opts)
// Or set ExtraBackendPaths directly on any LlamaDeviceOptions (or call LlamaRuntime.LoadBackendModule)
let custom = LlamaDeviceOptions.Auto(-1)
custom.ExtraBackendPaths = []string{"/opt/llama-b12110/libggml-cuda.so"}
When loading an explicit module, Cider probes the shared library and verifies:
- The OS loader can open the library and resolve all dependencies (
libcudart/libcublas/libggml-base), - The module exports
ggml_backend_init(and ifggml_backend_scoreis exported, that it returns> 0), and - The registered backend matches
GGML_BACKEND_API_VERSION == 3(llama.cpp b12110).
Any loader failure, missing symbol, score-0 unsupported device, or ABI mismatch throws InvalidOperationException
with the exact module path, underlying native error, and expected b12110 release version.
On cider-server, pass --llama-backend-path /opt/llama-b12110/libggml-cuda.so (repeatable; also works with
--list-devices and --explicit-config). In non-explicit mode, the legacy GGML_BACKEND_PATH environment variable
continues to work as before; when both CUDA and Vulkan devices are present, auto prefers CUDA.
NativeAOT Compatibility
Cider.Native is marked <IsAotCompatible>true</IsAotCompatible> and verified in CI under PublishAot=true on Linux, Windows, and macOS with zero IL2xxx/IL3xxx warnings and exact JIT/NativeAOT parity. When publishing a NativeAOT host for a target RID, include <PackageReference Include="Cider.Native.Runtime.<rid>" Version="..." /> alongside Cider.Native so the prebuilt libllama/ggml shared libraries are copied next to the native executable.
License
MIT — see LICENSE.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Cider.NET (>= 0.1.34)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Cider.Native:
| Package | Downloads |
|---|---|
|
Hyperplane.Cider
Optional reader adapter for Hyperplane.NET: CiderEmbedder turns any Cider.NET IEmbeddingBackend (including Cider.Native's in-process llama.cpp LlamaEmbedder over GGUF models) into a Hyperplane IEmbedder with an honest, provenance-derived experimental profile. |
GitHub repositories
This package is not used by any popular GitHub repositories.