models

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: 21 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package models manages ds4go's curated model catalog.

Index

Constants

View Source
const (

	// DefaultModelSymlink is the name of the active-model symlink in ModelsDir.
	DefaultModelSymlink = "ds4flash.gguf"

	// ConfigFileName is the ds4go configuration file name.
	ConfigFileName = "ds4go.json"

	// MTPAlias is the curated alias for the MTP companion model.
	MTPAlias = "mtp"

	// RecommendedModelAlias is the suggested default model for first-time users.
	RecommendedModelAlias = "q2-imatrix"
)

Variables

View Source
var ErrLocked = errors.New("lock already held by another process")

ErrLocked is returned by TryLock when another process already holds the lock.

Functions

func DefaultMTPPath added in v0.2.2

func DefaultMTPPath() string

DefaultMTPPath returns the path to the installed MTP companion model, or empty string if it is not present.

func DefaultModelPath

func DefaultModelPath() string

DefaultModelPath returns the configured default model path.

func FormatBytes added in v0.7.0

func FormatBytes(n int64) string

FormatBytes renders n in the binary units the CLI uses.

func GetLockHolder added in v0.4.0

func GetLockHolder(path string) (int, error)

GetLockHolder returns the PID of the process holding the lock on path. If the lock is not currently held, it returns 0, nil.

func GetProcessName added in v0.4.0

func GetProcessName(pid int) string

GetProcessName returns the executable name of the process with the given PID, or "unknown" if it cannot be determined.

Types

type Config

type Config struct {
	DefaultModel string           `json:"defaultModel"`
	DS4Dir       string           `json:"ds4Dir"`
	Models       map[string]Model `json:"models"`
}

Config is stored at $DS4_DIR/ds4go.json.

type DownloadState added in v0.7.0

type DownloadState string

DownloadState classifies a partial download.

const (
	// DownloadRunning: a downloader holds the file's lock and the part file
	// has grown recently.
	DownloadRunning DownloadState = "downloading"
	// DownloadStalled: a downloader holds the lock but nothing has been
	// written for longer than downloadStallAfter (it is likely in a retry
	// backoff or waiting on the network).
	DownloadStalled DownloadState = "stalled"
	// DownloadInterrupted: partial data on disk and no downloader; the next
	// `model download` resumes it.
	DownloadInterrupted DownloadState = "interrupted"
)

type DownloadStatus added in v0.7.0

type DownloadStatus struct {
	Alias string        `json:"alias"`
	State DownloadState `json:"state"`
	// PID is the downloader holding the lock, or 0.
	PID int `json:"pid,omitempty"`
	// Bytes is on disk so far; Total is the expected size (catalog, or the
	// sum of split parts), 0 when unknown.
	Bytes int64 `json:"bytes"`
	Total int64 `json:"total,omitempty"`
	// Idle is how long ago the part file last grew.
	Idle time.Duration `json:"-"`
	// BytesPerSec is the rate observed over the sampling window, 0 when not
	// sampled or nothing arrived; ETA follows from it and Total.
	BytesPerSec float64       `json:"bytes_per_sec,omitempty"`
	ETA         time.Duration `json:"-"`
}

DownloadStatus is the state of one catalog model's partial download.

func (DownloadStatus) MarshalJSON added in v0.7.0

func (s DownloadStatus) MarshalJSON() ([]byte, error)

MarshalJSON renders the durations in seconds rather than Go's nanosecond integers, for shells and scripts reading `model status --json`.

type FileLock added in v0.4.0

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

FileLock is an advisory, OS-level exclusive lock. The kernel releases it automatically when the holding process exits, so an interrupted process never leaves a stale lock behind.

func AcquireEngineRunLock added in v0.4.0

func AcquireEngineRunLock(modelPath string) (*FileLock, error)

AcquireEngineRunLock attempts to acquire the run lock file for a given model path. If the lock is already held by another process, it returns a descriptive error indicating the holding process PID and name.

func LockExclusive added in v0.4.0

func LockExclusive(path string) (*FileLock, error)

LockExclusive acquires an exclusive lock on path, creating the file if needed. Unlike TryLock, it waits for the existing holder to release it.

func TryLock added in v0.4.0

func TryLock(path string) (*FileLock, error)

TryLock acquires a non-blocking exclusive lock on path, creating the file if needed. It returns ErrLocked if another process holds the lock.

func (*FileLock) Close added in v0.4.0

func (l *FileLock) Close() error

Close releases the lock and closes the underlying file.

func (*FileLock) Path added in v0.8.0

func (l *FileLock) Path() string

Path returns the lock file this lock holds. Releasers remove this path rather than rebuilding the name from what they locked.

type Leftover added in v0.7.0

type Leftover struct {
	Path  string
	Kind  LeftoverKind
	Bytes int64
	// Alias is the catalog alias the file belongs to, or "" when the catalog
	// no longer lists the model.
	Alias string
	// Locked reports that a download for this model is in progress; such
	// files are listed but never removed.
	Locked bool
}

Leftover is one removable file in the models directory.

type LeftoverKind added in v0.7.0

type LeftoverKind string

LeftoverKind classifies a file in the models directory that is not an installed model.

const (
	// LeftoverPartial is a resumable ".part" download.
	LeftoverPartial LeftoverKind = "partial"
	// LeftoverQuarantined is a ".bad-<hash>" file set aside after a hash
	// mismatch.
	LeftoverQuarantined LeftoverKind = "quarantined"
	// LeftoverLock is a ".lock" file left by a finished download. The lock
	// itself is advisory and released on exit; only the empty file remains.
	LeftoverLock LeftoverKind = "lock"
)

type LoadedFile added in v0.7.0

type LoadedFile struct {
	Path  string     `json:"path"`
	Alias string     `json:"alias,omitempty"`
	Role  LoadedRole `json:"role,omitempty"`
}

LoadedFile is one GGUF a process has open, mapped onto the catalog.

func ClassifyLoadedFiles added in v0.7.0

func ClassifyLoadedFiles(paths []string) []LoadedFile

ClassifyLoadedFiles maps open model files onto catalog aliases and roles. The active-model link resolves to the checkpoint it points at (ModelForPath follows both symlinks and hard-link identity). Results are ordered model, then companions, then unknown, so the checkpoint leads.

type LoadedRole added in v0.7.0

type LoadedRole string

LoadedRole says what part a GGUF plays for a running engine.

const (
	// RoleModel is the language checkpoint.
	RoleModel LoadedRole = "model"
	// RoleMTP is a speculative-decoding companion (MTP or DSpark support).
	RoleMTP LoadedRole = "mtp"
	// RoleVision is a vision encoder.
	RoleVision LoadedRole = "vision"
	// RoleUnknown is a file the catalog does not describe.
	RoleUnknown LoadedRole = ""
)

type Manager

type Manager struct {
	DS4Dir             string
	ModelsDir          string
	ConfigPath         string
	HTTPClient         *http.Client
	Out                io.Writer
	ProgressOut        io.Writer
	NewProgressTracker func(out io.Writer, name string, start, total int64) ProgressTracker
}

Manager manages the local ds4 model directory and config.

func NewManager

func NewManager() *Manager

NewManager returns a manager rooted at DS4_DIR or ~/.ds4.

func (*Manager) Delete

func (m *Manager) Delete(alias string) error

Delete removes a curated model's downloaded file and any partial download. If the deleted model was the default, the default is cleared.

func (*Manager) DeletePartial added in v0.7.0

func (m *Manager) DeletePartial(alias string) error

DeletePartial removes a model's partial download and nothing else; the installed file, if any, stays.

func (*Manager) Download

func (m *Manager) Download(ctx context.Context, alias, token string, force bool) (Model, error)

Download downloads a curated model from Hugging Face with resume support.

func (*Manager) DownloadDryRun

func (m *Manager) DownloadDryRun(ctx context.Context, alias, token string) (Model, error)

DownloadDryRun resolves alias and reports what Download would fetch — the source URL, destination path, remote size/SHA256, and current local state — without downloading anything.

func (*Manager) DownloadMany added in v0.7.0

func (m *Manager) DownloadMany(ctx context.Context, aliases []string, token string, force bool) ([]Model, error)

DownloadMany downloads aliases one after another, in the order given. Every alias is validated and the combined catalog size of the models not yet installed is checked against the volume before the first byte moves, so a typo or a full disk fails up front rather than hours in. It stops at the first failure and returns the models installed so far along with an error naming the alias that failed. Each download still runs Download's own remote-size space check.

func (*Manager) DownloadStatus added in v0.7.0

func (m *Manager) DownloadStatus(sample time.Duration) ([]DownloadStatus, error)

DownloadStatus reports every catalog model with partial data on disk. Liveness comes from the download lock (a dead process releases it), progress from the part files, stalls from their modification time, and the rate from two size samples `sample` apart (0 skips sampling). Nothing is read from the downloader itself, so it works for any process that used this package to download.

func (*Manager) Leftovers added in v0.7.0

func (m *Manager) Leftovers() ([]Leftover, error)

Leftovers scans the models directory for partial downloads, quarantined files, and lock files. Installed models are never included.

func (*Manager) List

func (m *Manager) List() ([]Model, Config, error)

List returns curated models annotated with installed/default state.

func (*Manager) LoadConfig

func (m *Manager) LoadConfig() (Config, error)

LoadConfig reads ds4go.json.

func (*Manager) RemoveLeftovers added in v0.7.0

func (m *Manager) RemoveLeftovers(items []Leftover) ([]Leftover, error)

RemoveLeftovers deletes the given leftovers, skipping any whose download is in progress, and returns the ones it removed. A lock file is only removed while this process holds it, so a downloader cannot be racing on it.

func (*Manager) ResolvePath added in v0.7.0

func (m *Manager) ResolvePath(value string) string

ResolvePath maps an installed catalog alias to its GGUF file under ModelsDir, so --model accepts the same names as `model download`. Any other value, including an alias that is not installed, is returned unchanged for the caller to report.

func (*Manager) SaveConfig

func (m *Manager) SaveConfig(cfg Config) error

SaveConfig writes ds4go.json.

func (*Manager) Set

func (m *Manager) Set(alias string) error

Set switches the default model and updates models/ds4flash.gguf.

func (*Manager) WithEncoders added in v0.7.0

func (m *Manager) WithEncoders(aliases []string) (expanded, added []string)

WithEncoders appends each requested vision model's encoder alias right after it when the encoder is neither installed nor already in the list, so one download command yields a usable vision setup. Unknown aliases pass through for DownloadMany to report. added lists the appended aliases.

type Model

type Model struct {
	// Family groups quantization variants of the same checkpoint for selectors.
	// Empty for companion files such as vision encoders and speculative drafters.
	Family         string  `json:"family,omitempty"`
	Alias          string  `json:"alias"`
	GGUFPath       string  `json:"ggufPath"`
	FileName       string  `json:"fileName"`
	SizeGB         float64 `json:"sizeGB"`
	RecommendedRAM string  `json:"recommendedRAM"`
	SHA256         string  `json:"sha256,omitempty"`
	// Repo is the Hugging Face repo hosting this model. Empty means the default
	// DeepSeek repo, so existing entries and saved state stay valid.
	Repo string `json:"repo,omitempty"`
	// GLM marks a GLM DSA model. Its tool-calling markup, stop tokens, and
	// reasoning-effort prompt differ from DeepSeek's; libds4 selects the
	// behaviour from the GGUF, and ds4go exposes it via Engine.IsGLMDSA.
	GLM bool `json:"glm,omitempty"`
	// Vision marks a checkpoint that accepts images once its encoder is
	// loaded. Encoder is the catalog alias of that encoder GGUF; ds4go pairs
	// it automatically when installed (ds4.ApplyVisionDefaults).
	Vision  bool   `json:"vision,omitempty"`
	Encoder string `json:"encoder,omitempty"`
	// DSpark is the catalog alias of the DSpark support model this checkpoint
	// requires, when it is not the default one (Vision-Exp has its own).
	DSpark string `json:"dspark,omitempty"`
	// DeepSeek41 marks a DeepSeek V4.1 Flash checkpoint: Metal, or CUDA and
	// ROCm for text, upstream; its own DSpark drafter (a separate V4.1 support
	// GGUF with no published download; the V4 Flash drafter is rejected);
	// thinking as an effort level (--think-level).
	DeepSeek41 bool `json:"deepseek41,omitempty"`
	// Qwen marks a Qwen3.8 Flash Next file (checkpoint or its encoder): a
	// ChatML template with the reasoning effort in the system turn, an XML
	// <tool_call> dialect, built-in MTP enabled with --mtp-timing (no external
	// support model), and an on-disk n-gram table that stays on the SSD.
	Qwen bool `json:"qwen,omitempty"`
	// Parts lists the pieces a GGUF is published as when Hugging Face's single
	// file limit splits it. The downloader fetches each part, joins them into
	// FileName, and verifies the joined file against SHA256.
	Parts []ModelPart `json:"parts,omitempty"`
	// MergeGGUF selects standard GGUF shard merging instead of byte concatenation.
	MergeGGUF bool `json:"mergeGGUF,omitempty"`
	// MergedBytes is the exact output size required for a GGUF shard merge.
	MergedBytes int64 `json:"mergedBytes,omitempty"`
	Imatrix     bool  `json:"imatrix"`
	Legacy      bool  `json:"legacy"`
	Optional    bool  `json:"optional"`
	Distributed bool  `json:"distributed"`
	// DistributedRole and LayerRange describe a distributed split half. LayerRange
	// is in upstream ds4 --layers form (e.g. "0:30", "31:output"); DistributedRole
	// is "coordinator" or "worker". Both empty for non-distributed models.
	DistributedRole string `json:"distributedRole,omitempty"`
	LayerRange      string `json:"layerRange,omitempty"`
	Notes           string `json:"notes,omitempty"`
	// (fields below are populated at runtime, not part of the curated definition)
	Installed    bool  `json:"installed"`
	Partial      bool  `json:"partial"`
	PartialBytes int64 `json:"partialBytes,omitempty"`
	Default      bool  `json:"default"`
}

Model describes a curated ds4 GGUF model.

func Curated

func Curated() []Model

Curated returns a copy of the curated ds4 model catalog.

func Lookup added in v0.2.2

func Lookup(alias string) (Model, bool)

Lookup returns the curated model for alias, or false if unknown.

func ModelForPath added in v0.6.0

func ModelForPath(path string) (Model, bool)

ModelForPath returns the curated model whose GGUF file is selected by path. It follows a final-model symlink such as ds4flash.gguf before matching, while also accepting a direct path to a curated file.

type ModelPart added in v0.7.0

type ModelPart struct {
	FileName string  `json:"fileName"`
	SizeGB   float64 `json:"sizeGB"`
	// Bytes is the part's exact published size; the joiner truncates an
	// interrupted join back to the first part's boundary with it.
	Bytes  int64  `json:"bytes"`
	SHA256 string `json:"sha256"`
}

ModelPart is one published piece or standard GGUF shard (see Model.Parts).

type ProgressTracker added in v0.5.0

type ProgressTracker interface {
	io.ReadCloser
	SwapReader(r io.ReadCloser)
	Done(err error)
}

ProgressTracker wraps an io.ReadCloser to track and display download progress.

Jump to

Keyboard shortcuts

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