Cider.Native 0.1.35

There is a newer version of this package available.
See the version list below for details.
dotnet add package Cider.Native --version 0.1.35
                    
NuGet\Install-Package Cider.Native -Version 0.1.35
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Cider.Native" Version="0.1.35" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Cider.Native" Version="0.1.35" />
                    
Directory.Packages.props
<PackageReference Include="Cider.Native" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Cider.Native --version 0.1.35
                    
#r "nuget: Cider.Native, 0.1.35"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Cider.Native@0.1.35
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Cider.Native&version=0.1.35
                    
Install as a Cake Addin
#tool nuget:?package=Cider.Native&version=0.1.35
                    
Install as a Cake Tool

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 of N independent single-sequence llama_context slots (maxConcurrency, default 1) with prefix-affinity checkout, explicit per-context thread control (threads / threadsBatch, matching llama.cpp n_threads / n_threads_batch, with automatic pool-budgeted defaults when 0), and effective native thread reporting via Threads, ThreadsBatch, Placement.Describe(), and DescribeDiagnostics(). Implements IModelIdentityProvider (GetModelHash / GetModelHashAsync) reusing its bound-handle SHA-256 BoundModelFiles / BoundFileHasher identity (including multi-shard split GGUFs, without allocating the embedding context) so CalibrationWorkflow and DecisionClient.LoadCalibration verify exact loaded weights fail-closed (ADR-0018). Automatically detects the model family's PromptLayout (chatml, llama3, gemma, phi3, mistral, or llama_chat_apply_template probe) from GGUF tokenizer.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 shared System + State prefix once on seq_id = 0, reuses/branches prefix KV and recurrent SSM states both within and across consecutive requests (llama_memory_seq_rm LCP truncation for pure-attention models and bounded LRU PrefixStateCache snapshots via llama_state_seq_get/set_data_ext for hybrid/recurrent models), implements ITokenCountingBackend (ContextWindowTokens + exact llama_tokenize counting) with pre-decode StateTooLargeException guards, implements IEmbeddingBackend (Embed / EmbedAsync) via a dedicated lazily allocated llama_context sharing the loaded model weights so embedding passes never disturb decision KV/SSM prefix caches (ADR-0007 / ADR-0017), and wires per-slot native abort_callback flags with cancellable semaphore queuing so cancelling or timing out one decision or embedding call aborts cleanly without disturbing concurrent siblings.
  • LlamaEmbedder: Standalone IEmbeddingBackend & ITokenCountingBackend for dedicated contrastive/encoder embedding GGUFs (e.g., Qwen3-Embedding-0.6B, EmbeddingGemma-2, BERT/Nomic) or causal GGUFs, supporting Auto (model-native pooling or Mean fallback), Mean, Last, and Cls pooling, encoder-only (llama_encode) and decoder (llama_decode) models, L2 normalization, SHA-256 ModelHash provenance, LlamaDeviceOptions, ExplicitConfiguration, ICiderLogger, and native abort cancellation. Every result reports ordered per-row original/effective token counts (RowTokens). Setting EmbeddingOptions.MaxSequencesPerBatch above 1 evaluates 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.

Independent packed-token capacity

For EmbeddingGemma-2 (general.architecture = gemma-embedding2), use the new constructor overload:

using let embedder = LlamaEmbedder(
    "/absolute/path/model.gguf",
    LlamaEmbeddingCapacityOptions(){TotalTokens = 8192U},
    nCtx: 2048U,
    device: LlamaDeviceOptions.ExplicitCpu()
)
let result = embedder.Embed(texts, EmbeddingOptions(){MaxSequencesPerBatch = 8})

nCtx remains the per-input limit; TotalTokens allocates independent aggregate native context, batch and microbatch storage. Eight 900-token rows can fit one 8192-token evaluation instead of four 2048-token evaluations, without changing original/effective token counts or truncating at 8192. TotalTokens = 0 (default) preserves the old allocation; packing still defaults to one sequence. Nonzero capacity must be between resolved nCtx and MaxTotalTokens (16384); invalid values throw before loading native code. The existing constructor's binary signature remains available.

Expanded capacity is deliberately limited to the audited gemma-embedding2 graph with absent/none RoPE scaling. Unknown architectures, scaling modes, recurrent/hybrid models or missing capability queries retain legacy allocation (unsupported-model). This does not resize decision contexts or change calibration/model loading settings. Failed expanded allocations retry legacy capacity (allocation-fallback); if legacy allocation also fails, construction/evaluation throws. Native process-level OOM cannot be recovered by managed fallback. Larger allocations increase KV and graph memory (attention scratch can grow quadratically); the token cap is not a byte-memory guarantee.

embedder.Capacity and result.Capacity report requested input/total tokens, effective per-input ceiling, actual native context/batch/microbatch sizes, packed-token budget, sequence capacity, packing availability, model architecture and expansion status. The result snapshot describes that request; the embedder snapshot may change after a pooling switch, sequence-capacity growth or fallback. Before lazy allocation its status starts with not-allocated:. Native padding can exceed requested allocation; planning always uses actual native limits and the per-input ceiling separately. For compatibility, zero-capacity legacy construction retains its existing native-rounded per-input window; nonzero capacity explicitly bounds the per-input ceiling by requested nCtx. Bind the result capacity, Provenance, request options, Cider package version and runtime/device identity in a reader identity; do not use aggregate context as per-input context or presume the bundled llama.cpp version identifies a user-supplied native library. Other backends can report nil capacity.

Noncausal rows and packed groups always fit a single microbatch, with independent sequence IDs and positions starting at zero; they are never split across bidirectional-attention graphs. Backend rejection disables multi-sequence evaluation and retains exact row accounting. Throughput depends on tokens per row, actual budget, model, kernels and hardware: fewer native calls is not a universal speedup guarantee. The model-gated LlamaEmbedder_ExpandedCapacity_LongRowsScaleAtFixedInputLimit test uses CIDER_TEST_EMBEDDING_MODEL and optionally CIDER_TEST_EMBEDDING_DEVICE (default cpu, e.g. Vulkan1), checks long-row scaling and parity and prints warmed interleaved measurements.

  • 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 all 151,936 vocabulary rows (~38,000× output-head speedup).
  • GgufFile & GgufTokenizer: Zero-dependency memory-mapped GGUF v2/v3 parser (with GetChatTemplate() / 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 by SelectiveLmHead.
  • 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_rm truncation or a state copy).
    • A streaming loop whose per-step callback can stop, roll back to a checkpoint, or change the mask.

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: -1 all, 0 none. RequireGpu: throw instead of falling back to the CPU.
  • With the defaults, the CIDER_LLAMA_BACKEND and CIDER_LLAMA_DEVICE environment variables choose instead (for example CIDER_LLAMA_BACKEND=cpu).
  • Placement (on both classes) reports the devices the model was given and FallbackReason when 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=1 silences it). BackendName / Name() report llamacpp-cpu, llamacpp-vulkan, llamacpp-cuda or llamacpp-metal.
  • LlamaRuntime.Devices(), RegisteredBackends(), BackendLoadErrors() and Describe() show what the process loaded, and why a bundled GPU module did not load. cider-server --list-devices prints 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, and OLLAMA_MODELS (use LlamaDeviceOptions.NativeLibraryPath / ExtraBackendPaths for explicit overrides).
  • Rejects Ollama tags (e.g. qwen3:0.6b), relative paths, and modelsRoot; requires an explicit absolute file path (Path.IsPathFullyQualified).
  • Never falls back silently from GPU to CPU (throws InvalidOperationException unless CPU was explicitly requested).
  • Routes native llama.cpp/ggml logs (llama_log_set + ggml_log_set, reassembling GGML_LOG_LEVEL_CONT lines) and Cider.Native diagnostics exclusively through ICiderLogger, writing zero output to stderr.

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 when maxConcurrency > 1).
  • (T > 0, 0): sets both n_threads and n_threads_batch to T.
  • (0, B > 0): keeps the default n_threads (respecting pool budget) and sets n_threads_batch to B.
  • (T > 0, B > 0): sets n_threads = T and n_threads_batch = B for every context slot.
  • Effective native counts queried from llama_n_threads / llama_n_threads_batch are exposed via Threads, ThreadsBatch, Placement.Threads, Placement.ThreadsBatch, Placement.Describe(), and DescribeDiagnostics().

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

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:

  1. The OS loader can open the library and resolve all dependencies (libcudart / libcublas / libggml-base),
  2. The module exports ggml_backend_init (and if ggml_backend_score is exported, that it returns > 0), and
  3. 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.

Version Downloads Last Updated
0.1.52 0 12/4/2026
0.1.51 0 12/4/2026
0.1.35 103 11/29/2026
0.1.34 218 11/28/2026
0.1.33 295 11/25/2026
0.1.13 118 11/18/2026
0.1.11 128 11/16/2026
0.1.9 126 11/16/2026
0.1.8 127 11/16/2026
0.1.5 112 11/14/2026
0.1.2 115 11/13/2026