ds4api

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 17 Imported by: 2 modules, 1 package

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

Documentation

Overview

Package ds4api test infrastructure: a pure-Go mock of libds4.

NewMockLibrary creates a Library whose raw function pointers are Go implementations backed by in-memory state. This lets tests exercise the ds4go binding and generator layers without loading a real shared library.

Package ds4api provides pure-Go bindings for the ds4 inference engine.

The package does not use cgo. It loads a user-provided libds4 shared library at runtime through purego and wraps the public API from ds4.h.

Index

Constants

View Source
const (
	// DefaultTemperature is ds4's default sampling temperature.
	DefaultTemperature float32 = 1.0
	// DefaultTopP is ds4's default nucleus sampling probability.
	DefaultTopP float32 = 1.0
	// DefaultMinP is ds4's default minimum relative-probability filter.
	DefaultMinP float32 = 0.05
)

Sampling defaults mirror the DS4_DEFAULT_* macros in ds4.h. The default sampler keeps top-p at 1.0 and uses min-p as the active filter.

Variables

View Source
var ErrCancelNotSupported = errors.New("ds4: session cancellation is not supported by the loaded library (missing symbol)")

ErrCancelNotSupported is returned by Session.SetCancel when the loaded libds4 build does not export ds4_session_set_cancel.

View Source
var ErrDistributedNotSupported = errors.New("ds4: distributed inference is not supported by the loaded library (missing symbols)")

ErrDistributedNotSupported is returned by the distributed inference and layer-slice session methods when the loaded libds4 build does not export the ds4_session distributed symbols. Callers can check with errors.Is and fall back to single-node execution.

View Source
var ErrSessionSyncInterrupted = errors.New("ds4: session sync interrupted")

ErrSessionSyncInterrupted is returned when ds4_session_sync stops because the installed cancel callback requested cooperative cancellation.

View Source
var ErrSpeculativeSamplingNotSupported = errors.New("ds4: sampled speculative decoding is not supported by the loaded library (missing symbol)")

ErrSpeculativeSamplingNotSupported is returned by Session.EvalSpeculative when the loaded libds4 build predates ds4_session_eval_speculative. Callers can check with errors.Is and fall back to greedy speculation or plain sampling.

View Source
var ErrSteeringNotSupported = errors.New("ds4: session directional steering is not supported by the loaded library (missing symbol)")

ErrSteeringNotSupported is returned by Session.SetDirectionalSteering when the loaded libds4 build does not export ds4_session_set_directional_steering. Callers can check with errors.Is and downgrade to a warning so the rest of the program can continue without dynamic steering.

View Source
var ErrVisionNotSupported = errors.New("ds4: vision is not supported by the loaded library (missing symbols)")

ErrVisionNotSupported is returned by the vision entry points when the loaded libds4 predates the vision API.

Functions

func BackendName

func BackendName(backend Backend) string

BackendName returns ds4's printable name for backend, as the default library reports it: a ROCm build names BackendCUDA "rocm". BackendROCm is a Go-only value and is always "rocm", with no library needed. Use Backend.String for a fixed name that never consults a library.

func DumpTextTokenization

func DumpTextTokenization(modelPath, text string, fp File) error

DumpTextTokenization calls ds4_dump_text_tokenization.

func FreeVisionSpans added in v0.7.0

func FreeVisionSpans(spans []VisionSpan)

FreeVisionSpans frees every embedding in spans.

func LogIsTTY

func LogIsTTY(fp File) bool

LogIsTTY calls ds4_log_is_tty for a C FILE*.

func LogString

func LogString(fp File, typ LogType, msg string)

LogString writes a plain string through ds4_log.

ds4_log is C-variadic and purego cannot pass variadic arguments: a "%s" format with msg as a trailing argument makes va_arg read garbage on darwin/arm64 (the callee expects variadics on the stack). The message is therefore passed as the format string itself, with every '%' escaped as "%%", so vfprintf reproduces it verbatim and never consults va_arg.

func NewMockLibraryWithControls added in v0.6.0

func NewMockLibraryWithControls() (*Library, *MockControls)

NewMockLibraryWithControls returns a mock library alongside the controls that tune its model-family behaviour. See MockControls.

func RewriteRequiresRebuild

func RewriteRequiresRebuild(liveLen, canonicalLen, common int) bool

RewriteRequiresRebuild calls ds4_session_rewrite_requires_rebuild.

func SetAbortFunc added in v0.3.0

func SetAbortFunc(fn AbortFunc) error

SetAbortFunc installs a last-chance libds4 fatal-invariant callback for the default library.

Passing nil restores libds4's default behavior: no callback, then native abort(). The setting is process-global inside libds4; install it once during application startup. Returning from the callback does not recover the engine: libds4 calls abort() immediately afterward.

func SetDefaultLibrary

func SetDefaultLibrary(lib *Library)

SetDefaultLibrary makes lib the package default library.

func SetStderrFd added in v0.5.0

func SetStderrFd(fd int) error

SetStderrFd redirects libds4's diagnostic stream to fd for the default library. Pass -1 to restore the native stderr.

libds4 dups fd internally and writes its diagnostics there unbuffered, so the caller may close its own descriptor after this call. The redirect target is a process-global inside libds4; install it once during application startup, before generation is active.

func ThinkMaxMinContext

func ThinkMaxMinContext() uint32

ThinkMaxMinContext returns the minimum context size ds4 recommends for ThinkMax.

func ThinkMaxPrefix

func ThinkMaxPrefix() string

ThinkMaxPrefix returns ds4's maximum-effort thinking prompt prefix.

func ThinkModeEnabled

func ThinkModeEnabled(mode ThinkMode) bool

ThinkModeEnabled reports whether mode emits thinking markers, asking the default library. Callers holding a Library or Engine should ask it directly; this answers false when no default library can be loaded.

func ThinkModeName

func ThinkModeName(mode ThinkMode) string

ThinkModeName returns ds4's printable name for mode.

Types

type AbortFunc added in v0.3.0

type AbortFunc func(msg string)

AbortFunc receives a libds4 fatal-invariant message immediately before libds4 aborts the process.

libds4 calls this from ds4_die and allocation-guard failures after routing the same text through the log callback as LogError. Returning from AbortFunc does not recover the engine: libds4 calls abort() immediately afterward. Use this hook only for last-chance crash telemetry, flushing logs, or deliberate process termination. The callback may be invoked from native worker threads, so it must be concurrency-safe, quick, and must not call back into ds4go/libds4 APIs; doing so can deadlock during an active native call.

type ArgmaxGenerateOptions

type ArgmaxGenerateOptions struct {
	// NPredict is the number of tokens to generate.
	NPredict int
	// CtxSize is the context size used for this generation.
	CtxSize int
	// OnToken streams generated tokens.
	OnToken TokenEmitFunc
	// OnDone is called by ds4 when generation is complete.
	OnDone GenerationDoneFunc
	// OnProgress receives ds4 progress events.
	OnProgress ProgressFunc
}

ArgmaxGenerateOptions controls ds4_engine_generate_argmax.

type Backend

type Backend int32

Backend selects the accelerator implementation compiled into libds4.

const (
	// BackendMetal selects the Metal backend.
	BackendMetal Backend = iota
	// BackendCUDA selects the CUDA backend.
	BackendCUDA
	// BackendCPU selects the CPU reference backend.
	BackendCPU
	// BackendROCm selects a ROCm build of libds4. It is a Go-only value:
	// ds4.h has no ROCm entry, and a ROCm libds4 serves DS4_BACKEND_CUDA, so
	// ds4api sends BackendCUDA across the ABI and checks the library's
	// GPUFlavor instead. Never pass its numeric value to C directly.
	BackendROCm
)

func (Backend) String added in v0.9.0

func (b Backend) String() string

String returns a fixed name for b: "metal", "cuda", "rocm", "cpu", or "backend(N)". Unlike BackendName it never consults a library, so a ROCm libds4 does not rename BackendCUDA here.

type BackendMismatchError added in v0.9.0

type BackendMismatchError struct {
	Library   string    // path of the loaded libds4
	Requested Backend   // BackendCUDA or BackendROCm
	Flavor    GPUFlavor // what the library serves
}

BackendMismatchError reports a GPU backend request that the loaded libds4 build cannot serve: BackendROCm on a non-ROCm library, or (after the transition release) BackendCUDA on a ROCm library.

func (*BackendMismatchError) Error added in v0.9.0

func (e *BackendMismatchError) Error() string

type CancelFunc added in v0.5.1

type CancelFunc func() bool

CancelFunc is polled by ds4 at cooperative cancellation points. Returning true asks ds4_session_sync to stop at a valid checkpoint boundary.

type ContextMemory

type ContextMemory struct {
	// TotalBytes is the estimated total context memory.
	TotalBytes uint64
	// RawBytes is the raw KV-cache memory estimate.
	RawBytes uint64
	// CompressedBytes is the compressed KV-cache memory estimate.
	CompressedBytes uint64
	// ScratchBytes is the temporary scratch memory estimate.
	ScratchBytes uint64
	// PrefillCap is the prefill capacity.
	PrefillCap uint32
	// RawCap is the raw KV-cache row capacity.
	RawCap uint32
	// CompCap is the compressed KV-cache row capacity.
	CompCap uint32
}

ContextMemory is ds4_context_memory.

func ContextMemoryEstimate

func ContextMemoryEstimate(backend Backend, ctxSize int) ContextMemory

ContextMemoryEstimate estimates ds4 context memory for a backend and context size. libds4 derives the estimate from the active model shape selected by ds4_engine_open, so the result is only meaningful while at least one engine is open. Prefer Engine.ContextMemoryEstimate when you have an engine handle.

func ContextMemoryEstimateWithPrefill added in v0.5.1

func ContextMemoryEstimateWithPrefill(backend Backend, ctxSize int, prefillChunk uint32) ContextMemory

ContextMemoryEstimateWithPrefill estimates ds4 context memory for a backend, context size, and prefill chunk size.

type DecodeItem added in v0.12.0

type DecodeItem struct {
	Session *Session
	Token   int
}

DecodeItem advances one independent session by a sampled token in EvalBatch.

type DistributedLayers added in v0.5.0

type DistributedLayers struct {
	Start     uint32
	End       uint32
	HasOutput bool
	Set       bool
}

DistributedLayers defines the layer slice bounds for a distributed node.

type DistributedOptions added in v0.5.0

type DistributedOptions struct {
	Role            DistributedRole
	Layers          DistributedLayers
	ListenHost      string
	ListenPort      int
	CoordinatorHost string
	CoordinatorPort int
	PrefillChunk    uint32
	PrefillWindow   uint32
	ActivationBits  uint32
	ReplayCheck     bool
	Debug           bool
}

DistributedOptions configures the distributed inference data/control plane.

type DistributedRole added in v0.5.0

type DistributedRole int32

DistributedRole defines the distributed execution mode of the engine.

const (
	// DistributedRoleNone disables distributed execution.
	DistributedRoleNone DistributedRole = 0
	// DistributedRoleCoordinator acts as the entrypoint coordinator.
	DistributedRoleCoordinator DistributedRole = 1
	// DistributedRoleWorker executes a subset of layer computations.
	DistributedRoleWorker DistributedRole = 2
)

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine wraps a ds4_engine.

func NewEngine

func NewEngine(opts EngineOptions) (*Engine, error)

NewEngine opens a ds4 engine using the default shared library.

func (*Engine) ChatAppendAssistantPrefix

func (e *Engine) ChatAppendAssistantPrefix(tokens *Tokens, thinkMode ThinkMode) error

ChatAppendAssistantPrefix appends the assistant prefix for generation.

Passing ThinkHigh or ThinkMax appends the assistant marker followed by the normal <think> marker. Passing ThinkMax here does not append the maximum-effort prompt text; for incremental prompts, call ChatAppendMaxEffortPrefix once near the beginning of the prompt when the effective thinking mode is ThinkMax. The two methods compose and should not be treated as mutually exclusive for ThinkMax.

func (*Engine) ChatAppendMaxEffortPrefix

func (e *Engine) ChatAppendMaxEffortPrefix(tokens *Tokens) error

ChatAppendMaxEffortPrefix appends ds4's maximum-effort thinking prompt text.

Use this when constructing a chat prompt incrementally with ChatBegin, ChatAppendMessage, and ChatAppendAssistantPrefix, and the effective thinking mode is ThinkMax. To match ds4_encode_chat_prompt, append it once after ChatBegin and before the system/message turns. It does not append the assistant marker or <think> marker; call ChatAppendAssistantPrefix with the same effective thinking mode at the end of the prompt.

Do not call this in addition to EncodeChatPrompt: ds4_encode_chat_prompt already includes this prefix when thinkMode is ThinkMax.

func (*Engine) ChatAppendMessage

func (e *Engine) ChatAppendMessage(tokens *Tokens, role, content string) error

ChatAppendMessage appends a rendered role/content chat message.

func (*Engine) ChatAppendMultimodalMessage added in v0.7.0

func (e *Engine) ChatAppendMultimodalMessage(tokens *Tokens, role string, textParts []string, images []*VisionEmbedding) ([]VisionSpan, error)

ChatAppendMultimodalMessage calls ds4_chat_append_multimodal_message for a user or tool message whose text parts alternate with images: len(textParts) must equal len(images)+1. On success every embedding is moved into the returned spans (in order). On failure the embeddings are left untouched. With no images it delegates to ChatAppendMessage.

func (*Engine) ChatAppendThinkPrefix added in v0.7.0

func (e *Engine) ChatAppendThinkPrefix(tokens *Tokens, mode ThinkMode) error

ChatAppendThinkPrefix appends the model family's reasoning-effort prefix for mode (ds4_chat_append_think_prefix): GLM and V4.1 render a system line, V4 renders its max-effort prefix at ThinkMax, and nothing otherwise. Append it after ChatBegin and before the system message, as ds4_encode_chat_prompt does. Older libraries get the same result through the pre-V4.1 entry points.

func (*Engine) ChatBegin

func (e *Engine) ChatBegin(tokens *Tokens) error

ChatBegin appends ds4's chat preamble to tokens.

func (*Engine) Close

func (e *Engine) Close()

Close releases the underlying ds4_engine.

func (*Engine) CollectIMatrix

func (e *Engine) CollectIMatrix(datasetPath, outputPath string, ctxSize, maxPrompts, maxTokens int) error

CollectIMatrix calls ds4_engine_collect_imatrix with no minimum per-expert sample count, matching the upstream CLI default.

func (*Engine) CollectIMatrixWithMinExpertSamples added in v0.6.0

func (e *Engine) CollectIMatrixWithMinExpertSamples(datasetPath, outputPath string, ctxSize, maxPrompts, maxTokens, minExpertSamples int) error

CollectIMatrixWithMinExpertSamples calls ds4_engine_collect_imatrix. minExpertSamples > 0 keeps collecting until every routed expert has that many samples (upstream --imatrix-min-expert-samples).

func (*Engine) ContextMemoryEstimate added in v0.4.0

func (e *Engine) ContextMemoryEstimate(backend Backend, ctxSize int) ContextMemory

ContextMemoryEstimate calls ds4_context_memory_estimate using the active model shape selected by the underlying ds4_engine_open. Prefer this over the package-level ContextMemoryEstimate when an engine is open, since the libds4 estimate now depends on Flash-vs-Pro dimensions.

func (*Engine) ContextMemoryEstimateWithPrefill added in v0.5.1

func (e *Engine) ContextMemoryEstimateWithPrefill(backend Backend, ctxSize int, prefillChunk uint32) ContextMemory

ContextMemoryEstimateWithPrefill calls ds4_context_memory_estimate_with_prefill using the active model shape and prefill chunk size.

func (*Engine) DeepSeek41ReasoningEffortText added in v0.7.0

func (e *Engine) DeepSeek41ReasoningEffortText(mode ThinkMode) string

DeepSeek41ReasoningEffortText returns V4.1's reasoning-effort system line for mode (ds4_deepseek41_reasoning_effort_text): ThinkHigh is effort 75, ThinkMax 100, a ThinkLevel its own value; "" for none, level 0, and libraries without V4.1.

func (*Engine) DumpTokens

func (e *Engine) DumpTokens(tokens *Tokens) error

DumpTokens calls ds4_engine_dump_tokens.

func (*Engine) EmbdDim added in v0.7.0

func (e *Engine) EmbdDim() int

EmbdDim calls ds4_engine_embd_dim: the width of one embedding row.

func (*Engine) EncodeChatPrompt

func (e *Engine) EncodeChatPrompt(system, prompt string, thinkMode ThinkMode) (*Tokens, error)

EncodeChatPrompt encodes a system and user prompt with ds4's chat template.

func (*Engine) EvalBatch added in v0.12.0

func (e *Engine) EvalBatch(items []DecodeItem) error

EvalBatch advances independent sessions by one token each. libds4 selects native batching where available and sequential evaluation otherwise. Older libraries without the batch entry point use the same sequential fallback. Sessions must be distinct and belong to this engine. On failure some items may have advanced; callers should re-sync or discard the affected sessions.

func (*Engine) FirstTokenTest

func (e *Engine) FirstTokenTest(prompt *Tokens) error

FirstTokenTest calls ds4_engine_first_token_test.

func (*Engine) GLMReasoningEffortText added in v0.6.0

func (e *Engine) GLMReasoningEffortText(mode ThinkMode) string

GLMReasoningEffortText returns the GLM reasoning-effort system line for mode, or "" for ThinkNone and for libraries without GLM support. Callers should only emit it when Engine.IsGLMDSA reports true; DeepSeek shapes use Engine.ChatAppendMaxEffortPrefix instead.

func (*Engine) GenerateArgmax

func (e *Engine) GenerateArgmax(prompt *Tokens, opts ArgmaxGenerateOptions) ([]int, error)

GenerateArgmax calls ds4_engine_generate_argmax.

func (*Engine) HasMTP

func (e *Engine) HasMTP() bool

HasMTP reports whether this engine has an MTP draft model.

func (*Engine) HasOutputHead added in v0.5.0

func (e *Engine) HasOutputHead() bool

HasOutputHead reports whether the loaded GGUF includes the output head. For a distributed split this is false on the coordinator half (e.g. layers 0:30) and true on the worker half that owns the tail (e.g. 31:output).

func (*Engine) HasVision added in v0.7.0

func (e *Engine) HasVision() bool

HasVision calls ds4_engine_has_vision: whether an encoder is loaded.

func (*Engine) HeadTest

func (e *Engine) HeadTest(prompt *Tokens) error

HeadTest calls ds4_engine_head_test.

func (*Engine) IsDeepSeek41 added in v0.7.0

func (e *Engine) IsDeepSeek41() bool

IsDeepSeek41 reports whether the loaded model is DeepSeek V4.1 Flash (ds4_engine_is_deepseek41); false on libraries that predate V4.1.

func (*Engine) IsGLM53 added in v0.8.0

func (e *Engine) IsGLM53() bool

IsGLM53 reports whether the loaded model is a GLM 5.3 checkpoint (ds4_engine_is_glm53), a GLM DSA variant with an embedded MTP block; false on libraries that predate it.

func (*Engine) IsGLMDSA added in v0.6.0

func (e *Engine) IsGLMDSA() bool

IsGLMDSA reports whether the open model is a GLM DSA shape (ds4_engine_is_glm_dsa) rather than a DeepSeek V4 shape. GLM uses different chat markers, stop tokens, and tool-call markup, so callers building prompts or parsing completions must branch on this.

Returns false on libraries predating GLM support; see Library.SupportsGLM.

func (*Engine) IsQwen4 added in v0.8.0

func (e *Engine) IsQwen4() bool

IsQwen4 reports whether the loaded model is Qwen3.8 Flash Next (ds4_engine_is_qwen4); false on libraries that predate it.

func (*Engine) LayerCompressRatio added in v0.5.0

func (e *Engine) LayerCompressRatio(layer int) int

LayerCompressRatio returns the compression/quantization ratio of the specified layer, or 0 if not supported.

func (*Engine) LayerCount added in v0.5.0

func (e *Engine) LayerCount() int

LayerCount returns the total number of layers in the model, or 0 if not supported by the loaded library.

func (*Engine) MTPDraftTokens

func (e *Engine) MTPDraftTokens() int

MTPDraftTokens returns the configured MTP draft length.

func (*Engine) MTPExactSampling added in v0.6.0

func (e *Engine) MTPExactSampling() bool

MTPExactSampling calls ds4_engine_mtp_exact_sampling: whether exact stochastic p/q acceptance is active for DSpark or GLM's embedded MTP block (EngineOptions.DsparkExactSampling). Under exact sampling, a speculative block drafted under one parser mode must be resampled once the mode flips; opportunistic drafts match greedy continuation in either mode and need no resample. It returns false when the loaded library predates the symbol.

func (*Engine) MetalGraphFullTest

func (e *Engine) MetalGraphFullTest(prompt *Tokens) error

MetalGraphFullTest calls ds4_engine_metal_graph_full_test.

func (*Engine) MetalGraphPromptTest

func (e *Engine) MetalGraphPromptTest(prompt *Tokens, ctxSize int) error

MetalGraphPromptTest calls ds4_engine_metal_graph_prompt_test.

func (*Engine) MetalGraphTest

func (e *Engine) MetalGraphTest(prompt *Tokens) error

MetalGraphTest calls ds4_engine_metal_graph_test.

func (*Engine) ModelID added in v0.4.0

func (e *Engine) ModelID() int

ModelID returns ds4_engine_model_id: a stable id for cache compatibility. 0 is the original Flash shape; Pro and later shapes use nonzero ids.

func (*Engine) ModelName added in v0.4.0

func (e *Engine) ModelName() string

ModelName returns ds4_engine_model_name: the printable name of the opened model shape (e.g. "Flash", "Pro").

func (*Engine) NewSession

func (e *Engine) NewSession(ctxSize int) (*Session, error)

NewSession creates a ds4 session for this engine and context size.

func (*Engine) NewTokens

func (e *Engine) NewTokens(ids []int) (*Tokens, error)

NewTokens creates a libds4-owned token vector associated with this engine's library.

func (*Engine) Power added in v0.4.0

func (e *Engine) Power() int

Power returns ds4_engine_power: the current power-throttle duty cycle percentage (1..100). 100 means no throttling.

func (*Engine) PrefillChunk added in v0.6.0

func (e *Engine) PrefillChunk() uint32

PrefillChunk returns the engine's effective prefill chunk size (ds4_engine_prefill_chunk), or 0 on libraries without the accessor.

func (*Engine) PromptAppendVision added in v0.7.0

func (e *Engine) PromptAppendVision(tokens *Tokens, emb *VisionEmbedding) (VisionSpan, error)

PromptAppendVision calls ds4_prompt_append_vision: it appends the image placeholder block for emb to tokens and moves emb into the returned span.

func (*Engine) Qwen4ReasoningEffortText added in v0.8.0

func (e *Engine) Qwen4ReasoningEffortText(mode ThinkMode) string

Qwen4ReasoningEffortText returns Qwen3.8's reasoning-effort instruction for mode (ds4_qwen4_reasoning_effort_text): the xhigh text for ThinkHigh and ThinkMax, the low text for ThinkLow, and "" for ThinkMedium (the template sets nothing), ThinkNone, and libraries without Qwen. Unlike the other families it is not a think prefix: ds4-agent and ds4-server place it at the head of the system turn, and BuildChatPrompt does the same.

func (*Engine) RoutedQuantBits

func (e *Engine) RoutedQuantBits() int

RoutedQuantBits returns the routed expert quantization bits used by the engine.

func (*Engine) SetPower added in v0.4.0

func (e *Engine) SetPower(powerPercent int) error

SetPower calls ds4_engine_set_power. powerPercent must be in 1..100.

func (*Engine) Summary

func (e *Engine) Summary() error

Summary prints ds4's engine summary to its configured output.

func (*Engine) SupportsSampledSpeculative added in v0.6.0

func (e *Engine) SupportsSampledSpeculative() bool

SupportsSampledSpeculative reports whether the loaded library can speculate at positive temperature (ds4_session_eval_speculative). When false, only greedy speculation is available; see Library.SupportsSampledSpeculative.

func (*Engine) ThinkModeEnabled added in v0.7.0

func (e *Engine) ThinkModeEnabled(mode ThinkMode) bool

ThinkModeEnabled reports whether mode emits thinking markers, as decided by the library this engine was opened from.

func (*Engine) TokenAssistant

func (e *Engine) TokenAssistant() int

TokenAssistant returns ds4's assistant-role token id.

func (*Engine) TokenEOS

func (e *Engine) TokenEOS() int

TokenEOS returns ds4's end-of-sequence token id.

func (*Engine) TokenIsStop added in v0.6.0

func (e *Engine) TokenIsStop(token int) bool

TokenIsStop reports whether token ends generation for this model (ds4_token_is_stop). DeepSeek shapes stop only on EOS, but GLM DSA also stops on the system, user, assistant, and observation role tokens, so callers must use this instead of comparing against Engine.TokenEOS.

Libraries without ds4_token_is_stop fall back to an EOS comparison.

func (*Engine) TokenIsStopForThinkMode added in v0.6.0

func (e *Engine) TokenIsStopForThinkMode(token int, mode ThinkMode) bool

TokenIsStopForThinkMode reports whether token ends generation under mode (ds4_token_is_stop_for_think_mode). Beyond the ordinary stop set, a thinking control marker emitted while thinking is disabled is treated as a stop: the prompt already supplied the closing tag, so the marker is protocol noise rather than assistant content.

Libraries without the predicate fall back to Engine.TokenIsStop.

func (*Engine) TokenIsThinkingControl added in v0.6.0

func (e *Engine) TokenIsThinkingControl(token int) bool

TokenIsThinkingControl reports whether token is a <think> or </think> marker (ds4_token_is_thinking_control). Returns false on libraries that do not export the predicate.

func (*Engine) TokenText

func (e *Engine) TokenText(token int) (string, error)

TokenText decodes one token to text and frees the C allocation returned by ds4.

func (*Engine) TokenUser

func (e *Engine) TokenUser() int

TokenUser returns ds4's user-role token id.

func (*Engine) TokenizeRenderedChat

func (e *Engine) TokenizeRenderedChat(text string) (*Tokens, error)

TokenizeRenderedChat tokenizes a rendered chat prompt.

func (*Engine) TokenizeText

func (e *Engine) TokenizeText(text string) (*Tokens, error)

TokenizeText tokenizes plain text with ds4_tokenize_text.

func (*Engine) VisionEncodeFile added in v0.7.0

func (e *Engine) VisionEncodeFile(path string) (*VisionEmbedding, error)

VisionEncodeFile calls ds4_engine_vision_encode_file on a PNG or JPEG path.

func (*Engine) VisionEncodeMemory added in v0.7.0

func (e *Engine) VisionEncodeMemory(encoded []byte) (*VisionEmbedding, error)

VisionEncodeMemory calls ds4_engine_vision_encode_memory on encoded PNG or JPEG bytes.

func (*Engine) VocabSize added in v0.4.0

func (e *Engine) VocabSize() int

VocabSize returns ds4_engine_vocab_size: the model vocabulary size.

type EngineOpenGuard added in v0.8.0

type EngineOpenGuard func(opts EngineOptions) (release func(), err error)

EngineOpenGuard is runtime policy run before every engine open. It may refuse the open by returning an error, and may return a release function that the engine holds for its lifetime: called exactly once when the engine is closed (or collected), and called immediately when the native open fails. A guard returning both a release and an error has the release called immediately: the open never happens, so nothing else would free what the guard acquired.

ds4api itself installs no guard: the strict binding layer carries no model management policy. The module root installs the single-runner run-lock policy when it is imported.

func SetEngineOpenGuard added in v0.8.0

func SetEngineOpenGuard(guard EngineOpenGuard) (previous EngineOpenGuard)

SetEngineOpenGuard installs guard as the process-wide engine open policy and returns the previously installed guard, nil when there was none. Passing nil removes the policy. There is one slot: a caller adding policy of its own must chain to the returned guard, or the installed policy (the module root's run-lock, for one) is silently replaced.

type EngineOptions

type EngineOptions struct {
	// ModelPath is the path to the DeepSeek V4 Flash GGUF model.
	ModelPath string
	// MTPPath is the optional MTP draft model path.
	MTPPath string
	// VisionPath is the optional vision encoder GGUF for the selected model
	// (upstream --vision). libds4 requires it to match the language model.
	VisionPath string
	// Backend selects Metal, CUDA, ROCm, or CPU according to the libds4 build.
	Backend Backend
	// NThreads controls CPU worker threads when the backend uses them.
	NThreads int
	// ContextSize is the largest session context the engine should prepare for.
	// GLM uses it for startup graph-memory guards and cache sizing.
	ContextSize int
	// PlacementCtxHint prices per-layer KV storage for GPU placement. Callers
	// normally set it to the same value as ContextSize.
	PlacementCtxHint int
	// PlacementSessionCountHint is the number of independently allocated
	// session graphs/caches the placement planner should reserve for.
	PlacementSessionCountHint int
	// ShareSessionPrefillWorkspace reports that serialized sessions can share
	// their prefill scratch workspace.
	ShareSessionPrefillWorkspace bool
	// MTPDraftTokens controls speculative draft length.
	MTPDraftTokens int
	// MTPMargin controls speculative acceptance confidence.
	MTPMargin float32
	// GLMMTP enables GLM's or Qwen's model-embedded next-token predictor for
	// speculative decoding (upstream --mtp). No external MTPPath is
	// needed; libds4 rejects the option on models without embedded MTP weights.
	// When enabled, Engine.MTPDraftTokens reports > 1 while HasMTP stays false.
	GLMMTP bool
	// GLMMTPTiming enables GLMMTP and prints acceptance/timing counters
	// (upstream --mtp-timing).
	GLMMTPTiming bool
	// Dspark enables DSpark speculative decoding. It needs a draft model, so
	// set MTPPath alongside it.
	Dspark bool
	// DsparkStrict selects target-only DeepSeek decoding, disabling speculative
	// acceptance. It does not guarantee identical output across hardware.
	DsparkStrict bool
	// DsparkExactSampling selects exact stochastic p/q acceptance instead of
	// committing greedily verified draft tokens. It only affects
	// positive-temperature generation and applies to DSpark, GLM and Qwen MTP.
	DsparkExactSampling bool
	// DsparkConfidenceThreshold overrides DSpark's acceptance confidence. A
	// zero value leaves ds4's own default in place.
	DsparkConfidenceThreshold float32
	// DirectionalSteeringFile points at an optional directional steering file.
	DirectionalSteeringFile string
	// DirectionalSteeringAttn scales directional steering in attention blocks.
	DirectionalSteeringAttn float32
	// DirectionalSteeringFFN scales directional steering in FFN blocks.
	DirectionalSteeringFFN float32
	// PowerPercent throttles GPU work to roughly this duty cycle (1..100).
	// 0 or 100 disables throttling. Maps to ds4_engine_options.power_percent.
	PowerPercent int
	// PrefillChunk controls the prefill chunk size.
	PrefillChunk uint32
	// ExpertProfilePath is the path to the optional expert profile.
	ExpertProfilePath string
	// SSDStreamingCacheExperts is the number of routed experts to keep in VRAM.
	SSDStreamingCacheExperts uint32
	// SSDStreamingCacheBytes is the byte budget for the SSD streaming expert cache.
	SSDStreamingCacheBytes uint64
	// SSDStreamingPreloadExperts is the number of experts to preload during startup.
	SSDStreamingPreloadExperts uint32
	// SSDStreamingFullLayers keeps the first N routed layers fully resident
	// under GLM Metal streaming (upstream --ssd-streaming-full-layers). ds4
	// only reads it when SSDStreamingFullLayersSet is true, so an explicit 0
	// ("disable") stays distinct from the default of auto-sizing.
	SSDStreamingFullLayers    uint32
	SSDStreamingFullLayersSet bool
	// CUDATensorParallel enables the paired DeepSeek tensor/expert path on an
	// even multi-GPU CUDA placement (upstream --cuda-tensor-parallel).
	CUDATensorParallel bool
	// SimulateUsedMemoryBytes simulates a specific amount of used GPU memory in bytes.
	SimulateUsedMemoryBytes uint64
	// WarmWeights asks ds4 to warm model weights after load.
	WarmWeights bool
	// Quality requests ds4's quality-oriented execution path where supported.
	Quality bool
	// SSDStreaming enables SSD streaming of experts.
	SSDStreaming bool
	// SSDStreamingCold enables SSD streaming of experts with cold cache.
	SSDStreamingCold bool
	// InspectOnly opens the model for inspection without preparing the engine
	// for generation. Maps to ds4_engine_options.inspect_only.
	InspectOnly bool
	// LoadSlice asks ds4 to load only a subset of the model's layers.
	LoadSlice bool
	// LoadLayerStart is the starting layer index to load (inclusive).
	LoadLayerStart uint32
	// LoadLayerEnd is the ending layer index to load (inclusive).
	LoadLayerEnd uint32
	// LoadOutput indicates whether the output vocab projection head should be loaded.
	LoadOutput bool
	// Distributed configures the distributed inference mesh network options.
	Distributed DistributedOptions
}

EngineOptions configures ds4_engine_open.

type File

type File uintptr

File is an opaque C FILE* used by ds4 APIs that accept FILE pointers.

func OpenFile

func OpenFile(path, mode string) (File, error)

OpenFile opens a C FILE* with fopen for ds4 FILE*-based APIs.

func (File) Close

func (f File) Close() error

Close closes a C FILE* opened by OpenFile.

type GPUFlavor added in v0.9.0

type GPUFlavor string

GPUFlavor names the GPU runtime a libds4 build compiled behind the shared DS4_BACKEND_CUDA slot.

const (
	// GPUFlavorUnknown means the library's name for the slot was not
	// recognized (for example a mock).
	GPUFlavorUnknown GPUFlavor = ""
	// GPUFlavorCUDA means the slot is not ROCm. libds4 names it "cuda" in
	// CUDA builds and also in Metal and CPU-only builds, which have no GPU
	// behind it, so this does not by itself prove CUDA support.
	GPUFlavorCUDA GPUFlavor = "cuda"
	// GPUFlavorROCm means the library is a ROCm build.
	GPUFlavorROCm GPUFlavor = "rocm"
)

func (GPUFlavor) Backend added in v0.9.0

func (f GPUFlavor) Backend() (Backend, bool)

Backend returns the Go backend value that selects this flavor, and false for GPUFlavorUnknown.

type GenerationDoneFunc

type GenerationDoneFunc func()

GenerationDoneFunc is called after ds4 completes generation.

type IMatrixCall added in v0.7.0

type IMatrixCall struct {
	Dataset, Output                                  string
	CtxSize, MaxPrompts, MaxTokens, MinExpertSamples int
}

IMatrixCall records the arguments of the last ds4_engine_collect_imatrix call the mock served.

type Library

type Library struct {
	// contains filtered or unexported fields
}

Library is a loaded libds4 shared library.

func CurrentDefaultLibrary added in v0.8.0

func CurrentDefaultLibrary() *Library

CurrentDefaultLibrary returns the installed default library without lazily loading one, or nil when no default is set. It is the authoritative default: the module root keeps no copy of its own.

func DefaultLibrary

func DefaultLibrary() (*Library, error)

DefaultLibrary returns the lazily loaded default library.

func Load

func Load(path string) (*Library, error)

Load loads libds4 from path and registers all ds4.h symbols.

Passing an empty path uses DS4_LIB, then searches common local library locations. Higher-level ds4go runtime path policy lives in the module root.

func NewMockLibrary added in v0.2.2

func NewMockLibrary() *Library

NewMockLibrary returns a Library whose C symbols are backed by trivial in-memory state. The mock supports engine/session lifecycle, tokenization, deterministic generation, and optional MTP metadata.

func (*Library) CheckBackend added in v0.9.0

func (l *Library) CheckBackend(b Backend) error

CheckBackend validates a backend request against the library's GPUFlavor. Library.NewEngine calls it before opening anything; call it directly to fail early, before loading a model.

BackendROCm on a library that is not ROCm is an error. BackendCUDA on a ROCm library is still accepted for one transition release, because callers written before BackendROCm existed had to pass BackendCUDA for ROCm; it logs a deprecation warning once per library and will become an error. An unknown flavor is never rejected.

func (*Library) DisableSampledSpeculative added in v0.6.0

func (l *Library) DisableSampledSpeculative()

DisableSampledSpeculative drops ds4_session_eval_speculative from a mock library, modelling a libds4 build that predates upstream's exact stochastic DSpark work.

func (*Library) DumpChatTokenization added in v0.8.0

func (l *Library) DumpChatTokenization(modelPath, system, prompt string, mode ThinkMode, ctxSize int, fp File) error

DumpChatTokenization writes the rendered chat prompt's tokenization for system and prompt under mode to fp (ds4_dump_chat_tokenization), loading the model at modelPath on its own; see OpenFile. It fails on a library without the entry point.

func (*Library) GLMReasoningEffortText added in v0.6.0

func (l *Library) GLMReasoningEffortText(mode ThinkMode) string

GLMReasoningEffortText returns the GLM reasoning-effort system line for mode (ds4_glm_reasoning_effort_text), or "" for ThinkNone and for libraries without GLM support. GLM encodes thinking effort as a system message rather than the DeepSeek max-effort prompt prefix.

func (*Library) GPUFlavor added in v0.9.0

func (l *Library) GPUFlavor() GPUFlavor

GPUFlavor reports what the DS4_BACKEND_CUDA slot really is in this library, from ds4_backend_name(DS4_BACKEND_CUDA). It is read once at load.

func (*Library) NewEngine

func (l *Library) NewEngine(opts EngineOptions) (*Engine, error)

NewEngine opens a ds4 engine using this shared library. Any installed EngineOpenGuard runs first; its release is held for the engine lifetime.

func (*Library) Path

func (l *Library) Path() string

Path returns the filesystem path used to load this library.

func (*Library) SampleLogits added in v0.8.0

func (l *Library) SampleLogits(logits []float32, temperature float32, topK int, topP, minP float32, rng *uint64) int

SampleLogits samples a token from a caller-supplied logit vector with ds4's sampler (ds4_sample_logits): temperature 0 is greedy, top_k 0 is unlimited, top_p 1 and min_p 0 disable those filters, and rng advances the caller's state. It returns -1 on a library without the entry point and, like upstream, 0 for an empty vector.

func (*Library) SetAbortFunc added in v0.3.0

func (l *Library) SetAbortFunc(fn AbortFunc) error

SetAbortFunc installs a last-chance libds4 fatal-invariant callback for this loaded library.

libds4 invokes the callback from ds4_die and allocation-guard failures after logging the same message at LogError and immediately before abort(). Passing nil restores the default behavior. This hook is for crash telemetry, flushing diagnostics, or deliberate process termination; it is not a normal recovery mechanism. If the callback returns, libds4 still aborts. The callback may be invoked from native worker threads and must be concurrency-safe.

func (*Library) SetStderrFd added in v0.5.0

func (l *Library) SetStderrFd(fd int) error

SetStderrFd redirects this library's diagnostic stream to fd. Pass -1 to restore the native stderr.

libds4 dups fd internally (taking ownership of the dup) and writes its diagnostics there unbuffered, so the caller may close its own descriptor afterward. The redirect target is a process-global inside libds4, not a per-engine setting; install it once at startup, before generation, since it is not synchronized against concurrent logging from native worker threads.

func (*Library) SupportsDistributed added in v0.5.0

func (l *Library) SupportsDistributed() bool

SupportsDistributed reports whether the loaded library exports the distributed inference and layer-slice entry points. When false, the distributed session methods return ErrDistributedNotSupported and callers should fall back to single-node execution.

func (*Library) SupportsDynamicSteering added in v0.4.0

func (l *Library) SupportsDynamicSteering() bool

SupportsDynamicSteering reports whether the loaded library exports ds4_session_set_directional_steering. When false, callers should rely on engine-level (static) steering via EngineOptions.DirectionalSteering* fields.

func (*Library) SupportsGLM added in v0.6.0

func (l *Library) SupportsGLM() bool

SupportsGLM reports whether the loaded library exports the GLM DSA entry points. When false, the library predates upstream GLM 5.2 support and can only run DeepSeek V4 shapes; Engine.IsGLMDSA is then always false and the stop-token predicates fall back to EOS-only (DeepSeek) semantics.

func (*Library) SupportsLiveSteeringFFN added in v0.6.0

func (l *Library) SupportsLiveSteeringFFN() bool

SupportsLiveSteeringFFN reports whether the loaded library exports ds4_session_set_directional_steering_ffn (upstream commit 87495f6), which changes the FFN steering scale for future evaluation without rebuilding the session's KV state.

func (*Library) SupportsQwen4 added in v0.8.0

func (l *Library) SupportsQwen4() bool

SupportsQwen4 reports whether the library binds the Qwen3.8 Flash Next entry points (ds4_engine_is_qwen4, ds4_qwen4_reasoning_effort_text).

func (*Library) SupportsSampledSpeculative added in v0.6.0

func (l *Library) SupportsSampledSpeculative() bool

SupportsSampledSpeculative reports whether the loaded library exports ds4_session_eval_speculative, the positive-temperature counterpart to ds4_session_eval_speculative_argmax. When false, speculative decoding is only available in greedy mode.

func (*Library) SupportsSessionCancel added in v0.5.1

func (l *Library) SupportsSessionCancel() bool

SupportsSessionCancel reports whether the loaded library exports ds4_session_set_cancel. When false, Session.SetCancel returns ErrCancelNotSupported.

func (*Library) SupportsVision added in v0.7.0

func (l *Library) SupportsVision() bool

SupportsVision reports whether the loaded library exports the vision API (upstream ds4 fc8bf3c): image encoding, multimodal prompts, and image-aware session sync.

func (*Library) ThinkModeEnabled added in v0.7.0

func (l *Library) ThinkModeEnabled(mode ThinkMode) bool

ThinkModeEnabled binds ds4_think_mode_enabled: whether mode emits thinking markers. Named modes other than ThinkNone do; a V4.1 level does unless it is 0.

type LogType

type LogType int32

LogType is the category used by ds4_log.

const (
	// LogDefault is the default ds4 log style.
	LogDefault LogType = iota
	// LogPrefill marks prefill messages.
	LogPrefill
	// LogGeneration marks generation messages.
	LogGeneration
	// LogKVCache marks KV-cache messages.
	LogKVCache
	// LogTool marks tool-calling messages.
	LogTool
	// LogWarning marks warnings.
	LogWarning
	// LogTiming marks timing messages.
	LogTiming
	// LogOK marks successful status messages.
	LogOK
	// LogError marks errors.
	LogError
)

type MockControls added in v0.6.0

type MockControls struct {
	// contains filtered or unexported fields
}

MockControls tunes the model-family behaviour of a mock library after it is created. The zero behaviour of a fresh mock is a DeepSeek V4 engine: not GLM, EOS is the only generation stop, and no thinking-control markers. It is safe to call these from any goroutine.

func (*MockControls) LastEstimateBackend added in v0.9.0

func (c *MockControls) LastEstimateBackend() int32

LastEstimateBackend reports the C ds4_backend value the most recent mock context-memory estimate received, so tests can check ABI translation.

func (*MockControls) LastIMatrixCall added in v0.7.0

func (c *MockControls) LastIMatrixCall() *IMatrixCall

LastIMatrixCall returns the most recent imatrix collection call, or nil.

func (*MockControls) MultimodalSyncCalls added in v0.7.0

func (c *MockControls) MultimodalSyncCalls() int

MultimodalSyncCalls reports how many ds4_session_sync_multimodal calls the mock served.

func (*MockControls) RewindCalls added in v0.6.0

func (c *MockControls) RewindCalls() int

RewindCalls reports how many ds4_session_rewind calls the mock has served.

func (*MockControls) SetDeepSeek41 added in v0.7.0

func (c *MockControls) SetDeepSeek41(enabled bool)

SetDeepSeek41 makes the mock engine report DeepSeek V4.1 Flash (ds4_engine_is_deepseek41): thinking becomes an effort level and the think prefix is a "Reasoning Effort" system line.

func (*MockControls) SetGLM added in v0.6.0

func (c *MockControls) SetGLM(enabled bool)

SetGLM makes the mock engine report the GLM DSA family (ds4_engine_is_glm_dsa).

func (*MockControls) SetGLM53 added in v0.8.0

func (c *MockControls) SetGLM53(enabled bool)

SetGLM53 makes the mock engine report a GLM 5.3 checkpoint (ds4_engine_is_glm53). It does not imply SetGLM; set both for a GLM 5.3 engine.

func (*MockControls) SetGPUFlavor added in v0.9.0

func (c *MockControls) SetGPUFlavor(f GPUFlavor)

SetGPUFlavor makes the mock name its DS4_BACKEND_CUDA slot like a CUDA (GPUFlavorCUDA) or ROCm (GPUFlavorROCm) build of libds4, and updates the library's cached GPUFlavor. GPUFlavorUnknown restores the default "mock".

func (*MockControls) SetMultimodalAppendFailAt added in v0.7.0

func (c *MockControls) SetMultimodalAppendFailAt(index int)

SetMultimodalAppendFailAt makes ds4_chat_append_multimodal_message fail when it reaches image index (0-based) after appending the earlier ones, the way libds4 fails on a bad layout mid-message. Pass -1 to restore success.

func (*MockControls) SetPath added in v0.9.0

func (c *MockControls) SetPath(path string)

SetPath sets the path the mock library reports from Library.Path, so tests can pair it with files such as ds4go-install.json.

func (*MockControls) SetQwen4 added in v0.8.0

func (c *MockControls) SetQwen4(enabled bool)

SetQwen4 makes the mock engine report Qwen3.8 Flash Next (ds4_engine_is_qwen4): its reasoning effort is a system-turn instruction (ds4_qwen4_reasoning_effort_text), never a think prefix.

func (*MockControls) SetStopTokens added in v0.6.0

func (c *MockControls) SetStopTokens(tokens ...int)

SetStopTokens overrides the token ids the mock reports as generation stops (ds4_token_is_stop) in addition to EOS. GLM stops on the system, user, assistant, and observation role tokens, so tests use this to exercise callers that must not assume EOS is the only stop.

func (*MockControls) SetThinkingControlTokens added in v0.6.0

func (c *MockControls) SetThinkingControlTokens(tokens ...int)

SetThinkingControlTokens overrides the token ids the mock reports as <think> and </think> markers (ds4_token_is_thinking_control).

func (*MockControls) SetVision added in v0.7.0

func (c *MockControls) SetVision(enabled bool)

SetVision makes the mock engine report a loaded vision encoder (ds4_engine_has_vision) so encode and multimodal calls succeed.

func (*MockControls) SpeculativeCalls added in v0.6.0

func (c *MockControls) SpeculativeCalls() (argmax, sampled int)

SpeculativeCalls reports how many times each speculative entry point was invoked, so tests can assert which path a generator took.

func (*MockControls) SyncCalls added in v0.6.0

func (c *MockControls) SyncCalls() int

SyncCalls reports how many ds4_session_sync calls the mock has served, so tests can tell a rewind that rebuilt its prefix from one that kept state.

type ProgressFunc

type ProgressFunc func(event string, current, total int)

ProgressFunc receives ds4 progress events.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session wraps a ds4_session.

func (*Session) Argmax

func (s *Session) Argmax() int

Argmax returns the argmax token id for the current logits, or -1 when the session has no valid checkpoint (for example after a DeepSeek Rewind that was not followed by a sync).

func (*Session) ArgmaxExcluding

func (s *Session) ArgmaxExcluding(excludedID int) int

ArgmaxExcluding returns the argmax token id excluding one token.

func (*Session) ArgmaxIgnoringEOS added in v0.8.0

func (s *Session) ArgmaxIgnoringEOS(mode ThinkMode) int

ArgmaxIgnoringEOS returns the argmax token id skipping every token that is a generation stop under mode (ds4_session_argmax_ignoring_eos): EOS, the family's role markers, and thinking-control tokens when thinking is off. It returns -1 without a valid checkpoint or on a library without the entry point.

func (*Session) Close

func (s *Session) Close()

Close releases the underlying ds4_session.

func (*Session) CommonPrefix

func (s *Session) CommonPrefix(prompt *Tokens) int

CommonPrefix returns the common prefix length between the live session and prompt.

func (*Session) CopyLogits added in v0.4.0

func (s *Session) CopyLogits() ([]float32, error)

CopyLogits returns a copy of the current logits vector for the session. The slice length equals the engine vocabulary size.

func (*Session) Ctx

func (s *Session) Ctx() int

Ctx returns the session context size.

func (*Session) DirectionalSteeringFFN added in v0.6.0

func (s *Session) DirectionalSteeringFFN() float32

DirectionalSteeringFFN calls ds4_session_directional_steering_ffn and returns the session's current FFN steering scale. It returns 0 when the loaded library predates the symbol.

func (*Session) DistributedRouteReady added in v0.5.0

func (s *Session) DistributedRouteReady() (bool, error)

DistributedRouteReady returns 1 when the coordinator has a complete worker route, 0 when workers are still missing, and -1 for internal errors.

func (*Session) Eval

func (s *Session) Eval(token int) error

Eval evaluates one token and advances the session.

func (*Session) EvalLayerSlice added in v0.5.0

func (s *Session) EvalLayerSlice(
	tokens []int32,
	pos0 uint32,
	layerStart uint32,
	layerEnd uint32,
	inputHC []float32,
	outputHC []float32,
	outputLogits bool,
	logits []float32,
) error

EvalLayerSlice runs forward pass computations for a contiguous subset of model layers.

func (*Session) EvalOutputHeadFromHC added in v0.5.0

func (s *Session) EvalOutputHeadFromHC(hiddenHC []float32, nTokens uint32, logits []float32) error

EvalOutputHeadFromHC computes vocabulary logits from final hidden activations.

func (*Session) EvalSpeculative added in v0.6.0

func (s *Session) EvalSpeculative(firstToken, maxTokens, eosToken int, opts SpeculativeOptions) ([]int, error)

EvalSpeculative evaluates an already-sampled token and speculatively extends it under the given sampling parameters (ds4_session_eval_speculative), the positive-temperature counterpart to Session.EvalSpeculativeArgmax. It returns the accepted tokens, beginning with firstToken.

Returns ErrSpeculativeSamplingNotSupported on libds4 builds that predate the entry point; callers can check Library.SupportsSampledSpeculative first.

func (*Session) EvalSpeculativeArgmax

func (s *Session) EvalSpeculativeArgmax(firstToken, maxTokens, eosToken int) ([]int, error)

EvalSpeculativeArgmax calls ds4_session_eval_speculative_argmax.

func (*Session) EvalSpeculativeArgmaxIgnoringEOS added in v0.8.0

func (s *Session) EvalSpeculativeArgmaxIgnoringEOS(firstToken, maxTokens, eosToken int, mode ThinkMode) ([]int, error)

EvalSpeculativeArgmaxIgnoringEOS is Session.EvalSpeculativeArgmax with draft verification that ignores the stop tokens of mode (ds4_session_eval_speculative_argmax_ignoring_eos). It fails on a library without the entry point.

func (*Session) GPUWarmup added in v0.8.0

func (s *Session) GPUWarmup()

GPUWarmup pays the one-time first-submission GPU cost outside any measured window (ds4_session_gpu_warmup); a no-op on CPU, on non-DeepSeek families, and on libraries without the entry point.

func (*Session) HasVisionState added in v0.7.0

func (s *Session) HasVisionState() bool

HasVisionState calls ds4_session_has_vision_state: true while the session contains, or is syncing, image-conditioned state. Such state must not be written to a text-keyed disk cache.

func (*Session) Invalidate

func (s *Session) Invalidate()

Invalidate invalidates the live session state.

func (*Session) IsDistributed added in v0.5.0

func (s *Session) IsDistributed() bool

IsDistributed returns whether the session is operating in distributed mode.

func (*Session) LayerPayloadBytes added in v0.5.0

func (s *Session) LayerPayloadBytes(layerStart uint32, layerEnd uint32) uint64

LayerPayloadBytes returns the serialization size of a layer slice KV cache payload.

func (*Session) LayerSliceReset added in v0.5.0

func (s *Session) LayerSliceReset() error

LayerSliceReset resets the graph and KV cache state of a distributed layer slice.

func (*Session) LoadLayerPayload added in v0.5.0

func (s *Session) LoadLayerPayload(fp uintptr, payloadBytes uint64, tokens []int32, layerStart uint32, layerEnd uint32) error

LoadLayerPayload reads a layer slice KV cache payload from fp.

func (*Session) LoadPayload

func (s *Session) LoadPayload(fp File, payloadBytes uint64) error

LoadPayload reads a DS4-specific session payload from fp.

func (*Session) LoadPayloadFile

func (s *Session) LoadPayloadFile(path string, payloadBytes uint64) error

LoadPayloadFile reads a DS4-specific session payload from path.

func (*Session) LoadSnapshot

func (s *Session) LoadSnapshot(data []byte) error

LoadSnapshot restores a session snapshot previously returned by SaveSnapshot.

func (*Session) PayloadBytes

func (s *Session) PayloadBytes() uint64

PayloadBytes returns ds4_session_payload_bytes.

func (*Session) Pos

func (s *Session) Pos() int

Pos returns the current session token position.

func (*Session) Power added in v0.4.0

func (s *Session) Power() int

Power returns ds4_session_power. Sessions share the engine power setting, so this returns the engine's current duty-cycle percentage.

func (*Session) PrefillCap added in v0.6.0

func (s *Session) PrefillCap() int

PrefillCap returns the session's prefill capacity in tokens (ds4_session_prefill_cap), or 0 on libraries without the accessor.

func (*Session) RebaseVisionState added in v0.7.0

func (s *Session) RebaseVisionState(spans []VisionSpan) bool

RebaseVisionState calls ds4_session_rebase_vision_state: for a continuation authenticated by other means, restore the session's image offsets into spans (TokenStart is updated in place). Fingerprints and row counts must match; on failure spans are unchanged.

func (*Session) ReportProgress added in v0.8.0

func (s *Session) ReportProgress(event string, current, total int)

ReportProgress delivers one event to the session's progress callback (ds4_session_report_progress), the hook libds4 itself uses; nothing happens without a callback or on libraries without the entry point.

func (*Session) Rewind

func (s *Session) Rewind(pos int)

Rewind rewinds the session to token position pos. Rewind calls ds4_session_rewind, keeping the token prefix [0, pos) and discarding everything after it. Session.Tokens still reports the retained prefix, but since upstream ds4 233eeb8 the checkpoint is only kept valid for GLM (5.3 only when pos is its MTP rollback point): on DeepSeek the compressor frontier cannot be truncated, so Argmax and Sample return -1, Eval fails with "decode requires a synchronized checkpoint", and CommonPrefix returns 0 until the retained prefix is synced again. Since upstream fc80bd6, a GPU build first tries a cheap restore when pos lies inside the most recent DSpark verifier block (ds4_session_rewind_speculative); when that succeeds the checkpoint stays valid and no re-sync is needed. Use RewindSynced unless you re-sync yourself: it only rebuilds when the fast path did not apply. Qwen may defer recurrent-state replay until the next eval; use RewindSynced before sampling after a rewind.

func (*Session) RewindSynced added in v0.6.0

func (s *Session) RewindSynced(pos int, spans ...VisionSpan) error

RewindSynced rewinds to pos and then restores a valid checkpoint for the retained prefix when the rewind lost it, mirroring upstream's agent_worker_rewind / server_generation_rewind. Qwen also syncs after a rewind because its retained token checkpoint may still have stale logits; libds4 decides whether the recurrent graph needs replay. spans are the image spans of the prompt the session was synced with, classified against the retained prefix length: a span entirely inside it is kept and passed to the multimodal sync, as the header requires for image-bearing sessions; a span entirely after it is dropped; a span straddling the cut point is an error, since the retained prefix would then contain a partial image. A rewind at or past the current position is a no-op. Note that by the time a straddling span is detected the session has already been rewound (Rewind is unconditional), so on that error the session is left needing a fresh sync.

func (*Session) RewriteFromCommon

func (s *Session) RewriteFromCommon(prompt *Tokens, common int) (SessionRewriteResult, error)

RewriteFromCommon rewrites a session from a known common prefix length.

func (*Session) Sample

func (s *Session) Sample(temperature float32, topK int, topP, minP float32, rng *uint64) int

Sample samples the next token from current logits.

func (*Session) SaveLayerPayload added in v0.5.0

func (s *Session) SaveLayerPayload(fp uintptr, layerStart uint32, layerEnd uint32) error

SaveLayerPayload writes a layer slice KV cache payload to fp.

func (*Session) SavePayload

func (s *Session) SavePayload(fp File) error

SavePayload writes the DS4-specific session payload to fp.

func (*Session) SavePayloadFile

func (s *Session) SavePayloadFile(path string) error

SavePayloadFile writes the DS4-specific session payload to path.

func (*Session) SaveSnapshot

func (s *Session) SaveSnapshot() ([]byte, error)

SaveSnapshot serializes a session snapshot to a Go byte slice.

func (*Session) SetCancel added in v0.5.1

func (s *Session) SetCancel(fn CancelFunc) error

SetCancel sets a persistent cooperative cancellation callback for ds4_session_set_cancel. ds4_session_sync polls this callback only at safe boundaries where the live checkpoint remains valid.

func (*Session) SetDirectionalSteering deprecated added in v0.4.0

func (s *Session) SetDirectionalSteering(file string, mode SteeringMode, ffn float32, attn float32, threshold float32, scope SteeringScope) error

SetDirectionalSteering dynamically updates the directional steering configurations for this session. If the underlying libds4 shared library does not support dynamic steering, this returns an error.

Deprecated: upstream ds4 never exported ds4_session_set_directional_steering, so this always returns ErrSteeringNotSupported against upstream builds. Use SetDirectionalSteeringFFN, which binds the exported ds4_session_set_directional_steering_ffn.

func (*Session) SetDirectionalSteeringFFN added in v0.6.0

func (s *Session) SetDirectionalSteeringFFN(scale float32) error

SetDirectionalSteeringFFN calls ds4_session_set_directional_steering_ffn, changing the FFN steering scale for future evaluation without rebuilding the existing KV state. libds4 accepts finite scales in [-100, 100] and rejects live changes on distributed or tensor-parallel sessions. It returns ErrSteeringNotSupported when the loaded library lacks the symbol.

func (*Session) SetDisplayProgress added in v0.4.0

func (s *Session) SetDisplayProgress(fn ProgressFunc) error

SetDisplayProgress sets a persistent UI-only progress callback for ds4_session_set_display_progress. It may report fine-grained progress inside a prefill chunk; callers must not treat it as a durable KV checkpoint boundary. Use SetProgress for checkpoint-anchored events.

func (*Session) SetLogits added in v0.8.0

func (s *Session) SetLogits(logits []float32) error

SetLogits replaces the session's current logits (ds4_session_set_logits). The vector must hold exactly the engine's vocabulary size; the next Argmax, Sample, or logprob call reads it.

func (*Session) SetPower added in v0.4.0

func (s *Session) SetPower(powerPercent int) error

SetPower calls ds4_session_set_power. powerPercent must be in 1..100. This updates the engine-wide setting as well as the session's GPU graph, so concurrent sessions sharing the same engine see the new value.

func (*Session) SetProgress

func (s *Session) SetProgress(fn ProgressFunc) error

SetProgress sets a persistent progress callback for ds4_session_set_progress.

func (*Session) Sync

func (s *Session) Sync(prompt []int) error

Sync synchronizes the live session to a full prompt token prefix.

func (*Session) SyncMultimodal added in v0.7.0

func (s *Session) SyncMultimodal(prompt *Tokens, spans []VisionSpan) error

SyncMultimodal is Session.SyncTokens for a prompt containing image spans (ds4_session_sync_multimodal). With no spans it is the plain sync.

func (*Session) SyncMultimodalWithCancel added in v0.7.0

func (s *Session) SyncMultimodalWithCancel(prompt *Tokens, spans []VisionSpan, fn CancelFunc) error

SyncMultimodalWithCancel is SyncMultimodal polling fn for cancellation, as SyncTokensWithCancel does.

func (*Session) SyncTokens

func (s *Session) SyncTokens(prompt *Tokens) error

SyncTokens synchronizes the live session to a full prompt token prefix.

func (*Session) SyncTokensWithCancel added in v0.5.1

func (s *Session) SyncTokensWithCancel(prompt *Tokens, fn CancelFunc) error

SyncTokensWithCancel synchronizes the live session to a full prompt token prefix while polling fn for cooperative cancellation. Any persistent SetCancel callback is restored before SyncTokensWithCancel returns.

func (*Session) SyncWithCancel added in v0.5.1

func (s *Session) SyncWithCancel(prompt []int, fn CancelFunc) error

SyncWithCancel synchronizes the live session to a full prompt token prefix while polling fn for cooperative cancellation. Any persistent SetCancel callback is restored before SyncWithCancel returns.

func (*Session) TokenLogprob

func (s *Session) TokenLogprob(token int) (TokenScore, error)

TokenLogprob returns the score for a specific token.

func (*Session) Tokens

func (s *Session) Tokens() *Tokens

Tokens returns a borrowed snapshot of ds4_session_tokens.

func (*Session) TopLogprobs

func (s *Session) TopLogprobs(k int) ([]TokenScore, error)

TopLogprobs returns the top k token scores for the current logits.

func (*Session) VisionPrefixMatches added in v0.7.0

func (s *Session) VisionPrefixMatches(spans []VisionSpan) bool

VisionPrefixMatches calls ds4_session_vision_prefix_matches: every image the session already holds is unchanged in spans (same offset and fingerprint) and any new images start at or after the live frontier. The caller must still check the token prefix.

func (*Session) VisionStateMatches added in v0.7.0

func (s *Session) VisionStateMatches(spans []VisionSpan) bool

VisionStateMatches is VisionPrefixMatches plus an identical image count.

type SessionRewriteResult

type SessionRewriteResult int32

SessionRewriteResult is returned by ds4 session rewrite helpers.

const (
	// SessionRewriteError means the rewrite failed.
	SessionRewriteError SessionRewriteResult = -1
	// SessionRewriteOK means the rewrite completed in place.
	SessionRewriteOK SessionRewriteResult = 0
	// SessionRewriteRebuildNeeded means the caller should restore or rebuild the session state.
	SessionRewriteRebuildNeeded SessionRewriteResult = 1
)

type SpeculativeOptions added in v0.6.0

type SpeculativeOptions struct {
	Temperature float32
	TopK        int
	TopP        float32
	MinP        float32
	// RNG seeds and advances ds4's sampler. Passing nil uses a zero seed,
	// which is valid and deterministic.
	RNG *uint64
}

SpeculativeOptions carries the sampling parameters for Session.EvalSpeculative. They mirror Session.Sample: a non-positive Temperature makes the verifier greedy, in which case Session.EvalSpeculativeArgmax is the cheaper call.

type SteeringMode added in v0.4.0

type SteeringMode int32

SteeringMode defines the formula used to steer session activations.

const (
	// SteeringAblation projects out activations along the steering direction.
	SteeringAblation SteeringMode = 0
	// SteeringThreshold applies activation steering only above a projection threshold (CAST).
	SteeringThreshold SteeringMode = 1
	// SteeringAdditive projects activations along the steering direction (Golden Gate).
	SteeringAdditive SteeringMode = 2
)

type SteeringScope added in v0.4.0

type SteeringScope int32

SteeringScope defines the lifetime/scope of the dynamic steering settings.

const (
	// SteeringScopeNextMessage reverts the steering setting automatically after one message.
	SteeringScopeNextMessage SteeringScope = 0
	// SteeringScopeUntilRevert keeps the steering setting active until explicitly reverted or changed.
	SteeringScopeUntilRevert SteeringScope = 1
	// SteeringScopeOff disables dynamic steering.
	SteeringScopeOff SteeringScope = 2
)

type ThinkMode

type ThinkMode int32

ThinkMode controls ds4's rendered chat thinking mode.

const (
	// ThinkNone disables thinking markers in chat prompts.
	ThinkNone ThinkMode = iota
	// ThinkHigh enables ordinary high-effort thinking.
	ThinkHigh
	// ThinkMax requests maximum-effort thinking. ds4_think_mode_for_context
	// may downgrade it to ThinkHigh when the context is below ThinkMaxMinContext.
	ThinkMax
	// ThinkLow is upstream's DS4_THINK_LOW: the OpenAI "low" (and "minimal")
	// reasoning effort. Qwen3.8 renders it as its brief-thinking instruction;
	// GLM treats it as High and DeepSeek V4.1 as thinking with no effort line.
	ThinkLow
	// ThinkMedium is upstream's DS4_THINK_MEDIUM: the OpenAI "medium" effort.
	// Qwen3.8 adds no instruction for it; other families treat it as ThinkLow.
	ThinkMedium
)
const ThinkLevelBase ThinkMode = 1000

ThinkLevelBase is upstream's DS4_THINK_LEVEL_BASE: explicit numeric effort (DeepSeek V4.1) is carried as ThinkLevelBase + level, outside the named modes, so the ThinkMode type stays ABI-compatible.

func ParseThinkLevel added in v0.7.0

func ParseThinkLevel(text string) (ThinkMode, error)

ParseThinkLevel parses "--think-level" text the way ds4_think_mode_parse_level does: decimal digits only, 0 to 100.

func ThinkLevel added in v0.7.0

func ThinkLevel(level int) ThinkMode

ThinkLevel returns the ThinkMode for an explicit V4.1 reasoning effort, 0 (thinking off) to 100. It mirrors ds4_think_mode_parse_level's encoding without needing a loaded library; ParseThinkLevel validates text input.

func ThinkModeForContext

func ThinkModeForContext(mode ThinkMode, ctxSize int) ThinkMode

ThinkModeForContext returns the effective thinking mode for a context size.

func (ThinkMode) Level added in v0.7.0

func (m ThinkMode) Level() int

Level returns the explicit effort a ThinkMode carries, or -1 for the named modes (ds4_think_mode_level).

type TokenEmitFunc

type TokenEmitFunc func(token int)

TokenEmitFunc is called when ds4 emits a generated token.

type TokenScore

type TokenScore struct {
	// ID is the token id.
	ID int
	// Logit is the raw model logit.
	Logit float32
	// Logprob is the log probability for the token.
	Logprob float32
}

TokenScore is ds4_token_score.

type Tokens

type Tokens struct {
	// contains filtered or unexported fields
}

Tokens owns a ds4_tokens value allocated by libds4.

func NewTokens

func NewTokens(ids []int) (*Tokens, error)

NewTokens creates a libds4-owned token vector from ids.

func (*Tokens) Cap

func (t *Tokens) Cap() int

Cap returns the token vector capacity.

func (*Tokens) Copy

func (t *Tokens) Copy() *Tokens

Copy returns a deep copy of this token vector.

func (*Tokens) Free

func (t *Tokens) Free()

Free releases memory owned by this token vector.

func (*Tokens) Len

func (t *Tokens) Len() int

Len returns the number of tokens.

func (*Tokens) Push

func (t *Tokens) Push(token int)

Push appends one token id to the vector.

func (*Tokens) Slice

func (t *Tokens) Slice() []int

Slice returns a copy of the token ids.

func (*Tokens) StartsWith

func (t *Tokens) StartsWith(prefix *Tokens) bool

StartsWith reports whether t begins with prefix.

type VisionEmbedding added in v0.7.0

type VisionEmbedding struct {
	// contains filtered or unexported fields
}

VisionEmbedding owns the encoder output for one image: token_count rows of ds4_engine_embd_dim floats malloc'd by libds4. Appending it to a prompt moves ownership into a VisionSpan and empties this handle.

func (*VisionEmbedding) Clone added in v0.7.0

func (e *VisionEmbedding) Clone() (*VisionEmbedding, error)

Clone copies the embedding. The copy is independent: freeing either side leaves the other valid.

func (*VisionEmbedding) Fingerprint added in v0.7.0

func (e *VisionEmbedding) Fingerprint() [32]byte

Fingerprint identifies the image content; libds4 compares it when deciding whether a session's image state can be reused.

func (*VisionEmbedding) Free added in v0.7.0

func (e *VisionEmbedding) Free()

Free releases the embedding. It is a no-op after a move or a prior Free.

func (*VisionEmbedding) TokenCount added in v0.7.0

func (e *VisionEmbedding) TokenCount() int

TokenCount is the number of image tokens the embedding occupies.

type VisionSpan added in v0.7.0

type VisionSpan struct {
	TokenStart int
	Embedding  *VisionEmbedding
}

VisionSpan is an embedding placed at a token offset within a prompt.

Jump to

Keyboard shortcuts

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