Documentation
¶
Overview ¶
Package capacity is modeld's hardware capacity planner: it resolves the EFFECTIVE context window a model can actually be served at on this device, from the model's KV-cache footprint and the device's free memory — not the model's trained ceiling alone. modeld owns this calculation because it owns the backend process and hardware telemetry; the runtime consumes the resolved value and does not inspect model files.
Index ¶
- Constants
- func HeadroomFromEnv() float64
- func KVBytesPerToken(nLayers, nKVHeads, headDim int, kvType string) int64
- func KVTypeScale(kvType string) (num, den int64)
- func ParseBytes(s string) (int64, error)
- func ResolveComputeReserve(raw string, automatic int64, device DeviceSnapshot) (int64, error)
- type DeviceSnapshot
- type HardContextLimit
- type LayerKVProfile
- func (p LayerKVProfile) ContextForBudget(budget int64, maxContext int) int
- func (p LayerKVProfile) ContextForBudgetType(budget int64, maxContext int, kvType string) int
- func (p LayerKVProfile) DenseKVBytesPerToken() int64
- func (p LayerKVProfile) KVBytesForContext(ctx int) int64
- func (p LayerKVProfile) KVBytesForContextType(ctx int, kvType string) int64
- func (p LayerKVProfile) MarginalKVBytesPerToken() int64
- func (p LayerKVProfile) Valid() bool
- type MemorySetting
- type MemorySource
- type ModelCapacity
- type Params
- type Policy
- type SystemRAM
Constants ¶
const ( DefaultAcceleratorMinFreeBytes int64 = 384 << 20 DefaultAcceleratorMinFreeFrac = 0.05 )
Accelerator devices are shared with every other process holding a context on them (compositors, browsers, editors via PRIME render offload — even when the display is wired to another GPU). The reserve floor is what keeps those clients working: it covers their growth while modeld holds the device, which is why it never goes to zero, while the cap below (a quarter of the device) keeps a small card usable. When the user set no explicit MinFreeBytes, accelerators default to max(DefaultAcceleratorMinFreeBytes, DefaultAcceleratorMinFreeFrac × total).
const DefaultHeadroomFrac = 0.05
DefaultHeadroomFrac of free memory is reserved for activations, the compute graph, and fragmentation, leaving the rest for model weights + KV cache. The compute graph has its own explicit reserve (llamaGPUComputeReserveBytes), so this one covers activation churn and fragmentation only: a larger value stops a weights-heavy model from ever fitting a card it would run on.
const DefaultHostColdFrac = 0.25
DefaultHostColdFrac is the launch-time cap for the host-RAM KV cold store when the user did not set one explicitly.
const DefaultMaxResidentFrac = 0.95
DefaultMaxResidentFrac caps modeld's resident footprint at this fraction of the device's CURRENTLY free memory when the user did not set an explicit ceiling. It is evaluated fresh on every resolution, so the budget tracks the device live instead of freezing a launch-time view. Held only a little below the free total: the reserve below is what protects co-tenants, and a deeper cap only hides VRAM the operator already paid for.
const NativeHostOverheadBytes int64 = 64 << 20
NativeHostOverheadBytes reserves host staging and process buffers beyond model and KV storage.
Variables ¶
This section is empty.
Functions ¶
func HeadroomFromEnv ¶
func HeadroomFromEnv() float64
HeadroomFromEnv reads CONTENOX_MODELD_MEM_HEADROOM (a fraction in (0,1)), falling back to DefaultHeadroomFrac.
func KVBytesPerToken ¶
func KVTypeScale ¶
KVBytesPerToken is the memory one token of context costs in the KV cache: K and V, across every layer and KV head, at the KV precision. KVTypeScale is the fraction of an f16 cache a KV quantization costs, as the planner and the modeld session must agree on it: planning with one type while the worker allocates another is how a machine that fits gets reported as one that does not, or the reverse. llama.cpp exposes f16/q8_0/q4_0-class caches; anything unrecognized is treated as f16, the default the worker uses.
func ParseBytes ¶
ParseBytes parses byte strings used by modeld memory settings.
func ResolveComputeReserve ¶
func ResolveComputeReserve(raw string, automatic int64, device DeviceSnapshot) (int64, error)
ResolveComputeReserve resolves an explicit compute target against available device memory.
Types ¶
type DeviceSnapshot ¶
type DeviceSnapshot struct {
Kind string `json:"kind,omitempty"`
DeviceID string `json:"device_id,omitempty"`
TotalBytes int64 `json:"total_bytes,omitempty"`
FreeBytes int64 `json:"free_bytes,omitempty"`
}
DeviceSnapshot describes the memory pool the backend will allocate from.
func Snapshot ¶
func Snapshot(src MemorySource) (DeviceSnapshot, error)
Snapshot returns a DeviceSnapshot for either a richer source with Snapshot or a legacy FreeBytes-only source.
func (DeviceSnapshot) IsAccelerator ¶
func (d DeviceSnapshot) IsAccelerator() bool
IsAccelerator reports whether the snapshot describes a discrete/integrated accelerator (as opposed to system RAM), i.e. a device other processes share via driver contexts and that deserves a free-memory reserve floor.
type HardContextLimit ¶
type HardContextLimit int
HardContextLimit is a genuinely-current explicit context ceiling: a value a user or operator set right now (CONTENOX_LLAMA_CTX, a model profile's runtime.num_ctx, or the equivalent OpenVINO knob). Resolve always honors a positive value as a hard ceiling, even when more memory is available.
NEVER populate this from an EffectiveContext, HotContextTokens, or PlannerEffectiveContext that Resolve (or a prior Describe/OpenSession round-trip) itself returned earlier: feeding a stale advisory value back in as a request freezes every future resolution at it, even after the memory that constrained it has been freed. Leave it 0 to let Resolve compute purely from live FreeBytes/ModelMaxCtx/policy. The distinct type exists so a caller cannot pass a bare int without a visible, greppable conversion.
type LayerKVProfile ¶
LayerKVProfile describes how KV grows with context for one model. GlobalLayers grow linearly with context; WindowedLayers are capped at Window tokens. PerLayerKVBytes is the K+V cost for one token in one layer.
func (LayerKVProfile) ContextForBudget ¶
func (p LayerKVProfile) ContextForBudget(budget int64, maxContext int) int
ContextForBudget returns the context tokens fitting the supplied KV-only byte budget, capped at maxContext when positive. The caller accounts for weights and runtime reserves.
func (LayerKVProfile) ContextForBudgetType ¶
func (p LayerKVProfile) ContextForBudgetType(budget int64, maxContext int, kvType string) int
ContextForBudgetType is ContextForBudget at a KV quantization: the same memory buys proportionally more tokens from a smaller cache.
func (LayerKVProfile) DenseKVBytesPerToken ¶
func (p LayerKVProfile) DenseKVBytesPerToken() int64
DenseKVBytesPerToken is the legacy all-layers cost of one token.
func (LayerKVProfile) KVBytesForContext ¶
func (p LayerKVProfile) KVBytesForContext(ctx int) int64
KVBytesForContext returns the total KV bytes needed to hold ctx tokens.
func (LayerKVProfile) KVBytesForContextType ¶
func (p LayerKVProfile) KVBytesForContextType(ctx int, kvType string) int64
KVBytesForContextType is KVBytesForContext at a KV quantization, which is what a session configured with that type will actually allocate.
func (LayerKVProfile) MarginalKVBytesPerToken ¶
func (p LayerKVProfile) MarginalKVBytesPerToken() int64
MarginalKVBytesPerToken is the post-window growth cost of one more token.
func (LayerKVProfile) Valid ¶
func (p LayerKVProfile) Valid() bool
Valid reports whether the profile contains enough data to budget KV cache.
type MemorySetting ¶
MemorySetting is an allocation expressed as bytes, a fraction, or automatic policy. A non-nil Fraction distinguishes an explicit zero from automatic.
func ParseMemorySetting ¶
func ParseMemorySetting(raw string) (MemorySetting, error)
ParseMemorySetting parses byte sizes, percentages in [0,100], or "auto".
type MemorySource ¶
MemorySource reports the free memory of the device a backend serves on. modeld picks the source by device: system RAM for CPU; GPU VRAM (ov::Core / ggml) is a CGO seam filled per backend when a GPU device is selected.
type ModelCapacity ¶
type ModelCapacity struct {
ModelMaxContext int
EffectiveContext int
MemoryContextTokens int
HotContextTokens int
PlannerEffectiveContext int
KVBytesPerToken int64
FreeBytes int64
WeightsBytes int64
OverheadBytes int64
ReservedBytes int64
UserLimitBytes int64
MinFreeBytes int64
HostColdBudgetBytes int64
UsableBytes int64
RequiredBytes int64
Clamped bool
Reason string
}
ModelCapacity is the resolved result reported to the runtime. EffectiveContext remains the dense context window modeld will actually serve today and the value the cache identity must use. MemoryContextTokens is the raw KV-token budget from memory before model/request clamping. HotContextTokens is the physical hot KV budget. PlannerEffectiveContext is the logical planner window: it equals the dense window when no host cold budget exists, and can grow by the cold KV token budget once host offload is configured.
func Resolve ¶
func Resolve(p Params) ModelCapacity
Resolve computes the dense compatibility window, physical hot context budget, and logical planner window:
usable = min(free - minFree, userLimit - reserved) * (1 - headroom) effective = clamp(request, 0, min(modelMax, (usable - weights - overhead) / kvBytesPerToken))
PreferredLimit permits a resident target to expand within physical capacity when it cannot fit a usable window or the explicit request. Unknown inputs degrade gracefully: with no KV cost it falls back to the model ceiling (clamped by request); with no ceiling it uses the memory budget.
type Params ¶
type Params struct {
ModelMaxCtx int // model's trained context ceiling (0 = unknown)
KVBytesPerToken int64 // 0 = unknown (cannot budget by memory)
LayerKV LayerKVProfile
WeightsBytes int64 // resident model weight footprint
OverheadBytes int64 // fixed runtime buffers (compute graph, staging)
FreeBytes int64 // device free memory
ReservedBytes int64 // memory already reserved by resident sessions
UserLimitBytes int64 // user cap for modeld resident memory (0 = no cap)
MinFreeBytes int64 // memory to leave free for the desktop/other workloads
HostColdBudgetBytes int64 // host-RAM budget for cold KV blocks (0 = none)
Request HardContextLimit // explicit requested window (0 = use the resolved max); see HardContextLimit
HeadroomFrac float64
HeadroomExplicit bool
PreferredLimit bool
}
Params are the inputs to a capacity resolution. Zero values mean "unknown": an unknown ModelMaxCtx or KVBytesPerToken disables that side of the clamp rather than producing a bogus window.
type Policy ¶
type Policy struct {
ComputeReserve string `json:"compute_reserve,omitempty"`
MaxResidentBytes int64 `json:"max_resident_bytes,omitempty"`
MinFreeBytes int64 `json:"min_free_bytes,omitempty"`
HostColdBudgetBytes int64 `json:"host_cold_budget_bytes,omitempty"`
MaxResidentFrac *float64 `json:"max_resident_frac,omitempty"`
MinFreeFrac *float64 `json:"min_free_frac,omitempty"`
HostColdBudgetFrac *float64 `json:"host_cold_budget_frac,omitempty"`
MinHotContextTokens int `json:"min_hot_context_tokens,omitempty"` // 0 = backend default, <0 = explicitly disabled
HeadroomFrac float64 `json:"headroom_frac,omitempty"`
HeadroomExplicit bool `json:"headroom_explicit,omitempty"`
MaxResidentPreferred bool `json:"max_resident_preferred,omitempty"`
}
Policy is the user/operator memory policy modeld applies before opening a resident session. MaxResidentBytes is a hard ceiling on modeld's resident footprint unless MaxResidentPreferred marks an allocation target; MinFreeBytes preserves memory for the desktop or other local workloads that may share the same device. Non-nil fractions take precedence over byte fields and are resolved against live snapshots. MaxResidentFrac and HostColdBudgetFrac use free memory; MinFreeFrac uses total device memory. A zero reserve or cold fraction explicitly disables that budget.
func DefaultPolicy ¶
func DefaultPolicy() Policy
DefaultPolicy returns the automatic resident and host cold fractions and headroom. Its nil reserve fraction selects the accelerator reserve floor.
func LoadPolicy ¶
LoadPolicy reads <dataRoot>/modeld.json and then applies env overrides. The JSON accepts numeric byte or fraction fields and string settings containing byte sizes, percentages, or "auto":
{"memory":{"max_resident":"8GiB","reserve_free":"2GiB","headroom_frac":0.15}}
Returned warnings are operator-facing text; the caller prints them.
func ResolvePolicy ¶
func ResolvePolicy(p Policy, device, host DeviceSnapshot) (Policy, error)
ResolvePolicy resolves allocation fractions from device and host snapshots. Missing memory measurements required by positive fractions return an error. A measured zero free pool is valid when the snapshot supplies a total.
func WithHostColdDefaults ¶
func WithHostColdDefaults(p Policy, host DeviceSnapshot) Policy
WithHostColdDefaults fills the host-RAM cold-store budget from a host memory snapshot, resolving a configured fraction even if its byte field was already populated by an earlier resolution. It is separate from WithResidentDefault because the hot model budget may come from VRAM while the cold store always lives in host RAM.
func WithResidentDefault ¶
func WithResidentDefault(p Policy, dev DeviceSnapshot) Policy
WithResidentDefault fills a missing resident-memory cap from the device's CURRENT free memory. Services call it with a fresh snapshot on every resolution, so the default tracks the device live — it rises when memory frees up and falls when other workloads claim it. MaxResidentBytes is left untouched when no fraction is configured. On accelerator devices it also fills a missing MinFreeBytes reserve floor (see DefaultAcceleratorMinFreeBytes) so other GPU clients keep working memory; an explicit MinFreeBytes is preserved when no fraction is configured. Configured fractions are resolved from current free memory for the resident cap and total device memory for the reserve. The automatic accelerator reserve is capped at a quarter of a known device so the floor does not make small devices unusable.
func (Policy) WithHeadroom ¶
WithHeadroom applies automatic or percentage allocation headroom.
func (Policy) WithMemorySettings ¶
WithMemorySettings applies resident, reserve, and host cold overrides. Empty settings preserve the corresponding policy; "auto" restores its defaults. Zero percentages disable reserve or host cold storage; resident must be positive. Byte sizes preserve the legacy zero-means-automatic behavior.