modelops

package
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 19 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 modelops is the daemon's on-demand model operations service: catalog browsing, operator-triggered downloads (with cancel), and runtime load/unload/default switching. It is the write-half the local API lacked — before it, models moved only at daemon startup or via the coordinator's ModelAssignment stub.

Index

Constants

View Source
const DefaultFloorSlots = 2

DefaultFloorSlots is the auto slot floor: where a chat model starts. Two slots is the measured sweet spot for a lone stream of requests (1.44x aggregate, ~70 tok/s per request on Metal, flockd#46) at an eighth of the memory of the 16-slot ceiling.

Variables

View Source
var ErrDownloadRunning = errors.New("modelops: download already running")

ErrDownloadRunning is returned when a download for the id is in flight.

View Source
var ErrOverMemory = errors.New("modelops: over memory budget")

ErrOverMemory means a load does not fit the memory budget even after unloading every idle instance admission is allowed to touch. The assign service reports it to the coordinator as `cached` (the artifact stays on disk, loadable when demand returns); the local API returns it to the operator as an error.

View Source
var ErrUnknownModel = errors.New("modelops: model not in catalog")

ErrUnknownModel is returned when an id is in neither the catalog nor the local cache.

Functions

func SetScaleTimings added in v0.8.0

func SetScaleTimings(grow, shrink, cooldown time.Duration)

SetScaleTimings overrides the scaling windows (tests, scratch runs); zero values keep the current setting.

Types

type Layout added in v0.7.4

type Layout struct {
	Slots, CtxPerSlot int
	// Stale: the plan limits changed since this model was loaded; it
	// picks the new ones up when it is next loaded.
	Stale bool
}

Layout is the slot and context layout a loaded model runs with.

type Loader

type Loader interface {
	Load(ctx context.Context, m rt.ModelSpec, res rt.ResourceBudget) (rt.Instance, error)
}

Loader loads a model artifact into a serving runtime instance (*llamacpp.Adapter in production; fakes in tests).

type MemorySnapshot added in v0.4.0

type MemorySnapshot struct {
	// UsedMB is what admission charges against BudgetMB: the sum of
	// per-model footprints, or on a discrete GPU with a VRAM sample the
	// card's measured usage (plus estimates for loads newer than it).
	UsedMB   int64
	BudgetMB int64
	TotalMB  int64
	// HostMB is the runtimes' host-side footprint (measured where the
	// platform supports it, else the estimate) — the heartbeat's
	// ram_used_mb. Equal to UsedMB on unified memory.
	HostMB int64
	// VRAMMB is the last card sample (nvidia-smi, or amdgpu sysfs /
	// rocm-smi; discrete GPUs); VRAMMeasured is false when no sample
	// exists and callers fall back to UsedMB.
	VRAMMB       int64
	VRAMMeasured bool
	// Models is the per-model footprint (measured when available, else the
	// estimate) for every loaded model.
	Models map[string]int64
}

MemorySnapshot is the /api/v1/status memory view and the heartbeat's ram_used_mb / vram_used_mb source.

type PlanLimits added in v0.7.4

type PlanLimits struct {
	// MaxConcurrent is budget.max_concurrent as configured: the slot
	// ceiling, 0 = auto by accelerator class.
	MaxConcurrent int
	// MaxContext, MinContext and ContextLength are runtime.max_context,
	// min_context and context_length.
	MaxContext, MinContext, ContextLength int
	// MinConcurrent is budget.min_concurrent: the slots a chat model
	// starts with and shrinks back to (flockd#54). 0 = auto
	// (DefaultFloorSlots). At or above the ceiling it pins the slot count:
	// no scaling.
	MinConcurrent int
}

PlanLimits are the operator's inputs to the context plan: the slot ceiling and the per-slot context bounds. They are the settings that decide a runtime's launch arguments, so changing one takes a reload of the model to show.

type Service

type Service struct {
	Mgr    *models.Manager
	Eng    *engine.Engine
	Loader Loader
	Budget rt.ResourceBudget
	Log    *slog.Logger

	// Catalog sources, mirroring config (path wins).
	ManifestPath string
	ManifestURL  string

	// OnLoaded is called after a model becomes servable (used to stamp the
	// runtime build id into the capability profile). May be nil.
	OnLoaded func(inst rt.Instance)

	// Events receives models_changed on download-complete, load, unload and
	// default switches. May be nil.
	Events *events.Hub
	// Activity receives loaded/unloaded rows. May be nil.
	Activity *activity.Ring

	// Hardware sizes the auto memory budget and tells unified from
	// discrete memory. Nil disables admission unless a budget is
	// configured explicitly (SetMemoryBudgetMB).
	Hardware *typesv1.CapabilityProfile
	// MaxContext mirrors runtime.max_context: the per-slot context cap
	// (0 = the model's window).
	MaxContext int
	// MinContext mirrors runtime.min_context: the per-slot floor the
	// planner gives up slots to protect (0 = memory.DefaultMinContext).
	MinContext int
	// ContextLength is the operator's runtime.context_length pin on
	// per-slot context (0 = planned from the budget).
	ContextLength int
	// MinConcurrent mirrors budget.min_concurrent: the slot floor chat
	// models start at (0 = auto; see PlanLimits).
	MinConcurrent int
	// OnUnloaded is called after any unload (operator, idle, memory
	// pressure) with the model id; the assign service reports `cached` to
	// the coordinator from it. May be nil.
	OnUnloaded func(id string)
	// VRAM measures used VRAM on discrete GPUs (nvidia-smi). Nil = built
	// from Hardware on first use; tests inject one.
	VRAM *memory.VRAMSampler
	// contains filtered or unexported fields
}

Service wires catalog + cache + runtime together. Nil Service (mock runtime) means the local API reports these operations unsupported.

func (*Service) CancelDownload

func (s *Service) CancelDownload(id string) bool

CancelDownload aborts an in-flight download, whoever started it: an operator download, a mesh placement's fetch or a load of a model that was not on disk. The .partial file is kept so a later attempt resumes. A cancelled mesh fetch is reported to the coordinator as failed by the assign service, which keeps it off this node for its backoff.

func (*Service) Catalog

func (s *Service) Catalog(ctx context.Context, refresh bool) (*models.Catalog, error)

Catalog returns the model catalog, cached for catalogTTL. refresh forces a refetch. A failed refetch keeps the last good copy.

func (*Service) CheckRuntime added in v0.7.0

func (s *Service) CheckRuntime(ctx context.Context, m models.CatalogModel) error

CheckRuntime reports whether the runtime build this node runs can serve a catalog model, without downloading or loading anything. It returns an error wrapping rt.ErrRuntimeTooOld for a decision model on a llama.cpp build that predates decision support (the reason names both builds), and nil when the loader cannot tell (mock, an operator's own binary).

func (*Service) ConfiguredMemoryBudgetMB added in v0.4.0

func (s *Service) ConfiguredMemoryBudgetMB() int64

ConfiguredMemoryBudgetMB returns the raw configured value (0 = auto).

func (*Service) Downloading

func (s *Service) Downloading(id string) bool

Downloading reports whether a download for id is in flight.

func (*Service) Fetch added in v0.5.0

func (s *Service) Fetch(ctx context.Context, id, origin string) error

Fetch makes sure a catalog model is on disk — download and verify inside max_disk_mb, with the given cache origin — without loading it. It backs staged coordinator placements (ModelAssignment.stage). A cache hit returns immediately. models.ErrOverBudget when it cannot fit.

func (*Service) IdleSince added in v0.4.0

func (s *Service) IdleSince(id string) (time.Time, bool)

IdleSince reports when a loaded model last served a request, if it is idle right now (no requests in flight).

func (*Service) IdleUnload added in v0.4.0

func (s *Service) IdleUnload() time.Duration

IdleUnload is the live idle-unload threshold (0 = never).

func (*Service) Layouts added in v0.7.4

func (s *Service) Layouts() map[string]Layout

Layouts reports the layout of every loaded model.

func (*Service) Load

func (s *Service) Load(ctx context.Context, id string) error

Load makes a model servable: cache hit or download, then runtime load and engine registration. Synchronous — llama-server startup takes seconds and callers want the outcome. No-op if already loaded.

func (*Service) LoadInstance

func (s *Service) LoadInstance(ctx context.Context, id string) (rt.Instance, error)

LoadInstance is Load returning the runtime instance (startup needs it).

func (*Service) LoadInstanceOrigin

func (s *Service) LoadInstanceOrigin(ctx context.Context, id, origin string) (rt.Instance, error)

LoadInstanceOrigin is LoadInstance with ownership of a fresh download (models.OriginMesh for coordinator placements: the fetch may then only evict other mesh-placed models to make room).

Memory admission happens after the artifact is on disk and before the runtime starts: the load's estimated footprint must fit the budget, idle instances are unloaded to make room (see admit), and ErrOverMemory is returned — with the file kept — when they cannot.

func (*Service) Loading added in v0.4.0

func (s *Service) Loading(id string) bool

Loading reports whether a load of id is in progress (download, admission or runtime start). The store's retention pass treats it like loaded.

func (*Service) Lookup added in v0.7.2

func (s *Service) Lookup(ctx context.Context, id string) (models.CatalogModel, bool, error)

Lookup finds a catalog entry by id. A miss triggers one refetch before the answer is "not in catalog" — a model promoted since the last fetch is found without waiting for the TTL or a restart — rate-limited to one refetch per catalogMissRefetch so unknown ids cannot hammer the host.

func (*Service) Measure added in v0.4.0

func (s *Service) Measure(ctx context.Context)

Measure samples every loaded runtime's footprint and replaces the estimates. Cheap on macOS/Linux/Windows (one syscall / one procfs read per process, inside Instance.Health). On a discrete GPU it also takes one sample of used VRAM (nvidia-smi, or amdgpu sysfs / rocm-smi; ≤ 1 call per housekeeping tick, 3 s timeout; a failure keeps the previous figure or the estimates).

func (*Service) Memory added in v0.4.0

func (s *Service) Memory() MemorySnapshot

Memory reports the current accounting.

func (*Service) MemoryBudgetMB added in v0.4.0

func (s *Service) MemoryBudgetMB() int64

MemoryBudgetMB is the live budget for loaded models: the configured budget.max_ram_mb, or the auto derivation from hardware when it is 0. 0 means no hardware profile and no configured budget: admission is off.

func (*Service) PlanLimits added in v0.7.4

func (s *Service) PlanLimits() PlanLimits

PlanLimits returns the limits the next load plans with.

func (*Service) ReloadStale added in v0.7.4

func (s *Service) ReloadStale(ctx context.Context) (reloaded, busy []string)

ReloadStale applies changed plan limits to the models that are loaded: each one whose layout was planned under other limits and that has nothing in flight is unloaded and loaded again (a runtime restart: the weights are on disk, so seconds). A busy model is left alone — never interrupt a request for a setting — and picks the limits up at its next load. The default model stays the default. It returns the ids reloaded and the ids skipped because they were busy.

func (*Service) Remove added in v0.4.0

func (s *Service) Remove(ctx context.Context, id string) error

Remove unloads id if it is loaded and deletes it from the store. Unlike Unload followed by Manager.Remove, it never reports the model as `cached` to the coordinator in between: the file is going away.

func (*Service) Resize added in v0.8.0

func (s *Service) Resize(ctx context.Context, id string, target int) (from, to int, err error)

Resize restarts a loaded model with another slot count, without unloading it: a new runtime is started with the layout planned for target slots in the memory that is free right now, swapped in, and the old one shut down once its requests have finished. It returns the slot counts before and after. errNoRoom when a grow does not fit (the plan yields no more slots than the model has).

func (*Service) RunCatalogRefresh added in v0.7.2

func (s *Service) RunCatalogRefresh(ctx context.Context, interval time.Duration)

RunCatalogRefresh refetches the catalog every interval (<= 0: catalogTTL) until ctx ends, so a daemon that nobody asks about models still learns of a promoted catalog. Failures keep the last good copy.

func (*Service) RunHousekeeping added in v0.4.0

func (s *Service) RunHousekeeping(ctx context.Context)

RunHousekeeping measures footprints and applies idle unload every housekeepInterval until ctx ends.

func (*Service) RunSlotScaling added in v0.8.0

func (s *Service) RunSlotScaling(ctx context.Context)

RunSlotScaling follows demand until ctx ends.

func (*Service) ScaleTick added in v0.8.0

func (s *Service) ScaleTick(ctx context.Context, now time.Time)

ScaleTick samples every scalable model's demand once and resizes the ones whose windows say so. Exported for tests, which drive the clock.

func (*Service) SetDefault

func (s *Service) SetDefault(id string) error

SetDefault switches the model served when a request names none.

func (*Service) SetIdleUnload added in v0.4.0

func (s *Service) SetIdleUnload(d time.Duration)

SetIdleUnload changes the threshold live.

func (*Service) SetMemoryBudgetMB added in v0.4.0

func (s *Service) SetMemoryBudgetMB(mb int64)

SetMemoryBudgetMB changes the configured budget live (0 = auto). Nothing is unloaded immediately; the next load and the idle loop apply it.

func (*Service) SetPlanLimits added in v0.7.4

func (s *Service) SetPlanLimits(l PlanLimits)

SetPlanLimits changes the limits for every later load. Models already loaded keep their layout until they are reloaded (ReloadStale).

func (*Service) SlotCeiling added in v0.7.4

func (s *Service) SlotCeiling() int

SlotCeiling is the resolved slot ceiling of the current plan limits.

func (*Service) SlotFloor added in v0.8.0

func (s *Service) SlotFloor() int

SlotFloor is the resolved slot floor of the current plan limits.

func (*Service) StartDownload

func (s *Service) StartDownload(ctx context.Context, id string) (bool, error)

StartDownload begins fetching a catalog model in the background. It returns (false, nil) if the model is already cached and ready, and ErrDownloadRunning if a download is already in flight.

func (*Service) Starting added in v0.7.3

func (s *Service) Starting() map[string]time.Time

Starting lists the models whose runtime is starting right now (weights being read into memory), with when each start began.

func (*Service) Unload

func (s *Service) Unload(ctx context.Context, id string) error

Unload removes a model from serving (the artifact stays cached). It is the operator's explicit request, so requests in flight on the model fail rather than keep it loaded.

func (*Service) UnloadIdle added in v0.4.0

func (s *Service) UnloadIdle(ctx context.Context) []string

UnloadIdle unloads every non-default model idle for longer than the threshold. Returns the ids unloaded.

Jump to

Keyboard shortcuts

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