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)
}
Output:
Index ¶
- Constants
- Variables
- func ArchitectureSupported(arch string) bool
- func ArgmaxOutputToken(config Config, weights ModelWeights, buf *DecodeBuffer) (uint32, bool)
- func AxpyF32(out []float32, alpha float32, x []float32)
- func CompressModel(sourcePath, outPath string, opts CompressOptions) error
- func CosineSimilarity(a, b []float32) (float32, error)
- func DecodeImageBytes(data []byte) (image.Image, error)
- func DefaultModelDir() string
- func DequantRowMXFP4(row []byte, cols int) []float32
- func DequantRowMXFP4Into(row []byte, cols int, out []float32)
- func DequantRowQ1_0(row []byte, cols int) []float32
- func DequantRowQ1_0Into(row []byte, cols int, out []float32)
- func DequantRowQ2K(row []byte, cols int) []float32
- func DequantRowQ2KInto(row []byte, cols int, out []float32)
- func DequantRowQ2_0(row []byte, cols int) []float32
- func DequantRowQ2_0Into(row []byte, cols int, out []float32)
- func DequantRowQ3K(row []byte, cols int) []float32
- func DequantRowQ3KInto(row []byte, cols int, out []float32)
- func DequantRowQ4K(row []byte, cols int) []float32
- func DequantRowQ4KInto(row []byte, cols int, out []float32)
- func DequantRowQ4_0(row []byte, cols int) []float32
- func DequantRowQ4_0Into(row []byte, cols int, out []float32)
- func DequantRowQ4_1(row []byte, cols int) []float32
- func DequantRowQ4_1Into(row []byte, cols int, out []float32)
- func DequantRowQ5K(row []byte, cols int) []float32
- func DequantRowQ5KInto(row []byte, cols int, out []float32)
- func DequantRowQ5_0(row []byte, cols int) []float32
- func DequantRowQ5_0Into(row []byte, cols int, out []float32)
- func DequantRowQ5_1(row []byte, cols int) []float32
- func DequantRowQ5_1Into(row []byte, cols int, out []float32)
- func DequantRowQ6K(row []byte, cols int) []float32
- func DequantRowQ6KInto(row []byte, cols int, out []float32)
- func DequantRowQ8K(row []byte, cols int) []float32
- func DequantRowQ8KInto(row []byte, cols int, out []float32)
- func DequantRowQ8_0(row []byte, cols int) []float32
- func DequantRowQ8_0Into(row []byte, cols int, out []float32)
- func DequantRowQ8_1(row []byte, cols int) []float32
- func DequantRowQ8_1Into(row []byte, cols int, out []float32)
- func DequantRowTQ1_0(row []byte, cols int) []float32
- func DequantRowTQ1_0Into(row []byte, cols int, out []float32)
- func DequantRowTQ2_0(row []byte, cols int) []float32
- func DequantRowTQ2_0Into(row []byte, cols int, out []float32)
- func DotF32(a, b []float32) float32
- func DotMXFP4F32(row []byte, x []float32, cols int) float32
- func DotQ1_0F32(row []byte, x []float32, cols int) float32
- func DotQ2KF32(row []byte, x []float32, cols int) float32
- func DotQ2_0F32(row []byte, x []float32, cols int) float32
- func DotQ3KF32(row []byte, x []float32, cols int) float32
- func DotQ4KF32(row []byte, x []float32, cols int) float32
- func DotQ4_0F32(row []byte, x []float32, cols int) float32
- func DotQ4_1F32(row []byte, x []float32, cols int) float32
- func DotQ5KF32(row []byte, x []float32, cols int) float32
- func DotQ5_0F32(row []byte, x []float32, cols int) float32
- func DotQ5_1F32(row []byte, x []float32, cols int) float32
- func DotQ6KF32(row []byte, x []float32, cols int) float32
- func DotQ8KF32(row []byte, x []float32, cols int) float32
- func DotQ8_0F32(row []byte, x []float32, cols int) float32
- func DotQ8_1F32(row []byte, x []float32, cols int) float32
- func DotTQ1_0F32(row []byte, x []float32, cols int) float32
- func DotTQ2_0F32(row []byte, x []float32, cols int) float32
- func EmbedVoxtralRealtimeToken(cfg VoxtralRealtimeConfig, weights VoxtralRealtimeWeights, tokenID int) ([]float32, error)
- func EncodeAudioVoxtralRealtime(cfg VoxtralRealtimeConfig, weights VoxtralRealtimeWeights, samples []float32) (audioEmbeds [][]float32, err error)
- func EncodeAudioVoxtralRealtimeContext(ctx context.Context, cfg VoxtralRealtimeConfig, weights VoxtralRealtimeWeights, ...) (audioEmbeds [][]float32, err error)
- func EncodeImagePixtral(vc PixtralVisionConfig, weights PixtralVisionWeights, img *PreprocessedImage) (embeds [][]float32, mergedRows, mergedCols int, err error)
- func F16ToF32(h uint16) float32
- func F32ToF16(f float32) uint16
- func Forward(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, ...) []float32
- func ForwardBatchInto(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardBodyInto(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardDeepSeek2BodyInto(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardGemma4Into(config Config, weights Gemma4Weights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardGptOssInto(config Config, weights GptOssWeights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardHidden(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, ...) []float32
- func ForwardHiddenGemma4(config Config, weights Gemma4Weights, cache *KVCache, buf *DecodeBuffer, ...) []float32
- func ForwardHiddenGptOss(config Config, weights GptOssWeights, cache *KVCache, buf *DecodeBuffer, ...) []float32
- func ForwardInto(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardMamba2BodyInto(cfg Config, weights Mamba2Weights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardMamba2Into(cfg Config, weights Mamba2Weights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardNemotronHBodyInto(cfg Config, weights NemotronHWeights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardNemotronHInto(cfg Config, weights NemotronHWeights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardPrefill(config Config, weights ModelWeights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardQwen35BodyInto(cfg Config, weights Qwen35Weights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardQwen35Into(cfg Config, weights Qwen35Weights, cache *KVCache, buf *DecodeBuffer, ...)
- func ForwardQwen35MTPBodyInto(cfg Config, weights Qwen35MTPWeights, state *Qwen35MTPState, token uint32, ...)
- func ForwardQwen35MTPInto(cfg Config, weights Qwen35MTPWeights, state *Qwen35MTPState, token uint32, ...)
- func ForwardVoxtralRealtimeDecoderStep(cfg VoxtralRealtimeConfig, weights VoxtralRealtimeWeights, ...) (logits []float32, err error)
- func IsYOLOCheckpoint(path string) bool
- func LoadBERTModel(data []byte, gguf *GGUFFile, borrowQuantized, prepareQuantized, useMetal bool, ...) (Config, BERTWeights, error)
- func LoadDeepSeek2Model(data []byte, gguf *GGUFFile, borrowQuantized, prepareQuantized, useMetal bool, ...) (Config, ModelWeights, error)
- func LoadGemma4Model(data []byte, gguf *GGUFFile, borrowQuantized, prepareQuantized, useMetal bool, ...) (Config, Gemma4Weights, error)
- func LoadGptOssModel(data []byte, gguf *GGUFFile, borrowQuantized, prepareQuantized, useMetal bool, ...) (Config, GptOssWeights, error)
- func LoadMamba2Model(data []byte, gguf *GGUFFile, borrow, prepareQuantized, useMetal bool, ...) (Config, Mamba2Weights, error)
- func LoadModel(data []byte, gguf *GGUFFile, borrowQuantized, prepareQuantized, useMetal bool, ...) (Config, ModelWeights, error)
- func LoadNemotronHModel(data []byte, gguf *GGUFFile, borrow, prepareQuantized, useMetal bool, ...) (Config, NemotronHWeights, error)
- func LoadParakeetModel(data []byte, gguf *GGUFFile, logw io.Writer) (ParakeetConfig, ParakeetWeights, error)
- func LoadPhononModel(data, configData []byte, logw io.Writer) (ParakeetConfig, ParakeetWeights, error)
- func LoadPixtralVisionModel(data []byte, gguf *GGUFFile, useMetal bool, logw io.Writer) (PixtralVisionConfig, PixtralVisionWeights, error)
- func LoadQwen35Model(data []byte, gguf *GGUFFile, borrow, prepareQuantized, useMetal bool, ...) (Config, Qwen35Weights, error)
- func LoadVoxtralRealtimeModel(data []byte, gguf *GGUFFile, useMetal bool, logw io.Writer) (VoxtralRealtimeConfig, VoxtralRealtimeWeights, error)
- func LoadVoxtralRealtimeModelFromSafetensors(dir string, useMetal bool, logw io.Writer) (VoxtralRealtimeConfig, VoxtralRealtimeWeights, *Tokenizer, error)
- func MatvecF32(data, x []float32, rows, cols int) []float32
- func MatvecF32Into(data, x []float32, rows, cols int, out *[]float32)
- func MatvecMXFP4Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecPreparedQ4K2IntoWithXSums(aData []byte, aPrep *PreparedQuantizedWeight, aRows, aCols int, bData []byte, ...) bool
- func MatvecPreparedQ4K3IntoWithXSums(aData []byte, aPrep *PreparedQuantizedWeight, aRows, aCols int, bData []byte, ...) bool
- func MatvecPreparedQ4KInto(data []byte, p *PreparedQuantizedWeight, x []float32, rows, cols int, ...) bool
- func MatvecPreparedQ6KInto(data []byte, p *PreparedQuantizedWeight, x []float32, rows, cols int, ...) bool
- func MatvecQ1_0Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ2KInto(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ2_0Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ3KInto(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ4K2Into(aData []byte, aRows, aCols int, bData []byte, bRows, bCols int, x []float32, ...) bool
- func MatvecQ4K2IntoWithXSums(aData []byte, aRows, aCols int, bData []byte, bRows, bCols int, x []float32, ...) bool
- func MatvecQ4K2Q6KIntoWithXSums(aData []byte, aRows, aCols int, bData []byte, bRows, bCols int, cData []byte, ...) bool
- func MatvecQ4KInto(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ4_0(data []byte, x []float32, rows, cols int) []float32
- func MatvecQ4_0Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ4_1Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ5KInto(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ5_0Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ5_1Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ6K2Into(aData []byte, aRows, aCols int, bData []byte, bRows, bCols int, x []float32, ...) bool
- func MatvecQ6K3Into(aData []byte, aRows, aCols int, bData []byte, bRows, bCols int, cData []byte, ...) bool
- func MatvecQ6KInto(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ8KInto(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ8_0(data []byte, x []float32, rows, cols int) []float32
- func MatvecQ8_0Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecQ8_1Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecTQ1_0Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MatvecTQ2_0Into(data []byte, x []float32, rows, cols int, out *[]float32)
- func MetalAvailable() bool
- func MetalError() string
- func OllamaModelsRoot() string
- func PairedVisionProjectorPath(modelPath string) (string, error)
- func ParakeetArchitectureSupported(arch string) bool
- func ParakeetDecodeTokens(vocab []string, tokens []int) (string, error)
- func ParakeetEncode(cfg ParakeetConfig, w ParakeetWeights, samples []float32) ([][]float32, error)
- func ParakeetGreedyDecodeTDT(cfg ParakeetConfig, w ParakeetWeights, encoderFrames [][]float32) []int
- func PrintModelList(entries []ModelEntry)
- func ProjectLogitsInto(config Config, weights ModelWeights, buf *DecodeBuffer, logits *[]float32)
- func Q4KMatvec3Into(wq, wk, wv Q4KMatrix, x []float32, q, k, v *[]float32) bool
- func Q4KMatvec3IntoWithXSums(wq, wk, wv Q4KMatrix, x []float32, xSums *[]float32, q, k, v *[]float32) bool
- func QuantizeRowQ2K(row []float32, cols int) []byte
- func QuantizeRowQ3K(row []float32, cols int) []byte
- func QuantizeRowQ4K(row []float32, cols int) []byte
- func QuantizeRowQ4_0(row []float32, cols int) []byte
- func QuantizeRowQ5K(row []float32, cols int) []byte
- func QuantizeRowQ5_0(row []float32, cols int) []byte
- func QuantizeRowQ5_1(row []float32, cols int) []byte
- func QuantizeRowQ6K(row []float32, cols int) []byte
- func QuantizeRowQ8_0(row []float32, cols int) []byte
- func ResolveArchitecture(gguf *GGUFFile) (arch, prefix string)
- func ResolveModelPath(selection *string, modelDir string) (string, error)
- func RunKernelBench(r *Runner, modelPath string, runs, requestedLayer int, jsonOut bool) error
- func RunnerFromPath(path string) (*Runner, LoadInfo, error)
- func RunnerFromPathWithOptions(path string, options LoadOptions) (*Runner, LoadInfo, error)
- func Sample(logits []float32, config SamplerConfig, rng *Rng, recent []uint32) uint32
- func SampleWithScratch(logits []float32, config SamplerConfig, rng *Rng, recent []uint32, ...) uint32
- func SaveAutoTune(res AutoTuneResult) error
- func SaveMetalProbe(probe MetalProbe) error
- func ScaleAddF32(out []float32, alpha float32, x []float32)
- func ScaleF32(out []float32, alpha float32)
- func SchemaOf[Args any]() json.RawMessage
- func SetNumThreads(n int)
- func SetPrefillChunk(n int)
- func SetWebGPUForceDisabled(disabled bool)
- func SupportedArchitectures() []string
- func TranscribeParakeet(modelPath string, samples []float32, logw func(string, ...any)) (string, error)
- func TranscribeVoxtralRealtime(ctx context.Context, modelPath string, samples []float32, maxExtraSteps int, ...) (string, error)
- func TranscribeVoxtralRealtimeFromSafetensors(ctx context.Context, dir string, samples []float32, maxExtraSteps int, ...) (string, error)
- func ValidAutoTuneEffort(effort string) bool
- func WebGPUAvailable() bool
- func WritePrivacyReport(w io.Writer) error
- func YOLOCheckpointReference(name string) (string, bool)
- type AgentEvent
- type AgentEventKind
- type AgentObserver
- type AgenticTool
- type Analysis
- type ArchDType
- type ArchGraph
- type ArchGraphLayer
- type ArchGraphLayerGroup
- type ArchGraphNode
- type ArchGraphSummary
- type ArchGraphVision
- type ArchVisionInput
- type AutoTuneOptions
- type AutoTuneResult
- type AutoTuneSample
- type AutoTuneTrial
- type BERTLayerWeights
- type BERTWeights
- type BoundingBox
- type ChatContextPreparer
- type ChatGenerator
- type ChatMessage
- type ChatRole
- type CompressOptions
- type Config
- type ContextRecallInfo
- type ContextRecallSource
- type ContextWindowInfo
- type ContextWindowMode
- type CoreMLFFNOptions
- type DTypeStat
- type DecisionAction
- type DecisionAnswer
- type DecisionCSVOptions
- type DecisionCSVStats
- type DecisionPredictor
- type DecisionQuestion
- type DecisionRequest
- type DecisionResult
- type DecisionUsage
- type DecodeBuffer
- type Detection
- type DiffusionModel
- type DiffusionOptions
- type EmbeddingResult
- type ExpertBias
- type ExpertScore
- type ExpertWeight
- type Flux3ImageKleinModel
- type GGMLType
- type GGUFFile
- type GGUFWriter
- type GPUWeight
- type Gemma4LayerWeights
- type Gemma4MoEWeights
- type Gemma4PerLayerWeights
- type Gemma4Weights
- type GenOption
- func WithGenerationOptions(base GenerationOptions) GenOption
- func WithJSONObject() GenOption
- func WithMTPDraftTokens(n int) GenOption
- func WithMaxTokens(n int) GenOption
- func WithMinP(p float32) GenOption
- func WithPromptLookupTokens(n int) GenOption
- func WithRepeatPenalty(p float32) GenOption
- func WithSeed(seed uint64) GenOption
- func WithStop(sequences ...string) GenOption
- func WithSystemPrompt(s string) GenOption
- func WithTemperature(t float32) GenOption
- func WithToolChoice(choice string) GenOption
- func WithTools(tools ...ToolDefinition) GenOption
- func WithTopK(k int) GenOption
- func WithTopP(p float32) GenOption
- type GenerationOptions
- func AgenticOptionsFor(options GenerationOptions, skills []Skill) (GenerationOptions, bool)
- func AgenticOptionsForTools(options GenerationOptions, skills []Skill, tools []AgenticTool) (GenerationOptions, bool)
- func ApplyGenOptions(ctx context.Context, opts ...GenOption) GenerationOptions
- func DefaultGenerationOptions() GenerationOptions
- type GenerationResult
- func RunAgenticChat(r *Runner, messages []ChatMessage, options GenerationOptions, skills []Skill, ...) (GenerationResult, error)
- func RunAgenticChatObserved(r *Runner, messages []ChatMessage, options GenerationOptions, skills []Skill, ...) (GenerationResult, error)
- func RunAgenticChatWithGenerator(generate ChatGenerator, messages []ChatMessage, options GenerationOptions, ...) (GenerationResult, error)
- func RunAgenticChatWithTools(r *Runner, messages []ChatMessage, options GenerationOptions, skills []Skill, ...) (GenerationResult, error)
- type GenerationStats
- type GptOssWeights
- type ImageContent
- type ImageGenerationModel
- type ImageGenerationOptions
- type KVCache
- type KernelBenchRow
- type LayaModel
- type LayerWeights
- type LittleBitFactors
- type LittleBitScale
- type LittleBitWeight
- type LoadInfo
- type LoadOptions
- type MLAAttentionWeights
- type Mamba2LayerWeights
- type Mamba2Weights
- type MetaValue
- type MetalLittleBitWeight
- type MetalProbe
- type MetalWeight
- type MistralKVPrefixCacheStats
- type MistralPromptPrefixCacheStats
- type MistralThinkStreamSplitter
- type MmapFile
- type MmapPrefaultMode
- type Model
- type ModelEntry
- func DiscoverModels(root string, logw io.Writer) ([]ModelEntry, error)
- func DiscoverOllamaModels(root string, logw io.Writer) ([]ModelEntry, error)
- func DiscoverOllamaModelsDefault(logw io.Writer) ([]ModelEntry, error)
- func PromptModelSelection(dir string, entries []ModelEntry, in io.Reader, out io.Writer) (ModelEntry, error)
- func SelectModel(entries []ModelEntry, selector string) (ModelEntry, error)
- type ModelWeights
- type NemotronAttentionWeights
- type NemotronDenseFFNWeights
- type NemotronHCache
- type NemotronHLayerWeights
- type NemotronHWeights
- type NemotronMambaWeights
- type NemotronMoEWeights
- type Option
- type Pair
- type ParakeetConfig
- type ParakeetDecoderWeights
- type ParakeetEncoderAttention
- type ParakeetEncoderConfig
- type ParakeetEncoderConvLayer
- type ParakeetEncoderLayer
- type ParakeetEncoderWeights
- type ParakeetJointWeights
- type ParakeetLSTMLayer
- type ParakeetModel
- type ParakeetPreprocessorConfig
- type ParakeetRNNTConfig
- type ParakeetSubsamplingConv
- type ParakeetWeights
- type PixtralVisionConfig
- type PixtralVisionLayerWeights
- type PixtralVisionWeights
- type PlannedTensor
- type PreparedChat
- type PreparedQuantizedWeight
- type PreprocessedImage
- type PrivacyNetworkUse
- type PrivacyReport
- type PromptCacheInfo
- type Q4KMatrix
- type Qwen35AttentionWeights
- type Qwen35Cache
- type Qwen35DeltaNetWeights
- type Qwen35FFNWeights
- type Qwen35LayerWeights
- type Qwen35MTPState
- type Qwen35MTPWeights
- type Qwen35Weights
- type QwenImage21Model
- type QwenImage21Options
- type Rng
- type Runner
- type RuntimeTuning
- type SafetensorsDType
- type SafetensorsFile
- type SafetensorsTensorInfo
- type SamplerConfig
- type Skill
- type SparseMoEWeights
- type SpeculationStats
- type SpeechAudio
- type TTSModel
- type TTSOptions
- type TensorInfo
- type TensorStat
- type ThinkStreamSplitter
- type TokenMatch
- type TokenProb
- type Tokenizer
- type TokenizerMode
- type ToolCall
- type ToolCallFunction
- type ToolDefinition
- type ToolFunctionDef
- type VoxtralModel
- type VoxtralOption
- type VoxtralRealtimeConfig
- type VoxtralRealtimeDecoderConfig
- type VoxtralRealtimeDecoderLayer
- type VoxtralRealtimeDecoderState
- type VoxtralRealtimeDecoderWeights
- type VoxtralRealtimeEncoderConfig
- type VoxtralRealtimeEncoderConv
- type VoxtralRealtimeEncoderLayer
- type VoxtralRealtimeEncoderWeights
- type VoxtralRealtimeMelConfig
- type VoxtralRealtimeProjectorConfig
- type VoxtralRealtimeProjectorWeights
- type VoxtralRealtimeSession
- type VoxtralRealtimeTimeConfig
- type VoxtralRealtimeWeights
- type Weight
- type YOLOConfig
- type YOLOImage
- type YOLOModel
Examples ¶
Constants ¶
const AgentEventIteration = engineimpl.AgentEventIteration
AgentEventIteration fires when the model is asked to continue after a round of tool results.
const AgentEventToolEnd = engineimpl.AgentEventToolEnd
AgentEventToolEnd fires when it returns, carrying Duration and either Result or Error.
const AgentEventToolStart = engineimpl.AgentEventToolStart
AgentEventToolStart fires just before a tool executes.
const ChatRoleAssistant = engineimpl.ChatRoleAssistant
const ChatRoleSystem = engineimpl.ChatRoleSystem
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.
const ChatRoleUser = engineimpl.ChatRoleUser
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.
const ContextWindowFull = engineimpl.ContextWindowFull
ContextWindowFull sends every supplied message and preserves the existing context-limit error when the prompt is too large.
const ContextWindowRecent = engineimpl.ContextWindowRecent
ContextWindowRecent retains the newest complete user turn(s), dropping older complete turns only when necessary to reserve room for generation.
const DefaultConversationCacheBytes = engineimpl.DefaultConversationCacheBytes
DefaultConversationCacheBytes caps retained historical KV rows and token IDs separately from the live generation workspace.
const DefaultMaxToolResultBytes = engineimpl.DefaultMaxToolResultBytes
DefaultMaxToolResultBytes is the cap on what one tool result contributes to the prompt when AgenticTool.MaxResultBytes is zero.
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.
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.
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.
const DefaultToolTimeout = engineimpl.DefaultToolTimeout
DefaultToolTimeout is the per-call bound when AgenticTool.Timeout is zero.
const GGMLTypeBF16 = engineimpl.GGMLTypeBF16
const GGMLTypeF16 = engineimpl.GGMLTypeF16
const GGMLTypeF32 = engineimpl.GGMLTypeF32
const GGMLTypeF64 = engineimpl.GGMLTypeF64
const GGMLTypeI32 = engineimpl.GGMLTypeI32
const GGMLTypeIQ1_M = engineimpl.GGMLTypeIQ1_M
const GGMLTypeIQ1_S = engineimpl.GGMLTypeIQ1_S
const GGMLTypeIQ2_S = engineimpl.GGMLTypeIQ2_S
const GGMLTypeIQ2_XS = engineimpl.GGMLTypeIQ2_XS
const GGMLTypeIQ2_XXS = engineimpl.GGMLTypeIQ2_XXS
const GGMLTypeIQ3_S = engineimpl.GGMLTypeIQ3_S
const GGMLTypeIQ3_XXS = engineimpl.GGMLTypeIQ3_XXS
const GGMLTypeIQ4_NL = engineimpl.GGMLTypeIQ4_NL
const GGMLTypeIQ4_XS = engineimpl.GGMLTypeIQ4_XS
const GGMLTypeMXFP4 = engineimpl.GGMLTypeMXFP4
const GGMLTypeQ1_0 = engineimpl.GGMLTypeQ1_0
const GGMLTypeQ2_0 = engineimpl.GGMLTypeQ2_0
const GGMLTypeQ2_K = engineimpl.GGMLTypeQ2_K
const GGMLTypeQ3_K = engineimpl.GGMLTypeQ3_K
const GGMLTypeQ4_0 = engineimpl.GGMLTypeQ4_0
const GGMLTypeQ4_1 = engineimpl.GGMLTypeQ4_1
const GGMLTypeQ4_K = engineimpl.GGMLTypeQ4_K
const GGMLTypeQ5_0 = engineimpl.GGMLTypeQ5_0
const GGMLTypeQ5_1 = engineimpl.GGMLTypeQ5_1
const GGMLTypeQ5_K = engineimpl.GGMLTypeQ5_K
const GGMLTypeQ6_K = engineimpl.GGMLTypeQ6_K
const GGMLTypeQ8_0 = engineimpl.GGMLTypeQ8_0
const GGMLTypeQ8_1 = engineimpl.GGMLTypeQ8_1
const GGMLTypeQ8_K = engineimpl.GGMLTypeQ8_K
const GGMLTypeTQ1_0 = engineimpl.GGMLTypeTQ1_0
const GGMLTypeTQ2_0 = engineimpl.GGMLTypeTQ2_0
const GGMLTypeUnknown = engineimpl.GGMLTypeUnknown
const LoadSkillToolName = engineimpl.LoadSkillToolName
LoadSkillToolName is the name of the tool RunAgenticChat resolves internally (see agent.go) rather than returning to the caller.
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.
const MmapPrefaultAll = engineimpl.MmapPrefaultAll
MmapPrefaultAll retains the established behavior: warm every page before returning from load, making first-token latency predictable.
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.
const MmapPrefaultNone = engineimpl.MmapPrefaultNone
MmapPrefaultNone leaves every tensor demand-paged.
const NoToolResultLimit = engineimpl.NoToolResultLimit
NoToolResultLimit, passed as AgenticTool.MaxResultBytes, disables the loop's result-truncation cap entirely.
const NoToolTimeout = engineimpl.NoToolTimeout
NoToolTimeout, passed as AgenticTool.Timeout, disables the loop's per-call bound entirely.
const SafetensorsBF16 = engineimpl.SafetensorsBF16
const SafetensorsF16 = engineimpl.SafetensorsF16
const SafetensorsF32 = engineimpl.SafetensorsF32
Public dtype constants for callers inspecting safetensors metadata.
const TokenizerGPT2BPE = engineimpl.TokenizerGPT2BPE
const TokenizerSentencePiece = engineimpl.TokenizerSentencePiece
const TokenizerWordPiece = engineimpl.TokenizerWordPiece
const Version = "0.3.0-go"
Version is reported by the CLI's --version and usage header.
const VoxtralSampleRate = engineimpl.VoxtralSampleRate
VoxtralSampleRate is the required mono PCM sample rate, in Hz.
Variables ¶
var COCOClassNames = engineimpl.COCOClassNames
COCOClassNames are the 80 COCO detection labels in class-index order.
var ErrGenerationCanceled = engineimpl.ErrGenerationCanceled
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.
var ErrNoValidJSONToken = engineimpl.ErrNoValidJSONToken
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.
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.
var ErrStructuredOutputIncomplete = engineimpl.ErrStructuredOutputIncomplete
ErrStructuredOutputIncomplete accompanies a truncated JSON prefix. A nil generation error in JSON mode guarantees a complete syntactically valid object.
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.
var ErrVoxtralModelClosed = engineimpl.ErrVoxtralModelClosed
ErrVoxtralModelClosed indicates that Close has stopped new sessions.
var ErrVoxtralSessionClosed = engineimpl.ErrVoxtralSessionClosed
ErrVoxtralSessionClosed indicates a closed, finalized or failed session.
var YOLOStockModels = engineimpl.YOLOStockModels
YOLOStockModels lists stock names understood by YOLOCheckpointReference.
Functions ¶
func ArchitectureSupported ¶
func ArgmaxOutputToken ¶ added in v0.2.0
func ArgmaxOutputToken(config Config, weights ModelWeights, buf *DecodeBuffer) (uint32, bool)
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 DecodeImageBytes ¶ added in v1.0.0
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 DequantRowMXFP4Into ¶ added in v0.4.0
DequantRowMXFP4Into is the allocation-free MXFP4 row decoder used by RowInto and prompt batching.
func DequantRowQ1_0 ¶ added in v0.4.0
func DequantRowQ1_0Into ¶ added in v0.4.0
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 DequantRowQ2KInto ¶
func DequantRowQ2_0 ¶ added in v0.4.0
func DequantRowQ2_0Into ¶ added in v0.4.0
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 DequantRowQ3KInto ¶
func DequantRowQ4K ¶
func DequantRowQ4KInto ¶
func DequantRowQ4_0 ¶
func DequantRowQ4_0Into ¶ added in v0.4.0
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_1Into ¶
func DequantRowQ5K ¶
func DequantRowQ5KInto ¶ added in v0.4.0
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_0Into ¶
func DequantRowQ5_1 ¶
func DequantRowQ5_1Into ¶
func DequantRowQ6K ¶
func DequantRowQ6KInto ¶
func DequantRowQ8K ¶ added in v0.4.0
func DequantRowQ8KInto ¶ added in v0.4.0
func DequantRowQ8_0 ¶
func DequantRowQ8_0Into ¶ added in v0.4.0
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_1Into ¶
func DequantRowTQ1_0 ¶ added in v0.4.0
func DequantRowTQ1_0Into ¶ added in v0.4.0
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_0Into ¶ added in v0.4.0
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 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 F32ToF16 ¶ added in v0.3.0
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
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 LoadGptOssModel ¶
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 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):
- 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.
- v.pre_ln: RMSNorm, applied once, before the first transformer block.
- 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).
- 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).
- 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).
- 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 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 MatvecF32Into ¶
func MatvecMXFP4Into ¶
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 MatvecPreparedQ6KInto ¶
func MatvecQ1_0Into ¶ added in v0.4.0
func MatvecQ2_0Into ¶ added in v0.4.0
func MatvecQ4K2Into ¶
func MatvecQ4K2IntoWithXSums ¶
func MatvecQ4K2Q6KIntoWithXSums ¶ added in v0.2.0
func MatvecQ6K2Into ¶
func MatvecQ6K3Into ¶
func MatvecQ8KInto ¶ added in v0.4.0
func MatvecTQ1_0Into ¶ added in v0.4.0
func MatvecTQ2_0Into ¶ added in v0.4.0
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
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
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
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 ¶
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 QuantizeRowQ2K ¶ added in v1.1.0
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
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
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
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
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
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
QuantizeRowQ5_1 encodes affine 32-element blocks for the Q5_K fallback.
func QuantizeRowQ6K ¶ added in v0.7.0
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
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
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:
- 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).
- 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.
- 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 ¶
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 ¶
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 ¶
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 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
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
WritePrivacyReport writes a stable, indented JSON report suitable for `gopherllm --privacy`, logs, and deployment audits.
func YOLOCheckpointReference ¶ added in v1.12.0
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 ¶
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)
}
Output:
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
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 ¶
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
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 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
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 ¶
WithMaxTokens caps the number of generated tokens (default 256).
func WithPromptLookupTokens ¶ added in v1.12.0
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 ¶
WithRepeatPenalty penalizes recently generated tokens; 1 disables it.
func WithSystemPrompt ¶
WithSystemPrompt replaces the default system prompt; pass "" for none.
func WithTemperature ¶
WithTemperature sets the sampling temperature; 0 selects greedy decoding.
func WithToolChoice ¶
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.
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 ¶
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
NewKVCacheF16 is NewKVCache with half-precision row storage.
func NewKVCacheI8 ¶ added in v1.0.0
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.
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.
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).
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 ¶
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 ¶
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
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 ¶
WithPrepareQuantized precomputes supported quantized scale data at load time for the prepared quantized kernels.
func WithThreads ¶
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
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.
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 ¶
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 ¶
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.
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
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):
- 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.
- 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).
- 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.
- 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
LoadYOLO loads a safetensors or Ultralytics .pt detector checkpoint.
func LoadYOLOPyTorch ¶ added in v1.12.0
LoadYOLOPyTorch loads an Ultralytics .pt detector checkpoint without executing Python pickle code.
func LoadYOLOSafetensors ¶ added in v1.12.0
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. |