gopherllm

package module
v1.19.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 5 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

GopherLLM

DOI

GopherLLM has its own inference engine, written in Go with its own architecture-specific assembly kernels. It loads and runs GGUF models directly in the calling process, with no external runtime or child process required. The Go package and CLI cover generation, streaming chat, embeddings, tokenization, model inspection, compression, and benchmarks.

GopherLLM is closer to llama.cpp in scope than to LM Studio or Ollama: the core of the project is the inference engine itself, exposed as an embeddable library and CLI. Its chat UI, server, and model-management features build on that engine. The comparison describes its role, not a dependency on llama.cpp or a claim of feature or performance parity.

It is an independent implementation. GopherLLM does not wrap, bind to, or link against llama.cpp or any other inference library: the GGUF parser, the tokenizers, the quantized kernels, and the assembly are written for this project. go.mod has no require block at all, and make deps-check keeps it that way — see Dependency policy and layout. The same reasoning has its own Rust sibling in RustyLLM.

Project website · Go package documentation · Demo application documentation

Try it in five minutes

make build
bin/gopherllm --model-dir /path/to/your/models --serve --chat

That opens a chat server on http://127.0.0.1:8080/chat: loopback only, with the optional features off, and a model picker for the GGUFs in that directory. If you have no GGUF yet, bin/gopherllm --hf-list <owner/repo> lists the variants in a Hugging Face repository and hf:<owner>/<repo>:<quant> in place of the model path downloads one into the shared HF cache. See Serving and safety defaults for what "optional" covers and how to turn things on.

Classify a CSV with Laya

Ask one question for every record; receive the original CSV with one extra column. GopherLLM downloads the weights, loads the model once, and writes each result to stdout:

bin/gopherllm --laya-model hf:convaiinnovations/laya \
  --laya-subfolder multilingual --classify-csv examples/laya/tickets.csv \
  --csv-column text --instruction 'Welcher Bereich ist zuständig?' \
  --criteria '["Abrechnung","Technik","Vertrieb"]' \
  --result-column category > classified.csv

Use --classify-csv - for stdin and Unix pipes. For a browser upload, start the same model with --serve 127.0.0.1:8080 instead of the CSV options, then open CSV classification. Full guide: downloads, CSV/TSV, Go integration and HTTP API.

For previews, editable results, uncertainty filters and CSV export, use the standalone CSV Workbench. It embeds its browser UI and optionally runs Ministral for task suggestions and row explanations.

Contents

Features

  • Pure Go runtime with optional ARM64 (NEON) and x86-64 (SSE2, AVX2 + FMA) assembly kernels.
  • Memory-mapped GGUF loading for fast startup and lower copy pressure, on every platform (Unix mmap, Windows CreateFileMapping/MapViewOfFile): weights page in on demand and quantized tensors borrow the mapping zero-copy.
  • Split/sharded GGUF loading: point at any one shard of a <name>-00001-of-00005.gguf-style download and every sibling is discovered and merged automatically (see Performance Notes).
  • Quantized matrix kernels for TQ1_0, TQ2_0, Q1_0, Q2_0, Q2_K, Q3_K, Q4_K, Q5_K, Q6_K, Q8_K, IQ2_S, IQ3_S, IQ4_NL, IQ4_XS, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q8_1, and MXFP4 tensors; F32/F16/F64/BF16 load directly (BF16 covers QAT-derived and modern full-precision GGUFs).
  • Temperature, top-k, top-p, and min-p sampling with a repetition penalty.
  • OpenAI-compatible tool/function calling, with a native prompt format for Mistral-family models and a generic convention for everything else.
  • Chain-of-thought extraction (<think> blocks, gpt-oss channels) into a separate reasoning_content field instead of leaving it in the answer text.
  • CLI generation, REPL mode, embeddings, metadata inspection, and tensor listing.
  • Model discovery across the complete local LM Studio model library; discovered GGUFs run through GopherLLM's own inference engine.
  • Direct Hugging Face GGUF imports with cache reuse, split-model downloads, private/gated-model tokens, and revision selection.
  • quantize / --compress: convert local GGUF weights to Q8_0/Q4_0/Q2_K/Q3_K/ Q4_K/Q5_K/Q6_K or mixed Q4_K_M/Q5_K_M presets, writing an independently loadable file (see Model Compression).
  • Native Laya and compatible ModernBERT/mmBERT decision checkpoints: Hugging Face downloads, choice/score/noul classification, and a Jev-style /v1/systemone API, CSV stdin/stdout filters and browser uploads, with no Python runtime (workflow and examples).
  • Native YOLOv8 and YOLO11 object detection from safetensors or Ultralytics .pt files, without an ONNX, PyTorch or Python runtime (see Object detection (YOLO)).
  • Local speech transcription with Parakeet-TDT GGUF or Fermion Research’s multilingual Phonon 2.5, through the CLI and the audio transcription API. Model setup and commands.
  • Native Whisper transcription of 16 kHz clips with GGML F16/F32 weights. CLI and Go usage.
  • Gopher Voice demo for local spoken conversations with Ministral and Phonon, Voxtral or Whisper.
  • Native German MMS/VITS speech synthesis to WAV, Qwen-Image-2.1/Turbo and experimental FLUX 3 Image Klein text-to-image generation to PNG (including the Web UI with --image-model-dir), and unconditional CIFAR-10 diffusion. Image editing and video generation are not yet implemented (setup, limitations and examples).

Tested models

Recorded checkpoint tests through 2026-10-31. Each entry links to its evidence; the final table identifies component and synthetic-reference coverage. The broader architecture list describes implementation support rather than a successful run of every pretrained checkpoint. Results apply to the recorded formats, backends and workloads.

Text generation
Model Tested weights Upstream Recorded validation
Ministral 3 3B Instruct 2512 Q4_K_M Mistral AI · @mistralai Complete Metal chat requests and token/state parity; 64-token generation, RSS and paging
Ministral 3 14B Reasoning 2512 Q4_K_M Mistral AI · @mistralai 64-token generation, RSS and paging, plus fixed-input decoder parity through 415 positions
Qwen 4B Q8_0 Qwen / Alibaba · @QwenLM Complete serial/prompt-lookup generation comparisons; the historical record does not identify the checkpoint revision
Qwen3.5-4B with native MTP Q4_K_M, prithivMLmods conversion Qwen / Alibaba · @QwenLM Paired complete generation with identical tokens, using the linked pinned GGUF
Qwen3.8-27B Q4_K_M, qwen35 architecture Qwen / Alibaba · @QwenLM Complete prefill/decode requests and live-state parity
Ornith-1.0-35B Q4_K_M Ornith / DeepReinforce 64-token generation comparisons and all 40 routed FFNs checked with CPU/Metal loading
Gemma 4 E2B-it Q4_K_M Google DeepMind · @google-deepmind Complete generation, output/state parity and packed lookup-table checks
Gemma 4 26B-A4B-it Q4_K_M Google DeepMind · @google-deepmind Complete generation and fixed-input vocabulary-selection parity
Embeddings, classification, speech and images
Model Task Upstream Recorded validation
Granite Embedding 278m Multilingual, Q4_K_M Embeddings / retrieval IBM Granite · @ibm-granite Source-GGUF/Core ML comparisons and a multilingual retrieval fixture
Laya English, convaiinnovations/laya Structured classification Convai Innovations · @NandhaKishorM Pretrained tokenizer/decision outputs compared with the upstream CPU reference
Laya Multilingual, convaiinnovations/laya subfolder multilingual Multilingual classification Convai Innovations · @NandhaKishorM Download → native German classification, upstream output comparison and offline cache reuse
Parakeet-TDT-0.6B-v3, Q8_0 Speech-to-text NVIDIA · @NVIDIA Complete transcription of a 3.61-second clip; repeated text, token and encoder-output parity
facebook/mms-tts-deu, F32 German text-to-speech Meta / FAIR · @facebookresearch Full-checkpoint waveform comparison with PyTorch and native WAV generation
google/ddpm-cifar10-32, F32 Unconditional 32×32 image generation Google checkpoint; DDPM authors Full-checkpoint UNet and complete DDIM sampling compared with Diffusers
Qwen-Image-2.1-Turbo, Q8_0 matrices Text-to-image Qwen / Alibaba · @QwenLM Pretrained 64×64 and 256×256 PNG generation, visual inspection and recorded hashes
FLUX 3 Image Klein distilled, Q8_0 matrices Text-to-image Black Forest Labs · @black-forest-labs Pretrained 256×256 generation, 16 steps, seed 42: 103.21 s including loading, 6.89 GiB maximum RSS

The timing and RSS above describe one M2 Max run, not a speed guarantee or a swap-free memory budget. The linked reports retain workload, hardware and paging limitations. FLUX's generated image and raw measurements are included; its downloaded weights remain outside Git.

Component and reference coverage
Model / graph Upstream Scope of successful checks
Voxtral Mini 4B Realtime 2602, Q6_K GGUF Mistral AI · @mistralai Full checkpoint loading, real Metal decoder, RSS and paging, streaming encoder layer with real weights, and frontend/decoder fixtures; no complete transcription accuracy or latency measurement
Qwen3-VL-4B-Instruct Qwen / Alibaba · @QwenLM First 32 text layers and eight intermediate states exercised inside pretrained FLUX generation; no standalone vision-language evaluation
Qwen-Image-2.1 base Qwen / Alibaba · @QwenLM Shared component references and base scheduler checks; no pretrained base image run recorded
FLUX 3 Image Klein Base Black Forest Labs · @black-forest-labs Synthetic official-reference DiT and complete CFG pipelines; no pretrained base generation recorded
YOLOv8 / YOLO11 Ultralytics · @ultralytics Synthetic checkpoint loading, forward/detection and numerical-reference tests; .pt loading tests cover the supported tensor layouts

Requirements

  • Go 1.25 or newer.
  • A GGUF model for text generation; other modalities use the checkpoints described in their guides. By default the text-model tool scans:
~/.cache/lm-studio/models

This is only a default location for model files. LM Studio and Ollama are not required; GopherLLM loads the GGUF files and performs inference itself.

That default is resolved in this order: the --model-dir <path> flag (highest priority), then the GOPHERLLM_MODEL_DIR environment variable (with RUSTY_LLM_MODEL_DIR, the project's pre-rename spelling, still honored as a deprecated fallback), then the built-in default above. MODEL_DIR is a separate thing: it's a Makefile variable (see Make Targets) that make targets use to fill in --model-dir for you — it isn't read by the gopherllm binary itself, so MODEL_DIR=... bin/gopherllm ... (without make) has no effect.

Dependency policy and layout

The checked-in Go module intentionally has no third-party dependencies: its go.mod contains only this module and the Go version, and make deps-check enforces that policy.

The module-root Go files form the public gopherllm facade, preserving the stable import path github.com/SimonWaldherr/GopherLLM. Model loading, inference, kernels, assembly and their tests live in internal/engine/. Type aliases retain the engine's method sets and avoid copying model state; forwarding functions are regenerated with go generate . after API changes. Architecture-specific dispatch and assembly stay together there. Executable entry points live in cmd/, the embedding surface for other languages in mobile/ and bindings/, implementation details in internal/, and test-only fixtures in testdata/. Public-boundary and opt-in local model tests live in integration/. Build output and local model/RAG data are ignored and are not part of the repository. docs/PROJECT_STRUCTURE.md has the full directory map.

The optional demo application is documented separately in server/README.md.

Quickstart

make build                                    # -> bin/gopherllm
bin/gopherllm --model-dir /path/to/models --list-models
bin/gopherllm --model-dir /path/to/models --model "some-model" \
  --prompt "Explain local LLM inference in three sentences." --max-tokens 128

You can also pass an absolute .gguf path directly:

bin/gopherllm /path/to/model.gguf \
  --prompt "Explain local LLM inference in three sentences." \
  --max-tokens 128

Or, with make filling in the CLI flags for you:

make build
make list-models MODEL_DIR=/path/to/models
make run MODEL_DIR=/path/to/models MODEL="some-model" PROMPT="Explain local LLM inference in three sentences."
Reproducible configuration

For repeatable local runs or deployments, pass one explicit JSON file with --config. Precedence is built-in defaults and environment defaults → config file → CLI flags. The file is strict: unknown fields and unsupported schema versions fail early instead of being silently ignored. It is never discovered automatically, and it contains no access tokens.

{
  "version": 1,
  "preset": "precise",
  "model": "hf:bartowski/Qwen3-4B-GGUF:Q4_K_M@main",
  "model_dir": "/path/to/models",
  "generation": {
    "max_tokens": 384,
    "temperature": 0.25,
    "top_p": 0.9,
    "stop": ["<|end_of_text|>"],
    "context_window_mode": "recent"
  },
  "runtime": {
    "threads": 8,
    "prepare_quant": true,
    "timeout": "2m"
  },
  "huggingface": {"offline": true}
}
bin/gopherllm --config ./gopherllm.json
bin/gopherllm --config ./gopherllm.json --temp 0.4 --prompt "Summarize this."
bin/gopherllm --config ./gopherllm.json --print-config

balanced is the default sampler preset; precise, creative, and deterministic offer deliberate starting points. A preset is applied before explicit generation values, so a config or CLI --temp/--top-p setting can always fine-tune it. --print-config emits a reusable effective config and never prints HF_TOKEN or a transient user prompt.

context_window_mode (or --context-window) is full by default, which returns a context-limit error instead of dropping history. Choose recent to retain complete recent turns, or autoCompress to conservatively shorten older plain assistant prose only when the original prompt does not fit. Compression preserves user/system messages, the newest complete turn, tool/image payloads and formatted content; the same turn-preserving selection follows if needed.

Hugging Face imports

Use an hf: selector to download a GGUF directly. Add the quantization after the repository name when it contains more than one GGUF, and optionally add a branch, tag, or commit after @:

bin/gopherllm hf:bartowski/Qwen3-4B-GGUF:Q4_K_M --repl
bin/gopherllm hf:bartowski/Qwen3-4B-GGUF:Q4_K_M@main \
  --prompt "Explain local inference." --max-tokens 128

Explore a repository first when you do not know its available quantizations:

bin/gopherllm --hf-list bartowski/Qwen3-4B-GGUF

The output includes each selectable quantization, its total download size, the number of GGUF shards, and a ready-to-run hf: selector. Downloads show progress and resume from a saved partial blob after an interrupted transfer. Split-model downloads use a bounded three-worker pool; pressing Ctrl-C cancels repository requests and active transfers through Go contexts while retaining the partial blobs for a later resume.

Downloads, including every shard of split GGUFs, use the shared Hugging Face blobs/refs/snapshots cache under $HF_HUB_CACHE, or $HF_HOME/hub (or the platform cache when HF_HOME is unset). Existing cached snapshots remain usable offline. Set HF_TOKEN for gated or private repositories.

For an auditable air-gapped run, add --hf-offline (including to --hf-list). It makes no HTTP request and accepts only a complete cached snapshot for the selected revision. GopherLLM also honors Hugging Face's shared HF_HUB_OFFLINE=1 setting, so Python tooling and GopherLLM follow the same network policy:

bin/gopherllm hf:bartowski/Qwen3-4B-GGUF:Q4_K_M@main --hf-offline --repl
HF_HUB_OFFLINE=1 bin/gopherllm --hf-list bartowski/Qwen3-4B-GGUF@main
Text, audio, vision and other model artifacts

In the Web UI's Download a model section, choose a Task and a Format. GGUF mode offers quantization variants; ambiguous names (for example a model and vision projector both using F16) use exact file selectors. The filename and projector role are displayed alongside the quantization. All files / formats, Safetensors and ONNX enable repository file selection, including nested weights, tokenizer files, processor configuration, weight indexes and other assets. Select every required shard and companion file; the client does not guess which of several architectures or exports you intend to use. These selections are saved in the HF cache, preserving directory structure. They are not automatically loaded into the GGUF model library.

The public Go API provides the same model-independent operations:

opts := huggingface.DefaultOptions()
models, err := huggingface.SearchModels(ctx, huggingface.SearchOptions{
    Query: "voxtral", PipelineTag: "automatic-speech-recognition",
    // Format: "safetensors", // omit to search every format
}, opts)
if err != nil { return err }
_ = models

manifest, err := huggingface.Inspect(ctx, "owner/repository@main", opts)
if err != nil { return err }
_ = manifest // present Files and select exact paths from this inventory

files, err := huggingface.DownloadFiles(ctx, "owner/repository@main",
    []string{"config.json", "tokenizer.json", "model.safetensors"},
    os.Stderr, opts)
if err != nil { return err }
_ = files // local paths; use an appropriate runtime separately

Inspect returns file size, format and a filename-based role hint. Hub pipeline_tag and library metadata describe intended use, not runtime compatibility. Downloading Safetensors, ONNX, speech or vision artifacts does not add execution support for their architectures. Repository code is never executed. Existing Search, Variants, Resolve and ResolveFiles retain their GGUF-specific contracts.

Transfers pin to the commit reported by the Hub, share bounded download workers, validate resume ranges and publish the revision reference after the requested set completes. Mirrors that omit the commit header retain revision-based resolution. Offline Inspect lists only locally available files; offline DownloadFiles requires every explicitly selected file. The client coordinates concurrent writers to identical blobs within one process; this is not a cross-process cache lock.

For API consumers, /models/search accepts task and format (gguf, all, safetensors, onnx; default gguf). /models/download/variants?ref=owner/repo&artifacts=1 returns the file inventory. POST /models/download with {"ref":"owner/repo","files":["config.json"]} uses the existing NDJSON progress stream and finishes with artifacts: true and local files. These operations retain the existing administrator and model-download feature controls.

The integration belongs in GopherLLM's opt-in huggingface package so tinyRAG and other applications can reuse it without implementing another downloader. The root inference package continues to have no HTTP dependency. Hub task/filter semantics follow the Hugging Face API documentation.

Object detection (YOLO)

GopherLLM runs Ultralytics YOLOv8 and YOLO11 detection networks natively in Go (Accelerate BLAS on macOS), with no ONNX, PyTorch or Python. No weights are bundled. They come from one of three places:

  • A stock name is fetched once from Hugging Face and then reused from the HF cache, including offline. yolo11n … yolo11x come from Ultralytics' own Ultralytics/YOLO11, and yolov8n … yolov8x from lmz/candle-yolo-v8. Both are pinned to a fixed commit.
  • An Ultralytics .pt file (yolo11n.pt, yolov8s.pt, or your own best.pt from training) loads directly.
  • A safetensors file loads directly, in candle or Ultralytics tensor naming, as F32, F16 or BF16.
go run ./cmd/yolo-detect --image street.jpg --out boxes.png    # yolo11n, the default
go run ./cmd/yolo-detect --model yolov8s --image street.jpg --json
go run ./cmd/yolo-detect --model runs/detect/train/weights/best.pt --image part.jpg
go run ./cmd/yolo-detect --model hf:owner/repo:best.safetensors --image x.jpg --offline

The generation, model size, class count and head layout are read from the checkpoint itself. A custom-trained model therefore loads the same way as a stock one, and a .pt file brings its own class names. For safetensors files, pass --labels with one name per line; 80-class models default to the COCO names.

Images are letterboxed with the same bilinear resize and 114-grey padding Ultralytics uses, so confidences match the reference implementation. On an M-series Mac, one 640×640 image takes about 60 ms with yolov8n or yolo11n using Accelerate, and about 150 ms in pure Go (CGO_ENABLED=0).

.pt safety. A .pt file is a Python pickle, and pickle.load on an untrusted file is remote code execution. GopherLLM never runs pickle code. It interprets the opcodes as data and rebuilds only tensors, dicts and lists; every class or function the file names stays an inert value. See internal/vision/yolo/torch_checkpoint.go.

From Go, the root package stays offline. YOLOCheckpointReference only builds the pinned hf: reference for a stock name; downloading is left to the huggingface package, as cmd/yolo-detect shows:

model, err := gopherllm.LoadYOLO("yolo11n.pt") // or a .safetensors file
if err != nil { return err }
dets, err := model.Detect(img, gopherllm.DefaultYOLOConfig())
// dets[i].Label, .Confidence, .Box (source-image pixels); model.Version

A loaded model is safe for concurrent Detect calls. The server exposes the same detector as GET /models/detection and POST /v1/vision/detections (see server/README.md). Pose, segmentation, OBB and YOLO26 are not supported yet.

License: the Ultralytics weights (including the lmz/candle-yolo-v8 copies) are licensed AGPL-3.0. GopherLLM does not redistribute them; whoever downloads and uses them is bound by that license.

Use as a Go Library

GopherLLM is an importable module — inference runs in-process, with no child process and no HTTP round-trips:

go get github.com/SimonWaldherr/GopherLLM
import gopherllm "github.com/SimonWaldherr/GopherLLM"

model, err := gopherllm.Open(ctx, "model.gguf")
if err != nil { ... }
defer model.Close()

// Don't have a .gguf yet? huggingface.Resolve turns an "owner/repo" Hugging
// Face reference into a local path (see "Hugging Face imports" below); Open
// itself only understands local paths, and its error says so when a path
// looks like an unresolved Hub reference instead of a typo'd local file.

// One-shot generation with functional options.
res, err := model.Generate(ctx, "Explain GGUF in one sentence.",
    gopherllm.WithMaxTokens(128), gopherllm.WithTemperature(0.7))
fmt.Println(res.Text)

// Streaming (ctx cancels cleanly between tokens).
model.Stream(ctx, []gopherllm.ChatMessage{gopherllm.UserMessage("hi")},
    func(delta string) error { fmt.Print(delta); return nil })

// Embeddings, tokenization, GGUF analysis:
emb, _ := model.Embed(ctx, "semantic search query")
ids := model.Tokenize("hello")
gopherllm.AnalyzeGGUF(model.GGUF(), model.Tokenizer()).WriteText(os.Stdout)
Apple Neural Engine embeddings

The optional coreml package runs a separate embedding encoder with CPU and Neural Engine permission, leaving the GPU available to the chat model. It loads one compiled model and reuses its input arrays and output backing. It does not allocate a chat KV cache or load a second GGUF Runner. Build your application with CGO_ENABLED=1 go build -tags 'metal coreml'. The backend requires macOS 13/iOS 16 or newer; other builds return coreml.ErrUnavailable.

Export a local BERT embedding GGUF once, using Python 3.12 and the optional conversion dependencies. The exporter uses static shapes, FP16, BC1S tensors, 1×1 convolutions and separate attention heads following Apple's ANE transformer guidance. It supports mean and CLS pooling; Nomic/RoPE and chat decoder graphs are not supported by this exporter. FP16 exports can be larger than their Q4 sources.

python3.12 -m venv .venv-coreml
.venv-coreml/bin/python -m pip install 'coremltools>=9,<10' 'gguf>=0.19,<0.20'
.venv-coreml/bin/python scripts/export_coreml_embeddings.py encoder.gguf encoder.mlpackage \
  --sequence-length 128 --compile-to encoder.mlmodelc

Keep the compiled .mlmodelc at a stable path and keep the embedder open across requests, so loading and specialization stay outside the prediction path. For document indexing, --batch-size 2, 4 or 8 exports a fixed batch that shares one set of encoder weights across several texts. EmbedBatch groups inputs automatically, reuses bounded scratch and discards unused tail outputs. The default is one text per prediction, suitable for individual search queries. Larger exports can improve bulk throughput but also increase scratch and single-query latency; compare them on the target Mac before choosing one. For CLS-pooling encoders, --prune-cls omits the unused final-layer query and feed-forward positions while retaining keys and values for every input token. Optional --weight-compression palette8 stores only convolution weights in 256-entry palettes. Vocabulary embeddings, biases and normalization parameters remain FP16, as does model computation. Compression slightly changes vectors; use a new EmbedderID and check retrieval on the intended corpus. The default keeps FP16 weights and the complete final layer. Use the exact source checkpoint's tokenizer, including its boundary tokens:

import (
    "github.com/SimonWaldherr/GopherLLM/coreml"
    "github.com/SimonWaldherr/GopherLLM/rag"
)

tok, err := coreml.LoadTokenizer("encoder.gguf") // metadata only; no retained weights
if err != nil { return err }
encoder, err := coreml.OpenEmbedder("encoder.mlmodelc", tok, coreml.Options{PadToken: tok.PadToken})
if err != nil { return err }
defer encoder.Close()
chunks := rag.Chunker{Tokenizer: tok.Tokenizer,
    MaxRunes: encoder.Info().SequenceLength - len(tok.Encode("")), OverlapRunes: 8}
index := rag.New(rag.Options{Embedder: encoder, EmbedderID: "encoder-coreml-fp16-s128-v1", Chunker: chunks})
if err := index.Add(ctx, rag.Doc{ID: "note", Text: "The processor executes the program's instructions."}); err != nil {
    return err
}
// index.Search uses this encoder without disturbing a chat Runner.

server.HandlerOptions and ServeOptions accept the same caller-owned encoder through RAGEmbedder, RAGEmbedderID and RAGChunker. Close it after the handler stops. Change the ID when the model, tokenizer or embedding conventions change. Inputs exceeding the model's fixed sequence length fail explicitly; reserve tokens for boundaries and any document/query prefixes when chunking.

CPUAndNeuralEngine permits CPU fallback. coreml.Inspect(path, units) reports the preferred devices in Core ML's compute plan on macOS 14.4/iOS 17.4 or newer; these counts describe planned placement, not observed utilization or time share. On the M2 Max, CLS pruning plus palette8 reduced warm Granite Embedding 278m single-query latency from 3.18 to 1.75–1.77 ms at a 64-token capacity. Minimum source-GGUF cosine was 0.9998955; the small multilingual retrieval fixture retained every source Top-1 hit and Top-3 neighbour set. These encoder measurements exclude model loading and do not establish faster chat decoding. The benchmark methodology and results include CPU/ANE comparisons, batch sizes, compression, memory limits and raw data. M4 throughput has not been measured.

To repeat the encoder parity, compute-plan and warm-latency checks with the exported model:

GOPHERLLM_COREML_MODEL="$PWD/encoder.mlmodelc" GOPHERLLM_COREML_GGUF="$PWD/encoder.gguf" \
  CGO_ENABLED=1 go test -tags 'metal coreml' ./coreml -run '^TestCoreMLConfiguredEmbeddings$' -count=1 -v

To compare exports with different batch sizes, set GOPHERLLM_COREML_BATCH_MODELS to their colon-separated paths and run TestCoreMLBatchComparison instead. It checks source-GGUF parity and reports warm latency for 1, 4, 17 and 32 texts, loading one native model at a time. Repeat in reverse model order when other applications are active.

Core ML prefill for Qwen and Ministral

An optional FFN exporter and runtime can execute selected dense Qwen/Ministral SwiGLU blocks through Core ML during ordinary prefill. It reuses native buffers and checks source hashes, embedded graph metadata and numerical parity before attaching an export. Complete Metal prefill chunks retain priority; decode, speculative verification and Qwen MTP prefill retain their current arithmetic. Build with -tags 'metal coreml' and enable exports explicitly through Runner.SetCoreMLFFN.

CoreMLFFNOptions{AutoTune: true, LogWriter: os.Stderr} optionally compares CPU-only and CPU/Neural Engine execution for each export at attachment time. Each candidate must pass the source quality probe to be eligible. When both are valid, CPU-only replaces the default after two measurements show at least 10% lower latency. Calibrate on an otherwise idle machine. This adds startup work and keeps the GPU available to Metal.

This adds separately compiled weights and is not a RAM-saving setting. Benchmark the actual prompt/model before enabling it; layer timings do not establish an end-to-end generation speedup.

Tools with a Go function

gopherllm.NewTool derives a tool's JSON Schema from a plain Go struct by reflection, so a function is a tool with no schema string to keep in sync:

type WeatherArgs struct {
    City string `json:"city" desc:"City name, e.g. Hamburg"`
    Unit string `json:"unit,omitempty" desc:"Temperature unit" enum:"c,f"`
}

weather := gopherllm.NewTool("get_weather", "Current weather for a city.",
    func(ctx context.Context, a WeatherArgs) (string, error) {
        return fmt.Sprintf("22 degrees in %s", a.City), nil
    })
weather.Trusted = true // first-party data, skip the injection-warning wrapper

// RunAgenticChatWithTools predates the GenOption veneer and takes a plain
// GenerationOptions; ApplyGenOptions builds one the same way Model's own
// methods do, ctx included — that's what makes the loop's per-call tool
// timeouts and generation itself actually cancel with ctx, easy to forget
// since every other Model method takes ctx as a plain first argument instead.
options := gopherllm.ApplyGenOptions(ctx, gopherllm.WithTemperature(0.2))

result, err := gopherllm.RunAgenticChatWithTools(model.Runner(),
    []gopherllm.ChatMessage{gopherllm.UserMessage("Weather in Hamburg?")},
    options, nil, []gopherllm.AgenticTool{weather},
    func(s string) bool { fmt.Print(s); return true })

Prefer a *Model you already own, tools with retrieval, or citations? The agent package wraps this same loop into Agent.Ask/Chat with a validated ToolSet and deduplicated sources.

The agent loop that executes a tool call bounds it with a per-call timeout (default 30s), recovers a panic as a failed call instead of crashing the process, caps and marks a truncated result before it reaches the model, and replays an identical (name, arguments) call from an earlier round instead of re-executing it — all opt-out-able per AgenticTool field (gopherllm.NoToolTimeout, gopherllm.NoToolResultLimit). See AgenticTool's doc comment for the full contract.

Compile-time note: AgenticTool gained the Timeout, MaxResultBytes and Trusted fields above. Every construction site in this repository already used field names (AgenticTool{Definition: ..., Execute: ...}), so this is a no-op here — but an unkeyed literal (AgenticTool{def, exec}) outside this repo will now fail to compile. Add the field names.

examples/tool-calling is this pattern as a complete, runnable program (go run ./examples/tool-calling -model /path/to/model.gguf) with a real arithmetic tool instead of a fake string, so the output is self-verifying.

Retrieval over your own documents

rag.Index is a hybrid BM25 + optional-vector index — a chunker, an inverted keyword index, and (when you supply an Embedder) a cosine-similarity scan — with no database and no third-party dependency:

import "github.com/SimonWaldherr/GopherLLM/rag"

ix := rag.New(rag.Options{}) // pure BM25; add Embedder: model for hybrid search
if err := ix.Add(ctx, rag.Doc{ID: "handbook", Title: "Employee Handbook", Text: handbookText}); err != nil {
    return err
}
hits, err := ix.Search(ctx, "return window for GX-1180", rag.Query{TopK: 3})
for _, h := range hits {
    fmt.Printf("%s (score %.2f): %s\n", h.Title, h.Score, h.Text)
}

BM25 alone already wins the queries people actually type at their own documents — part numbers, error codes, invoice ids, surnames — which a chat model's mean-pooled hidden states (not a trained embedding head) tend to lose; see rag.Options.Embedder's doc comment before wiring one up. Index.Save/rag.Load persist a built index so a second run skips re-embedding. The bundled server adds runtime ingestion for pasted text, multi-file and ZIP uploads, and public web URLs (with clean full-article imports for Wikipedia), plus an interactive retrieval preview; see Knowledge base search. See the rag package documentation for chunking, ranking weights, and directory ingestion via Index.AddFS.

Speculative decoding

Greedy generation can propose a short continuation and let the target model verify it in one block. A block contains 2–8 target inputs, including the already-emitted seed, so it accepts at most seven draft candidates. An entirely accepted block also supplies the next target prediction. Stop tokens, stop strings, repetition penalties and cancellation retain their ordinary semantics.

Prompt lookup proposes known continuations of repeated 4–64-token suffixes in the most recent 8192 prompt/output tokens. Enable it explicitly with --prompt-lookup-tokens 7, WithPromptLookupTokens(7), or the JSON configuration field generation.prompt_lookup_tokens. Values are 0–7; zero disables it. For example:

bin/gopherllm model.gguf --temp 0 --repeat-penalty 1 --prompt-lookup-tokens 7 \
  --prompt 'Continue this repeated code pattern...'
res, err := model.Generate(ctx, prompt,
    gopherllm.WithTemperature(0), gopherllm.WithRepeatPenalty(1),
    gopherllm.WithPromptLookupTokens(7))

These copying examples disable repetition penalties because intentional reuse is the task. Repetition penalties remain supported; keep the application's sampling settings unchanged when comparing performance.

Qwen GGUFs with a loaded NextN head can also use --mtp-draft-tokens N or WithMTPDraftTokens(N). Both methods require deterministic sampling (--temp 0 or --top-k 1) and are incompatible with JSON-object constrained output. When both are enabled, a prompt-lookup hit takes precedence; a miss falls back to MTP. Every proposed token is checked against the target's own greedy choice. Both options are off by default.

Each request starts at the second available window, usually three candidates, and adjusts among 1/3/7 drafts plus an exact smaller user cap. Including the seed, the regular windows fill 2/4/8 target positions. Selection uses acceptance and elapsed draft, verification and reconciliation cost per emitted token. Measurements are discarded after generation. A slow four-position block with at least 85% draft acceptance can test one previously unmeasured larger window before shrinking; its measured cost decides whether to retain it. Two completely rejected blocks shrink the window early, independently of cold kernel timings. If the one-candidate window accepts fewer than half its proposals or costs over 10% more than measured serial decoding, drafting pauses for twelve serial steps before retrying. Eligible dense Metal transformers share unpacked weights across the short block's positions in registers, with the body, vocabulary projection and position-specific token reductions in one command buffer. Dense CPU vocabulary projections reuse weight rows across four to eight positions. Qwen hybrids batch target projections while keeping DeltaNet updates chronological. On rejection, up to 32 MiB of retained projection inputs avoid repeating the large target projections when restoring the accepted recurrent prefix. The MTP head batches catch-up from known target states, including prefill. Catch-up computes only embedding/hidden mixing and K/V: attention output, Q, O, FFN and vocabulary projections are unused because the next boundary comes from the target model. Eligible dense Metal hybrids batch FFNs, CPU-Q8 DeltaNet input/output projections and direct Q6_K QKV projections. Single-token and batched FFNs use the same GPU reduction order; attention and recurrent updates retain their chronological CPU/Metal schedule. Contracting Q6_K FFN down projections can be fused from 2048 rows, while standalone matvec thresholds stay unchanged. This dense path supports F32, F16 and I8 KV. MoE, out-of-core and unsupported accelerator-backed Qwen graphs retain serial MTP. Quantized CPU Qwen projections also retain it when Q8 activations are disabled. For drafting, sufficiently large prepared Q/O and fused FFN matrices can stay on Metal. The MTP input mixing and K/V remain on the CPU so drafting and cache catch-up keep the same K/V arithmetic. WebGPU projection views retain full-body catch-up. Set GOPHERLLM_NO_BLOCK_VERIFY=1 to compare against serial target verification.

GenerationResult.Stats.Speculation reports Blocks, DraftedTokens, AcceptedTokens, DiscardedInputs, DraftTime, VerificationTime and ReconcileTime. Discarded inputs are tentative target rows excluded from the resident prefix, including work undone on cancellation. The field is nil when drafting is disabled; serial fallback leaves Blocks at zero. Measure total decode time and accepted tokens on the intended model and hardware before assuming a throughput gain.

On M2 Max with eight CPU threads and Metal, a 128-token record-copying task produced exactly the same token IDs with serial decoding and prompt lookup. Five measured rounds alternated execution order after one warmup per mode; prompt caches were cleared between requests. Greedy sampling used repeat penalty 1. Median times were:

Model Serial decode Lookup decode Serial total Lookup total
Ministral-3B Q4_K_M 2.196 s 1.427 s 2.955 s 2.183 s
Qwen-4B Q8_0 2.427 s 2.140 s 3.160 s 2.888 s

These gains depend on reusable text. A code-editing task with few accepted proposals remained slower, so speculation remains opt-in. The record-copying results measure prompt lookup; neither checkpoint contains a native MTP head.

The same 128-token copying task also measured native MTP on Qwen3.5-4B-MTP Q4_K_M. With --mtp-draft-tokens 7, five alternating pairs after warmup produced identical tokens. Median decode time fell from 6.628 s to 6.107 s (7.9% less time), and total request time from 13.540 s to 12.847 s (5.1% less time). Decode was faster in all five pairs; total time was faster in four. Both modes used the same default Metal FFN kernels, eight CPU threads and cleared prompt caches. This is workload-dependent: separate three-pair code-editing runs with one or three MTP candidates took about 3% and 9% longer to decode than serial.

TestSpeculationConfiguredGenerationAB repeats the paired copy/code comparison when GOPHERLLM_SPEC_AB_MODEL points to a local GGUF. Set GOPHERLLM_SPEC_AB_METAL=1, GOPHERLLM_SPEC_AB_MAX_TOKENS=128 and build with -tags metal; GOPHERLLM_SPEC_AB_MODES selects lookup7, mtp1, mtp3, mtp7 or combinations such as lookup7_mtp3. GOPHERLLM_SPEC_AB_SAMPLES=5 and GOPHERLLM_SPEC_AB_WARMUPS=1 select the rounds above; GOPHERLLM_SPEC_AB_WORKLOAD=copy selects the copying task; GOPHERLLM_SPEC_AB_JSON saves samples and medians. The separate TestSpeculationConfiguredFullMTPBounded accepts a complete Qwen hybrid model through GOPHERLLM_SPEC_AB_RAW_MODEL for a bounded MTP parity/performance check.

TestSpeculativeConfiguredModelParity provides a shorter parity check when GOPHERLLM_VALIDATE_MODEL points to a local dense GGUF; set GOPHERLLM_VALIDATE_METAL=1 and build with -tags metal to require the GPU.

Repeated Mistral chat prefixes

For a Ministral/Mistral application that repeatedly renders the same system prompt and tool schema (especially with PrepareChatContext), opt into the small, per-model render cache:

runner := model.Runner()
runner.EnableMistralPromptPrefixCache(8 << 20) // 8 MiB; 0 selects this default
defer runner.DisableMistralPromptPrefixCache()

// Optional explicit boundary when rotating sensitive system instructions.
runner.ClearMistralPromptPrefixCache()

It retains only tokenized BOS/system/tool-prefix text; message content, image embeddings, logits, and KV state are not stored by this cache. The normal generation KV-prefix cache remains independent.

The separate opt-in EnableMistralKVPrefixCache snapshot cache does not trigger another static-prefix render while disabled. Its invalidation epoch is captured before prompt rendering, so a concurrent clear cannot be undone by that request's later snapshot store.

Reusing conversations

A Runner reuses exact token prefixes in its live KV workspace. For standard attention-only models and Gemma, it also retains up to four displaced text conversations, capped at 128 MiB of KV snapshots and token IDs, so returning to an earlier chat can skip its already processed prefix. Historical snapshots require at least 32 matching tokens and compatible KV storage. Recurrent models, MLA, image-bearing requests, and out-of-core execution keep their existing paths.

runner.SetConversationCacheLimit(64 << 20) // optional smaller history budget
runner.SetConversationCacheLimit(0)       // disable history; keep live prefix reuse
runner.ClearConversationCache()          // clear history and resident reuse metadata

The history budget is additional to the live workspace.

Package layout

The root package is inference only. Its import closure excludes the optional demo application and its UI assets:

Import You get
github.com/SimonWaldherr/GopherLLM GGUF loading, generation, chat, embeddings, tokenizer, sampling, autotuning, skills/agent loop
github.com/SimonWaldherr/GopherLLM/rag Document chunking, hybrid BM25 + vector retrieval
github.com/SimonWaldherr/GopherLLM/huggingface Model/task search, artifact inspection/download, and local GGUF resolution

TestInferencePackageStaysFreeOfServerDependencies enforces that boundary against the real dependency graph, so it cannot regress silently.

Dependencies are standard-library packages and packages within this module; there is no require block, go.sum or vendor directory. The exact count depends on the Go version and build tags. Stdlib is not the same as free, since an embedder compiles every package in the closure. The root package therefore avoids crypto/sha256 and regexp, each of which cost far more than its single use was worth, and TestInferencePackageStaysFreeOfTheCryptoAndRegexpTrees pins that.

The PNG and JPEG decoders are the remaining optional chunk. Vision needs them, so they are a build-time knob rather than a removal:

go build -tags noimagedecoders ./...

That drops image/png and image/jpeg along with compress/zlib, compress/flate, hash/adler32 and hash/crc32. The public API is unchanged either way — image.Image stays in DecodeImageBytes' and PreprocessImagePixtral's signatures — and so is the default build; what the tag costs is PNG and JPEG input to the vision path. Because Go's image-format registry is process-global, a program built with the tag can take back just the formats it wants with its own import _ "image/png".

Hub access is a separate import for the same reason: it needs net/http, which drags in crypto/tls and the HTTP/2 stack. A program that only ever opens a local file never pays for that, and one that wants hf:owner/repo resolution opts in explicitly:

path, err := huggingface.Resolve(ctx, "hf:owner/repo:model-Q4_K_M.gguf", os.Stderr, huggingface.DefaultOptions())
if err != nil {
    return err
}
model, err := gopherllm.Open(ctx, path)

Models already pulled with Ollama need no download at all — they are ordinary GGUF blobs in a content-addressed store, so DiscoverOllamaModels reads them in place, keyed by the same name:tag you would pass to ollama run:

entries, err := gopherllm.DiscoverOllamaModelsDefault(os.Stderr)

--list-models includes them automatically. Set OLLAMA_MODELS when the store is not at ~/.ollama/models. This lets an embedder reuse existing local model files without another download.

The library never writes to stdout/stderr on its own; pass gopherllm.WithLogWriter(os.Stderr) to opt into diagnostics. Tool calling, reasoning extraction, and agentic runs are available via WithTools, Result.ReasoningText, and RunAgenticChat; see the godoc and runnable examples in example_test.go. testdata/consumer is a complete external application using the API.

Build

make build

The binary is written to bin/gopherllm.

To run formatting, tests, vet, and the release build:

make all

To verify release builds for macOS, Linux, and Windows on amd64 and arm64:

make cross-build

On sandboxed macOS shells, /usr/bin/make may print xcrun_db-* cache warnings before the Makefile can set its build environment. Use the Command Line Tools make directly if that happens:

/Library/Developer/CommandLineTools/usr/bin/make build-metal

Serving and safety defaults

--serve starts the HTTP API; --chat adds the browser workspace at /chat.

bin/gopherllm --model-dir /path/to/models --serve --chat

Two defaults are deliberate.

It listens on loopback. --serve without an address binds 127.0.0.1:8080, so nothing outside the machine can reach it. Giving it a network address is allowed — sharing a model with a phone or a second machine is a reasonable thing to want — but it prints what that exposes, and a local deployment reached that way switches its privileged routes off: model loading, downloads, autotune, remote forwarding, and OS commands all answer 403, because local mode has no token to check and "everyone on the subnet is an administrator" is not a boundary. Use --deployment managed with an admin token to keep those controls available on a shared server.

Optional capabilities are off. A server that nobody configured is a chat and completions server plus the model catalog for --model-dir. Anything that reaches the internet, rewrites process-wide state, or benchmarks the host has to be asked for by name:

--enable name Adds
model-download /models/search, /models/download (Hugging Face)
autotune /autotune, /autotune/run
remote /remote — forwards completions to another endpoint
web-lookup Wikimedia and OpenStreetMap tools for chat requests
spreadsheet /batch/parse for the batch runner
all Everything above (also spelled --full)
bin/gopherllm --model-dir /path/to/models --serve --chat --enable model-download,autotune

A capability that is off is not registered at all, so its route answers 404 rather than presenting a permission check, and the Web UI drops the panels for it instead of showing controls that cannot work. OS commands stay separate and off unless --os-commands sets a policy. The same set is available to library users through server.Features and server.AllFeatures(), and to config files under server.features.

The Web UI itself opens in a Simple mode that shows the handful of settings most people change; the Advanced toggle in the settings header reveals the rest. That choice is per browser and changes nothing on the server.

CLI Usage

List discovered GGUF models:

bin/gopherllm --model-dir "$HOME/.cache/lm-studio/models" --list-models

Run a prompt against a selected model:

bin/gopherllm --model-dir "$HOME/.cache/lm-studio/models" \
  --model "model-name-or-file-fragment" \
  --prompt "Explain local LLM inference in three sentences." \
  --max-tokens 128

Run a prompt against an exact GGUF file:

bin/gopherllm /path/to/model.gguf \
  --prompt "Explain local LLM inference in three sentences." \
  --max-tokens 128 \
  --temp 0.7

Start an interactive REPL:

bin/gopherllm --model-dir "$HOME/.cache/lm-studio/models" \
  --model "model-name-or-file-fragment" \
  --repl

Run with a local skill available (one-shot or REPL alike):

bin/gopherllm --model-dir "$HOME/.cache/lm-studio/models" \
  --model "model-name-or-file-fragment" \
  --skills-dir ./skills \
  --prompt "How do I fill out a PDF form on the command line?"

Inspect metadata without loading all weights:

bin/gopherllm /path/to/model.gguf --inspect --list-metadata

Create an embedding:

bin/gopherllm /path/to/model.gguf --embed --prompt "semantic search query"

GGUF Analyzer

Inspect any GGUF's structure without loading weights (instant, even on multi-gigabyte files):

bin/gopherllm /path/to/model.gguf --analyze

Reports architecture/geometry, parameter count, effective bits per weight, the quantization mix per tensor type, rope/sliding-window configuration, tokenizer + detected chat-template family, KV-cache size estimates, and the largest tensors.

Search the vocabulary:

bin/gopherllm /path/to/model.gguf --find-token "weather"

Explore embedding space — which tokens the model treats as related (this loads the weights and scans the embedding table):

bin/gopherllm /path/to/model.gguf --token-neighbors king --neighbors 8
#  34567  "King"      cos=0.5807
#  12566  " king"     cos=0.5079
#  108083 "キング"     cos=0.3692
#  25776  "王"         cos=0.3416

The same features are available in the library as AnalyzeGGUF, SearchTokens, and Model.NearestTokens.

Model Compression

Quantize a local GGUF with positional arguments, like llama-quantize:

bin/gopherllm quantize model-f16.gguf model-Q4_K_M.gguf Q4_K_M
# Optional: limit CPU workers
bin/gopherllm quantize model-f16.gguf model-Q5_K_M.gguf Q5_K_M --threads 8

Supported targets: Q8_0, Q4_0, Q2_K, Q3_K, Q4_K, Q4_K_M, Q5_K, Q5_K_M, and Q6_K. Float sources (F32, F16, BF16, F64) and supported quantized sources can be converted. Existing command-line flags remain available:

bin/gopherllm model-f16.gguf --compress --compress-format Q4_K_M --compress-out model-Q4_K_M.gguf

Q4_K_M and Q5_K_M are mixed tensor presets, rather than aliases for a single GGML type. They use Q4_K or Q5_K for most matrices and Q6_K for selected attention-value and FFN-down projections and the output head. A separate input embedding keeps the base type; a tied embedding receives the output-head upgrade. Small tensors, normalization weights, expert routers, and recurrent convolution kernels retain their source precision. The planner also accounts for MoE/hybrid layouts and uses Q5_0, Q5_1, Q8_0, or F16 when a matrix's row width cannot fit the selected block layout. This tensor policy follows llama.cpp's mixed presets.

The base targets retain the previous policy: quantize eligible matrices with compatible row widths, keep norm/bias vectors unchanged, and floor both token embeddings and output heads at Q6_K when the target is lower. Use --uniform with the subcommand, or --compress-uniform with the legacy flags, to disable that floor. Uniform mode cannot be combined with a mixed preset; choose its base type (Q4_K or Q5_K) instead.

Conversion streams row chunks with an 8 MiB shared float/output scratch budget, plus the writer buffer and one encoded row per active worker. A single oversized row is the minimum chunk. Entire MoE expert banks are never expanded into float32 at once. The source stays memory-mapped; normal OS page-cache usage is additional to this scratch budget.

Output is a normal, independently loadable GGUF, with updated file-type and quantization-version metadata and preserved tokenizer/model metadata. A sibling temporary file is flushed, closed, and its tensor descriptors and byte ranges verified before replacing the destination. Conversion errors or cancellation preserve an existing destination and remove the temporary file. Input and output must identify different files, including through symlinks or hardlinks. Split GGUF shards must be merged first.

The encoders use plain round-to-nearest (RTN), without calibration data or weighted error optimization. Matching a llama.cpp preset's tensor policy does not promise identical bytes, perplexity, or model quality. Evaluate the converted model on representative tasks before choosing a low-bit artifact. Q3_K and Q2_K reduce packed weight traffic relative to Q4_K by about 24% and 42%, respectively, with a larger quality trade-off. They use the CPU quantized kernels rather than the selective Q4_K/Q6_K Metal path; measure --bench-json on the deployment machine.

The library API is CompressModel(source, output, options). ParseCompressOptions("Q4_K_M") retains the mixed preset in CompressOptions.Preset; the older ParseCompressFormat returns only its base GGML type. Set CompressOptions.Context for cancellation.

LittleBit and LittleBit-2

GopherLLM runs native binary-factorized projections on dense Llama and Qwen3 text models. The bundled Go tool converts a trained checkpoint into a GGUF file that the main CLI can run directly.

go run ./cmd/gopherllm-convert-littlebit -in /path/to/checkpoint -out littlebit.gguf
go run ./cmd/gopherllm littlebit.gguf --prompt "Why is the sky blue?"

See the LittleBit guide for the GGUF schema, supported checkpoint layouts, Metal commands, validation and measurements.

Auto Mode (hardware autotuning)

--auto measures this model on this machine at startup and runs it with the fastest settings it can find, instead of trusting a default that was tuned on somebody else's hardware:

bin/gopherllm /path/to/model.gguf --auto --prompt "Explain local inference."
Auto-tuning mistral3 on amd64+avx2+f16c (12 CPUs)...
  q8-activations on
  threads        12
  oversubscribe  on (was off)
  kv-cache-f16   on
  verify: oversubscribe wins, 145.2 -> 132.9 ms/token
Auto: calibrated in 7.9s
  threads=12 q8-activations=true kv-f16=true oversubscribe=true prefill-chunk=128
  decode 145.2 -> 132.9 ms/token (1.09x)

The result is cached per model + hardware under the user cache directory, so only the first run pays for calibration. It applies to one-shot generation, --repl, and --bench.

Flag Effect
--auto Tune (or reuse a cached tuning) before generating
--auto-effort quick Decode knobs only, ~8s. Prefill samples cost a whole chunk of prompt processing, so they are skipped here
--auto-effort balanced Default. Adds prefill chunk tuning, ~1-2 min on a 3B model
--auto-effort thorough More interleaved rounds and a 2048-token probe context; minutes, but the most reliable on a noisy machine
--auto-refresh Re-measure and overwrite the cached result
--auto-json Print the full result — including every candidate's median — and exit
Makefile workflow

The generation, REPL, and model-benchmark targets accept AUTO=1, so the same cached tuning is used regardless of how the model is started:

# Fast first-pass calibration, then generate.
make run MODEL="my-model.gguf" AUTO=1 AUTO_EFFORT=quick

# Inspect the cached result (or force a fresh calibration) as JSON and exit.
make autotune MODEL="my-model.gguf"
make autotune MODEL="my-model.gguf" AUTO_REFRESH=1

AUTO_EFFORT accepts quick, balanced (the default), or thorough. AUTO_REFRESH=1 bypasses the cache. AUTO_JSON=1 can be used with any of those Make targets, but it prints the tuning report and exits before generation; make autotune is the convenient report-only target. run-auto and run-auto-metal are shortcuts for their corresponding command with AUTO=1.

The Runner tuner measures thread count, int8-activation matvec kernels, f16 KV, worker-dispatch oversubscription, prefill chunk size and eligible Metal decode scheduling. These settings reuse the loaded weights. The CLI can first compare CPU and Metal by loading each backend when --metal was not explicitly selected; that separate probe runs before Runner tuning. --prepare-quant remains an explicit load-time choice. The report records the active backend and prepared state, and both are part of the tuning cache key.

Why it is built the way it is

The measurement methodology is the substance here, not the knob list. Naively timing candidate A and then candidate B produces garbage on any thermally limited machine: this repo's dev laptop drops from ~4 GHz burst to ~1.2 GHz sustained, so two runs of identical code can differ by 2-3x — far more than any real tuning gain. The tuner therefore:

  • interleaves candidates in serpentine order (A B C, then C B A). Plain round-robin is not enough: under a steady thermal ramp, whichever candidate is visited first each round is always measured at the coolest moment and wins systematically. Alternating direction cancels that gradient.
  • reports medians, never means or minimums.
  • requires two independent hurdles to change a setting: beat the incumbent's median by a margin and win a majority of individual rounds. A single lucky sample during a clock spike clears neither.
  • treats coordinate descent as a hypothesis, not an answer. After the cheap per-knob exploration, one final interleaved sweep judges the starting config, the full proposed set, and each proposed change in isolation. So a set that only looked good because two knobs each got a lucky sample is rejected, while a single measured win inside a losing set can still be kept. The starting config remains a candidate. These checks reduce bad choices under measurement noise; they do not guarantee a speedup for later requests or different host conditions.
  • repeats probes until they are measurable. A single forward pass through a small model times as exactly zero against the Windows clock's granularity, which would leave every candidate tied.

Expect run-to-run variation in which knobs it changes on a noisy machine — that is the honest reflection of the hardware, and --auto-effort thorough buys more rounds where it matters.

Benchmarking and Profiling

Run synthetic Go microbenchmarks:

go test -run '^$' -bench=. -benchmem ./internal/engine

Run an end-to-end generation benchmark against a real GGUF:

bin/gopherllm /path/to/model.gguf \
  --prompt "Wer war Albert Einstein?" \
  --max-tokens 128 \
  --temp 0 \
  --bench --bench-json --bench-runs 3

Time individual model kernels for one transformer layer:

bin/gopherllm /path/to/model.gguf \
  --kernel-bench-json \
  --kernel-bench-runs 25 \
  --kernel-bench-layer 0

Capture a CPU profile during a real generation benchmark:

bin/gopherllm /path/to/model.gguf \
  --prompt "Wer war Albert Einstein?" \
  --max-tokens 128 \
  --temp 0 \
  --bench --bench-json --bench-runs 1 \
  --cpuprofile /tmp/gopherllm.prof

If your Go toolchain includes pprof, inspect it with:

go tool pprof -top bin/gopherllm /tmp/gopherllm.prof

For repeatable comparisons, keep the prompt, token count, sampler settings, thread count, and model path fixed. The first run may include cache and warmup effects, so prefer --bench-runs 3 or more when comparing changes.

For 32-GiB Mac decoding and memory measurements, use the real-checkpoint sampler. It records process RSS and global VM counters alongside load, prefill and decode phases. Keep warm cached requests separate from uncached prefill, and verify the generated token count and digest before comparing timings. RSS, Go heap and system swap counters measure different things; they are not additive RAM totals.

Make Targets

  • make build, make run, and make repl auto-detect Metal: on macOS with Xcode Command Line Tools installed, they build with CGO_ENABLED=1 -tags metal and pass --metal for you. Throughput depends on the model and workload; see the measurement records. Set METAL=0 (e.g. make build METAL=0) to force the portable CPU-only build instead — useful for CI or a machine without Xcode. Cross-compiled binaries (make cross-build) are unaffected either way; they always use CROSS_CGO_ENABLED (default 0) since Metal only exists on macOS.
  • make run MODEL=... PROMPT='...' builds and runs one prompt.
  • make run-prep MODEL=... runs the prompt with --prepare-quant.
  • make build-metal builds bin/gopherllm-metal explicitly, regardless of the METAL auto-detection above (useful to keep both binaries around).
  • make run-metal MODEL=... runs with experimental --metal enabled.
  • make run-auto MODEL=... and make run-auto-metal MODEL=... tune (or reuse a cached tuning) before generating; set AUTO_EFFORT=quick|balanced|thorough to select calibration depth.
  • make run-full MODEL=... and make run-full-prep MODEL=... run 256-token prompt checks without and with --prepare-quant.
  • make run-full-metal MODEL=... and make run-full-metal-prep MODEL=... run 256-token prompt checks with Metal enabled.
  • make run ARGS='...' runs the CLI with a fully custom argument list instead (bypasses MODEL/PROMPT/sampler variables entirely).
  • make repl MODEL=... starts the REPL.
  • make autotune MODEL=... prints the cached or newly measured tuning result as JSON and exits; add AUTO_REFRESH=1 to force a fresh measurement. Use make autotune-metal MODEL=... to report a Metal-enabled load.
  • make list-models scans MODEL_DIR.
  • make inspect MODEL=... prints model metadata summary.
  • make list-tensors MODEL=... prints the tensor inventory.
  • make bench runs Go microbenchmarks.
  • make bench-model MODEL=... runs generation benchmark JSON.
  • make bench-model-prep MODEL=... and make compare-bench MODEL=... benchmark the prepared quant path.
  • make bench-model-metal MODEL=... benchmarks the experimental Metal path.
  • make synonym-bench MODEL=... / make nato-bench MODEL=... run fixed benchmark prompts useful for spotting output-quality regressions.
  • make kernel-bench MODEL=... benchmarks isolated model kernels.
  • make kernel-bench-prep MODEL=... and make compare-kernel-bench MODEL=... benchmark isolated kernels with prepared quant enabled.
  • make kernel-bench-metal MODEL=... benchmarks isolated kernels with Metal enabled.
  • make test, make vet, and make check verify the codebase.
  • make coverage runs the test suite and prints per-function coverage; make coverage-html does the same and opens an HTML report.
  • make cross-build compiles release binaries for macOS, Linux, and Windows on amd64 and arm64.
  • run and repl accept SKILLS_DIR=path/to/skills to enable skills; they also accept MIN_P, REPEAT_PENALTY, and SEED alongside the existing TEMP/TOP_P/TOP_K.
  • Run make help for the full target and variable list.

Performance Notes

Use --auto to measure supported settings for the loaded model on the target machine. Keep the model quantization, prompt, generated token count, sampler, thread count and KV format fixed when comparing versions. Report loading, prefill and decoding separately; kernel speedups do not establish generation throughput. See Benchmarking and Profiling.

  • Apple GPU: build with CGO_ENABLED=1 -tags metal and enable --metal. Make targets select it automatically on macOS with Command Line Tools. Eligible dense models keep the complete decoder on the GPU; other models use selective offload. Auto mode can compare CPU and Metal when neither is explicitly selected.
  • Memory and paging: --prefault core is the CLI default. It warms backbone tensors while leaving sparse expert banks and untied packed embeddings demand-paged. Avoid --prepare-quant when extra tables would exhaust RAM. For models that do not fit comfortably, --out-of-core uses CPU inference and maps GGUF shards separately. It does not impose a hard RSS limit.
  • Repeated requests: prefix caching and prepared prompts reduce repeated prompt work. Speculative decoding remains opt-in; its benefit depends on acceptance and verification cost. See Speculative decoding and Reusing conversations.
  • Core ML: embeddings and dense prefill FFNs are optional integrations. Exported FFNs retain the original weights and require additional memory. They do not accelerate autoregressive decoding. See Core ML prefill.

Performance and memory reference documents backend limits, kernel behavior and historical measurements. For recent complete experiments, use the recorded methodology and raw data:

Workload Measurement record
Ministral 3B/14B and Voxtral Metal kernels, 32-GiB M2 Max Alternating real-model decode comparisons
Ministral 3B/14B and Voxtral decoder, 32-GiB M2 Max KV lifetime, warm decode, RSS and paging
Ministral 3B Metal decode, M2 Max Paired requests and decode steps
Decoder scratch and Voxtral teacher-forced CPU steps Allocation savings and component timings
Ministral/Voxtral Tekken tokenization Splitter timing and allocation measurements
Voxtral offline convolution stem, M2 Max Accelerate timing and scratch usage
Core ML embeddings, M2 Max CPU/Neural Engine comparisons
Core ML FFNs, Qwen and Ministral Validation, memory and timing
M2 Max, M4 and M4 Pro Macs

Thread topology, memory bandwidth and GPU size differ between these Macs. Auto mode measures settings on the current machine and includes its hardware identity in the cache key. The hardware and backend reference records the differences. M2 Max results do not establish M4/M4 Pro performance; the SME experiment still requires validation on supported hardware.

Environment variables

Quick reference for runtime toggles (unset by default). Backend constraints and measurements are in the performance reference.

Variable Effect
GOPHERLLM_MODEL_DIR Default model directory when --model-dir is not given (RUSTY_LLM_MODEL_DIR remains a deprecated fallback)
GOPHERLLM_DISABLE_SIMD Disable SSE2/AVX2 on x86-64, ARM64 Q8 activation quantization, and ARM64 FEAT_DotProd detection
GOPHERLLM_NO_BATCH_PREFILL Per-token prefill instead of batched
GOPHERLLM_NO_BLOCK_VERIFY 1 disables speculative block verification for serial A/B comparison; native MTP retains its serial verifier
GOPHERLLM_NO_MTP_BATCH 1 restores per-token MTP catch-up for comparison
GOPHERLLM_MTP_METAL_BODY 0 keeps the complete native MTP draft body on the CPU; the shared vocabulary head remains on its configured backend
GOPHERLLM_PREFILL_CHUNK Override batched-prefill chunk size (1-256)
GOPHERLLM_NO_GROUPED_GQA Disable the grouped-GQA/MQA decode path (any ratio, any KV cache format) (A/B benchmarking and debugging)
GOPHERLLM_Q8_ACTIVATIONS 0 disables the default int8-activation Q4_K/Q5_K/Q6_K/Q8_0/Q4_0/Q4_1/MXFP4/Q2_K/Q3_K matvecs (x86-64, and arm64 with FEAT_DotProd)
GOPHERLLM_NO_PREFAULT Skip the post-mmap page warm-up; restores pure lazy paging
GOPHERLLM_KV_F16 0 stores the KV cache as exact f32 instead of the default f16 cache on fast x86-64; 1 opts into f16 on other targets (NEON-accelerated on all of arm64) to halve KV memory
GOPHERLLM_KV_I8 1 opts into the Q8_0-block KV cache tier (off by default everywhere) — a memory-capacity option, not a speed one; see KV cache and paging
GOPHERLLM_METAL_ROWS_PER_GROUP Override legacy Metal rows per threadgroup (2, 4, 6, or 8; default 4, adaptively 6 for Ministral-3B FFNs); new Q8_0 and coalesced prefill kernels use four rows
GOPHERLLM_METAL_COALESCED 0 disables the four-token Q4_K/Q6_K prefill fallback; also set GOPHERLLM_METAL_MATRIX=0 to restore the legacy prefill kernels
GOPHERLLM_METAL_MATRIX 0 disables SIMD-group matrix prefill and restores the four-token kernels; decode is unchanged
GOPHERLLM_METAL_VERIFY_VECTOR 0 disables register-shared 2–8-position matvecs, including short prefill batches; larger batches and serial decode are unchanged
GOPHERLLM_METAL_QWEN_FFN_VECTOR 0 restores the legacy Qwen FFN reduction in both single-token decode and block verification
GOPHERLLM_NO_MOE_DOWN_BATCH 1 restores separate worker dispatches for selected experts' down projections
GOPHERLLM_METAL_GEMMA 0 disables fused GeGLU, vectorized Gemma output and native Metal batch prefill (enabled by default)
GOPHERLLM_METAL_DENSE_DECODE 0 disables complete dense Metal decode for eligible Ministral/Qwen models (enabled by default)
GOPHERLLM_METAL_WHOLE_PREFILL 0 disables complete GPU-resident dense prefill chunks (enabled by default for eligible shapes)
GOPHERLLM_METAL_DENSE_VECTOR 0 uses legacy matvec kernels within complete Metal decode for comparison
GOPHERLLM_METAL_DENSE_ROWS_PER_GROUP Override dense Metal SIMD groups per threadgroup (2, 4, or 8; uncalibrated default 4, auto mode measures all three)
GOPHERLLM_METAL_DENSE_Q4_SPLIT_SUM 0 restores the previous FP32 addition order in dense Q4_K decode; default uses independent low/high sums
GOPHERLLM_METAL_DENSE_FUSED_GATE 0 uses separate gate/up projections and SiLU in dense Metal decode; default fuses matching Q4_K or Q6_K projections
GOPHERLLM_METAL_DENSE_CONCURRENT 0 serializes all dispatches within complete Metal decode
GOPHERLLM_METAL_DENSE_PARALLEL_ARGMAX 0 restores single-threadgroup vocabulary selection in dense Metal greedy decode for A/B measurements
GOPHERLLM_METAL_DENSE_SHARED_KV 0 uses staging copies instead of pinned shared F32 KV buffers
GOPHERLLM_METAL_FUSED_FFN 0 disables hybrid-path Metal Gate/Up + SiLU + Down fusion; disable dense decode above to select that path
GOPHERLLM_DISABLE_YARN Ignore declared YaRN RoPE scaling

Settings chosen by --auto apply process-wide. Explicit dense Metal row counts and GOPHERLLM_METAL_DENSE_VECTOR=0 take precedence over schedule calibration; other calibrated settings override their corresponding environment defaults.

Supported Architectures

The loader currently accepts GGUF files whose general.architecture is one of (also available at runtime via gopherllm.SupportedArchitectures(), which backs the same check ArchitectureSupported makes — useful to check a file before ever calling Open, e.g. to grey it out in a picker):

llama, llama2, llama3, mistral, mistral3, ministral, mixtral, qwen2, qwen2moe, qwen3, qwen3moe,
qwen35, qwen35moe,
deepseek2, kimi_k2,
phi2, phi3, granite (dense), granitemoe, exaone, exaone4, smollm3, internlm2, stablelm,
olmo2, gpt-oss, gemma, gemma2, gemma3, gemma4,
nemotron_h, nemotron_h_moe, mamba2, bert, nomic-bert,
gpt2, gptneox, gptj, bloom, mpt, falcon, starcoder, starcoder2, chatglm, glm4, command-r, minicpm

The architecture value is only accepted when its execution graph and expected tensor layout are implemented; an unknown GGUF is not treated as Llama merely because some tensor names happen to match. Before that check, though, the loader resolves the label against the file itself (ResolveArchitecture), so imperfect third-party conversions of supported architectures still load:

  • Spelling variants normalize. Hugging Face class names (Qwen2ForCausalLM, GPT2LMHeadModel, CohereForCausalLM), case, and hyphen/underscore variants (command_r, gpt_oss, deepseek-v2) resolve to the canonical label. Nothing maps across graphs: mamba (Mamba-1) does not become mamba2, and OLMoE stays unsupported.
  • A missing general.architecture is detected, not assumed. The loader finds the <arch>.* hyperparameter namespace actually present in the metadata (block_count, embedding_length, ...) and uses it; the historic blanket "assume llama" default only remains for files with no namespace at all.
  • A mislabeled file follows its hyperparameters. When the declared label has no metadata namespace of its own (Kimi K2 conversions carrying deepseek2.* keys, llama2/llama3 compatibility labels over llama.*), hyperparameters are read from the namespace that exists. When the label is entirely unknown but the namespace belongs to a supported architecture (e.g. a fine-tune label over stock llama.* metadata), the file loads as that architecture and the load log says so.
  • Vision projectors are diagnosed. Passing an mmproj/CLIP GGUF as a text model produces an error pointing at --mmproj instead of a generic unsupported-architecture failure.

The main coverage is:

Family Covered GGUF models / notes
Llama-style Llama 2/3 text models, compatible llama exports, SmolLM3 3B (including its every-fourth-layer no-RoPE schedule)
Mistral Mistral, Mistral Small/Devstral exports, Mistral 3, Ministral, and Mixtral
Qwen Qwen2/2.5, QwQ, dense/sparse Qwen3 and Qwen3 Coder, plus experimental text-only Qwen3.5/3.6/3.8 hybrid exports
DeepSeek / Kimi Modern DeepSeek-V2/V3 and Kimi K2 MLA layouts
Gemma Gemma 1–3 and native dense/MoE/E2B Gemma 4 text graphs
Other decoders Phi-2, Phi-3/3.5, dense/sparse Granite (GraniteMoE), EXAONE 3, EXAONE 4 1.2B/32B, OLMo 2/3, InternLM2, StableLM, GPT-OSS
Classic / vendor decoders GPT-2, GPT-NeoX, GPT-J, BLOOM (ALiBi), MPT (ALiBi), Falcon, StarCoder/StarCoder2, ChatGLM, GLM4 (dense), Command-R, MiniCPM
Recurrent / hybrid Mamba2 and Nemotron-H / Nemotron-H-MoE
Embeddings BERT and Nomic-BERT (embedding generation only; not chat generation)

Important upstream GGUF families that are not implemented yet:

Missing family Required work
Llama 4 Its architecture-specific attention/normalization graph and model validation
Phi-MoE Sparse expert routing and the architecture-specific expert graph
OLMoE Its sparse expert router and expert execution graph
Cohere2 Its attention, normalization, and tokenizer/chat conventions (Command-R itself is implemented)
GLM4-MoE, MiniMax M2, LFM2 Dedicated sparse or hybrid execution graphs (dense GLM4 is implemented)
Jamba, RWKV, Hyena-family hybrids Recurrent/state-space cache and mixing kernels
Multimodal Qwen/Gemma/Llama models Vision projector loading, visual-token injection, and multimodal positional encoding
Standalone MTP/assistant draft files (deepseek4_mtp*, gemma4-assistant) A parent-model speculative-decoding runtime; these auxiliary GGUFs are not standalone chat models

This gap list tracks architecture families, not every fine-tune name: a fine-tune is supported when its GGUF declares one of the implemented architectures and retains that architecture's tensor layout. The reference catalog is llama.cpp's current GGUF architecture enum; adding a family generally requires both the hyperparameter/tensor loader and a matching computation graph.

Sparse MoE is native for Mixtral-style GGUFs (including checkpoints that declare llama), qwen2moe, and qwen3moe. The loader validates the router and every [input, output, expert] tensor before loading; Mixtral/Qwen3 use top-k-renormalized routing, while Qwen2-MoE preserves its full-router mass and adds its gated shared expert. gpt-oss uses the same sparse foundation with its expert/router biases, OAI-SwiGLU activation, learned attention sinks, and alternating local/full-attention schedule. These sparse graphs share the per-token decode kernels; Qwen3.5-MoE also has the grouped prefill path below.

The common sparse graph and native Gemma 4 A4B coalesce eligible selected experts' gate/up and down projections into one worker dispatch per stage. Down inputs remain distinct per expert, and the weighted sum retains router order, biases, activation functions and Gemma's branch norms. The down path supports F32, Q4_K, Q5_K, Q6_K, Q8_0 and MXFP4, provided gate/up batching is available. It reuses existing CPU SIMD kernels and bounds additional down-stage scratch to 8 MiB and 32 active experts; other layouts retain per-expert decode. Set GOPHERLLM_NO_MOE_DOWN_BATCH=1 to disable down batching.

Gate/up dispatch tasks are pooled and cleared after use, so they retain no model mappings or request buffers. On M2 Max with Go 1.25.3, eight threads, eight active experts and 2048×512 projections, the warmed BenchmarkExpertGateUpBatch went from five allocations per Q4_K/Q6_K call to zero (F32: three to zero). Compatible CPU shared experts also combine gate/up into one dispatch and reuse activation preprocessing; direct GPU and prepared projections keep their existing kernels. These changes apply to serial prefill and decoding, including the CPU expert work in Metal models. TestMoEConfiguredSharedParity compares every shared-expert layer of a local Qwen3.5-MoE checkpoint with the original separate projections. Alternating timing runs encountered competing builds in all 32 host-load samples, so the allocation reduction is verified but no additional throughput or paging gain is claimed from those runs.

Down projections prepare all selected experts' activation blocks in one pass, using one temporary Q8/scales buffer pair instead of one pair per expert. Block scales and offset sums remain independent, and expert outputs retain their original reduction order. The grouped prefill path also quantizes directly into its existing workspace, avoiding the temporary-buffer copy. TestMoEConfiguredDownParity checks all routed FFNs against separately dispatched down projections; Ornith's 40 layers match exactly with both CPU and Metal loading. BenchmarkExpertDownInputs isolates input preparation from matrix multiplication and worker dispatch. On M2 Max, Go 1.25.3, one thread and eight 512-wide expert inputs, four alternating pairs measured median preparation times of 2.503 µs → 2.306 µs for Q4_K and 2.810 µs → 2.612 µs for Q6_K (7.9% and 7.1% less time). No competing compiler/test process appeared in 32 host-load samples. These are preparation timings, not full-model token throughput. ARM64 SIMD and portable tests pass; AMD64 fallback tests also pass under Rosetta; the AMD64 Q8 tests are skipped there because the required CPU features are unavailable.

Bias-free SwiGLU experts with eight-lane-aligned hidden rows also share one activation call across the slab. Biases, GPT-OSS activations and scalar tails retain per-expert evaluation. BenchmarkMoEActivation measured 3.477 µs per-expert versus 3.426 µs batched for eight 512-wide experts on M2 Max (Go 1.25.3, one thread, four alternating pairs, no competing compiler/test process in 39 load samples). This is a small activation-stage saving of 1.5%; the 32-expert case showed no clear benefit. The arithmetic and reduction order are unchanged, with bit-exact output checks.

Qwen3.5-MoE/Ornith prefill can group up to 32 tokens by selected expert, streams that expert's gate/up/down rows across its matching tokens, distributes work by each group's token count, and retains the original router order when summing each token's result. It reuses the CPU Q8 activation kernels, including ARM's four-position Q4_K/Q6_K row kernels. Attention and DeltaNet stay chronological and retain their CPU/Metal choices. Additional grouped-expert scratch is limited to 16 MiB per decode workspace; expert banks stay mapped and are never copied to Metal or expanded to floats. This path requires Q8 activations, F32 KV, Q4_K/Q6_K gate/up, and a supported quantized down projection. Compressed KV, unsupported layouts and MTP-enabled sparse prefill use the token-by-token path. Eligible --out-of-core models group by default. Use GOPHERLLM_MOE_PREFILL=1 to enable grouping on regular loads and GOPHERLLM_NO_MOE_PREFILL=1 to disable it.

Metal loading without --prepare-quant skips the separate token embedding and Qwen3.5-MoE projection pairs that always execute in fused CPU kernels. Tied output heads and used GPU projections retain their accelerator resources. The CLI defaults to --prefault core, warming backbone tensors without eagerly reading every expert bank; --prefault all restores full warm-up, and none leaves all weights demand-paged. The library's zero-value load option still means all; --out-of-core remains CPU-only. Avoid --prepare-quant when minimizing RAM use. The operating system can still evict mapped pages under memory pressure.

On macOS, TestMoEConfiguredPrefillParity compares complete 64-token responses with grouping on/off, clears conversation caches for each request, and reports prefill/decode times, process-local major/minor faults and scratch bytes. On an M2 Max with 32 GB, three alternating pairs after a warmup (45 prompt tokens, 64 generated tokens, eight threads, Q8 activations, F32 KV, no prepared weights, prefault=none) reproduced identical output IDs within each backend. A follow-up with other builds paused recorded median CPU prefill of 10.206 s serial versus 11.316 s grouped; complete-request latency was 23.435 s versus 25.363 s, and median major faults were 722,232 versus 745,751. This remains an observation under memory pressure, with no continuous host-load monitoring for the CPU series. A fresh Metal series also passed output parity, but host-load monitoring captured other Go compilers or test binaries in 25 of 39 samples; those timings are unsuitable for a speedup claim.

On the same Ornith checkpoint with --out-of-core and warm model pages, grouping reduced median CPU prefill from 1.594 s to 1.183 s across three alternating pairs. Across all runs, the same 64 tokens were generated. Median decode was 2.697 s serial and 2.704 s grouped. Reusing the parsed GGUF header also reduced median open/close time with --prefault none from 111.6 ms to 93.3 ms and Go heap allocation from 91.9 MB to 68.5 MB per open. The open/close benchmark uses the OS file cache and measures allocation volume over the operation.

Three fresh APFS clones per mode tested first requests without a global cache purge. Median prefill was 11.361 s serial and 10.087 s grouped. Median end-to-end time was 17.436 s and 15.434 s. Each run recorded about 701,000 major faults and produced the same 64-token sequence. This measures first access to the cloned files on the M2 Max. Use the same GOPHERLLM_MOE_MODEL and optional GOPHERLLM_MOE_METAL=1 settings as the generation benchmark below. Set GOPHERLLM_MOE_OUT_OF_CORE=1 to exercise the SSD mode in the parity test, or use go test -run '^$' -bench '^BenchmarkMoEConfiguredOpenOutOfCore$' -benchmem ./internal/engine to repeat the load benchmark.

With Ornith-1.0-35B Q4_K_M on M2 Max, eight CPU threads and Q8 activations, three alternating warm pairs generated the same 64 tokens. Median CPU-only decode fell from 3.951 s to 3.240 s, and total request time from 5.338 s to 4.339 s. Prefix caches were cleared before every request and both modes used the same greedy sampling. Later CPU/Metal comparisons under memory pressure retained output parity but had substantially higher absolute times; the 21.2 GB checkpoint's working set matters on a 32 GB Mac. To repeat this full-model comparison, set GOPHERLLM_MOE_MODEL to a local MoE GGUF and run go test -run '^TestMoEConfiguredGenerationParity$' -v ./internal/engine; add -tags metal and GOPHERLLM_MOE_METAL=1 to test Metal. BenchmarkMoEConfiguredLayer isolates one real sparse layer with synthetic inputs, rather than reporting whole-model throughput.

qwen2 covers text-only Qwen2/Qwen2.5 GGUFs, including Qwen2.5-Coder, Qwen2.5-Math, and QwQ checkpoints when they declare that architecture; qwen2moe implements Qwen2-MoE's unnormalized selected-router mass and gated shared expert. qwen3 covers dense text-only Qwen3 (including Qwen3-based DeepSeek-R1 distills) with mandatory per-head QK-norm. qwen3moe adds the matching normalized sparse routing and QK-norm required by Qwen3-MoE, including Qwen3-Coder GGUFs that declare qwen3moe. qwen35 and qwen35moe have a native experimental hybrid Gated-DeltaNet / periodic-attention path; qwen35moe also uses the sparse-expert implementation and Qwen-style gated shared experts (including Ornith-style GGUFs). The hybrid DeltaNet graph has focused scalar-reference tests and text-only local-GGUF smoke coverage; full cross-runtime logit parity remains pending, so the runtime emits an explicit experimental warning. Dense CPU hybrids batch attention/DeltaNet and FFN projections in chunks of up to 32 tokens while preserving the existing chronological convolution/DeltaNet recurrence and causal attention. MTP prefill uses the same batches and catches its separate draft head up with every target hidden state. Dense Metal hybrids preserve their decode arithmetic while batching supported projections and FFNs, including with F16/I8 KV. Other accelerator-backed layouts and dense out-of-core models retain serial prefill. With active MTP, quantized CPU-only projections retain serial prefill when Q8 activations are disabled. GOPHERLLM_NO_BATCH_PREFILL=1 disables hybrid batching. CPU float projection kernels can reduce sums differently from serial decode; F16/I8 cache rounding can therefore produce different stored bytes. On the M2 Max, the small quantized test graph measured 1.9–2.4× faster prefill. A separate check using the first four of a real 27B model's 64 layers produced identical logits, convolution and recurrent state for 8/32-token prompts. This partial-graph check is not a throughput measurement of the complete 27B model.

ARM64 DeltaNet fuses decay/recall and update/output into two passes per row, preserving the previous dot-product reduction and rounding. Four-tap convolution, SiLU and output gating use NEON, and the recurrent worker task is reused without per-step allocations. Other architectures and unsupported dimensions retain the existing kernels. This includes Qwen3.8-27B GGUFs declaring qwen35.

Metal prefill prepares independent DeltaNet inputs across up to 32 positions before chronological state updates. CPU projections retain Q8 row arithmetic; prepared and float-only inputs keep their token path. Direct Q6_K QKV retains the scalar GPU reduction with one submission/readback per block. Weight storage is unchanged. Dense F16/I8 KV uses the same schedule with token-local cache codecs. Tests compare state, cache bytes, replay and continuation bit-for-bit.

For memory-constrained Macs, the Qwen prefix cache reuses the unchanged live DeltaNet state rather than retaining a second copy. Qwen3.8-27B keeps 149.625 MiB of recurrent state instead of 299.25 MiB; KV growth transfers that allocation. Serial requests release unused MTP KV and speculative verification scratch. Mapped, unprepared MTP weights register their Metal resources only when used. --prefault core skips the optional NextN block and the separate packed input embedding: 251.1 + 682.0 MiB of avoided eager reads in this GGUF. Tied output embeddings remain warm; physical residency remains under OS control. Metal borrowing failures retain the CPU path without silently copying a matrix. Explicit --prefault all and prepared loading retain their existing policies.

TestQwen35ConfiguredMemory uses the same model environment variables as the comparison below. On a 32-GB M2 Max, Qwen3.8-27B Q4_K_M with Metal, Q8 activations, no prepared weights and no prefault used 380.8 → 232.1 MiB of retained Go heap after GC for a 16-token prompt plus four generated tokens, with identical token digests. This excludes mapped weights and driver allocations; it is not total model residency or a paging speedup measurement. Leave --prepare-quant off when conserving memory: its expanded scale tables are unused by Q8 activation kernels.

Component benchmarks on a 32-GB M2 Max with Go 1.25.3 measured these medians over four alternating pairs. Parallel CPU work used eight threads.

Component Previous Optimized
DeltaNet step, 48 heads × 128, excluding projections 389.8 µs 124.3 µs
Four-tap convolution, 10240 channels, single-threaded 47.5 µs 14.9 µs
Metal Q6_K QKV, 10240×5120 matrix, 32 positions 37.45 ms 13.30 ms
Recurrent mixer including input/output projections, 32 positions 72.49 ms 34.60 ms

The projection/mixer fixtures retain one layer with repeated encoded row patterns; both mixer modes use the same batched output projection. These measurements exclude FFN, periodic full attention and vocabulary work and do not establish complete-model throughput.

For a complete local-model comparison, set GOPHERLLM_QWEN_PERF_MODEL to the GGUF path and run TestQwen35ConfiguredSerialPerformance; add GOPHERLLM_QWEN_PERF_METAL=1 with a -tags metal test build for Metal. Each run uses 16 raw prompt tokens, a 16-token output cap, cleared conversation caches, one warm-up and three samples, logging token digests and separate prefill/decode times. A complete Qwen3.8-27B Q4_K_M check completed four requests per build: all eight emitted 16 tokens with identical token digests. Paging and concurrent compiler/simulator activity prevented a reliable timing comparison; no full-model speedup is claimed.

Vision families that require visual-feature injection or multimodal MRoPE remain outside this text-generation scope: qwen2vl, qwen3vl, qwen3vlmoe, and qwen3next. Qwen3.6/3.8 GGUFs with one trailing MTP/NextN draft layer load that layer into its own KV cache. It is opt-in via --mtp-draft-tokens N (or WithMTPDraftTokens(N)) and requires deterministic generation (--temp 0 or --top-k 1): every candidate is verified by the target before it is emitted. Eligible dense CPU hybrids verify short target blocks, restore rejected recurrent suffixes and retain an exact accepted-prefix checkpoint. Unsupported graphs use serial verification. MTP remains off by default; see Speculative decoding for prompt lookup, adaptive windows, diagnostics and measurement counters.

deepseek2 and kimi_k2 provide a dedicated Multi-head Latent Attention (MLA) path for Kimi K2 and compatible modern DeepSeek-V2/V3 GGUFs. It uses a compressed KV cache, the split attn_k_b/attn_v_b MLA tensors, and the sigmoid/noaux sparse router with its always-on shared expert. Group-limited DeepSeek-V3 routing is native: it ranks the configured expert groups from corrected sigmoid scores, chooses the final experts within those groups, then mixes them using the original sigmoid probabilities. This path is currently CPU-only (--metal is rejected); legacy fused attn_kv_b layouts and MLA files without the compact modern metadata remain unsupported.

DeepSeek-R1 reasoning output is separated into reasoning_content in both template conventions (self-opened <think> blocks and the newer forced-open templates whose output begins mid-reasoning). Mistral-family models support assistant-message prefill: a conversation ending in an assistant message leaves the turn open so generation continues it.

Upstage SOLAR's ### System: / ### User: / ### Assistant: template is detected as its own family (alpaca-chat) and rendered exactly, including the asymmetric spacing the original uses — system and user turns are followed by a blank line, assistant turns are not. It uses no special tokens, so without explicit detection it fell through to the generic User: /Assistant: fallback, which is close enough to look correct and different enough to be out of distribution. This covers every SOLAR derivative, including SauerkrautLM-SOLAR-Instruct, plus the wider class of Alpaca/Orca-style community fine-tunes that share the format.

Phi-3 (including the Phi-3.5 GGUFs that declare phi3), dense Granite, EXAONE 3, and InternLM2 use GopherLLM's standard pre-norm RoPE/GQA/SwiGLU decoder path. SmolLM3 shares the dense SwiGLU graph but uses interleaved RoPE and deliberately omits RoPE in every fourth layer. EXAONE 4 has its own post-norm block behavior: raw residual input feeds attention/FFN, Q and K are RMS-normalized per head, branch projections are RMS-normalized before the residual add, and the 32B model follows its three-local/one-global SWA/RoPE schedule. Its [|system|] / [|user|] / [|assistant|] / [|endofturn|] instruct protocol is rendered natively. StableLM adds LayerNorm and learned norm biases. Its residual layout is selected from the actual tensors rather than the sometimes-stale use_parallel_residual metadata: checkpoints with ffn_norm (including Stable Code) use the sequential attention-then-FFN graph, while variants without it feed attention and FFN from one shared normalized input. Sparse Granite MoE checkpoints remain intentionally rejected: their expert router and expert tensors require the separate MoE execution graph.

phi2 uses its native parallel block rather than the Phi-3 graph: one biased mean/variance LayerNorm feeds both attention and the sequential, ungated exact-GELU MLP; both branch outputs are added to the original residual. Attention-output, FFN-up/down, output-norm, and vocabulary-output biases are loaded and validated. The vocabulary bias is applied in both ordinary logits and the allocation-saving greedy argmax path. Dense Phi-2 prompt ingestion uses batched prefill; Phi-MoE remains a separate unsupported architecture.

olmo2 covers both dense OLMo 2 and OLMo 3 GGUFs. The latter retains the olmo2 architecture label and adds a three-local/one-global sliding-attention schedule. Q and K use one RMSNorm over their complete projections rather than one norm per head; attention and FFN branches are normalized before their residual adds. OLMo 3 local layers use a separate SWA frequency base with ordinary unscaled RoPE, while global layers retain the checkpoint's normal long-context scaling. Both decode and batched prefill select the matching precomputed RoPE table per layer. Sparse olmoe remains unsupported.

Mistral-family instruct models (including Ministral) use the [INST]…[/INST] chat format, the Tekken byte-level BPE pre-tokenizer, and YaRN RoPE context scaling when the GGUF declares it.

nemotron_h and nemotron_h_moe are native hybrid Mamba-2 / attention graphs. The dense variant (including NVIDIA Nemotron 3 Nano 4B) uses ffn_up → ReLU² → ffn_down; the MoE variant retains its sparse router. Both retain Mamba convolution and SSM state locally and do not rely on a llama.cpp process. Prompt prefill is deliberately per-token for these architectures because recurrent state makes the regular batched transformer prefill invalid. The MoE variant also supports canonical ffn_latent_down/up projections and the optional shared ReLU² expert.

Pure mamba2 GGUFs (including the canonical 2.7B/7B family) run through a native convolution/SSM recurrence with no fabricated attention cache. The canonical RMSNorm(y · SiLU(z)) gate and state update are shared with Nemotron-H's Mamba-2 blocks; Mamba2 variants with an additional MLP branch are rejected explicitly rather than being evaluated with an incompatible graph.

Gemma-family support (gemma/gemma2/gemma3/gemma4, including Gemma QAT GGUFs) implements sqrt(dim) embedding scaling, GELU FFN, QK-norm, post-attention/post-FFN norms, attention/final-logit softcapping and the per-layer sliding-window map. Native Gemma 4 12B dense, 26B A4B MoE and E2B GGUFs use their real mixed local/global attention geometry: the local/global RoPE bases and global proportional rope_freqs.weight, K-as-V with V RMSNorm where declared, per-layer output scales, and the <|turn>…<turn|> chat protocol are all executed. 26B additionally executes its real shared-dense-plus-sparse GEGLU graph: scaled RMS router input, fused expert gate/up banks, expert down scales, and the three branch/sum norms. E2B executes the exact token-conditioned per-layer embedding residual (its global pre-norm-scaled projection, gated exact-GELU residual) and its query-only shared-KV tail: 15 physical slots, with tail SWA blocks reading slot 13 and global blocks slot 14. Local 12B, 26B and E2B Q4 out-of-core decode smoke tests are green.

Multimodal mmproj files remain separate work. Gemma 1--3 and Gemma 4 retain an experimental warning until cross-runtime logit-parity coverage is available. A sensible Gemma sampling starting point is --temp 1.0 --top-p 0.95 --top-k 64.

Projector files such as mmproj-* are detected and excluded from text-model selection.

bert and nomic-bert are encoder-only architectures: they are available for embedding generation but intentionally cannot be selected for chat generation. This covers BERT-format Granite Embedding GGUFs as well as Nomic Embed GGUFs carrying general.architecture = nomic-bert. GGUF tokenizers declaring tokenizer.ggml.model = bert use native WordPiece normalization and greedy segmentation, including CLS/SEP boundaries and both llama.cpp's phantom-space vocabulary layout and raw ## continuation pieces.

Development

Project layout
Area Files
Public API api_generated.go (type aliases and forwarding functions), doc.go (package overview and version); implementations in internal/engine/api.go
GGUF parsing + file mapping internal/engine/gguf.go over internal/formats/gguf/; internal/engine/mmap.go over internal/mmapfile/
Model loading + forward pass internal/engine/runner.go, internal/engine/model_*.go, per-family files (internal/engine/gemma4.go, internal/engine/qwen35.go, internal/engine/moe.go, …), internal/engine/forward_batch.go (batched prefill)
Compute kernels + worker pool internal/engine/simd_*.go, internal/engine/quant_*.go; platform dispatch and assembly in internal/engine/kernels_*.go / internal/engine/kernels_*.s
Tokenizers internal/tokenizer/ (SentencePiece, GPT-2/Tekken BPE, WordPiece), tables in internal/wordpiece/
Sampling internal/engine/sampling.go
Generation orchestration + chat templates internal/engine/runtime.go, internal/engine/chat_render_*.go
Tool calling / reasoning / skills internal/engine/agent.go, internal/engine/extract.go, internal/engine/skills.go; wire types in internal/tooling/
Model discovery + selection internal/engine/catalog.go, internal/engine/catalog_ollama.go
Embedding from other languages mobile/, bindings/ (C ABI, Swift, Rust, Python)
CLI cmd/gopherllm/, internal/engine/kernel_bench.go

docs/PROJECT_STRUCTURE.md maps every directory, shows how the language bindings layer on each other, and says where new code belongs. Every SIMD kernel has a portable Go scalar reference implementation, and differential tests assert they agree — when touching a kernel, run the Q4K/Q6K/DotF32/VectorOps test groups first.

Run the full local check:

make check

Validate every supported GGUF layout in a local model library without loading all weights into RAM:

GOPHERLLM_MODEL_SMOKE_DIR="$HOME/.cache/lm-studio/models" \
  go test -run TestLocalGGUFLoadSmoke -v ./integration

For a slower end-to-end answer check of every supported text model below 5 GB, first build the CLI and then run the opt-in sweep. Embedding GGUFs are deliberately excluded from chat generation and remain covered by the loader test plus embedding tests.

go build -o /tmp/gopherllm-model-sweep ./cmd/gopherllm
GOPHERLLM_RUN_MODEL_SWEEP=1 \
GOPHERLLM_SWEEP_BINARY=/tmp/gopherllm-model-sweep \
GOPHERLLM_MODEL_DIR="$HOME/.cache/lm-studio/models" \
  go test -run TestSmallLocalModelsAnswerEinsteinPrompt -v ./integration

Check test coverage:

make coverage      # per-function summary in the terminal
make coverage-html  # same, plus an interactive HTML report

Run a focused benchmark:

go test -run '^$' -bench=BenchmarkMatvecQ4K -benchmem ./internal/engine

Profile a real-model benchmark:

bin/gopherllm /path/to/model.gguf --prompt "test" --max-tokens 128 \
  --temp 0 --bench --bench-json --bench-runs 1 \
  --cpuprofile /tmp/gopherllm.prof

Local build artifacts are kept in bin/ and .cache/, both ignored by git.

iOS / iPhone

GopherLLM runs in iOS and macOS apps through a Swift package (bindings/swift) with an async/await API: load a GGUF, stream or await chat replies, cancel, count tokens, and inspect a model file before loading it. Its binary part is an XCFramework built from the C ABI with only Go and Xcode:

make xcframework    # bindings/swift/GopherLLMCore.xcframework
make swift-test     # the package's tests against a synthetic model

Inference runs on the device with ARM64/NEON kernels and an opt-in Metal GPU path; nothing goes over the network. iOS integration covers adding the package to an app, getting models onto the device, memory planning and entitlements, and the SwiftUI demo in examples/ios.

GitHub Actions runs go test, go vet, and go build on Linux, macOS, and Windows, the make cross-build release matrix, the C ABI test on Linux and macOS, and the XCFramework, Swift tests and iOS demo build on macOS.

Bindings for Rust, Python, and C

Swift (above), Rust and Python all embed GopherLLM in-process through one small C ABI (bindings/c/include/gopherllm.h) over the mobile.Engine surface — no server process, no HTTP round trip. The C ABI loads a GGUF, generates, chats or streams a completion, counts tokens and inspects models; the Rust and Python packages currently wrap its load, generate, stream and model-info calls.

make capi-build   # or: ./scripts/build-capi.sh

builds build/capi/libgopherllm.{dylib,so,dll} plus gopherllm.h. Then:

# Rust — bindings/rust/gopherllm (see its README for details)
cd bindings/rust/gopherllm && cargo run --example generate -- model.gguf "Hello!"

# Python — bindings/python (see its README for details)
cd bindings/python && pip install -e . && python3 examples/generate.py model.gguf "Hello!"

bindings/c/shim is a thin, hand-written cgo layer (no new business logic — everything forwards to the already-tested mobile.Engine); it is kept behind a capi build tag so go build ./... never needs a C toolchain to find it, and CGO_ENABLED=1 with the tag is required to build it. If you only need to call GopherLLM's OpenAI-compatible HTTP API from Rust, Python, or anywhere else, the Quickstart server needs none of this — these bindings are specifically for embedding the engine in-process.

Documentation

Overview

Package gopherllm is a pure-Go GGUF inference runtime: it memory-maps a quantized model file, runs the transformer forward pass on CPU (with optional ARM64 NEON / x86-64 AVX2 assembly kernels), and exposes generation, chat, streaming, embeddings, tokenization, and GGUF analysis directly to Go programs — no external process, no HTTP round-trips.

import gopherllm "github.com/SimonWaldherr/GopherLLM"

model, err := gopherllm.Open(ctx, "model.gguf")
if err != nil { ... }
defer model.Close()

res, err := model.Generate(ctx, "Explain GGUF in one sentence.",
    gopherllm.WithMaxTokens(128), gopherllm.WithTemperature(0.7))
fmt.Println(res.Text)

API layers

  • Model: the primary embedding API — context-first methods with functional options (Open, Generate, Chat, Stream, Embed, Tokenize, Detokenize). Start here.
  • server.NewHandler (server/server.go, a separate package): the OpenAI-/Ollama-compatible HTTP API as a mountable http.Handler for applications that expose the model over HTTP themselves.
  • Runner: the lower-level engine underneath both, exposed for advanced uses (the agentic skill loop via RunAgenticChat, kernel benchmarking, custom loops).
  • AnalyzeGGUF / SearchTokens: header-only model structure reports and vocabulary inspection without loading weights.
  • rag (rag/, a separate package): a hybrid BM25 + optional-vector index over your own documents. No dependency on this package's model type beyond the Embedder interface — retrieval works without a model at all.
  • agent (agent/, a separate package): composes a Model, a rag.Index and a tool set into Ask/Chat with citations. Neither subpackage is imported by this one.
  • mobile (mobile/, a separate package): the JSON-in, JSON-out surface behind the C ABI (bindings/c) and the Swift, Rust and Python packages.

The library never writes to stdout/stderr on its own; pass WithLogWriter (or HandlerOptions.LogWriter) to opt into diagnostics.

The implementation lives in internal/engine. This package preserves the public import path with type aliases and forwarding functions, generated from the engine's exported declarations by go generate .

The go doc command does not expand methods behind type aliases. From a repository checkout, use go doc ./internal/engine.Model.Generate to read the implementation's method documentation.

Platform backends, container formats, tokenizers and numeric helpers have their own packages under internal/. See docs/PROJECT_STRUCTURE.md for the directory map.

Example

Example demonstrates the simplest possible use: load a model, generate a completion, print it.

package main

import (
	"context"
	"fmt"
	"log"

	gopherllm "github.com/SimonWaldherr/GopherLLM"
)

func main() {
	ctx := context.Background()
	model, err := gopherllm.Open(ctx, "model.gguf")
	if err != nil {
		log.Fatal(err)
	}
	defer model.Close()

	res, err := model.Generate(ctx, "Explain GGUF in one sentence.",
		gopherllm.WithMaxTokens(128),
		gopherllm.WithTemperature(0.7),
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.Text)
}

Index

Examples

Constants

View Source
const AgentEventIteration = engineimpl.AgentEventIteration

AgentEventIteration fires when the model is asked to continue after a round of tool results.

View Source
const AgentEventToolEnd = engineimpl.AgentEventToolEnd

AgentEventToolEnd fires when it returns, carrying Duration and either Result or Error.

View Source
const AgentEventToolStart = engineimpl.AgentEventToolStart

AgentEventToolStart fires just before a tool executes.

View Source
const ChatRoleAssistant = engineimpl.ChatRoleAssistant
View Source
const ChatRoleSystem = engineimpl.ChatRoleSystem
View Source
const ChatRoleTool = engineimpl.ChatRoleTool

ChatRoleTool carries the result of a previously requested tool call back to the model. ToolCallID must match the id the assistant's ToolCalls entry used.

View Source
const ChatRoleUser = engineimpl.ChatRoleUser
View Source
const ContextWindowAutoCompress = engineimpl.ContextWindowAutoCompress

ContextWindowAutoCompress first condenses older plain assistant prose, preserving user/system instructions and the complete newest turn, then retains newest complete turns when the history still exceeds the budget.

View Source
const ContextWindowFull = engineimpl.ContextWindowFull

ContextWindowFull sends every supplied message and preserves the existing context-limit error when the prompt is too large.

View Source
const ContextWindowRecent = engineimpl.ContextWindowRecent

ContextWindowRecent retains the newest complete user turn(s), dropping older complete turns only when necessary to reserve room for generation.

View Source
const DefaultConversationCacheBytes = engineimpl.DefaultConversationCacheBytes

DefaultConversationCacheBytes caps retained historical KV rows and token IDs separately from the live generation workspace.

View Source
const DefaultMaxToolResultBytes = engineimpl.DefaultMaxToolResultBytes

DefaultMaxToolResultBytes is the cap on what one tool result contributes to the prompt when AgenticTool.MaxResultBytes is zero.

View Source
const DefaultMistralKVPrefixCacheBytes = engineimpl.DefaultMistralKVPrefixCacheBytes

DefaultMistralKVPrefixCacheBytes is the default cap for the opt-in KV snapshot cache used by Mistral/Ministral's static system-and-tools prefix. It is deliberately smaller than maxReusableKVCacheBytes: the normal Runner workspace remains useful for the most recent complete prompt, while this cache adds a small set of immutable snapshots for otherwise unrelated conversations which share their system prompt and tool schema.

View Source
const DefaultMistralPromptPrefixCacheBytes = engineimpl.DefaultMistralPromptPrefixCacheBytes

DefaultMistralPromptPrefixCacheBytes is the bounded storage budget used when EnableMistralPromptPrefixCache receives a non-positive limit. The cache is deliberately opt-in because it retains system prompts and tool definitions in memory between requests.

View Source
const DefaultToolRounds = engineimpl.DefaultToolRounds

DefaultToolRounds is the model-pass budget when GenerationOptions.MaxToolRounds is zero. This is the historical maxAgenticIterations value; the zero-value behavior of every existing caller is unchanged.

View Source
const DefaultToolTimeout = engineimpl.DefaultToolTimeout

DefaultToolTimeout is the per-call bound when AgenticTool.Timeout is zero.

View Source
const GGMLTypeBF16 = engineimpl.GGMLTypeBF16
View Source
const GGMLTypeF16 = engineimpl.GGMLTypeF16
View Source
const GGMLTypeF32 = engineimpl.GGMLTypeF32
View Source
const GGMLTypeF64 = engineimpl.GGMLTypeF64
View Source
const GGMLTypeI32 = engineimpl.GGMLTypeI32
View Source
const GGMLTypeIQ1_M = engineimpl.GGMLTypeIQ1_M
View Source
const GGMLTypeIQ1_S = engineimpl.GGMLTypeIQ1_S
View Source
const GGMLTypeIQ2_S = engineimpl.GGMLTypeIQ2_S
View Source
const GGMLTypeIQ2_XS = engineimpl.GGMLTypeIQ2_XS
View Source
const GGMLTypeIQ2_XXS = engineimpl.GGMLTypeIQ2_XXS
View Source
const GGMLTypeIQ3_S = engineimpl.GGMLTypeIQ3_S
View Source
const GGMLTypeIQ3_XXS = engineimpl.GGMLTypeIQ3_XXS
View Source
const GGMLTypeIQ4_NL = engineimpl.GGMLTypeIQ4_NL
View Source
const GGMLTypeIQ4_XS = engineimpl.GGMLTypeIQ4_XS
View Source
const GGMLTypeMXFP4 = engineimpl.GGMLTypeMXFP4
View Source
const GGMLTypeQ1_0 = engineimpl.GGMLTypeQ1_0
View Source
const GGMLTypeQ2_0 = engineimpl.GGMLTypeQ2_0
View Source
const GGMLTypeQ2_K = engineimpl.GGMLTypeQ2_K
View Source
const GGMLTypeQ3_K = engineimpl.GGMLTypeQ3_K
View Source
const GGMLTypeQ4_0 = engineimpl.GGMLTypeQ4_0
View Source
const GGMLTypeQ4_1 = engineimpl.GGMLTypeQ4_1
View Source
const GGMLTypeQ4_K = engineimpl.GGMLTypeQ4_K
View Source
const GGMLTypeQ5_0 = engineimpl.GGMLTypeQ5_0
View Source
const GGMLTypeQ5_1 = engineimpl.GGMLTypeQ5_1
View Source
const GGMLTypeQ5_K = engineimpl.GGMLTypeQ5_K
View Source
const GGMLTypeQ6_K = engineimpl.GGMLTypeQ6_K
View Source
const GGMLTypeQ8_0 = engineimpl.GGMLTypeQ8_0
View Source
const GGMLTypeQ8_1 = engineimpl.GGMLTypeQ8_1
View Source
const GGMLTypeQ8_K = engineimpl.GGMLTypeQ8_K
View Source
const GGMLTypeTQ1_0 = engineimpl.GGMLTypeTQ1_0
View Source
const GGMLTypeTQ2_0 = engineimpl.GGMLTypeTQ2_0
View Source
const GGMLTypeUnknown = engineimpl.GGMLTypeUnknown
View Source
const LoadSkillToolName = engineimpl.LoadSkillToolName

LoadSkillToolName is the name of the tool RunAgenticChat resolves internally (see agent.go) rather than returning to the caller.

View Source
const MaxToolRoundsCeiling = engineimpl.MaxToolRoundsCeiling

MaxToolRoundsCeiling clamps GenerationOptions.MaxToolRounds. The budget needs to move — six rounds is generous for a single lookup, thin for multi-hop research — but an unbounded value turns a misconfigured deployment into a model that spends minutes calling tools: on a laptop CPU each round is seconds of decode, not a hosted API's milliseconds.

View Source
const MmapPrefaultAll = engineimpl.MmapPrefaultAll

MmapPrefaultAll retains the established behavior: warm every page before returning from load, making first-token latency predictable.

View Source
const MmapPrefaultCore = engineimpl.MmapPrefaultCore

MmapPrefaultCore warms dense/router/backbone tensors but skips known sparse-MoE expert banks, Qwen's optional NextN draft layer, and untied quantized input embeddings and Gemma 4's per-layer lookup tables. These tensors remain demand-paged until inference needs their rows.

View Source
const MmapPrefaultNone = engineimpl.MmapPrefaultNone

MmapPrefaultNone leaves every tensor demand-paged.

View Source
const NoToolResultLimit = engineimpl.NoToolResultLimit

NoToolResultLimit, passed as AgenticTool.MaxResultBytes, disables the loop's result-truncation cap entirely.

View Source
const NoToolTimeout = engineimpl.NoToolTimeout

NoToolTimeout, passed as AgenticTool.Timeout, disables the loop's per-call bound entirely.

View Source
const SafetensorsBF16 = engineimpl.SafetensorsBF16
View Source
const SafetensorsF16 = engineimpl.SafetensorsF16
View Source
const SafetensorsF32 = engineimpl.SafetensorsF32

Public dtype constants for callers inspecting safetensors metadata.

View Source
const TokenizerGPT2BPE = engineimpl.TokenizerGPT2BPE
View Source
const TokenizerSentencePiece = engineimpl.TokenizerSentencePiece
View Source
const TokenizerWordPiece = engineimpl.TokenizerWordPiece
View Source
const Version = "0.3.0-go"

Version is reported by the CLI's --version and usage header.

View Source
const VoxtralSampleRate = engineimpl.VoxtralSampleRate

VoxtralSampleRate is the required mono PCM sample rate, in Hz.

Variables

View Source
var COCOClassNames = engineimpl.COCOClassNames

COCOClassNames are the 80 COCO detection labels in class-index order.

View Source
var ErrGenerationCanceled = engineimpl.ErrGenerationCanceled
View Source
var ErrInvalidDecision = engineimpl.ErrInvalidDecision

ErrInvalidDecision identifies invalid input, including questions that exceed the configured prompt budget. Callers can use errors.Is for HTTP 422 handling.

View Source
var ErrNoValidJSONToken = engineimpl.ErrNoValidJSONToken
View Source
var ErrRunnerBusy = engineimpl.ErrRunnerBusy

ErrRunnerBusy means the per-runner bound of 64 active/waiting inference operations was reached. Hosts can impose a smaller admission bound.

View Source
var ErrRunnerClosed = engineimpl.ErrRunnerClosed

ErrRunnerClosed is returned when an operation begins after Runner.Close. A Runner may be shared between goroutines; the generation lock makes a concurrent Close deterministic rather than letting a waiter reach cleared or unmapped weights after Close wins the lock.

View Source
var ErrStructuredOutputIncomplete = engineimpl.ErrStructuredOutputIncomplete

ErrStructuredOutputIncomplete accompanies a truncated JSON prefix. A nil generation error in JSON mode guarantees a complete syntactically valid object.

View Source
var ErrVoxtralBusy = engineimpl.ErrVoxtralBusy

ErrVoxtralBusy indicates that the model already has an active session. Close that session before starting another, or use another model instance.

View Source
var ErrVoxtralModelClosed = engineimpl.ErrVoxtralModelClosed

ErrVoxtralModelClosed indicates that Close has stopped new sessions.

View Source
var ErrVoxtralSessionClosed = engineimpl.ErrVoxtralSessionClosed

ErrVoxtralSessionClosed indicates a closed, finalized or failed session.

View Source
var YOLOStockModels = engineimpl.YOLOStockModels

YOLOStockModels lists stock names understood by YOLOCheckpointReference.

Functions

func ArchitectureSupported

func ArchitectureSupported(arch string) bool

func ArgmaxOutputToken added in v0.2.0

func ArgmaxOutputToken(config Config, weights ModelWeights, buf *DecodeBuffer) (uint32, bool)

func AxpyF32

func AxpyF32(out []float32, alpha float32, x []float32)

func CompressModel added in v0.7.0

func CompressModel(sourcePath, outPath string, opts CompressOptions) error

CompressModel writes a requantized, single-file GGUF. Rows are converted in bounded chunks, including 3-D expert banks. Preset selects a mixed tensor policy; without it the existing TargetFormat/output-floor policy applies.

The source remains mapped and must differ from outPath, including through symlinks or hardlinks. The destination is replaced only after a sibling temporary file has been flushed, closed, and verified. Cancellation or a conversion error preserves any existing destination.

func CosineSimilarity

func CosineSimilarity(a, b []float32) (float32, error)

func DecodeImageBytes added in v1.0.0

func DecodeImageBytes(data []byte) (image.Image, error)

DecodeImageBytes decodes an image from its encoded bytes.

func DefaultModelDir

func DefaultModelDir() string

DefaultModelDir returns the directory scanned when --model-dir is not given: $GOPHERLLM_MODEL_DIR if set, else the deprecated $RUSTY_LLM_MODEL_DIR (the project's pre-rename spelling, kept so existing environments keep working), else the LM Studio library root under $HOME. If that root does not exist yet, the former community-only path remains the fallback. (MODEL_DIR is a Makefile variable, not read here.)

func DequantRowMXFP4

func DequantRowMXFP4(row []byte, cols int) []float32

func DequantRowMXFP4Into added in v0.4.0

func DequantRowMXFP4Into(row []byte, cols int, out []float32)

DequantRowMXFP4Into is the allocation-free MXFP4 row decoder used by RowInto and prompt batching.

func DequantRowQ1_0 added in v0.4.0

func DequantRowQ1_0(row []byte, cols int) []float32

func DequantRowQ1_0Into added in v0.4.0

func DequantRowQ1_0Into(row []byte, cols int, out []float32)

DequantRowQ1_0Into decodes 128 weights from each 18-byte block: one f16 scale followed by 128 sign bits. A set bit is +scale and a clear bit is -scale.

func DequantRowQ2K

func DequantRowQ2K(row []byte, cols int) []float32

func DequantRowQ2KInto

func DequantRowQ2KInto(row []byte, cols int, out []float32)

func DequantRowQ2_0 added in v0.4.0

func DequantRowQ2_0(row []byte, cols int) []float32

func DequantRowQ2_0Into added in v0.4.0

func DequantRowQ2_0Into(row []byte, cols int, out []float32)

DequantRowQ2_0Into decodes 64 weights from each 18-byte block. Four consecutive weights occupy each byte and map 00/01/10/11 to -1/0/+1/+2 times the block's f16 scale.

func DequantRowQ3K

func DequantRowQ3K(row []byte, cols int) []float32

func DequantRowQ3KInto

func DequantRowQ3KInto(row []byte, cols int, out []float32)

func DequantRowQ4K

func DequantRowQ4K(row []byte, cols int) []float32

func DequantRowQ4KInto

func DequantRowQ4KInto(row []byte, cols int, out []float32)

func DequantRowQ4_0

func DequantRowQ4_0(row []byte, cols int) []float32

func DequantRowQ4_0Into added in v0.4.0

func DequantRowQ4_0Into(row []byte, cols int, out []float32)

DequantRowQ4_0Into is the allocation-free Q4_0 decoder used by batched prefill. Stable Code GGUFs commonly use this legacy format.

func DequantRowQ4_1

func DequantRowQ4_1(row []byte, cols int) []float32

func DequantRowQ4_1Into

func DequantRowQ4_1Into(row []byte, cols int, out []float32)

func DequantRowQ5K

func DequantRowQ5K(row []byte, cols int) []float32

func DequantRowQ5KInto added in v0.4.0

func DequantRowQ5KInto(row []byte, cols int, out []float32)

DequantRowQ5KInto decodes a Q5_K row into caller-owned storage. Token embedding lookup and batched prefill use it to avoid a throwaway row slice.

func DequantRowQ5_0

func DequantRowQ5_0(row []byte, cols int) []float32

func DequantRowQ5_0Into

func DequantRowQ5_0Into(row []byte, cols int, out []float32)

func DequantRowQ5_1

func DequantRowQ5_1(row []byte, cols int) []float32

func DequantRowQ5_1Into

func DequantRowQ5_1Into(row []byte, cols int, out []float32)

func DequantRowQ6K

func DequantRowQ6K(row []byte, cols int) []float32

func DequantRowQ6KInto

func DequantRowQ6KInto(row []byte, cols int, out []float32)

func DequantRowQ8K added in v0.4.0

func DequantRowQ8K(row []byte, cols int) []float32

func DequantRowQ8KInto added in v0.4.0

func DequantRowQ8KInto(row []byte, cols int, out []float32)

func DequantRowQ8_0

func DequantRowQ8_0(row []byte, cols int) []float32

func DequantRowQ8_0Into added in v0.4.0

func DequantRowQ8_0Into(row []byte, cols int, out []float32)

DequantRowQ8_0Into is the allocation-free Q8_0 decoder used by batched prefill, where one decoded weight row is shared across many prompt tokens.

func DequantRowQ8_1

func DequantRowQ8_1(row []byte, cols int) []float32

func DequantRowQ8_1Into

func DequantRowQ8_1Into(row []byte, cols int, out []float32)

func DequantRowTQ1_0 added in v0.4.0

func DequantRowTQ1_0(row []byte, cols int) []float32

func DequantRowTQ1_0Into added in v0.4.0

func DequantRowTQ1_0Into(row []byte, cols int, out []float32)

DequantRowTQ1_0Into decodes 256 ternary weights from each 54-byte block. The first 48 bytes hold five scaled base-3 digits apiece, the next four hold four digits apiece, and the final two bytes are the f16 scale.

func DequantRowTQ2_0 added in v0.4.0

func DequantRowTQ2_0(row []byte, cols int) []float32

func DequantRowTQ2_0Into added in v0.4.0

func DequantRowTQ2_0Into(row []byte, cols int, out []float32)

DequantRowTQ2_0Into decodes 256 ternary weights from each 66-byte block. Each 32-byte group stores four 2-bit planes in output order; the final two bytes hold the f16 scale.

func DotF32

func DotF32(a, b []float32) float32

func DotMXFP4F32

func DotMXFP4F32(row []byte, x []float32, cols int) float32

func DotQ1_0F32 added in v0.4.0

func DotQ1_0F32(row []byte, x []float32, cols int) float32

func DotQ2KF32

func DotQ2KF32(row []byte, x []float32, cols int) float32

func DotQ2_0F32 added in v0.4.0

func DotQ2_0F32(row []byte, x []float32, cols int) float32

func DotQ3KF32

func DotQ3KF32(row []byte, x []float32, cols int) float32

func DotQ4KF32

func DotQ4KF32(row []byte, x []float32, cols int) float32

func DotQ4_0F32

func DotQ4_0F32(row []byte, x []float32, cols int) float32

func DotQ4_1F32

func DotQ4_1F32(row []byte, x []float32, cols int) float32

func DotQ5KF32

func DotQ5KF32(row []byte, x []float32, cols int) float32

func DotQ5_0F32

func DotQ5_0F32(row []byte, x []float32, cols int) float32

func DotQ5_1F32

func DotQ5_1F32(row []byte, x []float32, cols int) float32

func DotQ6KF32

func DotQ6KF32(row []byte, x []float32, cols int) float32

func DotQ8KF32 added in v0.4.0

func DotQ8KF32(row []byte, x []float32, cols int) float32

func DotQ8_0F32

func DotQ8_0F32(row []byte, x []float32, cols int) float32

func DotQ8_1F32

func DotQ8_1F32(row []byte, x []float32, cols int) float32

func DotTQ1_0F32 added in v0.4.0

func DotTQ1_0F32(row []byte, x []float32, cols int) float32

func DotTQ2_0F32 added in v0.4.0

func DotTQ2_0F32(row []byte, x []float32, cols int) float32

func EmbedVoxtralRealtimeToken added in v1.9.0

func EmbedVoxtralRealtimeToken(cfg VoxtralRealtimeConfig, weights VoxtralRealtimeWeights, tokenID int) ([]float32, error)

EmbedVoxtralRealtimeToken looks up one token's embedding row (also usable as the tied output projection's input width check).

func EncodeAudioVoxtralRealtime added in v1.9.0

func EncodeAudioVoxtralRealtime(cfg VoxtralRealtimeConfig, weights VoxtralRealtimeWeights, samples []float32) (audioEmbeds [][]float32, err error)

EncodeAudioVoxtralRealtime runs the mel frontend, causal conv stem, and the NLayers-block causal audio-encoder transformer over one offline (complete, non-streaming) audio clip, then the adapter, producing one DecoderHiddenSize-wide embedding per group of Projector.DownsampleFactor encoder frames -- ready to be summed into the decoder's text token embeddings at matching sequence positions (see voxtral_realtime.go's doc comment, point 4).

func EncodeAudioVoxtralRealtimeContext added in v1.9.0

func EncodeAudioVoxtralRealtimeContext(ctx context.Context, cfg VoxtralRealtimeConfig, weights VoxtralRealtimeWeights, samples []float32) (audioEmbeds [][]float32, err error)

EncodeAudioVoxtralRealtimeContext is the cancellable variant of EncodeAudioVoxtralRealtime.

func EncodeImagePixtral added in v1.0.0

func EncodeImagePixtral(vc PixtralVisionConfig, weights PixtralVisionWeights, img *PreprocessedImage) (embeds [][]float32, mergedRows, mergedCols int, err error)

EncodeImagePixtral runs the whole vision tower + projector (see LoadPixtralVisionModel's doc comment for the full graph) over one image's preprocessed patches and returns one embedding per MERGED patch, sized PixtralVisionConfig.ProjectionDim, in row-major (merged row, then merged column) order, plus the merged grid shape (for IMG_BREAK placement by the caller). It has no KV cache and no causal mask: every patch of this one image attends to every other patch of this same image, matching the published Pixtral architecture -- callers must encode one image at a time (see the "no block-diagonal masking" simplification in the project plan).

func F16ToF32

func F16ToF32(h uint16) float32

func F32ToF16 added in v0.3.0

func F32ToF16(f float32) uint16

F32ToF16 converts a float32 to IEEE 754 half-precision bits with round-to-nearest-even, the scalar counterpart of F16ToF32.

func Forward

func Forward(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int) []float32

Forward runs one token through the transformer and returns its next-token logits; ForwardInto is the allocation-free form. Both append the token's K/V to the cache at position pos as a side effect.

func ForwardBatchInto

func ForwardBatchInto(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, tokens []uint32, startPos int, computeLast bool, logits *[]float32)

ForwardBatchInto processes a chunk of prompt tokens (positions startPos..startPos+len(tokens)-1) through the standard transformer, populating the KV cache. The matvecs are batched so each weight is streamed once for the whole chunk. When computeLast is set, the final token's logits are written to logits. Passing nil still leaves the final normalized hidden state in buf.XN, but skips the vocabulary projection; greedy prefill then reduces that state through the exact no-logits argmax path. Only the non-fused standard path is supported (callers must check).

func ForwardBodyInto

func ForwardBodyInto(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int)

ForwardBodyInto is the transformer body shared by logits, prefill, and embedding paths: embed the token, then per layer run pre-norm attention (RoPE'd Q/K, K/V appended to the cache, online-softmax attention over all cached positions, output projection, residual add) followed by a pre-norm SwiGLU FFN, and finally apply the output norm, leaving the normed hidden state in buf.XN for the caller to project (or pool, for embeddings). Attention heads are spread across the worker pool once the attended span is long enough to amortize dispatch (see the comment at the call site); the Q/K/V and gate/up matvecs go through the fused multi-matrix kernels when the quant types allow (tryMatvec3Into/tryMatvec2Into).

func ForwardDeepSeek2BodyInto added in v0.4.0

func ForwardDeepSeek2BodyInto(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int)

ForwardDeepSeek2BodyInto executes MLA attention followed by the normal pre-norm SwiGLU/MoE residual graph. It is intentionally separate from the ordinary GQA fast path: its cache holds compressed KV latents, and applying the normal Q/K/V code would produce plausible-looking but invalid output.

func ForwardGemma4Into

func ForwardGemma4Into(config Config, weights Gemma4Weights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int, logits *[]float32)

func ForwardGptOssInto

func ForwardGptOssInto(config Config, weights GptOssWeights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int, logits *[]float32)

func ForwardHidden

func ForwardHidden(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int) []float32

func ForwardHiddenGemma4

func ForwardHiddenGemma4(config Config, weights Gemma4Weights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int) []float32

func ForwardHiddenGptOss

func ForwardHiddenGptOss(config Config, weights GptOssWeights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int) []float32

func ForwardInto

func ForwardInto(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int, logits *[]float32)

func ForwardMamba2BodyInto added in v0.4.0

func ForwardMamba2BodyInto(cfg Config, weights Mamba2Weights, cache *KVCache, buf *DecodeBuffer, token uint32, arg5 int)

func ForwardMamba2Into added in v0.4.0

func ForwardMamba2Into(cfg Config, weights Mamba2Weights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int, logits *[]float32)

func ForwardNemotronHBodyInto added in v0.3.0

func ForwardNemotronHBodyInto(cfg Config, weights NemotronHWeights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int)

func ForwardNemotronHInto added in v0.3.0

func ForwardNemotronHInto(cfg Config, weights NemotronHWeights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int, logits *[]float32)

func ForwardPrefill

func ForwardPrefill(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int)

func ForwardQwen35BodyInto added in v0.4.0

func ForwardQwen35BodyInto(cfg Config, weights Qwen35Weights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int)

func ForwardQwen35Into added in v0.4.0

func ForwardQwen35Into(cfg Config, weights Qwen35Weights, cache *KVCache, buf *DecodeBuffer, token uint32, pos int, logits *[]float32)

func ForwardQwen35MTPBodyInto added in v1.4.0

func ForwardQwen35MTPBodyInto(cfg Config, weights Qwen35MTPWeights, state *Qwen35MTPState, token uint32, hPrev []float32, pos int)

ForwardQwen35MTPBodyInto runs the one-layer Qwen NextN draft head and leaves its shared-head-normalized hidden state in state.Scratch.XN. The caller chooses whether to project logits: prompt/cache catch-up only needs K/V and skips the expensive vocabulary projection, while drafting needs it.

hPrev is the target's final hidden state at pos-1. This one-position shift is part of Qwen's MTP training graph: at position p the draft layer combines token[p] with target_hidden[p-1] and predicts token[p+1].

func ForwardQwen35MTPInto added in v1.4.0

func ForwardQwen35MTPInto(cfg Config, weights Qwen35MTPWeights, state *Qwen35MTPState, token uint32, hPrev []float32, pos int, logits *[]float32)

func ForwardVoxtralRealtimeDecoderStep added in v1.9.0

func ForwardVoxtralRealtimeDecoderStep(cfg VoxtralRealtimeConfig, weights VoxtralRealtimeWeights, state *VoxtralRealtimeDecoderState, input []float32, pos int) (logits []float32, err error)

ForwardVoxtralRealtimeDecoderStep runs one autoregressive decode step. input is the already-fused audio+token embedding for this position (see voxtral_realtime.go's doc comment point 4: audio embeddings are summed elementwise into the text token embedding, not interleaved or placed at special tokens). pos is this position's index in the sequence, used for RoPE and the sliding-window causal mask; state accumulates K/V history across calls and must be reused across a single generation's steps in order.

func IsYOLOCheckpoint added in v1.12.0

func IsYOLOCheckpoint(path string) bool

IsYOLOCheckpoint reports whether a file looks like a supported detector checkpoint.

func LoadBERTModel added in v0.4.0

func LoadBERTModel(data []byte, gguf *GGUFFile, borrowQuantized, prepareQuantized, useMetal bool, logw io.Writer, outOfCore ...bool) (Config, BERTWeights, error)

LoadBERTModel loads an encoder-only BERT or Nomic-BERT GGUF. Both use the same canonical tensor names; their architecture-specific metadata namespace is read from ConfigFromGGUF. This makes Nomic and Granite embedding models usable by /embeddings and the history-RAG index without treating them as chat models.

func LoadDeepSeek2Model added in v0.4.0

func LoadDeepSeek2Model(data []byte, gguf *GGUFFile, borrowQuantized, prepareQuantized, useMetal bool, logw io.Writer, outOfCore ...bool) (Config, ModelWeights, error)

LoadDeepSeek2Model loads DeepSeek-V2/V3 MLA models, including all current Kimi-K2 GGUFs. It deliberately rejects Metal: the existing Metal kernels assume ordinary Q/K/V matrices and would otherwise silently bypass MLA's latent compression/expansion math.

func LoadGemma4Model

func LoadGemma4Model(data []byte, gguf *GGUFFile, borrowQuantized, prepareQuantized, useMetal bool, logw io.Writer, outOfCore ...bool) (Config, Gemma4Weights, error)

func LoadGptOssModel

func LoadGptOssModel(data []byte, gguf *GGUFFile, borrowQuantized, prepareQuantized, useMetal bool, logw io.Writer, outOfCore ...bool) (Config, GptOssWeights, error)

func LoadMamba2Model added in v0.4.0

func LoadMamba2Model(data []byte, gguf *GGUFFile, borrow, prepareQuantized, useMetal bool, logw io.Writer, outOfCore ...bool) (Config, Mamba2Weights, error)

LoadMamba2Model loads the canonical pure Mamba-2 graph. Models containing an additional MLP branch intentionally fail here: that branch has a different input projection layout and accepting it would produce plausible but wrong logits.

func LoadModel

func LoadModel(data []byte, gguf *GGUFFile, borrowQuantized, prepareQuantized, useMetal bool, logw io.Writer, outOfCore ...bool) (Config, ModelWeights, error)

LoadModel loads the standard llama-style weight set from a parsed GGUF. With borrowQuantized set (the mmap path), quantized tensors are zero-copy sub-slices of data — the caller must keep data alive for the model's lifetime; without it they are copied into owned memory (the in-memory test path). Models without a separate output.weight tie the output projection to the token embeddings.

func LoadNemotronHModel added in v0.3.0

func LoadNemotronHModel(data []byte, gguf *GGUFFile, borrow, prepareQuantized, useMetal bool, logw io.Writer, outOfCore ...bool) (Config, NemotronHWeights, error)

func LoadParakeetModel added in v1.11.0

func LoadParakeetModel(data []byte, gguf *GGUFFile, logw io.Writer) (ParakeetConfig, ParakeetWeights, error)

LoadParakeetModel loads a Parakeet-TDT GGUF's config and weights -- see parakeet.go's doc comment for the architecture and tensor-family overview. Every 2D linear weight loads as F32 the same way voxtral's loaders already do (loadF32Vec/loadWeight's F32 branch is dtype-agnostic up to the quantized-kernel dispatch this doesn't need, since Weight.MatvecInto infers rows/cols from the caller's input length for F32 weights regardless of quantization). No axis permutation is needed for any tensor here: every multi-dimensional tensor inspected (the subsampling Conv2d weights, the per-head pos_bias_u/v vectors, the per-channel depthwise_conv kernel) has GGUF-native dims already ordered so that a plain sequential byte copy reproduces PyTorch's own row-major layout -- verified per-tensor against the shapes reported by --list-tensors, the same way voxtral_official.go's safetensors path needed none either, unlike GGUF's "voxtral.*" convention's transposed mel filterbank.

func LoadPhononModel added in v1.19.0

func LoadPhononModel(data, configData []byte, logw io.Writer) (ParakeetConfig, ParakeetWeights, error)

LoadPhononModel loads the original model.fermion and its bundled config.json into the Parakeet FastConformer/TDT graph.

func LoadPixtralVisionModel added in v1.0.0

func LoadPixtralVisionModel(data []byte, gguf *GGUFFile, useMetal bool, logw io.Writer) (PixtralVisionConfig, PixtralVisionWeights, error)

LoadPixtralVisionModel loads a Pixtral-projector "mmproj" GGUF (companion to, and structurally unrelated to, a text-decoder GGUF loaded separately via LoadModel/RunnerFromGGUFBytes*). It fails loudly if the file isn't a vision encoder or doesn't use the "pixtral" projector type -- this loader implements exactly that one graph, not a general CLIP loader.

The full computational graph (confirmed against llama.cpp's own clip.cpp graph-builder and HF transformers' Mistral3 modeling code, both read only to extract this factual sequence of operations -- nothing below is transcribed from either):

  1. Patch embedding: a stride-equals-kernel conv2d, which is mathematically identical to a per-patch linear projection over a flattened [channel][kh][kw] (channel slowest-varying) patch vector -- see the shape check below for why this reinterpretation is safe.
  2. v.pre_ln: RMSNorm, applied once, before the first transformer block.
  3. BlockCount transformer blocks, each pre-norm: x += Attn(RMSNorm_ln1(x)) (attention uses 2D RoPE on Q/K, full/non-causal, no KV cache -- see EncodeImagePixtral), then x += FFN(RMSNorm_ln2(x)) (gated SiLU/GELU).
  4. mm.input_norm: RMSNorm on the final per-patch hidden states, applied to every patch before merging -- despite being named/owned by the projector, this is functionally the vision tower's post-encoder norm (there is no separate v.post_ln tensor in this format).
  5. Spatial merge: non-overlapping SpatialMergeSize x SpatialMergeSize windows of the patch grid are packed into one vector in CHANNEL-MAJOR order (merged[c*merge^2 + dy*merge + dx] = patch[dy,dx][c] -- NOT naive whole-patch concatenation, which would silently produce a plausible-looking but wrong result), then linearly projected back down to EmbeddingLength via mm.patch_merger (no bias, no activation).
  6. mm.1 (linear) -> GELU -> mm.2 (linear, no activation after) produces the final ProjectionDim-wide embedding, one per merged patch.

Callers splice these embeddings into the paired LLM's input sequence in place of image-placeholder tokens (see EncodeImagePixtral's return shape and runtime.go's renderMistralInstMessages).

func LoadQwen35Model added in v0.4.0

func LoadQwen35Model(data []byte, gguf *GGUFFile, borrow, prepareQuantized, useMetal bool, logw io.Writer, outOfCore ...bool) (Config, Qwen35Weights, error)

func LoadVoxtralRealtimeModel added in v1.9.0

func LoadVoxtralRealtimeModel(data []byte, gguf *GGUFFile, useMetal bool, logw io.Writer) (VoxtralRealtimeConfig, VoxtralRealtimeWeights, error)

LoadVoxtralRealtimeModel loads a self-contained Voxtral Realtime GGUF's config and weights. useMetal requests accelerator-resident copies of the large matmul weights where supported, matching LoadPixtralVisionModel's convention. See this file's doc comment for the computational graph these weights feed.

func LoadVoxtralRealtimeModelFromSafetensors added in v1.11.0

func LoadVoxtralRealtimeModelFromSafetensors(dir string, useMetal bool, logw io.Writer) (VoxtralRealtimeConfig, VoxtralRealtimeWeights, *Tokenizer, error)

LoadVoxtralRealtimeModelFromSafetensors loads the official mistralai/Voxtral-Mini-4B-Realtime-2602 release from a directory containing consolidated.safetensors, params.json, and tekken.json -- the exact file set the official Hugging Face repo publishes for this model. Config, weights, and tokenizer are returned together (unlike the GGUF loader's split LoadVoxtralRealtimeModel/TokenizerFromMetadata) because StreamingPadTokenID can only be resolved after the tokenizer exists (it's the vocabulary ID of the literal "[STREAMING_PAD]" special token, not a small fixed metadata field the way it is in both GGUF conventions).

func MatvecF32

func MatvecF32(data, x []float32, rows, cols int) []float32

func MatvecF32Into

func MatvecF32Into(data, x []float32, rows, cols int, out *[]float32)

func MatvecMXFP4Into

func MatvecMXFP4Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecPreparedQ4K2IntoWithXSums

func MatvecPreparedQ4K2IntoWithXSums(aData []byte, aPrep *PreparedQuantizedWeight, aRows, aCols int, bData []byte, bPrep *PreparedQuantizedWeight, bRows, bCols int, x []float32, xSums *[]float32, aOut, bOut *[]float32) bool

func MatvecPreparedQ4K3IntoWithXSums

func MatvecPreparedQ4K3IntoWithXSums(aData []byte, aPrep *PreparedQuantizedWeight, aRows, aCols int, bData []byte, bPrep *PreparedQuantizedWeight, bRows, bCols int, cData []byte, cPrep *PreparedQuantizedWeight, cRows, cCols int, x []float32, xSums *[]float32, aOut, bOut, cOut *[]float32) bool

func MatvecPreparedQ4KInto

func MatvecPreparedQ4KInto(data []byte, p *PreparedQuantizedWeight, x []float32, rows, cols int, out *[]float32) bool

func MatvecPreparedQ6KInto

func MatvecPreparedQ6KInto(data []byte, p *PreparedQuantizedWeight, x []float32, rows, cols int, out *[]float32) bool

func MatvecQ1_0Into added in v0.4.0

func MatvecQ1_0Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ2KInto

func MatvecQ2KInto(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ2_0Into added in v0.4.0

func MatvecQ2_0Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ3KInto

func MatvecQ3KInto(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ4K2Into

func MatvecQ4K2Into(aData []byte, aRows, aCols int, bData []byte, bRows, bCols int, x []float32, aOut, bOut *[]float32) bool

func MatvecQ4K2IntoWithXSums

func MatvecQ4K2IntoWithXSums(aData []byte, aRows, aCols int, bData []byte, bRows, bCols int, x []float32, xSums *[]float32, aOut, bOut *[]float32) bool

func MatvecQ4K2Q6KIntoWithXSums added in v0.2.0

func MatvecQ4K2Q6KIntoWithXSums(aData []byte, aRows, aCols int, bData []byte, bRows, bCols int, cData []byte, cRows, cCols int, x []float32, q4Sums *[]float32, aOut, bOut, cOut *[]float32) bool

func MatvecQ4KInto

func MatvecQ4KInto(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ4_0

func MatvecQ4_0(data []byte, x []float32, rows, cols int) []float32

func MatvecQ4_0Into

func MatvecQ4_0Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ4_1Into

func MatvecQ4_1Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ5KInto

func MatvecQ5KInto(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ5_0Into

func MatvecQ5_0Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ5_1Into

func MatvecQ5_1Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ6K2Into

func MatvecQ6K2Into(aData []byte, aRows, aCols int, bData []byte, bRows, bCols int, x []float32, aOut, bOut *[]float32) bool

func MatvecQ6K3Into

func MatvecQ6K3Into(aData []byte, aRows, aCols int, bData []byte, bRows, bCols int, cData []byte, cRows, cCols int, x []float32, aOut, bOut, cOut *[]float32) bool

func MatvecQ6KInto

func MatvecQ6KInto(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ8KInto added in v0.4.0

func MatvecQ8KInto(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ8_0

func MatvecQ8_0(data []byte, x []float32, rows, cols int) []float32

func MatvecQ8_0Into

func MatvecQ8_0Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecQ8_1Into

func MatvecQ8_1Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecTQ1_0Into added in v0.4.0

func MatvecTQ1_0Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MatvecTQ2_0Into added in v0.4.0

func MatvecTQ2_0Into(data []byte, x []float32, rows, cols int, out *[]float32)

func MetalAvailable

func MetalAvailable() bool

func MetalError

func MetalError() string

func OllamaModelsRoot added in v1.1.0

func OllamaModelsRoot() string

OllamaModelsRoot reports the Ollama model store to scan, honouring the OLLAMA_MODELS override Ollama itself uses. It returns "" when no store is present, so callers can treat Ollama as simply absent rather than an error.

func PairedVisionProjectorPath added in v1.0.0

func PairedVisionProjectorPath(modelPath string) (string, error)

PairedVisionProjectorPath returns the automatically safe Pixtral projector next to modelPath, if one exists. It starts at modelPath's containing directory and never accepts a merely similarly named projector outside the model's exact parent directory. An explicit --mmproj remains the caller's override; this helper is for the no-explicit-projector case.

func ParakeetArchitectureSupported added in v1.11.0

func ParakeetArchitectureSupported(arch string) bool

ParakeetArchitectureSupported reports whether a GGUF's general.architecture names this loader's format ("asr"), for callers that dispatch on architecture before committing to a specific loader the way runner.go's ArchitectureSupported does for the main text-model list. Kept separate from that list because this is a wholly different loading/inference path, not a Runner-integrated architecture.

func ParakeetDecodeTokens added in v1.11.0

func ParakeetDecodeTokens(vocab []string, tokens []int) (string, error)

ParakeetDecodeTokens renders TDT-decoded token IDs back to text. Unlike every text-generation tokenizer in this codebase, a transducer's output never needs an encode-side algorithm (there is no text prompt to tokenize -- only IDs a greedy search already chose), so this is a plain SentencePiece piece lookup and "▁" (word-boundary marker) -> " " substitution, not a Tokenizer-mode dispatch.

func ParakeetEncode added in v1.11.0

func ParakeetEncode(cfg ParakeetConfig, w ParakeetWeights, samples []float32) ([][]float32, error)

ParakeetEncode runs the full FastConformer encoder: the mel frontend, dw_striding subsampling, then every Conformer block, returning one DModel-wide embedding per output frame (row-major [T][DModel]).

func ParakeetGreedyDecodeTDT added in v1.11.0

func ParakeetGreedyDecodeTDT(cfg ParakeetConfig, w ParakeetWeights, encoderFrames [][]float32) []int

ParakeetGreedyDecodeTDT runs TDT's greedy decoding loop over encoder output frames, returning the emitted (non-blank) token IDs in order. durationCursor advances by the predicted duration on every step (0 means "stay on this frame and try again" -- capped by MaxSymbolsPerStep to guarantee termination the way NeMo's own decoder bounds it); a positive duration or the blank symbol both consume at least one frame.

func PrintModelList

func PrintModelList(entries []ModelEntry)

func ProjectLogitsInto added in v0.2.0

func ProjectLogitsInto(config Config, weights ModelWeights, buf *DecodeBuffer, logits *[]float32)

func Q4KMatvec3Into

func Q4KMatvec3Into(wq, wk, wv Q4KMatrix, x []float32, q, k, v *[]float32) bool

Q4KMatvec3Into computes three Q4_K matvecs (attention Q/K/V projections) against the same activation vector in one fused pass: the per-32-element activation sums are computed once and the combined row range is spread over the worker pool as a single parallel dispatch instead of three. Returns false (nothing written) if shapes are incompatible, in which case the caller falls back to three separate matvecs.

func Q4KMatvec3IntoWithXSums

func Q4KMatvec3IntoWithXSums(wq, wk, wv Q4KMatrix, x []float32, xSums *[]float32, q, k, v *[]float32) bool

func QuantizeRowQ2K added in v1.1.0

func QuantizeRowQ2K(row []float32, cols int) []byte

QuantizeRowQ2K encodes cols float32 values as Q2_K: 84-byte superblocks of 256 elements (16 scale bytes — low nibble a 4-bit d-code 0..15, high nibble a 4-bit min-code 0..15 per sub-block, no cross-sub-block joint packing like Q4_K's — plus 64 bytes of 2-bit-packed quants, then f16 d and f16 dmin), decoded value = d*(sc&0xf)*q - dmin*(sc>>4), 16 sub-blocks of 16 elements each (quant_extra.go:230-263).

Two passes per superblock, like QuantizeRowQ4K: pass 1 finds each sub-block's ideal (scale, min) from its actual [lo,hi] range; d/dmin are shared across all 16 sub-blocks and so aren't known until every one has been seen, even though — unlike Q4_K — each sub-block's own 4-bit codes live in an independent byte with no joint bit-packing to freeze first. Pass 2 rounds the 2-bit codes against the scale/min the decoder will actually reconstruct (d*scCode, dmin*mCode), not the ideal float ones.

func QuantizeRowQ3K added in v1.1.0

func QuantizeRowQ3K(row []float32, cols int) []byte

QuantizeRowQ3K encodes cols float32 values as Q3_K: 110-byte superblocks of 256 elements (32-byte hmask + 64 bytes of 2-bit-packed low quants + 12 jointly-packed 6-bit scale bytes + f16 d), decoded value = d*(sc-32)*(q-hi*4), sc a 6-bit code biased by 32, q the 2-bit low code, hi a bit from hmask (quant_extra.go:309-368).

Single pass, unlike Q4_K/Q2_K: Q3_K's per-element code already covers the full -4..3 range a sub-block needs (the hmask bit folds the -4 offset in per element, not as a separate superblock-wide min), so there is no separate min term whose scale must be solved for jointly across sub-blocks — only the (sign-preserving, Q4_0/Q6_K-style) signed scale.

func QuantizeRowQ4K added in v0.7.0

func QuantizeRowQ4K(row []float32, cols int) []byte

QuantizeRowQ4K encodes cols float32 values as Q4_K: 144-byte superblocks of 256 elements (f16 d + f16 dmin + 12B packed 6-bit scale/min table + 128 nibble-packed bytes), decoded value = d*sc*nibble - dmin*m (simd.go:1510-1543).

Two passes per superblock, not one: the 12-byte scale/min table packs all 8 sub-blocks' 6-bit codes jointly (packScaleMinK4All above), so no sub-block's stored scale is knowable until all 8 have been computed. Pass 1 computes and freezes those codes; pass 2 rounds nibbles against the scales the decoder will actually reconstruct from them, not the ideal float scale — otherwise a caller (GPTQ) computing an error term from this function's output would compute it against a scale the file doesn't actually store.

func QuantizeRowQ4_0 added in v0.7.0

func QuantizeRowQ4_0(row []float32, cols int) []byte

QuantizeRowQ4_0 encodes cols float32 values as Q4_0: one f16 scale plus 16 nibble-packed bytes per 32-element block, decoded value = scale * (nibble-8) (simd.go:1487-1508).

nibble-8 is an ASYMMETRIC range (-8..+7, not -8..+8: a 4-bit unsigned code only has 16 values total). Scaling by plain amax/8 therefore clips the block's extreme value whenever it's positive (its ideal code, +8, doesn't exist). The fix — matching llama.cpp's reference quantize_row_q4_0 — is to let the scale take the SIGN of whichever signed extreme has the largest magnitude, not just its absolute value: d = extremeSigned/-8. That maps the extreme to code 0 exactly regardless of its sign (code 0 decodes to d*(0-8) = -8d = extremeSigned either way), fully using the available range instead of silently clipping one side.

func QuantizeRowQ5K added in v1.0.0

func QuantizeRowQ5K(row []float32, cols int) []byte

QuantizeRowQ5K encodes cols float32 values as Q5_K: 176-byte superblocks of 256 elements (f16 d + f16 dmin + the same 12B packed 6-bit scale/min table as Q4_K + 32B high-bit plane + 128B low-nibble plane), decoded value = d*sc*(nibble|hibit<<4) - dmin*m, a 5-bit unsigned code (0..31) split into a 4-bit low nibble and one bit of the 32-byte high-bit plane (simd.go:1545-1593). Shares Q4_K's joint scale/min packing exactly (getScaleMinK4/packScaleMinK4All), so the same two-pass approach applies: freeze the 8 sub-blocks' 6-bit scale/min codes first, then round 5-bit values against the scales the decoder will actually reconstruct.

func QuantizeRowQ5_0 added in v1.14.0

func QuantizeRowQ5_0(row []float32, cols int) []byte

QuantizeRowQ5_0 encodes signed 32-element blocks. Mixed K-quant presets use this fallback when a matrix row is not divisible by 256.

func QuantizeRowQ5_1 added in v1.14.0

func QuantizeRowQ5_1(row []float32, cols int) []byte

QuantizeRowQ5_1 encodes affine 32-element blocks for the Q5_K fallback.

func QuantizeRowQ6K added in v0.7.0

func QuantizeRowQ6K(row []float32, cols int) []byte

QuantizeRowQ6K encodes cols float32 values as Q6_K: 210-byte superblocks of 256 elements (128B low-nibble plane + 64B 2-bit-high plane + 16 signed int8 sub-block scales + f16 d at the end), decoded value = d*int8(scale)*(code-32), code a 6-bit unsigned value (simd.go:1595-1629). Unlike Q4_K, the 16 sub-block scales are independent int8 values with no joint packing, so this needs only one pass.

func QuantizeRowQ8_0 added in v0.7.0

func QuantizeRowQ8_0(row []float32, cols int) []byte

QuantizeRowQ8_0 encodes cols float32 values as Q8_0: one f16 scale plus 32 signed int8 values per 32-element block (simd.go:1466-1485). Symmetric, no zero-point.

func ResolveArchitecture added in v1.1.0

func ResolveArchitecture(gguf *GGUFFile) (arch, prefix string)

ResolveArchitecture determines the architecture a GGUF loads as and the metadata namespace its hyperparameters live under. The two differ whenever a converter kept a non-canonical public label: kimi_k2 files with deepseek2.* hparams resolve to ("kimi_k2", "deepseek2"), llama3 files with llama.* hparams to ("llama3", "llama"), and a "command_r" file with command_r.* hparams to ("command-r", "command_r").

Resolution rules, in order:

  1. The hyperparameter namespace is the declared label's own when its marker keys exist, otherwise the best namespace actually present in the metadata (this generalizes the historic llama2/llama3/kimi_k2 special cases to every converter that mislabels a file).
  2. A missing/empty general.architecture takes the detected namespace as its label, keeping the historic "llama" default only when the file has no hyperparameter namespace at all.
  3. A label that is not in ArchitectureSupported is normalized via canonicalArchAlias (case, hyphen/underscore, HF class-name suffixes, known alias table); if that fails but the namespace belongs to a supported architecture, the file loads as the namespace architecture.

Labels that are already supported are never rewritten, so alias labels with dedicated behavior (llama2/llama3, kimi_k2) keep their identity.

func ResolveModelPath

func ResolveModelPath(selection *string, modelDir string) (string, error)

ResolveModelPath turns the CLI's model selector into a concrete .gguf path. A selector that is an existing file wins outright; an existing directory (or a nil selector) opens the interactive picker over that directory; anything else is matched against the discovered models by SelectModel.

func RunKernelBench

func RunKernelBench(r *Runner, modelPath string, runs, requestedLayer int, jsonOut bool) error

RunKernelBench times each weight matvec of one transformer layer (plus the embedding row lookup and the output projection) in isolation, printing a table or, with jsonOut, the machine-readable llm-kernel-bench.v1 document that `make kernel-bench` emits for cross-runtime comparisons.

func RunnerFromPath

func RunnerFromPath(path string) (*Runner, LoadInfo, error)

RunnerFromPath memory-maps a GGUF file and loads it with zero-copy borrowed quantized weights. Silent; prefer Open, which adds context support, configurable logging, and a higher-level Model wrapper.

func RunnerFromPathWithOptions

func RunnerFromPathWithOptions(path string, options LoadOptions) (*Runner, LoadInfo, error)

func Sample

func Sample(logits []float32, config SamplerConfig, rng *Rng, recent []uint32) uint32

Sample picks the next token id from logits. recent is the trailing token window the repeat penalty applies to. NOTE: logits is mutated in place (penalties and softmax are applied destructively) — callers must not reuse the slice's prior contents afterwards.

func SampleWithScratch

func SampleWithScratch(logits []float32, config SamplerConfig, rng *Rng, recent []uint32, candidates *[]TokenProb) uint32

SampleWithScratch is Sample with a caller-owned candidate scratch buffer so the per-token decode loop allocates nothing. Same logits-mutation caveat.

func SaveAutoTune added in v0.4.0

func SaveAutoTune(res AutoTuneResult) error

SaveAutoTune persists a result so later runs can skip calibration. Cache failures are reported but never fatal — a missing cache only costs time.

func SaveMetalProbe added in v0.4.0

func SaveMetalProbe(probe MetalProbe) error

SaveMetalProbe persists a verdict. A cache failure only costs time, so it is reported rather than fatal.

func ScaleAddF32

func ScaleAddF32(out []float32, alpha float32, x []float32)

func ScaleF32

func ScaleF32(out []float32, alpha float32)

func SchemaOf added in v1.8.0

func SchemaOf[Args any]() json.RawMessage

SchemaOf derives a JSON Schema object (as raw bytes) from the exported fields of Args, using the same field-tag rules as NewTool. It is exported so a caller who needs a construct this subset does not cover (oneOf, a regex pattern, a tuned enum) can start from the derived bytes, edit them, and build an AgenticTool by hand — the escape hatch that keeps this subset allowed to stay small. Panics on an unsupported field kind; see NewTool.

func SetNumThreads

func SetNumThreads(n int)

SetNumThreads overrides the worker count used by the parallel matvec dispatch (default GOMAXPROCS). The CLI's --threads flag calls this and sets GOMAXPROCS to the same value.

func SetPrefillChunk added in v0.4.0

func SetPrefillChunk(n int)

SetPrefillChunk pins the prompt-prefill chunk size; 0 restores the default (env var, else the model-aware heuristic).

func SetWebGPUForceDisabled added in v1.0.0

func SetWebGPUForceDisabled(disabled bool)

SetWebGPUForceDisabled lets a caller opt out of GPU acceleration (e.g. for an A/B throughput comparison against the CPU path) before the next model load. Has no effect on weights already prepared by an earlier load.

func SupportedArchitectures added in v1.8.0

func SupportedArchitectures() []string

SupportedArchitectures returns every general.architecture label the loader currently accepts, after ResolveArchitecture's alias and hyperparameter- namespace normalization — the same check ArchitectureSupported makes, so this list and that predicate cannot silently diverge. Useful to list valid values without grepping source or the README's Supported Architectures table, e.g. to grey out an incompatible file in a model picker before ever calling Open. The order is unspecified; callers must not depend on it. The returned slice is a fresh copy and may be mutated freely.

func TranscribeParakeet added in v1.11.0

func TranscribeParakeet(modelPath string, samples []float32, logw func(string, ...any)) (string, error)

TranscribeParakeet transcribes 16 kHz mono PCM using a local Parakeet-TDT GGUF (general.architecture=="asr", asr.head_type=="tdt") or unpacked Phonon model.fermion with its sibling config.json. See parakeet.go's doc comment for the architecture this loads and runs, and this package's other parakeet_*.go files for each stage's implementation.

For the older Parakeet GGUF, unlike the Voxtral loaders in this codebase (each cross-validated component-by-component against a second, independently-converted file of the identical checkpoint, down to byte-identical intermediate tensors), this implementation has no such second reference to diff against -- Parakeet-TDT is only known to this codebase through one community GGUF conversion. Every formula was implemented against NVIDIA NeMo's own published source (features.py/rnnt.py) rather than guessed, and it has been verified end-to-end: two known English utterances transcribed correctly (TestTranscribeParakeetRealAudio), including exact punctuation and capitalization on the longer one. The one remaining flagged unknown is the joint network's activation (relu, chosen as NeMo's common published default; the checkpoint's own training config isn't recoverable from this GGUF) -- it produced correct output on both test clips regardless, but hasn't been independently confirmed against this specific checkpoint's actual training configuration or a from-scratch NeMo run.

func TranscribeVoxtralRealtime added in v1.9.0

func TranscribeVoxtralRealtime(ctx context.Context, modelPath string, samples []float32, maxExtraSteps int, logw io.Writer) (string, error)

TranscribeVoxtralRealtime transcribes 16 kHz mono PCM using a local GGUF. Model mappings and weights are owned by this call and released on return. Cancellation is checked between encoder frames/layers and decoder steps. maxExtraSteps adds optional right-padding tokens (normally zero). Decoding always stays within the encoded audio span, matching the reference schedule.

Uses the Metal fast decoder when available (MetalAvailable()), same as VoxtralModel/OpenVoxtral's own default; on a non-metal build or without a usable GPU this is always false, so behavior there is unchanged. A caller that already holds a loaded *VoxtralModel across multiple calls should still prefer VoxtralModel.TranscribeOffline, which shares this same decode algorithm but also skips the reload this function always pays.

func TranscribeVoxtralRealtimeFromSafetensors added in v1.11.0

func TranscribeVoxtralRealtimeFromSafetensors(ctx context.Context, dir string, samples []float32, maxExtraSteps int, logw io.Writer) (string, error)

TranscribeVoxtralRealtimeFromSafetensors is TranscribeVoxtralRealtime's counterpart for mistralai's official (non-GGUF) release -- see LoadVoxtralRealtimeModelFromSafetensors's doc comment for the exact directory contents expected. Shares the identical decode algorithm via decodeVoxtralRealtimeOffline; only how the config/weights/tokenizer are obtained differs.

func ValidAutoTuneEffort added in v0.4.0

func ValidAutoTuneEffort(effort string) bool

ValidAutoTuneEffort reports whether effort is an accepted public calibration level. An empty value means the default balanced profile.

func WebGPUAvailable added in v1.0.0

func WebGPUAvailable() bool

WebGPUAvailable reports whether a WebGPU device was successfully acquired. The first call performs the (one-time, cached) device acquisition and shader compilation; every subsequent call, and every prepareWebGPUWeight call, reuses the cached result -- one wasm binary transparently runs GPU-accelerated when a device is available and falls back to the existing pure-Go scalar path otherwise, with no build-time flag or LoadOptions field required.

func WritePrivacyReport added in v0.5.0

func WritePrivacyReport(w io.Writer) error

WritePrivacyReport writes a stable, indented JSON report suitable for `gopherllm --privacy`, logs, and deployment audits.

func YOLOCheckpointReference added in v1.12.0

func YOLOCheckpointReference(name string) (string, bool)

YOLOCheckpointReference maps a stock name to its pinned Hugging Face file reference. It builds the reference but does not download the checkpoint.

Types

type AgentEvent added in v0.4.0

type AgentEvent = engineimpl.AgentEvent

AgentEvent reports one step of the agentic loop while it happens.

Without this the loop is a black box: a request that fires three Wikipedia lookups and two model passes looks identical, from the outside, to one that simply took a long time. Callers use these events to show what ran, with what arguments, and how long each part took.

type AgentEventKind added in v0.4.0

type AgentEventKind = engineimpl.AgentEventKind

AgentEventKind names a step of the agentic loop.

type AgentObserver added in v0.4.0

type AgentObserver = engineimpl.AgentObserver

AgentObserver receives loop progress. It is called synchronously from the generating goroutine, so it must not block.

type AgenticTool added in v0.4.0

type AgenticTool = engineimpl.AgenticTool

AgenticTool is a server-owned tool that the agent loop may execute itself. Unlike a caller-supplied ToolDefinition, its result is fed straight back to the model. This is appropriate for bounded, read-only integrations such as knowledge retrieval; caller-owned tools remain the caller's responsibility.

Construct it with field names. Timeout, MaxResultBytes and Trusted were added after the type shipped, so an unkeyed composite literal (gopherllm.AgenticTool{def, exec}) no longer compiles. Every construction site in this repository was already keyed (see server/research.go, server/wikimedia.go, and every test), which is why the fields could be added at all — this is a loud, compile-time break for an external unkeyed literal, not a silent behavior change.

func NewTool added in v1.8.0

func NewTool[Args any](name, description string, run func(context.Context, Args) (string, error)) AgenticTool

NewTool builds an AgenticTool from a Go function, deriving the tool's JSON Schema from Args by reflection and unmarshalling the model's arguments back into it.

type args struct {
    City string `json:"city" desc:"City name, e.g. Hamburg"`
    Unit string `json:"unit,omitempty" desc:"Temperature unit" enum:"c,f"`
}
tool := gopherllm.NewTool("get_weather", "Current weather for a city.",
    func(ctx context.Context, a args) (string, error) { ... })

Schema rules, all derivable from tags a Go developer already writes:

  • the property name is the json tag, or the lowercased field name;
  • desc:"…" becomes the property description — write it for a small model, since this text is most of what decides whether the tool gets called correctly, and it is paid for on every request;
  • enum:"a,b,c" becomes a JSON Schema enum, which small models honor far more reliably than the same constraint stated in prose;
  • a field is required unless it is a pointer or its json tag carries omitempty — chosen so the zero value of Args is always a valid, all-optional tool with no extra ceremony.

Supported field kinds: string, the integer and float kinds, bool, slices of those, and one level of nested struct. Use struct{} for a tool that takes no arguments.

NewTool panics on a type it cannot describe (a channel, a func, an interface, a map with non-string keys). This is deliberate and is the one panic in this package's public API: the failure depends only on a compile-time type, so it cannot be triggered by a model, a request, or a file on disk — it fires on the first line of your program or never. Returning an error here would cost every caller a check for a condition their own first test run already catches, and would stop tools composing inside a slice literal.

A decode failure or a missing required field is returned to the MODEL as the tool's result (as ordinary content, with a nil error), not to the caller as an error, so the model can repair its own call on the next round instead of the turn simply failing.

The generated schema bytes are fixed at construction time. Keep the returned AgenticTool value and reuse it across requests: the rendered tools block must be byte-identical across the loop's rounds for the Runner's KV prefix cache to hit on it, which on local CPU decode is real prefill time.

type Analysis

type Analysis = engineimpl.Analysis

Analysis is a structural report over a GGUF header: identity, geometry, quantization mix, tokenizer properties, and derived estimates. Everything here comes from the header and metadata — no tensor data is read — so analyzing a multi-gigabyte file is instant.

func AnalyzeGGUF

func AnalyzeGGUF(g *GGUFFile, tok *Tokenizer) *Analysis

AnalyzeGGUF builds an Analysis from a parsed GGUF. tok may be nil (tokenizer metadata is then reported from raw metadata only, without template detection).

Example

ExampleAnalyzeGGUF inspects a model file's structure without loading any weights.

package main

import (
	"log"
	"os"

	gopherllm "github.com/SimonWaldherr/GopherLLM"
)

func main() {
	mmap, err := gopherllm.OpenMmap("model.gguf")
	if err != nil {
		log.Fatal(err)
	}
	defer mmap.Close()
	gguf, err := gopherllm.ParseGGUF(mmap.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	tok, _ := gopherllm.TokenizerFromMetadata(gguf.Metadata)
	gopherllm.AnalyzeGGUF(gguf, tok).WriteText(os.Stdout)
}

type ArchDType added in v1.2.0

type ArchDType = engineimpl.ArchDType

ArchDType is Analysis.DTypes reshaped for JSON: a human-readable type name and its byte share, rather than the internal GGMLType enum.

type ArchGraph added in v1.2.0

type ArchGraph = engineimpl.ArchGraph

ArchGraph is the full response for the architecture viewer: stats, an optional vision tower, the node graph, the per-layer schedule, and a glossary of the terms referenced by node badges.

func BuildArchGraph added in v1.2.0

func BuildArchGraph(g *GGUFFile, cfg Config, a *Analysis, vision *ArchVisionInput) *ArchGraph

BuildArchGraph turns a parsed GGUF header, its derived Config, and an already-computed Analysis into a renderable architecture graph. vision may be nil for a text-only model.

func RunnerArchGraph added in v1.2.0

func RunnerArchGraph(r *Runner) *ArchGraph

RunnerArchGraph builds the architecture graph for an already-loaded Runner, including its paired vision encoder if one was loaded via LoadOptions.VisionProjector*. Exported so server-side handlers holding a *Runner (rather than the higher-level Model) can reuse it directly.

type ArchGraphLayer added in v1.2.0

type ArchGraphLayer = engineimpl.ArchGraphLayer

ArchGraphLayer records one decoder layer's mechanism, detected from tensor name presence rather than assumed from the architecture label -- so hybrid schedules (Nemotron-H's attention/Mamba mix, Qwen3.5/3.6/3.8's attention/Gated DeltaNet mix, leading dense blocks before MoE starts) show up accurately.

type ArchGraphLayerGroup added in v1.2.0

type ArchGraphLayerGroup = engineimpl.ArchGraphLayerGroup

ArchGraphLayerGroup is a consecutive run of layers with the same mechanisms. It makes a hybrid schedule readable without having to inspect every cell in the layer strip.

type ArchGraphNode added in v1.2.0

type ArchGraphNode = engineimpl.ArchGraphNode

ArchGraphNode is one box in the rendered graph. Badges are keys into ArchGraph.Glossary. Children, when present, are the node's internal structure (e.g. what is inside one transformer block).

type ArchGraphSummary added in v1.2.0

type ArchGraphSummary = engineimpl.ArchGraphSummary

ArchGraphSummary is the "at a glance" stat panel: everything a reader wants before looking at the graph itself.

type ArchGraphVision added in v1.2.0

type ArchGraphVision = engineimpl.ArchGraphVision

ArchGraphVision summarizes a paired Pixtral-style vision encoder, when one is loaded alongside the text decoder. It is nil for text-only models.

type ArchVisionInput added in v1.2.0

type ArchVisionInput = engineimpl.ArchVisionInput

ArchVisionInput carries the paired vision encoder's shape, when one is loaded, into BuildArchGraph. Runner.VisionConfig supplies this.

type AutoTuneOptions added in v0.4.0

type AutoTuneOptions = engineimpl.AutoTuneOptions

AutoTuneOptions controls calibration cost. Zero values get sane defaults.

func AutoTuneOptionsForEffort added in v0.4.0

func AutoTuneOptionsForEffort(effort string) AutoTuneOptions

AutoTuneOptionsForEffort maps a calibration effort level onto AutoTuneOptions. It is the single source of truth for what "quick", "balanced", and "thorough" mean, shared by the CLI's --auto-effort flag and the HTTP API's POST /autotune/run so the two surfaces can never silently drift apart. Unrecognized values (including "") fall back to "balanced".

Measured on a 3B Q4_K_M model: quick ~10-20s, balanced ~75s, thorough several minutes. The extra time buys interleaved rounds, which is exactly what helps on a machine whose clock swings under sustained load.

type AutoTuneResult added in v0.4.0

type AutoTuneResult = engineimpl.AutoTuneResult

AutoTuneResult is the chosen configuration plus the evidence for it. It is what gets cached, so a second run with the same model on the same machine starts instantly.

type AutoTuneSample added in v0.4.0

type AutoTuneSample = engineimpl.AutoTuneSample

AutoTuneSample is the median measurement for one candidate value.

type AutoTuneTrial added in v0.4.0

type AutoTuneTrial = engineimpl.AutoTuneTrial

AutoTuneTrial is one knob's measured outcome.

type BERTLayerWeights added in v0.4.0

type BERTLayerWeights = engineimpl.BERTLayerWeights

type BERTWeights added in v0.4.0

type BERTWeights = engineimpl.BERTWeights

BERTWeights is the encoder-only transformer graph used by GGUF BERT embeddings, including Nomic Embed and Granite Embedding models. Unlike the causal decoder graph, BERT attends over the complete input in both directions and uses LayerNorm after each residual addition.

type BoundingBox added in v1.10.0

type BoundingBox = engineimpl.BoundingBox

BoundingBox uses source-image pixel coordinates, with Max values exclusive.

type ChatContextPreparer added in v1.12.0

type ChatContextPreparer = engineimpl.ChatContextPreparer

ChatContextPreparer selects an exactly budgeted prompt. A nil preparer in PrepareChatGeneration uses the Runner's ordinary context-window planner. Custom preparers can add request-local context, such as conversation recall. A preparer must not start inference on the same Runner: preflight holds its inference lease to prevent Close from freeing model resources while rendering.

type ChatGenerator added in v1.8.0

type ChatGenerator = engineimpl.ChatGenerator

ChatGenerator matches Runner.GenerateChatStreamUntil's signature. It is exported so a tool author can drive the real loop with a scripted model and assert on exactly what their tool received and returned — the alternative is shipping a GGUF with your test suite, which is why nobody tests their tools today. *Runner satisfies it with no adapter needed.

type ChatMessage

type ChatMessage = engineimpl.ChatMessage

func AssistantMessage

func AssistantMessage(content string) ChatMessage

func AssistantToolCallMessage added in v1.8.0

func AssistantToolCallMessage(calls ...ToolCall) ChatMessage

AssistantToolCallMessage replays a turn in which the model asked for calls. It exists because every caller doing single-round tool use had to hand-build ChatMessage{Role: ChatRoleAssistant, ToolCalls: calls} — the one message shape with no constructor, and the one people got wrong by putting the call arguments in Content instead of ToolCalls.

func ToolResultMessage

func ToolResultMessage(callID, name, content string) ChatMessage

ToolResultMessage renders the output of tool call callID (named name) back into the conversation for the model to see on its next turn.

func UserMessage

func UserMessage(content string) ChatMessage

func UserMessageWithImages added in v1.0.0

func UserMessageWithImages(content string, images ...ImageContent) ChatMessage

UserMessageWithImages is UserMessage plus one or more attached images. The Mistral/Pixtral renderer accepts all of them; other vision-capable renderers may reject a message carrying more than one at render time rather than silently dropping the extras.

type ChatRole

type ChatRole = engineimpl.ChatRole

type CompressOptions added in v0.7.0

type CompressOptions = engineimpl.CompressOptions

CompressOptions configures CompressModel.

func ParseCompressOptions added in v1.14.0

func ParseCompressOptions(name string) (CompressOptions, bool)

ParseCompressOptions parses a compression target without losing the mixed tensor policy carried by Q4_K_M and Q5_K_M. ParseCompressFormat remains useful for callers that only need the corresponding base GGML encoding.

type Config

type Config = engineimpl.Config

Config is the model's hyperparameter set, read from GGUF metadata by ConfigFromGGUF and then refined against actual tensor shapes by inferAttentionShape (GGUF metadata is frequently missing or wrong about head dims, so the tensor shapes are authoritative).

Attention shape vocabulary used throughout the forward pass: HeadDim is the per-head Q/K width, ValueDim the per-head V width (usually equal), NKVHeads the number of K/V heads (< NHeads under grouped-query attention), KVMul = NHeads/NKVHeads the number of query heads sharing each KV head, and KVDim = NKVHeads*ValueDim the per-position V cache width. The scale factors (Embedding/Residual/Logit/Attention) default to 1 (or 0 meaning "use 1/sqrt(HeadDim)" for AttentionScale) and are only non-trivial for architectures whose GGUFs carry them.

func ConfigFromGGUF

func ConfigFromGGUF(gguf *GGUFFile) Config

type ContextRecallInfo added in v1.12.0

type ContextRecallInfo = engineimpl.ContextRecallInfo

ContextRecallInfo accounts for conversation history retrieved into one selected prompt. Sources contains only turns that the model actually sees, rather than every turn considered by the retrieval search.

type ContextRecallSource added in v1.12.0

type ContextRecallSource = engineimpl.ContextRecallSource

ContextRecallSource identifies one original historical turn included as reference data. EndMessage is exclusive; offsets refer to the caller's original history, before context reduction or reference-data injection.

type ContextWindowInfo added in v0.4.0

type ContextWindowInfo = engineimpl.ContextWindowInfo

ContextWindowInfo describes the exact, template-aware prompt selected for a request. The UI uses it to explain that older messages remain saved locally even when they were not sent to the model for this reply.

type ContextWindowMode added in v0.4.0

type ContextWindowMode = engineimpl.ContextWindowMode

ContextWindowMode controls how a request behaves when its rendered chat history would crowd out the model's context window. The zero value keeps the API's historical full-history behavior.

type CoreMLFFNOptions added in v1.14.0

type CoreMLFFNOptions = engineimpl.CoreMLFFNOptions

CoreMLFFNOptions selects devices for explicitly exported prefill FFNs. The default permits CPU and Neural Engine execution, leaving the GPU to Metal. Core ML decides where each operation executes.

type DTypeStat

type DTypeStat = engineimpl.DTypeStat

DTypeStat summarizes one tensor dtype's share of a model.

type DecisionAction added in v1.12.0

type DecisionAction = engineimpl.DecisionAction

type DecisionAnswer added in v1.12.0

type DecisionAnswer = engineimpl.DecisionAnswer

type DecisionCSVOptions added in v1.12.0

type DecisionCSVOptions = engineimpl.DecisionCSVOptions

DecisionCSVOptions describes the single question applied to every CSV record. With headers (the default), InputColumn names a column; without headers it is a one-based column number. Empty InputColumn sends the complete record as a JSON object (headers) or array (no headers). The result is always appended.

type DecisionCSVStats added in v1.12.0

type DecisionCSVStats = engineimpl.DecisionCSVStats

func ClassifyCSV added in v1.12.0

func ClassifyCSV(ctx context.Context, model DecisionPredictor, in io.Reader, out io.Writer, opts DecisionCSVOptions) (DecisionCSVStats, error)

ClassifyCSV is a record-at-a-time io.Reader -> io.Writer filter. It loads no model, buffers no whole file, preserves record order and flushes every output record. Quoted fields and embedded newlines follow encoding/csv semantics. On an error it stops immediately and returns completed-row stats; previously written records remain in the output. The caller owns both streams and model.

type DecisionPredictor added in v1.12.0

type DecisionPredictor = engineimpl.DecisionPredictor

DecisionPredictor allows record processing to use any native decision model.

type DecisionQuestion added in v1.12.0

type DecisionQuestion = engineimpl.DecisionQuestion

DecisionQuestion defines a choice, an ordinal score, or a noul (yes/no probability). Criteria is a label-to-description object for choice, a list of level descriptions for score, or optional false/true descriptions for noul. Choice also accepts a list of labels. json.RawMessage preserves option order; ordinary Go maps use encoding/json's deterministic key order.

type DecisionRequest added in v1.12.0

type DecisionRequest = engineimpl.DecisionRequest

DecisionRequest is the Jev-style System One request. Model is an identifier for a preloaded checkpoint, not a path or a request to download weights. MaxLen and HeadMaxLen optionally override the checkpoint's token budgets.

func DecodeDecisionRequest added in v1.12.0

func DecodeDecisionRequest(r io.Reader) (DecisionRequest, error)

DecodeDecisionRequest decodes a single request, rejecting trailing JSON.

type DecisionResult added in v1.12.0

type DecisionResult = engineimpl.DecisionResult

type DecisionUsage added in v1.12.0

type DecisionUsage = engineimpl.DecisionUsage

type DecodeBuffer

type DecodeBuffer = engineimpl.DecodeBuffer

DecodeBuffer is reusable request scratch for single-token decode and batched prefill: activation vectors (X residual stream, XN/XN2 normed views, Q/K/V/AttnOut/Proj attention buffers, Gate/Up/Hidden FFN buffers), the output logits and generation/token scratch, the sampler's candidate scratch, and precomputed RoPE tables (per-pair inverse frequencies plus per-position sin/cos filled in prepareRopeScratch). One DecodeBuffer serves successive requests and retains activation storage at its high-water capacity. Optional paths grow their scratch on first use. Not safe for concurrent use; Runner.genLock serializes requests.

func NewDecodeBuffer

func NewDecodeBuffer(config Config, maxHeadDim, maxNKVHeads, maxValueDim int) *DecodeBuffer

NewDecodeBuffer allocates reusable activations for the supplied maximum head dimensions. Optional GateUp and MTPInput storage is allocated on first use.

type Detection added in v1.10.0

type Detection = engineimpl.Detection

Detection is one class-specific, non-max-suppressed result.

func DecodeYOLOv8 added in v1.10.0

func DecodeYOLOv8(output []float32, rows, cols int, input YOLOImage, cfg YOLOConfig) ([]Detection, error)

DecodeYOLOv8 decodes standard or transposed YOLOv8 head output.

type DiffusionModel added in v1.14.0

type DiffusionModel = engineimpl.DiffusionModel

DiffusionModel runs the google/ddpm-cifar10-32 UNet locally. Calls to Generate are serialized to bound workspace memory. Close waits for an active call. Loaders never download weights or execute model-supplied code.

func OpenDiffusion added in v1.14.0

func OpenDiffusion(ctx context.Context, path string) (*DiffusionModel, error)

OpenDiffusion loads the original F32 safetensors checkpoint and its config.json and scheduler_config.json from path. Path may name the directory or diffusion_pytorch_model.safetensors. Only the validated CIFAR-10 graph and noise schedule are supported; other diffusion architectures are rejected.

type DiffusionOptions added in v1.14.0

type DiffusionOptions = engineimpl.DiffusionOptions

DiffusionOptions controls unconditional CIFAR-10 image sampling. The model produces 32×32 RGB images; it does not accept text prompts. Steps selects deterministic DDIM sampling (eta=0), with 50 steps when zero. Seed fixes the initial Gaussian noise. Results can differ slightly between compute backends.

type EmbeddingResult

type EmbeddingResult = engineimpl.EmbeddingResult

func EmbedBERT added in v0.4.0

func EmbedBERT(config Config, weights BERTWeights, tokens []uint32) (EmbeddingResult, error)

EmbedBERT executes one full bidirectional BERT encoder pass and applies the GGUF pooling mode (mean=1, CLS=2). It intentionally has no KV cache: every token needs to see all other tokens in the input.

type ExpertBias added in v0.4.0

type ExpertBias = engineimpl.ExpertBias

ExpertBias is the optional [output, expert] bias plane paired with an ExpertWeight. It is used by GPT-OSS-style MoE checkpoints, but is harmless for the bias-free Mixtral and Qwen layouts.

type ExpertScore

type ExpertScore = engineimpl.ExpertScore

type ExpertWeight added in v0.3.0

type ExpertWeight = engineimpl.ExpertWeight

ExpertWeight retains the third GGUF tensor dimension. Weight itself stores matrices, while expert tensors are laid out as [input, output, expert]. Keeping the plane geometry explicitly prevents a three-dimensional tensor from accidentally being treated as one very wide dense matrix.

type Flux3ImageKleinModel added in v1.15.0

type Flux3ImageKleinModel = engineimpl.Flux3ImageKleinModel

Flux3ImageKleinModel implements native text-to-image inference for BFL's base and flow-map (distilled) checkpoints. Reference-image editing and layout conditioning are not supported. It owns all mapped component files.

func OpenFlux3ImageKlein added in v1.15.0

func OpenFlux3ImageKlein(ctx context.Context, path string) (_ *Flux3ImageKleinModel, err error)

OpenFlux3ImageKlein loads model.safetensors, ae.safetensors and text_encoder/ from BFL's native repository layout, or their Q8_0 GGUF counterparts made by scripts/download_flux3.py. Large matrices remain packed and mmap-backed. NVFP4/FP8 CUDA variants and Diffusers-renamed tensors are not accepted.

type GGMLType

type GGMLType = engineimpl.GGMLType

GGMLType identifies a tensor's on-disk element encoding.

func ParseCompressFormat added in v0.7.0

func ParseCompressFormat(name string) (GGMLType, bool)

ParseCompressFormat maps a CLI-facing format name to the GGMLType CompressModel accepts, restricted to the formats quantize_rtn.go has encoders for (the full GGMLType enum covers many more read-only formats that aren't valid compression targets here). This legacy parser returns only a base type; use ParseCompressOptions to retain mixed preset policies. Q3_K and Q2_K are opt-in: they reduce the memory bandwidth consumed per generated token, at a progressively larger model-quality cost.

type GGUFFile

type GGUFFile = engineimpl.GGUFFile

func ParseGGUF

func ParseGGUF(data []byte) (*GGUFFile, error)

func ParseGGUFQuiet

func ParseGGUFQuiet(data []byte) (*GGUFFile, error)

type GGUFWriter added in v0.7.0

type GGUFWriter = engineimpl.GGUFWriter

func NewGGUFWriter added in v0.7.0

func NewGGUFWriter(w io.Writer, metadata map[string]MetaValue, planned []PlannedTensor, alignment int) (*GGUFWriter, error)

type GPUWeight added in v1.0.0

type GPUWeight = engineimpl.GPUWeight

GPUWeight is one tensor's WebGPU-resident copy (see Weight.GPU), uploaded once at load time by prepareWebGPUWeight and reused for every subsequent matvec -- re-uploading a multi-megabyte weight matrix on every decode step would make this slower than the CPU path it replaces, not faster.

type Gemma4LayerWeights

type Gemma4LayerWeights = engineimpl.Gemma4LayerWeights

type Gemma4MoEWeights added in v0.4.0

type Gemma4MoEWeights = engineimpl.Gemma4MoEWeights

Gemma4MoEWeights is deliberately separate from SparseMoEWeights. Gemma 4 does not replace its dense MLP with a generic sparse branch: each MoE block runs a shared dense GEGLU MLP and a scaled-router expert GEGLU MLP in parallel, normalizes each independently, then normalizes their sum.

type Gemma4PerLayerWeights added in v0.4.0

type Gemma4PerLayerWeights = engineimpl.Gemma4PerLayerWeights

Gemma4PerLayerWeights holds the global part of Gemma 4 E2B's PLE graph. TokenEmbd stores one Dim-wide slice per decoder layer in every token row. ModelProj and ProjNorm mix the scaled regular input into those slices before each layer's own gate/projection consumes its selected slice.

type Gemma4Weights

type Gemma4Weights = engineimpl.Gemma4Weights

type GenOption

type GenOption = engineimpl.GenOption

GenOption configures a single generation request on top of DefaultGenerationOptions.

func WithGenerationOptions

func WithGenerationOptions(base GenerationOptions) GenOption

WithGenerationOptions replaces the entire options struct (escape hatch for callers that already hold a GenerationOptions); later GenOptions still apply on top.

func WithJSONObject added in v1.10.0

func WithJSONObject() GenOption

WithJSONObject constrains sampling to a JSON object grammar. Stops, active tools and speculative decoding are incompatible and rejected. Streams carry JSON prefixes; only successful completion guarantees a complete object.

func WithMTPDraftTokens added in v1.4.0

func WithMTPDraftTokens(n int) GenOption

WithMTPDraftTokens enables Qwen3.5/3.6/3.8's exact greedy MTP draft head. The model must contain a NextN block and generation must be deterministic (temperature 0 or top-k 1); zero leaves MTP disabled.

func WithMaxTokens

func WithMaxTokens(n int) GenOption

WithMaxTokens caps the number of generated tokens (default 256).

func WithMinP

func WithMinP(p float32) GenOption

WithMinP drops candidates below fraction p of the best token's probability.

func WithPromptLookupTokens added in v1.12.0

func WithPromptLookupTokens(n int) GenOption

WithPromptLookupTokens enables up to n known-history draft candidates (1–7). Each candidate is target-verified; generation must use temperature 0 or top-k 1. Zero disables lookup. With MTP enabled, matching history is tried first.

func WithRepeatPenalty

func WithRepeatPenalty(p float32) GenOption

WithRepeatPenalty penalizes recently generated tokens; 1 disables it.

func WithSeed

func WithSeed(seed uint64) GenOption

WithSeed makes sampling deterministic for a fixed seed (0 = time-based).

func WithStop

func WithStop(sequences ...string) GenOption

WithStop adds stop sequences that end generation when they appear.

func WithSystemPrompt

func WithSystemPrompt(s string) GenOption

WithSystemPrompt replaces the default system prompt; pass "" for none.

func WithTemperature

func WithTemperature(t float32) GenOption

WithTemperature sets the sampling temperature; 0 selects greedy decoding.

func WithToolChoice

func WithToolChoice(choice string) GenOption

WithToolChoice sets the tool_choice behavior ("none" suppresses tools).

func WithTools

func WithTools(tools ...ToolDefinition) GenOption

WithTools offers OpenAI-shaped tool definitions to the model; calls the model makes come back in Result.ToolCalls with FinishReason "tool_calls" for the CALLER to execute and continue itself (e.g. via ToolResultMessage on a follow-up Chat call).

For a tool the loop should execute and answer with automatically — the far more common case for a "give the model a Go function" tool — build one with NewTool and run it through RunAgenticChatWithTools(model.Runner(), ...) instead, or use the agent package's Agent.Ask/Chat, which wraps that same loop with retrieval and citations on top. WithTools and an AgenticTool's Definition are otherwise the same OpenAI-shaped schema; the difference is only who executes the call.

func WithTopK

func WithTopK(k int) GenOption

WithTopK restricts sampling to the k most likely tokens; 0 disables it.

func WithTopP

func WithTopP(p float32) GenOption

WithTopP sets nucleus sampling mass in (0, 1]; 1 disables it.

type GenerationOptions

type GenerationOptions = engineimpl.GenerationOptions

func AgenticOptionsFor added in v0.4.0

func AgenticOptionsFor(options GenerationOptions, skills []Skill) (GenerationOptions, bool)

AgenticOptionsFor returns the effective generation settings for the next agent loop iteration. Keeping this separate lets the HTTP handler measure a recent-context request against the same tool definition that the model will actually see before it starts an SSE response.

func AgenticOptionsForTools added in v0.4.0

func AgenticOptionsForTools(options GenerationOptions, skills []Skill, tools []AgenticTool) (GenerationOptions, bool)

AgenticOptionsForTools adds server-owned tool definitions before applying tool_choice, so a request can opt into a built-in integration without the browser needing to send executable tool schemas itself.

func ApplyGenOptions added in v1.8.0

func ApplyGenOptions(ctx context.Context, opts ...GenOption) GenerationOptions

ApplyGenOptions builds a GenerationOptions the same way Model's own context-first methods do (DefaultGenerationOptions plus every opt, in order, with ctx attached), for the functions that don't take ...GenOption themselves — RunAgenticChat, RunAgenticChatWithTools, RunAgenticChatObserved, and RunAgenticChatWithGenerator all take a plain GenerationOptions, since they existed before the GenOption veneer and are also called by hosts (the HTTP server, the CLI) that already build one by hand from their own request/flag parsing.

options := gopherllm.ApplyGenOptions(ctx, gopherllm.WithTemperature(0.2))
result, err := gopherllm.RunAgenticChatWithTools(model.Runner(), messages, options, nil, tools, nil)

Without this, reaching for WithTemperature/WithMaxTokens/etc. on that path means either setting the corresponding GenerationOptions field directly, or noticing that a GenOption is just a func(*GenerationOptions) and invoking one by hand.

func DefaultGenerationOptions

func DefaultGenerationOptions() GenerationOptions

type GenerationResult

type GenerationResult = engineimpl.GenerationResult

func RunAgenticChat

func RunAgenticChat(r *Runner, messages []ChatMessage, options GenerationOptions, skills []Skill, onToken func(string) bool) (GenerationResult, error)

RunAgenticChat runs a chat generation, automatically resolving any load_skill call the model makes: it looks up the named skill's full body and feeds it back as a tool result, then lets the model continue, before ever returning to the caller. A tool call for anything else — i.e. every tool the CALLER supplied, as opposed to the server's own load_skill — is left untouched in the result for the caller to execute and continue via a follow-up request with a ToolResultMessage, exactly like ordinary (non-agentic) tool use. A turn that mixes a skill call with a caller tool call is treated as needing the caller (not resolved internally), so the caller never has calls silently dropped out from under it.

A turn's raw output isn't known to be "the final answer" versus a tool call until generation for that turn completes, so whenever ANY tool activity is possible this turn (skills configured, or the caller supplied tools), onToken only fires once, with the complete, already-classified content of the winning turn — never with raw, mid-formation tool-call syntax. This also holds for plain (non-skill) tool use, since a client streaming "[TOOL_CALLS]get_weather[ARGS]..." as if it were visible answer text would be exactly the kind of leak this is meant to prevent. When there is no tool activity at all for this request, this is a zero-overhead passthrough to GenerateChatStreamUntil with full incremental streaming — the common case is unaffected.

func RunAgenticChatObserved added in v0.4.0

func RunAgenticChatObserved(r *Runner, messages []ChatMessage, options GenerationOptions, skills []Skill, tools []AgenticTool, onToken func(string) bool, observe AgentObserver) (GenerationResult, error)

RunAgenticChatObserved is RunAgenticChatWithTools plus progress reporting. observe may be nil, in which case this is exactly RunAgenticChatWithTools.

func RunAgenticChatWithGenerator added in v1.8.0

func RunAgenticChatWithGenerator(generate ChatGenerator, messages []ChatMessage, options GenerationOptions, skills []Skill, tools []AgenticTool, onToken func(string) bool, observe AgentObserver) (GenerationResult, error)

RunAgenticChatWithGenerator is RunAgenticChatObserved against an arbitrary generator instead of a Runner, and is what RunAgenticChat, RunAgenticChatWithTools and RunAgenticChatObserved delegate to. Exposing the generator as ChatGenerator turns this whole loop into something testable without model weights.

func RunAgenticChatWithTools added in v0.4.0

func RunAgenticChatWithTools(r *Runner, messages []ChatMessage, options GenerationOptions, skills []Skill, tools []AgenticTool, onToken func(string) bool) (GenerationResult, error)

RunAgenticChatWithTools is RunAgenticChat with bounded, server-owned tools. It resolves a turn only when every call belongs to the supplied tools or to load_skill. A mixed turn is returned untouched so a client never loses one of its own tool calls.

type GenerationStats

type GenerationStats = engineimpl.GenerationStats

type GptOssWeights

type GptOssWeights = engineimpl.GptOssWeights

type ImageContent added in v1.0.0

type ImageContent = engineimpl.ImageContent

ImageContent is one encoded image (PNG/JPEG/anything image.Decode understands) attached to a ChatMessage. Decoding and vision-tower encoding happen lazily during rendering, not when the message is constructed.

type ImageGenerationModel added in v1.15.0

type ImageGenerationModel = engineimpl.ImageGenerationModel

ImageGenerationModel owns its mapped weights and serializes generation. Close releases them after any active generation finishes.

func OpenImageModel added in v1.15.0

func OpenImageModel(ctx context.Context, path string) (ImageGenerationModel, error)

OpenImageModel recognizes a local Qwen-Image-2.1 pipeline or a FLUX 3 Image Klein checkpoint in BFL's native layout. It never downloads or executes code.

type ImageGenerationOptions added in v1.15.0

type ImageGenerationOptions = engineimpl.ImageGenerationOptions

ImageGenerationOptions controls native text-to-image generation. Dimensions, step defaults and guidance support depend on the checkpoint. Progress runs synchronously and must not call back into the same model.

type KVCache

type KVCache = engineimpl.KVCache

KVCache stores the attention keys and values of every processed position, one flat slice per layer laid out position-major: position p's keys occupy K[layer][p*PerPosKDim : (p+1)*PerPosKDim] (all KV heads concatenated), and likewise for V. Sized to prompt+max_tokens (capped at the model context length) and reused by Runner when capacity permits; there is no ring/eviction and generation stops at its request-local cache length.

func NewKVCache

func NewKVCache(layers, kDim, vDim, maxLen int) *KVCache

NewKVCache allocates an f32 cache for `layers` layers of maxLen positions with the given per-position K and V widths (see KVCache).

func NewKVCacheF16 added in v0.3.0

func NewKVCacheF16(layers, kDim, vDim, maxLen int) *KVCache

NewKVCacheF16 is NewKVCache with half-precision row storage.

func NewKVCacheI8 added in v1.0.0

func NewKVCacheI8(layers, kDim, vDim, maxLen int) *KVCache

NewKVCacheI8 is NewKVCache with Q8_0-block row storage. Callers must have already verified kvI8Eligible(kDim, vDim, headDim, valueDim) — this constructor does not re-check alignment itself, matching NewKVCacheF16's contract of trusting its caller's format decision.

type KernelBenchRow

type KernelBenchRow = engineimpl.KernelBenchRow

KernelBenchRow is one kernel's timing in the --kernel-bench report: a named matvec (attn_q, ffn_down, output, ...) from a real layer of the loaded model, so the numbers reflect the model's true shapes and quant types rather than synthetic sizes.

type LayaModel added in v1.12.0

type LayaModel = engineimpl.LayaModel

LayaModel is a native, CPU decision encoder. It runs Laya-compatible ModernBERT/mmBERT checkpoints, including fine-tunes using the same graph. Predict is safe to share between goroutines and serializes requests. Close waits for an active request and releases all weights. No Python is executed.

func OpenLaya added in v1.12.0

func OpenLaya(ctx context.Context, dir string) (model *LayaModel, err error)

OpenLaya loads a local checkpoint directory containing rl_agent_config.json, encoder/config.json, tokenizer/{tokenizer,tokenizer_config}.json and model.safetensors. Use huggingface.DownloadLaya for Hub downloads.

type LayerWeights

type LayerWeights = engineimpl.LayerWeights

LayerWeights holds one transformer block. Attention is either split (WQ/WK/WV, with optional biases BQ/BK/BV) or fused into a single WQKV (HasQKV); the SwiGLU FFN is likewise either split (W1 = gate, W3 = up, W2 = down — llama.cpp naming) or fused gate+up in WGateUp (HasGateUp).

type LittleBitFactors added in v1.19.0

type LittleBitFactors = engineimpl.LittleBitFactors

LittleBitFactors borrows the GGUF tensor bytes for one pair of binary matrices and their scale vectors. U is [out, Rank] and V is [Rank, in]. The binary rows are padded to 32 bits, with bit zero encoding +1.

type LittleBitScale added in v1.19.0

type LittleBitScale = engineimpl.LittleBitScale

LittleBitScale holds a validated GGUF F16, BF16 or F32 vector in its original little-endian representation.

type LittleBitWeight added in v1.19.0

type LittleBitWeight = engineimpl.LittleBitWeight

LittleBitWeight stores an affine projection with one or two binary factorizations. Weight carries the input and output dimensions.

type LoadInfo

type LoadInfo = engineimpl.LoadInfo

type LoadOptions

type LoadOptions = engineimpl.LoadOptions

type MLAAttentionWeights added in v0.4.0

type MLAAttentionWeights = engineimpl.MLAAttentionWeights

MLAAttentionWeights is the DeepSeek-V2/V3/Kimi-K2 Multi-head Latent Attention layout. Q/K/V cache widths in Config are compressed widths; KB absorbs the no-position Q projection into the cached KV latent and VB expands the attended latent back into normal per-head values.

type Mamba2LayerWeights added in v0.4.0

type Mamba2LayerWeights = engineimpl.Mamba2LayerWeights

type Mamba2Weights added in v0.4.0

type Mamba2Weights = engineimpl.Mamba2Weights

type MetaValue

type MetaValue = engineimpl.MetaValue

type MetalLittleBitWeight added in v1.19.0

type MetalLittleBitWeight = engineimpl.MetalLittleBitWeight

type MetalProbe added in v0.4.0

type MetalProbe = engineimpl.MetalProbe

MetalProbe is the measured verdict on whether to enable Metal.

func LoadMetalProbe added in v0.4.0

func LoadMetalProbe(path string) (MetalProbe, bool)

LoadMetalProbe returns a cached verdict for this model+machine.

func ProbeMetal added in v0.4.0

func ProbeMetal(path string, base LoadOptions, tokens int) (MetalProbe, error)

ProbeMetal measures this model on this machine with and without Metal and reports which is faster. tokens is the generation length per side; 0 picks a sensible default.

It loads the weights twice and discards both runners, so callers should use the cached path (ProbeMetalOrCached) rather than calling this per run.

func ProbeMetalOrCached added in v0.4.0

func ProbeMetalOrCached(path string, base LoadOptions, tokens int, refresh bool) (MetalProbe, bool, error)

ProbeMetalOrCached returns a cached verdict when one exists for this model+machine, otherwise measures and caches a new one. refresh forces a re-measurement. The bool reports whether the result came from the cache.

type MetalWeight

type MetalWeight = engineimpl.MetalWeight

type MistralKVPrefixCacheStats added in v1.7.0

type MistralKVPrefixCacheStats = engineimpl.MistralKVPrefixCacheStats

MistralKVPrefixCacheStats describes the opt-in cross-conversation KV prefix cache. It is distinct from GenerationResult.PromptCache, which reports the actual prefix reuse for one generation, including the normal most-recent workspace cache.

Entries retain only token IDs and immutable K/V rows for the static Mistral prefix -- never messages, image embeddings, logits, or generated output.

type MistralPromptPrefixCacheStats added in v1.7.0

type MistralPromptPrefixCacheStats = engineimpl.MistralPromptPrefixCacheStats

MistralPromptPrefixCacheStats describes the opt-in render-time cache. It is separate from GenerationResult.PromptCache: the latter caches KV rows for a complete token prefix, while this cache only avoids repeatedly tokenizing Mistral's static BOS/system/tools prefix during rendering and context-window planning.

type MistralThinkStreamSplitter added in v0.4.0

type MistralThinkStreamSplitter = engineimpl.MistralThinkStreamSplitter

MistralThinkStreamSplitter is the streaming counterpart of extractMistralThink. It is kept separate from ThinkStreamSplitter because [THINK]...[/THINK] is a model-specific protocol verified against the Ministral-3-Reasoning GGUF template, not a generic alternate syntax.

func NewMistralThinkStreamSplitter added in v0.4.0

func NewMistralThinkStreamSplitter() MistralThinkStreamSplitter

type MmapFile

type MmapFile = engineimpl.MmapFile

MmapFile exposes a model file as one immutable byte slice, memory-mapped where the platform allows so multi-gigabyte weights are paged in on demand rather than copied. It must stay open for the Runner's lifetime.

func OpenMmap

func OpenMmap(path string) (*MmapFile, error)

OpenMmap opens path through the platform's read-only file-mapping backend. If mapping is unavailable for a specific file, it falls back to a read copy.

type MmapPrefaultMode added in v0.4.0

type MmapPrefaultMode = engineimpl.MmapPrefaultMode

MmapPrefaultMode controls how much of a mapped model is eagerly touched at load time. It affects physical page residency, not the immutable mmap view itself; the operating system remains free to evict pages later.

type Model

type Model = engineimpl.Model

Model is a loaded LLM ready for generation, chat, embeddings, and tokenization. It wraps a Runner; the same concurrency contract applies (safe to share across goroutines, requests execute one at a time).

func Open

func Open(ctx context.Context, path string, opts ...Option) (*Model, error)

Open memory-maps and loads a GGUF model file. The returned Model borrows quantized weights from the mapping zero-copy; Close releases it. ctx only gates the start of the load (weight loading itself is not interruptible).

func OpenBytes

func OpenBytes(ctx context.Context, data []byte, opts ...Option) (*Model, error)

OpenBytes loads a model from an in-memory GGUF image, copying quantized tensors into owned memory (data may be released afterwards).

type ModelEntry

type ModelEntry = engineimpl.ModelEntry

ModelEntry describes one model file found under the model directory. ID is the root-relative path (GGUF IDs omit the suffix). IsProjector marks multimodal companion files (mmproj-*/clip).

func DiscoverModels

func DiscoverModels(root string, logw io.Writer) ([]ModelEntry, error)

DiscoverModels recursively finds GGUF and Phonon .fermion files under root and reads their headers to fill in architecture, name, and support status. Unparseable files are skipped with a stderr note rather than failing the whole scan. Results put supported models first, then sort case-insensitively by their display name with ID as a deterministic tie.

func DiscoverOllamaModels added in v1.1.0

func DiscoverOllamaModels(root string, logw io.Writer) ([]ModelEntry, error)

DiscoverOllamaModels lists the GGUF models in an Ollama store at root, identified by the same "name:tag" a user would pass to `ollama run`. Entries are otherwise identical to DiscoverModels' — the same header parse fills in architecture, context length and support status — so callers can merge the two lists freely.

A manifest that is unreadable, unparseable, or whose model blob is missing is skipped with a note rather than failing the scan: a partially pulled or half-deleted model should not hide the rest of the store.

func DiscoverOllamaModelsDefault added in v1.1.0

func DiscoverOllamaModelsDefault(logw io.Writer) ([]ModelEntry, error)

DiscoverOllamaModelsDefault scans the default store, returning no entries and no error when Ollama is not installed.

func PromptModelSelection

func PromptModelSelection(dir string, entries []ModelEntry, in io.Reader, out io.Writer) (ModelEntry, error)

PromptModelSelection runs the interactive terminal picker: a numbered menu that accepts an index, a filter substring (re-listing the matches), or q/quit/exit to abort.

func SelectModel

func SelectModel(entries []ModelEntry, selector string) (ModelEntry, error)

SelectModel matches selector against the usable (supported, non-projector) entries: exact matches on id/repo/filename/name/path beat substring matches, a unique match wins, and ambiguity or matching only an unsupported/projector file produces a descriptive error listing the choices.

type ModelWeights

type ModelWeights = engineimpl.ModelWeights

type NemotronAttentionWeights added in v0.3.0

type NemotronAttentionWeights = engineimpl.NemotronAttentionWeights

type NemotronDenseFFNWeights added in v0.4.0

type NemotronDenseFFNWeights = engineimpl.NemotronDenseFFNWeights

NemotronDenseFFNWeights is the non-expert feed-forward block used by dense Nemotron-H models: up -> ReLU squared -> down. It has no router and does not use the SwiGLU graph of llama-style layers.

type NemotronHCache added in v0.3.0

type NemotronHCache = engineimpl.NemotronHCache

NemotronHCache stores the recurrent Mamba-2 state. Attention K/V continues to use KVCache so the existing f16 cache and online-attention kernels apply unchanged. Conv is [layer, channel, d_conv-1]; State is [layer, head, head_dim, d_state].

type NemotronHLayerWeights added in v0.3.0

type NemotronHLayerWeights = engineimpl.NemotronHLayerWeights

type NemotronHWeights added in v0.3.0

type NemotronHWeights = engineimpl.NemotronHWeights

type NemotronMambaWeights added in v0.3.0

type NemotronMambaWeights = engineimpl.NemotronMambaWeights

type NemotronMoEWeights added in v0.3.0

type NemotronMoEWeights = engineimpl.NemotronMoEWeights

type Option

type Option = engineimpl.Option

Option configures model loading.

func WithLogWriter

func WithLogWriter(w io.Writer) Option

WithLogWriter directs load-progress and warning diagnostics (GGUF summary, per-layer load progress, experimental-architecture warnings) to w. The default is io.Discard: as a library, GopherLLM produces no output unless asked to.

func WithMetal

func WithMetal(enabled bool) Option

WithMetal enables experimental Metal-backed kernels when the current build supports them.

func WithMmapPrefault added in v0.4.0

func WithMmapPrefault(mode MmapPrefaultMode) Option

WithMmapPrefault sets the explicit mmap warm-up policy. The zero value (MmapPrefaultAll) preserves normal eager readiness; MmapPrefaultNone is useful for profiling demand paging. WithOutOfCore changes All to Core so sparse expert banks stay cold by default.

func WithOutOfCore added in v0.4.0

func WithOutOfCore(enabled bool) Option

WithOutOfCore loads a GGUF through a CPU-only demand-paged mmap path. Scalar F16/F32/BF16 weights stay in their on-disk form rather than expanding into an owned float32 copy, and sparse MoE expert banks are not prewarmed. It cannot be combined with Metal or prepared quantized weights.

Split (sharded) models are supported and are the main reason to use this: each shard stays mapped separately and no merged copy is ever materialised, so peak memory tracks resident pages rather than model size.

func WithPrepareQuantized

func WithPrepareQuantized(enabled bool) Option

WithPrepareQuantized precomputes supported quantized scale data at load time for the prepared quantized kernels.

func WithThreads

func WithThreads(n int) Option

WithThreads sets the compute worker count. NOTE: the worker pool is shared process-wide (all Models in the process use one pool), so this is a global knob despite being a load option; the last value set wins.

func WithVisionProjector added in v1.0.0

func WithVisionProjector(path string) Option

WithVisionProjector loads a companion Pixtral-style "mmproj" vision encoder GGUF from path alongside the text decoder, enabling image content on ChatMessage (see ImageContent, Runner.HasVision).

type Pair

type Pair = engineimpl.Pair

type ParakeetConfig added in v1.11.0

type ParakeetConfig = engineimpl.ParakeetConfig

type ParakeetDecoderWeights added in v1.11.0

type ParakeetDecoderWeights = engineimpl.ParakeetDecoderWeights

type ParakeetEncoderAttention added in v1.11.0

type ParakeetEncoderAttention = engineimpl.ParakeetEncoderAttention

ParakeetEncoderAttention is one Conformer block's relative-position multi-head self-attention (Transformer-XL style).

type ParakeetEncoderConfig added in v1.11.0

type ParakeetEncoderConfig = engineimpl.ParakeetEncoderConfig

ParakeetEncoderConfig is the FastConformer encoder's configuration.

type ParakeetEncoderConvLayer added in v1.11.0

type ParakeetEncoderConvLayer = engineimpl.ParakeetEncoderConvLayer

ParakeetEncoderConvLayer is one Conformer block's convolution module.

type ParakeetEncoderLayer added in v1.11.0

type ParakeetEncoderLayer = engineimpl.ParakeetEncoderLayer

ParakeetEncoderLayer is one Conformer block: half-step FFN, relative self-attention, conv module, half-step FFN, final norm.

type ParakeetEncoderWeights added in v1.11.0

type ParakeetEncoderWeights = engineimpl.ParakeetEncoderWeights

type ParakeetJointWeights added in v1.11.0

type ParakeetJointWeights = engineimpl.ParakeetJointWeights

type ParakeetLSTMLayer added in v1.11.0

type ParakeetLSTMLayer = engineimpl.ParakeetLSTMLayer

type ParakeetModel added in v1.11.0

type ParakeetModel = engineimpl.ParakeetModel

ParakeetModel owns one loaded Parakeet-family speech model's weights. The weights are reused across calls, like those of VoxtralModel, simplified: Parakeet has no live/streaming session support yet (see parakeet.go's doc comment), only offline transcription of a complete clip, so there is no session lifecycle to manage here. Safe for concurrent use; TranscribeOffline calls do not overlap each other, since ParakeetGreedyDecodeTDT's LSTM state is call-local, but callers wanting real concurrent transcription throughput should use separate ParakeetModel instances (each maps its own weights) rather than share one.

func OpenParakeet added in v1.11.0

func OpenParakeet(path string, logw io.Writer) (*ParakeetModel, error)

OpenParakeet loads a local Parakeet-TDT GGUF or an unpacked Phonon model.fermion with its sibling config.json. It does not access the network.

type ParakeetPreprocessorConfig added in v1.11.0

type ParakeetPreprocessorConfig = engineimpl.ParakeetPreprocessorConfig

ParakeetPreprocessorConfig is the log-mel frontend's configuration.

type ParakeetRNNTConfig added in v1.11.0

type ParakeetRNNTConfig = engineimpl.ParakeetRNNTConfig

ParakeetRNNTConfig is the prediction network + joint network's configuration, including TDT's duration-bin extension over plain RNN-T.

type ParakeetSubsamplingConv added in v1.11.0

type ParakeetSubsamplingConv = engineimpl.ParakeetSubsamplingConv

ParakeetSubsamplingConv is one Conv2d stage of the dw_striding subsampling stem. Weight is flat, row-major [OutChannels][InPerGroup][KH][KW] (PyTorch's native Conv2d layout; GGUF's own dims order needed reversing to get here -- see the loader). Groups is InChannels/InPerGroup implicitly: InPerGroup==1 and OutChannels==InChannels for a depthwise stage, or InPerGroup==InChannels for a regular/pointwise stage.

type ParakeetWeights added in v1.11.0

type ParakeetWeights = engineimpl.ParakeetWeights

type PixtralVisionConfig added in v1.0.0

type PixtralVisionConfig = engineimpl.PixtralVisionConfig

PixtralVisionConfig holds a Pixtral-style vision encoder's hyperparameters, read from a companion "mmproj" GGUF's clip.*/clip.vision.* metadata. Field values below (patch_size=14, spatial_merge_size=2, etc.) were confirmed against a real mistralai/Ministral-3-3B-Instruct-2512 mmproj GGUF (Unsloth's F16 conversion) via --list-metadata/--list-tensors — they differ from vanilla Pixtral-12B (patch_size 16, no patch merging), which is exactly why every value here is read from metadata, never hardcoded.

type PixtralVisionLayerWeights added in v1.0.0

type PixtralVisionLayerWeights = engineimpl.PixtralVisionLayerWeights

PixtralVisionLayerWeights is one of the vision tower's transformer blocks: RMSNorm pre-norm residual, full (non-causal) multi-head attention with 2D RoPE, then a gated SiLU (or GELU, per UseGELU) FFN.

type PixtralVisionWeights added in v1.0.0

type PixtralVisionWeights = engineimpl.PixtralVisionWeights

PixtralVisionWeights is a loaded Pixtral vision tower + projector. See LoadPixtralVisionModel's doc comment for the full computational graph.

type PlannedTensor added in v0.7.0

type PlannedTensor = engineimpl.PlannedTensor

type PreparedChat added in v1.12.0

type PreparedChat = engineimpl.PreparedChat

PreparedChat is a single-use, request-local result of chat preflight. Its tokens and messages are private: callers cannot substitute token IDs for a different prompt. It is bound to the Runner that prepared it.

type PreparedQuantizedWeight

type PreparedQuantizedWeight = engineimpl.PreparedQuantizedWeight

func PrepareQuantizedWeight

func PrepareQuantizedWeight(data []byte, typ GGMLType, rows, cols int) *PreparedQuantizedWeight

type PreprocessedImage added in v1.0.0

type PreprocessedImage = engineimpl.PreprocessedImage

PreprocessedImage holds a patch grid ready for Pixtral's vision encoder.

func PreprocessImagePixtral added in v1.0.0

func PreprocessImagePixtral(img image.Image, patchSize, roundTo, maxEdge int, mean, std [3]float32) (*PreprocessedImage, error)

PreprocessImagePixtral resizes and normalizes an image into fixed-size patches.

func PreprocessImagePixtralDynamic added in v1.0.0

func PreprocessImagePixtralDynamic(img image.Image, patchSize, mergeSize, minTokens, maxTokens int, mean, std [3]float32) (*PreprocessedImage, error)

PreprocessImagePixtralDynamic applies Pixtral's dynamic image-sizing rule.

type PrivacyNetworkUse added in v0.5.0

type PrivacyNetworkUse = engineimpl.PrivacyNetworkUse

PrivacyNetworkUse describes data that may leave the machine only after a caller or user explicitly enables the named feature.

type PrivacyReport added in v0.5.0

type PrivacyReport = engineimpl.PrivacyReport

PrivacyReport makes GopherLLM's local-first behavior inspectable by people and deployment tooling. It deliberately describes network-capable features separately from normal inference: none are enabled implicitly.

func DefaultPrivacyReport added in v0.5.0

func DefaultPrivacyReport() PrivacyReport

DefaultPrivacyReport returns the privacy contract shared by the CLI and HTTP server. Normal model loading and inference are local and telemetry-free.

type PromptCacheInfo added in v0.4.0

type PromptCacheInfo = engineimpl.PromptCacheInfo

PromptCacheInfo reports how much of a rendered prompt was already present in the Runner's bounded KV prefix cache. It is deliberately about exact token positions, not message count: templates, tool calls, and edited turns can all change the rendered sequence without changing an obvious UI label.

type Q4KMatrix

type Q4KMatrix = engineimpl.Q4KMatrix

Q4KMatrix is a borrowed view of a Q4_K weight tensor: Rows x Cols elements packed as (Cols/256) 144-byte superblocks per row (see GGMLType.DataSize).

type Qwen35AttentionWeights added in v0.4.0

type Qwen35AttentionWeights = engineimpl.Qwen35AttentionWeights

type Qwen35Cache added in v0.4.0

type Qwen35Cache = engineimpl.Qwen35Cache

Qwen35Cache holds the Gated DeltaNet recurrent state (one HeadDim x HeadDim matrix per head per recurrent layer — the delta rule's associative memory) plus the short causal-conv history. Attention-kind layers use the separate compact K/V cache, exactly like Nemotron-H's dual-cache pattern.

type Qwen35DeltaNetWeights added in v0.4.0

type Qwen35DeltaNetWeights = engineimpl.Qwen35DeltaNetWeights

Qwen35DeltaNetWeights holds one Gated DeltaNet layer's projections. QKVConv projects the normalized hidden state to the concatenated [Q | K | V] input of the causal short convolution. Q/K are per-key-group streams, while V has one stream per value head. Gate/AlphaProj/BetaProj read directly from the un-convolved hidden state.

type Qwen35FFNWeights added in v0.4.0

type Qwen35FFNWeights = engineimpl.Qwen35FFNWeights

type Qwen35LayerWeights added in v0.4.0

type Qwen35LayerWeights = engineimpl.Qwen35LayerWeights

type Qwen35MTPState added in v1.4.0

type Qwen35MTPState = engineimpl.Qwen35MTPState

Qwen35MTPState is the independent state of the MTP draft head. Unlike the target hybrid graph it has exactly one full-attention layer, so it needs only one KV-cache slot. PendingHidden carries the target's final hidden state from the preceding position; it is intentionally separate from draft-only hidden state, because speculative candidate rows must never overwrite the accepted target boundary.

type Qwen35MTPWeights added in v1.4.0

type Qwen35MTPWeights = engineimpl.Qwen35MTPWeights

Qwen35MTPWeights is Qwen3.5/3.6/3.8's one-layer NextN/MTP draft head. The transformer sub-block has the same gated full-attention and dense SwiGLU shape as a regular Qwen full-attention layer, while the input pair and final shared head are specific to MTP.

type Qwen35Weights added in v0.4.0

type Qwen35Weights = engineimpl.Qwen35Weights

type QwenImage21Model added in v1.14.0

type QwenImage21Model = engineimpl.QwenImage21Model

QwenImage21Model owns native text-to-image components. Image editing and the vision encoder are not supported. Requests serialize their workspaces; no Python process, network service or model-supplied code runs during inference.

func OpenQwenImage21 added in v1.14.0

func OpenQwenImage21(ctx context.Context, path string) (_ *QwenImage21Model, err error)

OpenQwenImage21 loads a local Diffusers layout or the compact GGUF component layout produced by scripts/download_qwen_image21.py. Large matrices stay mmap-backed; this function does not download model files.

type QwenImage21Options added in v1.14.0

type QwenImage21Options = engineimpl.QwenImage21Options

QwenImage21Options controls native text-to-image generation. Zero dimensions use 256x256 for a manageable local workload; the official pipeline defaults to 2048x2048. Dimensions must be multiples of 32, between 32 and 2048. Zero Steps uses 40 for the base model or the checkpoint's fixed Turbo schedule. Zero GuidanceScale means 1 (no classifier-free guidance). A scale above 1 requires NegativePrompt and executes a second transformer branch each step.

type Rng

type Rng = engineimpl.Rng

Rng is a xorshift64 generator. Generation is fully deterministic for a fixed seed (the CLI's --seed): the same seed replays the same tokens.

func NewRng

func NewRng(seed uint64) *Rng

NewRng seeds an Rng; a zero seed is remapped to a fixed non-zero constant because xorshift has an all-zero fixed point.

type Runner

type Runner = engineimpl.Runner

Runner is a fully loaded model ready to generate: parsed GGUF header, tokenizer, config, and weights (one of the three kind-specific sets). Generations and embeddings are serialized by genLock — a Runner is safe to share across goroutines (the HTTP server does), but runs one request at a time. modelMu keeps borrowed weight storage alive for every active reader; Close takes it exclusively, then resource-consuming calls begun afterwards return ErrRunnerClosed.

func RunnerFromGGUFBytes

func RunnerFromGGUFBytes(data []byte) (*Runner, error)

RunnerFromGGUFBytes loads a model from an in-memory GGUF, copying quantized tensors into owned memory. It is silent; use Open with WithLogWriter for load-progress diagnostics.

func RunnerFromGGUFBytesWithOptions

func RunnerFromGGUFBytesWithOptions(data []byte, options LoadOptions) (*Runner, error)

func RunnerFromGGUFBytesWithVision added in v1.0.0

func RunnerFromGGUFBytesWithVision(textData, visionData []byte, options LoadOptions) (*Runner, error)

RunnerFromGGUFBytesWithVision loads a text-decoder GGUF plus a paired Pixtral-style vision-encoder "mmproj" GGUF, both from bytes. Sugar over LoadOptions.VisionProjectorBytes.

type RuntimeTuning added in v0.4.0

type RuntimeTuning = engineimpl.RuntimeTuning

RuntimeTuning is an opaque snapshot of the process-wide runtime knobs that Auto Mode may change. Hosts that tune after initialization can capture it first and restore it when switching to an uncalibrated model.

The snapshot includes raw prefill and Metal-scheduling overrides rather than resolved values, preserving environment and model-aware defaults on restore.

func CaptureRuntimeTuning added in v0.4.0

func CaptureRuntimeTuning() RuntimeTuning

CaptureRuntimeTuning captures the current process-wide runtime settings.

type SafetensorsDType added in v1.12.0

type SafetensorsDType = engineimpl.SafetensorsDType

SafetensorsDType is the stored numeric representation of a safetensors tensor. The root alias keeps the original API available while the parser lives in its format package.

type SafetensorsFile added in v1.11.0

type SafetensorsFile = engineimpl.SafetensorsFile

SafetensorsFile is a parsed safetensors container. Data is the raw file bytes (typically mmap-backed); tensor bytes are indexed by DataOffset, Begin, and End.

func ParseSafetensors added in v1.11.0

func ParseSafetensors(data []byte) (*SafetensorsFile, error)

ParseSafetensors reads a safetensors container's header and indexes every tensor's location, without copying or decoding tensor data.

type SafetensorsTensorInfo added in v1.11.0

type SafetensorsTensorInfo = engineimpl.SafetensorsTensorInfo

SafetensorsTensorInfo is one tensor's entry in a safetensors header.

type SamplerConfig

type SamplerConfig = engineimpl.SamplerConfig

SamplerConfig holds the user-tunable sampling knobs. Disabled values: TopK <= 0 (consider all tokens), TopP >= 1, MinP <= 0, RepeatPenalty == 1. Temperature 0 means greedy decoding. See the file comment above for how the knobs compose, and GenerationOptions.Validate for the accepted ranges.

func DefaultSamplerConfig

func DefaultSamplerConfig() SamplerConfig

DefaultSamplerConfig is a generic chat baseline. Model vendors publish family-specific recommendations that override these (e.g. Gemma wants temp 1.0 / top-p 0.95 / top-k 64).

type Skill

type Skill = engineimpl.Skill

Skills give a model on-demand access to written-out instructions it doesn't need in context by default: a name and one-line description are always visible (via the load_skill tool's description), and the full body is only loaded when the model actually asks for it — the same progressive-disclosure design as Claude's Agent Skills. Layout on disk mirrors that convention too:

skills/
  pdf-fill/SKILL.md
  git-review/SKILL.md

each SKILL.md is a Markdown file with a YAML-ish frontmatter header:

---
name: pdf-fill
description: Fill out a PDF form given field values.
---
Full instructions the model receives once it loads this skill...

A flat "skills/*.md" layout (no per-skill subdirectory) is also accepted, using the filename (minus extension) as the fallback name.

func LoadSkills

func LoadSkills(dir string) ([]Skill, error)

LoadSkills discovers every skill under dir. An empty dir returns (nil, nil) so the feature is a no-op unless explicitly configured.

type SparseMoEWeights added in v0.4.0

type SparseMoEWeights = engineimpl.SparseMoEWeights

SparseMoEWeights describes the common llama/Mixtral/Qwen sparse FFN graph. The router is followed by selected SwiGLU experts. Qwen2-MoE additionally supplies a gated shared expert; GPT-OSS uses the same sparse layout with a slightly different SwiGLU activation and expert biases.

type SpeculationStats added in v1.12.0

type SpeculationStats = engineimpl.SpeculationStats

type SpeechAudio added in v1.14.0

type SpeechAudio = engineimpl.SpeechAudio

SpeechAudio is mono, floating-point PCM at SampleRate samples per second.

type TTSModel added in v1.14.0

type TTSModel = engineimpl.TTSModel

TTSModel runs the single-speaker MMS/VITS architecture directly in Go. The initial supported tokenizer is the German MMS character tokenizer. Model weights have their own license; OpenTTS never downloads or redistributes them.

func OpenTTS added in v1.14.0

func OpenTTS(ctx context.Context, path string) (*TTSModel, error)

OpenTTS loads config.json, tokenizer_config.json, vocab.json and model.safetensors from a local facebook/mms-tts-deu model directory. Training-only posterior and duration-posterior weights are not retained.

type TTSOptions added in v1.14.0

type TTSOptions = engineimpl.TTSOptions

TTSOptions controls MMS speech synthesis. Zero Speed means the model's default rate. Seed makes repeated calls reproducible within this engine; it does not select the same random sequence as PyTorch.

type TensorInfo

type TensorInfo = engineimpl.TensorInfo

type TensorStat

type TensorStat = engineimpl.TensorStat

TensorStat identifies one tensor and its size for the largest-tensors list.

type ThinkStreamSplitter added in v0.4.0

type ThinkStreamSplitter = engineimpl.ThinkStreamSplitter

ThinkStreamSplitter separates <think> blocks while text is still arriving in arbitrary-sized chunks. Tokens need not align with tags, so a short suffix is retained until it can no longer be the beginning of a marker. It deliberately preserves whitespace: the final GenerationResult remains the canonical trimmed representation, while stream consumers receive each character exactly once.

func NewThinkStreamSplitter added in v0.4.0

func NewThinkStreamSplitter(initialReasoning bool) ThinkStreamSplitter

type TokenMatch

type TokenMatch = engineimpl.TokenMatch

TokenMatch is one vocabulary entry, with Score meaning depending on the producing call: SearchTokens leaves it 0; NearestTokens sets cosine similarity.

func SearchTokens

func SearchTokens(tok *Tokenizer, query string, limit int) []TokenMatch

SearchTokens finds vocabulary entries whose decoded text contains query (case-insensitive), exact matches first, capped at limit (<=0 means 100). Both the raw vocab form (with byte/▁ markers) and the human-decoded form are searched, so "hello", " hello", and "▁hello"-style pieces all match.

type TokenProb

type TokenProb = engineimpl.TokenProb

TokenProb pairs a token id with its (possibly unnormalized) weight while a candidate set is being filtered and sampled.

type Tokenizer

type Tokenizer = engineimpl.Tokenizer

func TokenizerFromMetadata

func TokenizerFromMetadata(metadata map[string]MetaValue) (*Tokenizer, error)

TokenizerFromMetadata builds a tokenizer from GGUF tokenizer metadata.

type TokenizerMode

type TokenizerMode = engineimpl.TokenizerMode

type ToolCall

type ToolCall = engineimpl.ToolCall

ToolCall is one function call requested by the assistant, OpenAI-compatible.

type ToolCallFunction

type ToolCallFunction = engineimpl.ToolCallFunction

ToolCallFunction is the OpenAI-compatible function payload of a tool call.

type ToolDefinition

type ToolDefinition = engineimpl.ToolDefinition

ToolDefinition is one entry of an OpenAI-compatible "tools" array.

type ToolFunctionDef

type ToolFunctionDef = engineimpl.ToolFunctionDef

ToolFunctionDef describes a callable function, OpenAI-compatible.

type VoxtralModel added in v1.10.0

type VoxtralModel = engineimpl.VoxtralModel

VoxtralModel owns one loaded Voxtral Realtime GGUF. Open once and create a fresh session for each recording. Exactly one session may be active per model; separate instances can serve independent concurrent recordings. All lifecycle methods are safe to call concurrently. Do not copy a model. The zero value is closed; use OpenVoxtral.

func OpenVoxtral added in v1.10.0

func OpenVoxtral(ctx context.Context, path string, opts ...VoxtralOption) (*VoxtralModel, error)

OpenVoxtral maps a local GGUF, loads its tokenizer, and prepares weights once. No network access or audio capture is performed. NewSession warms the silence prefix for each recording before accepting live audio.

func OpenVoxtralFromGGUFBytes added in v1.10.0

func OpenVoxtralFromGGUFBytes(ctx context.Context, data []byte, opts ...VoxtralOption) (*VoxtralModel, error)

OpenVoxtralFromGGUFBytes loads a self-contained Voxtral Realtime GGUF already held in memory. It is intended for browser/WASM callers, where a user-selected File cannot be memory-mapped. The caller must keep data alive until Close returns when the supplied bytes are backed by external storage.

type VoxtralOption added in v1.10.0

type VoxtralOption = engineimpl.VoxtralOption

VoxtralOption configures the local speech runtime without global settings.

func WithVoxtralLogWriter added in v1.10.0

func WithVoxtralLogWriter(w io.Writer) VoxtralOption

WithVoxtralLogWriter enables diagnostics. The default is io.Discard.

func WithVoxtralMetal added in v1.10.0

func WithVoxtralMetal(enabled bool) VoxtralOption

WithVoxtralMetal selects Metal when supported by the build. The default enables it when available; false disables both loading and fast decoding.

type VoxtralRealtimeConfig added in v1.9.0

type VoxtralRealtimeConfig = engineimpl.VoxtralRealtimeConfig

type VoxtralRealtimeDecoderConfig added in v1.9.0

type VoxtralRealtimeDecoderConfig = engineimpl.VoxtralRealtimeDecoderConfig

type VoxtralRealtimeDecoderLayer added in v1.9.0

type VoxtralRealtimeDecoderLayer = engineimpl.VoxtralRealtimeDecoderLayer

VoxtralRealtimeDecoderLayer is one decoder block: standard pre-norm GQA attention (split-half RoPE, sliding-window causal mask), then FFN preceded by the Ada-RMSNorm scale gate (AdaLinear1/2, no biases) computed from the fixed time-conditioning vector. No biases anywhere in this block.

type VoxtralRealtimeDecoderState added in v1.9.0

type VoxtralRealtimeDecoderState = engineimpl.VoxtralRealtimeDecoderState

VoxtralRealtimeDecoderState is one generation's mutable state: per-layer K/V history (each entry NKVHeads*HeadDim wide) and the fixed per-layer Ada scale gates, computed once from the checkpoint's built-in delay and reused for every position.

func NewVoxtralRealtimeDecoderState added in v1.9.0

func NewVoxtralRealtimeDecoderState(cfg VoxtralRealtimeConfig, weights VoxtralRealtimeWeights, numDelayTokens int) (*VoxtralRealtimeDecoderState, error)

NewVoxtralRealtimeDecoderState allocates decode state and precomputes the fixed per-layer Ada scale gates. numDelayTokens selects the streaming delay to condition on; pass cfg.Time.DefaultNumDelayTokens for the checkpoint's own default (see this file's doc comment -- MODEL.md verified this is a scalar "how many tokens do we lag behind the audio", not a position-dependent signal).

type VoxtralRealtimeDecoderWeights added in v1.9.0

type VoxtralRealtimeDecoderWeights = engineimpl.VoxtralRealtimeDecoderWeights

type VoxtralRealtimeEncoderConfig added in v1.9.0

type VoxtralRealtimeEncoderConfig = engineimpl.VoxtralRealtimeEncoderConfig

type VoxtralRealtimeEncoderConv added in v1.9.0

type VoxtralRealtimeEncoderConv = engineimpl.VoxtralRealtimeEncoderConv

VoxtralRealtimeEncoderConv is one of the two causal Conv1d layers in the encoder's conv stem. Weight is flattened [Kernel][In][Out] (fastest to slowest, matching the GGUF tensor's own dim order) rather than a Weight matvec type: a strided causal conv isn't a single matrix multiply.

type VoxtralRealtimeEncoderLayer added in v1.9.0

type VoxtralRealtimeEncoderLayer = engineimpl.VoxtralRealtimeEncoderLayer

VoxtralRealtimeEncoderLayer is one pre-norm transformer block of the audio encoder: full (non-GQA) attention with split-half RoPE and a sliding causal mask, then a gated SwiGLU FFN. K carries no bias (see this file's doc comment); every other projection does.

type VoxtralRealtimeEncoderWeights added in v1.9.0

type VoxtralRealtimeEncoderWeights = engineimpl.VoxtralRealtimeEncoderWeights

type VoxtralRealtimeMelConfig added in v1.9.0

type VoxtralRealtimeMelConfig = engineimpl.VoxtralRealtimeMelConfig

This file loads mistralai's Voxtral Realtime streaming speech-to-text model (general.architecture "voxtral_realtime") from a single self-contained GGUF. Unlike Pixtral's vision tower (a companion "mmproj" GGUF paired with a separate text-model GGUF, see pixtral_vision.go), a Voxtral Realtime GGUF bundles the mel-spectrogram frontend, the causal audio encoder, the audio-to-text adapter, and the LLM decoder in one file under four tensor-name prefixes: "frontend.*", "enc.*", "proj.*", "dec.*".

Architecture (verified against a real mistralai/Voxtral-Mini-4B-Realtime-2602 Q6_K GGUF via --list-metadata / --list-tensors, cross-checked against huggingface/transformers' modeling_voxtral_realtime.py and antirez/voxtral.c's from-scratch C port):

  1. Frontend: log-mel spectrogram. STFT with the model's own precomputed Hann window (frontend.window) and mel filterbank (frontend.mel_filterbank, [NFFT/2+1 -> NumMels]), then the stt.frontend.* normalize/global_log_mel_max settings -- not a generic librosa-default mel, so both tensors must come from the checkpoint, never be recomputed from scratch.
  2. Causal audio encoder ("enc.*"): two causal Conv1d layers (kernel 3; conv.0 stride 1, mel bins -> DModel; conv.1 stride 2, DModel -> DModel, halving the frame rate) each followed by GELU, then NLayers pre-norm transformer blocks -- full (non-GQA) attention with split-half RoPE (GGUF Q/K rows and Q bias are permuted from the interleaved source) and a sliding-window causal mask, SwiGLU FFN. Biases are present on q/v/out/ffn_down but not on k (verified: k.bias is absent from the tensor inventory while q/v/out/ffn_down.bias are present).
  3. Adapter ("proj.*"): concatenate DownsampleFactor consecutive encoder output frames (DModel*DownsampleFactor == InputDim), linear -> GELU -> linear, no biases, producing one embedding per AudioLengthPerTok output tokens in the decoder's own hidden size.
  4. Decoder ("dec.*"): a Ministral-style GQA transformer (split-half RoPE for the GGUF's permuted Q/K rows, unlike the original safetensors, sliding-window causal attention, SwiGLU FFN, tied token embedding / output projection) with one addition: each block's FFN branch is modulated by an Ada-RMSNorm-style scale gate conditioned on a fixed "time" signal (dec.time_embed.inv_freq, sinusoidal in DefaultNumDelayTokens) -- h_norm * (1 + ada_up(gelu(ada_down(t_cond)))) applied only before the FFN, never before attention. Audio embeddings are summed elementwise into the text token embeddings at matching sequence positions (no interleaving, no placeholder tokens).

This file only loads and validates the weights; the forward pass (encoder attention/conv graph, adapter, ada-conditioned decoder graph) and Runner integration land separately.

type VoxtralRealtimeProjectorConfig added in v1.9.0

type VoxtralRealtimeProjectorConfig = engineimpl.VoxtralRealtimeProjectorConfig

type VoxtralRealtimeProjectorWeights added in v1.9.0

type VoxtralRealtimeProjectorWeights = engineimpl.VoxtralRealtimeProjectorWeights

type VoxtralRealtimeSession added in v1.9.0

type VoxtralRealtimeSession = engineimpl.VoxtralRealtimeSession

VoxtralRealtimeSession keeps one Voxtral GGUF mapped while a microphone is active. Audio may be appended in small chunks; model weights are never reloaded between chunks. Frontend, encoder and decoder state persist so only new frames and tokens are evaluated on each Push.

func NewVoxtralRealtimeSession added in v1.9.0

func NewVoxtralRealtimeSession(modelPath string, logw io.Writer) (*VoxtralRealtimeSession, error)

NewVoxtralRealtimeSession loads a local Voxtral Realtime GGUF once for a live transcription session. Call Close when microphone capture ends.

func NewVoxtralRealtimeSessionContext added in v1.9.0

func NewVoxtralRealtimeSessionContext(ctx context.Context, modelPath string, logw io.Writer) (*VoxtralRealtimeSession, error)

NewVoxtralRealtimeSessionContext prepares the fixed silence prefix before microphone capture begins. Loading, warmup and subsequent pushes can cancel.

type VoxtralRealtimeTimeConfig added in v1.9.0

type VoxtralRealtimeTimeConfig = engineimpl.VoxtralRealtimeTimeConfig

type VoxtralRealtimeWeights added in v1.9.0

type VoxtralRealtimeWeights = engineimpl.VoxtralRealtimeWeights

type Weight

type Weight = engineimpl.Weight

Weight stores owned F32 values, raw quantized or scalar tensor bytes, or a LittleBit projection. Raw scalar bytes let out-of-core loads keep a mmap-backed matrix in its on-disk representation and convert rows on demand. Rows/Cols describe the raw and factored forms. The owned F32 form infers rows from len(F32)/cols at the call site for compatibility with existing callers.

type YOLOConfig added in v1.10.0

type YOLOConfig = engineimpl.YOLOConfig

YOLOConfig controls native YOLO image preparation and post-processing. It aliases the vision package type to preserve the root API.

func DefaultYOLOConfig added in v1.10.0

func DefaultYOLOConfig() YOLOConfig

DefaultYOLOConfig returns defaults for a 640x640 detector input.

type YOLOImage added in v1.10.0

type YOLOImage = engineimpl.YOLOImage

YOLOImage is a letterboxed, CHW RGB image prepared for a detector.

func PrepareYOLOImage added in v1.10.0

func PrepareYOLOImage(img image.Image, cfg YOLOConfig) (YOLOImage, error)

PrepareYOLOImage letterboxes an image into CHW RGB float32 pixels.

type YOLOModel added in v1.12.0

type YOLOModel = engineimpl.YOLOModel

YOLOModel is a loaded YOLOv8 or YOLO11 detection network.

func LoadYOLO added in v1.12.0

func LoadYOLO(path string) (*YOLOModel, error)

LoadYOLO loads a safetensors or Ultralytics .pt detector checkpoint.

func LoadYOLOPyTorch added in v1.12.0

func LoadYOLOPyTorch(data []byte) (*YOLOModel, error)

LoadYOLOPyTorch loads an Ultralytics .pt detector checkpoint without executing Python pickle code.

func LoadYOLOSafetensors added in v1.12.0

func LoadYOLOSafetensors(data []byte) (*YOLOModel, error)

LoadYOLOSafetensors loads a detector from safetensors bytes.

Directories

Path Synopsis
Package agent composes a gopherllm.Model, a rag.Index and a set of tools into Ask/Chat with citations — the layer that used to be two hundred lines of everybody's main.go.
Package agent composes a gopherllm.Model, a rag.Index and a set of tools into Ask/Chat with citations — the layer that used to be two hundred lines of everybody's main.go.
Package agentos lets a model propose local shell commands and gates whether they may run.
Package agentos lets a model propose local shell commands and gates whether they may run.
benchmarks
sme
Package sme contains an opt-in SME microkernel experiment, independent of model inference.
Package sme contains an opt-in SME microkernel experiment, independent of model inference.
Package chatmemory recalls complete, older conversation turns with BM25.
Package chatmemory recalls complete, older conversation turns with BM25.
cmd
csv-workbench command
CSV Workbench runs native Laya classification and optional Ministral assistance.
CSV Workbench runs native Laya classification and optional Ministral assistance.
gopherllm command
gopherllm-convert-littlebit command
Command gopherllm-convert-littlebit converts an already trained LittleBit checkpoint into a GopherLLM GGUF.
Command gopherllm-convert-littlebit converts an already trained LittleBit checkpoint into a GopherLLM GGUF.
gopherllm-eval command
gopherllm-eval evaluates configurable Chat Completions endpoints.
gopherllm-eval evaluates configurable Chat Completions endpoints.
gopherllm-synth-testmodel command
Command gopherllm-synth-testmodel writes internal/testmodel's minimal, deterministic GGUF so the non-Go binding test suites (bindings/rust, bindings/python, bindings/swift) have a real model to run against without a binary .gguf checked into the repository:
Command gopherllm-synth-testmodel writes internal/testmodel's minimal, deterministic GGUF so the non-Go binding test suites (bindings/rust, bindings/python, bindings/swift) have a real model to run against without a binary .gguf checked into the repository:
gopherllm-wasm command
Command gopherllm-wasm compiles GopherLLM's inference engine to WebAssembly for in-browser use.
Command gopherllm-wasm compiles GopherLLM's inference engine to WebAssembly for in-browser use.
gopherllm-wasm/devserver command
Command devserver is a tiny static file server for manually exercising the wasm browser harness (cmd/gopherllm-wasm/testdata/harness) during development.
Command devserver is a tiny static file server for manually exercising the wasm browser harness (cmd/gopherllm-wasm/testdata/harness) during development.
image-generate command
Command image-generate runs native Qwen/FLUX text-to-image generation or the unconditional CIFAR-10 reference model.
Command image-generate runs native Qwen/FLUX text-to-image generation or the unconditional CIFAR-10 reference model.
parakeet-transcribe command
Command parakeet-transcribe transcribes audio with Parakeet-TDT GGUF models and unpacked Phonon models.
Command parakeet-transcribe transcribes audio with Parakeet-TDT GGUF models and unpacked Phonon models.
tts-synthesize command
Command tts-synthesize runs native MMS/VITS text-to-speech and writes mono PCM WAV.
Command tts-synthesize runs native MMS/VITS text-to-speech and writes mono PCM WAV.
voxtral-transcribe command
Command voxtral-transcribe is a minimal, standalone smoke-test CLI for GopherLLM's Voxtral Realtime support (see voxtral_realtime.go, voxtral_realtime_audio.go, voxtral_realtime_decoder.go in the module root).
Command voxtral-transcribe is a minimal, standalone smoke-test CLI for GopherLLM's Voxtral Realtime support (see voxtral_realtime.go, voxtral_realtime_audio.go, voxtral_realtime_decoder.go in the module root).
whisper-transcribe command
Command whisper-transcribe runs GopherLLM's native Whisper recognizer.
Command whisper-transcribe runs GopherLLM's native Whisper recognizer.
yolo-detect command
Command yolo-detect runs GopherLLM's native YOLO object detector (YOLOv8 and YOLO11; see internal/vision/yolo) over one image.
Command yolo-detect runs GopherLLM's native YOLO object detector (YOLOv8 and YOLO11; see internal/vision/yolo) over one image.
Package coreml runs separately exported embedding encoders through Core ML.
Package coreml runs separately exported embedding encoders through Core ML.
examples
complaints-assistant command
Complaints Assistant is a deliberately small local demo server.
Complaints Assistant is a deliberately small local demo server.
embedded-reply-service command
Embedded Reply Service shows how an application can own its HTTP surface while using one GopherLLM Model directly in the same process.
Embedded Reply Service shows how an application can own its HTTP surface while using one GopherLLM Model directly in the same process.
embedded-speech command
Embedded Speech streams raw PCM recordings through one reusable local model.
Embedded Speech streams raw PCM recordings through one reusable local model.
model-sources command
Model Sources shows every place GopherLLM can get a model from, and that they all end at the same thing: a local .gguf path you hand to Open.
Model Sources shows every place GopherLLM can get a model from, and that they all end at the same thing: a local .gguf path you hand to Open.
pool-lifeguard-assist command
Pool Lifeguard Assist (CLI) is the smallest local, non-UI companion to the example described in README.md.
Pool Lifeguard Assist (CLI) is the smallest local, non-UI companion to the example described in README.md.
ticket-triage command
Ticket Triage reads fake/support JSONL records and emits one local human-review draft per input line.
Ticket Triage reads fake/support JSONL records and emits one local human-review draft per input line.
tool-calling command
Tool Calling is the smallest complete tool-calling program: one Go function becomes a model tool via gopherllm.NewTool, and the model executes it and answers using the result — no HTTP server, no manual tool_calls round-trip.
Tool Calling is the smallest complete tool-calling program: one Go function becomes a model tool via gopherllm.NewTool, and the model executes it and answers using the result — no HTTP server, no manual tool_calls round-trip.
vision-inspector command
Vision Inspector is the smallest useful example of local multimodal inference: one GGUF text model, one Pixtral-compatible mmproj, one image.
Vision Inspector is the smallest useful example of local multimodal inference: one GGUF text model, one Pixtral-compatible mmproj, one image.
voice-assistant command
Command voice-assistant serves a local browser speech assistant.
Command voice-assistant serves a local browser speech assistant.
Package huggingface is the public Hugging Face Hub client for GopherLLM: searching across model tasks and formats, inspecting repository artifacts, downloading exact file sets, and resolving GGUF variants for local inference.
Package huggingface is the public Hugging Face Hub client for GopherLLM: searching across model tasks and formats, inspecting repository artifacts, downloading exact file sets, and resolving GGUF variants for local inference.
internal
audioinput
Package audioinput decodes audio for the transcription commands.
Package audioinput decodes audio for the transcription commands.
cmd/genapi command
Command genapi regenerates the public facade from the engine's exported API.
Command genapi regenerates the public facade from the engine's exported API.
coreml
Package coreml executes compiled, stateless embedding models through Core ML.
Package coreml executes compiled, stateless embedding models through Core ML.
cpuinfo
Package cpuinfo provides platform CPU feature probes, core topology and hardware identity for kernel dispatch and autotuning.
Package cpuinfo provides platform CPU feature probes, core topology and hardware identity for kernel dispatch and autotuning.
engine
Package engine implements GopherLLM's model loading, inference, generation, speech and image pipelines.
Package engine implements GopherLLM's model loading, inference, generation, speech and image pipelines.
formats/phonon
Package phonon reads Fermion Research's five-value Parakeet weight container.
Package phonon reads Fermion Research's five-value Parakeet weight container.
formats/safetensors
Package safetensors reads dense tensors from the safetensors container format.
Package safetensors reads dense tensors from the safetensors container format.
jsonconstraint
Package jsonconstraint implements a bounded incremental JSON-object grammar.
Package jsonconstraint implements a bounded incremental JSON-object grammar.
layablas
Package layablas supplies bounded-workspace bidirectional attention using Accelerate.
Package layablas supplies bounded-workspace bidirectional attention using Accelerate.
numeric
Package numeric contains small numeric conversions shared by internal model and format packages.
Package numeric contains small numeric conversions shared by internal model and format packages.
outputfile
Package outputfile writes generated CLI output without replacing existing files.
Package outputfile writes generated CLI output without replacing existing files.
testmodel
Package testmodel writes a minimal, structurally complete, deterministic GGUF that GopherLLM can load and run a real (if meaningless) generation against, so tests of the embedding surfaces (mobile, the C ABI and the Rust, Python and Swift bindings built on it) exercise a real model without a binary .gguf in the repository.
Package testmodel writes a minimal, structurally complete, deterministic GGUF that GopherLLM can load and run a real (if meaningless) generation against, so tests of the embedding surfaces (mobile, the C ABI and the Rust, Python and Swift bindings built on it) exercise a real model without a binary .gguf in the repository.
threads
Package threads holds the process-wide worker override shared by internal subsystems.
Package threads holds the process-wide worker override shared by internal subsystems.
tokenizer
Code generated by scripts/generate_unicode_nfc.py; DO NOT EDIT.
Code generated by scripts/generate_unicode_nfc.py; DO NOT EDIT.
wav
Package wav reads canonical PCM16 and IEEE float32 WAV containers.
Package wav reads canonical PCM16 and IEEE float32 WAV containers.
webgpu
Package webgpu is a thin, hand-written Go wrapper over the browser's native WebGPU API (accessed via syscall/js), mirroring how internal/metal wraps Apple's Metal API for the darwin/cgo build.
Package webgpu is a thin, hand-written Go wrapper over the browser's native WebGPU API (accessed via syscall/js), mirroring how internal/metal wraps Apple's Metal API for the darwin/cgo build.
yolotest
Package yolotest builds small random-weight YOLO checkpoints (YOLOv8 and YOLO11 layouts) as safetensors or torch.save bytes, so tests of the loader, the HTTP routes and the demo can run without redistributing any real (AGPL-licensed) weights.
Package yolotest builds small random-weight YOLO checkpoints (YOLOv8 and YOLO11 layouts) as safetensors or torch.save bytes, so tests of the loader, the HTTP routes and the demo can run without redistributing any real (AGPL-licensed) weights.
Package mobile is GopherLLM's small, stable embedding surface for other languages.
Package mobile is GopherLLM's small, stable embedding surface for other languages.
Package rag is retrieval over the caller's own documents: a chunker, a hybrid BM25 + optional-vector index, and nothing else.
Package rag is retrieval over the caller's own documents: a chunker, a hybrid BM25 + optional-vector index, and nothing else.
Package speech provides resident, local speech recognition for native hosts.
Package speech provides resident, local speech recognition for native hosts.
Package voiceweb holds the one browser-side audio-capture building block that is genuinely generic enough to share between GopherLLM's own chat web UI (server/web_ui) and other GopherLLM-based applications, such as cmd/hestia: an AudioWorkletProcessor that resamples the microphone to 16kHz mono PCM16 and posts it back in ~200ms blocks.
Package voiceweb holds the one browser-side audio-capture building block that is genuinely generic enough to share between GopherLLM's own chat web UI (server/web_ui) and other GopherLLM-based applications, such as cmd/hestia: an AudioWorkletProcessor that resamples the microphone to 16kHz mono PCM16 and posts it back in ~200ms blocks.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL