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
- func BackendName(backend Backend) string
- func DumpTextTokenization(modelPath, text string, fp File) error
- func LogIsTTY(fp File) bool
- func LogString(fp File, typ LogType, msg string)
- func RewriteRequiresRebuild(liveLen, canonicalLen, common int) bool
- func SetDefaultLibrary(lib *Library)
- func ThinkMaxMinContext() uint32
- func ThinkMaxPrefix() string
- func ThinkModeEnabled(mode ThinkMode) bool
- func ThinkModeName(mode ThinkMode) string
- type ArgmaxGenerateOptions
- type Backend
- type ContextMemory
- type Engine
- func (e *Engine) ChatAppendAssistantPrefix(tokens *Tokens, thinkMode ThinkMode) error
- func (e *Engine) ChatAppendMaxEffortPrefix(tokens *Tokens) error
- func (e *Engine) ChatAppendMessage(tokens *Tokens, role, content string) error
- func (e *Engine) ChatBegin(tokens *Tokens) error
- func (e *Engine) Close()
- func (e *Engine) CollectIMatrix(datasetPath, outputPath string, ctxSize, maxPrompts, maxTokens int) error
- func (e *Engine) DumpTokens(tokens *Tokens) error
- func (e *Engine) EncodeChatPrompt(system, prompt string, thinkMode ThinkMode) (*Tokens, error)
- func (e *Engine) FirstTokenTest(prompt *Tokens) error
- func (e *Engine) GenerateArgmax(prompt *Tokens, opts ArgmaxGenerateOptions) ([]int, error)
- func (e *Engine) HasMTP() bool
- func (e *Engine) HeadTest(prompt *Tokens) error
- func (e *Engine) MTPDraftTokens() int
- func (e *Engine) MetalGraphFullTest(prompt *Tokens) error
- func (e *Engine) MetalGraphPromptTest(prompt *Tokens, ctxSize int) error
- func (e *Engine) MetalGraphTest(prompt *Tokens) error
- func (e *Engine) NewSession(ctxSize int) (*Session, error)
- func (e *Engine) NewTokens(ids []int) (*Tokens, error)
- func (e *Engine) RoutedQuantBits() int
- func (e *Engine) Summary() error
- func (e *Engine) TokenAssistant() int
- func (e *Engine) TokenEOS() int
- func (e *Engine) TokenText(token int) (string, error)
- func (e *Engine) TokenUser() int
- func (e *Engine) TokenizeRenderedChat(text string) (*Tokens, error)
- func (e *Engine) TokenizeText(text string) (*Tokens, error)
- type EngineOptions
- type File
- type GenerationDoneFunc
- type Library
- type LogType
- type ProgressFunc
- type Session
- func (s *Session) Argmax() int
- func (s *Session) ArgmaxExcluding(excludedID int) int
- func (s *Session) Close()
- func (s *Session) CommonPrefix(prompt *Tokens) int
- func (s *Session) Ctx() int
- func (s *Session) Eval(token int) error
- func (s *Session) EvalSpeculativeArgmax(firstToken, maxTokens, eosToken int) ([]int, error)
- func (s *Session) Invalidate()
- func (s *Session) LoadPayload(fp File, payloadBytes uint64) error
- func (s *Session) LoadPayloadFile(path string, payloadBytes uint64) error
- func (s *Session) LoadSnapshot(data []byte) error
- func (s *Session) PayloadBytes() uint64
- func (s *Session) Pos() int
- func (s *Session) Rewind(pos int)
- func (s *Session) RewriteFromCommon(prompt *Tokens, common int) (SessionRewriteResult, error)
- func (s *Session) Sample(temperature float32, topK int, topP, minP float32, rng *uint64) int
- func (s *Session) SavePayload(fp File) error
- func (s *Session) SavePayloadFile(path string) error
- func (s *Session) SaveSnapshot() ([]byte, error)
- func (s *Session) SetProgress(fn ProgressFunc) error
- func (s *Session) Sync(prompt []int) error
- func (s *Session) SyncTokens(prompt *Tokens) error
- func (s *Session) TokenLogprob(token int) (TokenScore, error)
- func (s *Session) Tokens() *Tokens
- func (s *Session) TopLogprobs(k int) ([]TokenScore, error)
- type SessionRewriteResult
- type ThinkMode
- type TokenEmitFunc
- type TokenScore
- type Tokens
Constants ¶
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 ¶
This section is empty.
Functions ¶
func BackendName ¶
BackendName returns ds4's printable name for backend.
func DumpTextTokenization ¶
DumpTextTokenization calls ds4_dump_text_tokenization.
func RewriteRequiresRebuild ¶
RewriteRequiresRebuild calls ds4_session_rewrite_requires_rebuild.
func SetDefaultLibrary ¶
func SetDefaultLibrary(lib *Library)
SetDefaultLibrary makes lib the package default library.
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 ¶
ThinkModeEnabled reports whether mode emits thinking markers.
func ThinkModeName ¶
ThinkModeName returns ds4's printable name for mode.
Types ¶
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.
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.
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 ¶
ChatAppendAssistantPrefix appends the assistant prefix for generation.
func (*Engine) ChatAppendMaxEffortPrefix ¶
ChatAppendMaxEffortPrefix appends ds4's maximum-effort thinking prefix.
func (*Engine) ChatAppendMessage ¶
ChatAppendMessage appends a rendered role/content chat message.
func (*Engine) CollectIMatrix ¶
func (e *Engine) CollectIMatrix(datasetPath, outputPath string, ctxSize, maxPrompts, maxTokens int) error
CollectIMatrix calls ds4_engine_collect_imatrix.
func (*Engine) DumpTokens ¶
DumpTokens calls ds4_engine_dump_tokens.
func (*Engine) EncodeChatPrompt ¶
EncodeChatPrompt encodes a system and user prompt with ds4's chat template.
func (*Engine) FirstTokenTest ¶
FirstTokenTest calls ds4_engine_first_token_test.
func (*Engine) GenerateArgmax ¶
func (e *Engine) GenerateArgmax(prompt *Tokens, opts ArgmaxGenerateOptions) ([]int, error)
GenerateArgmax calls ds4_engine_generate_argmax.
func (*Engine) MTPDraftTokens ¶
MTPDraftTokens returns the configured MTP draft length.
func (*Engine) MetalGraphFullTest ¶
MetalGraphFullTest calls ds4_engine_metal_graph_full_test.
func (*Engine) MetalGraphPromptTest ¶
MetalGraphPromptTest calls ds4_engine_metal_graph_prompt_test.
func (*Engine) MetalGraphTest ¶
MetalGraphTest calls ds4_engine_metal_graph_test.
func (*Engine) NewSession ¶
NewSession creates a ds4 session for this engine and context size.
func (*Engine) NewTokens ¶
NewTokens creates a libds4-owned token vector associated with this engine's library.
func (*Engine) RoutedQuantBits ¶
RoutedQuantBits returns the routed expert quantization bits used by the engine.
func (*Engine) TokenAssistant ¶
TokenAssistant returns ds4's assistant-role token id.
func (*Engine) TokenText ¶
TokenText decodes one token to text and frees the C allocation returned by ds4.
func (*Engine) TokenizeRenderedChat ¶
TokenizeRenderedChat tokenizes a rendered chat prompt.
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
// Backend selects Metal, CUDA, or CPU according to the libds4 build.
Backend Backend
// NThreads controls CPU worker threads when the backend uses them.
NThreads int
// MTPDraftTokens controls speculative draft length.
MTPDraftTokens int
// MTPMargin controls speculative acceptance confidence.
MTPMargin 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
// WarmWeights asks ds4 to warm model weights after load.
WarmWeights bool
// Quality requests ds4's quality-oriented execution path where supported.
Quality bool
}
EngineOptions configures ds4_engine_open.
type File ¶
type File uintptr
File is an opaque C FILE* used by ds4 APIs that accept FILE pointers.
type GenerationDoneFunc ¶
type GenerationDoneFunc func()
GenerationDoneFunc is called after ds4 completes generation.
type Library ¶
type Library struct {
// contains filtered or unexported fields
}
Library is a loaded libds4 shared library.
func DefaultLibrary ¶
DefaultLibrary returns the lazily loaded default library.
func Load ¶
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.
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 ProgressFunc ¶
ProgressFunc receives ds4 progress events.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session wraps a ds4_session.
func (*Session) ArgmaxExcluding ¶
ArgmaxExcluding returns the argmax token id excluding one token.
func (*Session) CommonPrefix ¶
CommonPrefix returns the common prefix length between the live session and prompt.
func (*Session) EvalSpeculativeArgmax ¶
EvalSpeculativeArgmax calls ds4_session_eval_speculative_argmax.
func (*Session) Invalidate ¶
func (s *Session) Invalidate()
Invalidate invalidates the live session state.
func (*Session) LoadPayload ¶
LoadPayload reads a DS4-specific session payload from fp.
func (*Session) LoadPayloadFile ¶
LoadPayloadFile reads a DS4-specific session payload from path.
func (*Session) LoadSnapshot ¶
LoadSnapshot restores a session snapshot previously returned by SaveSnapshot.
func (*Session) PayloadBytes ¶
PayloadBytes returns ds4_session_payload_bytes.
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) SavePayload ¶
SavePayload writes the DS4-specific session payload to fp.
func (*Session) SavePayloadFile ¶
SavePayloadFile writes the DS4-specific session payload to path.
func (*Session) SaveSnapshot ¶
SaveSnapshot serializes a session snapshot to a Go byte slice.
func (*Session) SetProgress ¶
func (s *Session) SetProgress(fn ProgressFunc) error
SetProgress sets a persistent progress callback for ds4_session_set_progress.
func (*Session) SyncTokens ¶
SyncTokens synchronizes the live session to a full prompt token prefix.
func (*Session) TokenLogprob ¶
func (s *Session) TokenLogprob(token int) (TokenScore, error)
TokenLogprob returns the score for a specific token.
func (*Session) TopLogprobs ¶
func (s *Session) TopLogprobs(k int) ([]TokenScore, error)
TopLogprobs returns the top k token scores for the current logits.
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 ThinkMode ¶
type ThinkMode int32
ThinkMode controls ds4's rendered chat thinking mode.
func ThinkModeForContext ¶
ThinkModeForContext returns the effective thinking mode for a context size.
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 (*Tokens) StartsWith ¶
StartsWith reports whether t begins with prefix.