Documentation
¶
Overview ¶
Package gpualloc is where a request for cards becomes a decision: the live state the card allocator reads (the card table, the leases, the quarantine sidecars, resident seats, the display card's cap, host RAM), the choice itself (PickAuto), and the rule that says which seats a lease on some cards may unload (LeaseScope, UnloadModels).
It exists so the two callers that need a card decision read ONE rule: `gpu reserve --cards` (package main) and the media admission path (internal/pipeline), which takes a card per generation call. The allocator itself is internal/gpulease's pure function; this package assembles its input and interprets its answer. Nothing here acquires a lease: the callers differ in how they claim (the reserve verb queues in the foreground, the pipeline holds a place with a token), so claiming stays with them.
Index ¶
- Constants
- func BuildInput(ctx context.Context, m *gpulease.Manager, cfg config.Config, need Need, ...) (gpulease.AllocInput, error)
- func Claims(m *gpulease.Manager, need Need) (wholeNodeHeld bool, claimed map[string]bool)
- func DisplayBusy(cfg config.Config, cards []gpuprobe.Card) string
- func EffectiveMemoryStack(cfg config.Config) []string
- func Explain(vs []Verdict) []string
- func GrantCheck(build func() (gpulease.AllocInput, error), ids []string) func() error
- func PickAuto(plan Plan, wait time.Duration, build func() (gpulease.AllocInput, error), ...) (ids []string, free bool, err error)
- func QueuedClaims(m *gpulease.Manager, cards []gpuprobe.Card, ownToken string, ...) map[string]bool
- func QueuedClaimsBefore(m *gpulease.Manager, cards []gpuprobe.Card, ownToken string, ...) map[string]bool
- func ReadCards(ctx context.Context, cfg config.Config) ([]gpuprobe.Card, string, error)
- func ResidentFrom(cfg config.Config, cards []gpuprobe.Card, loaded map[string]bool) map[string]gpulease.ResidentInfo
- func ResidentSeats(ctx context.Context, cfg config.Config, cards []gpuprobe.Card, ...) map[string]gpulease.ResidentInfo
- func SkipSummary(e *gpulease.NoCardsError) string
- func UnloadEnv(models []string, known bool) string
- func UnloadModels(ctx context.Context, cfg config.Config, roster []string, rosterErr error, ...) ([]string, bool)
- func Unloading(vs []Verdict) []string
- type CardTableError
- type Deps
- type LeaseScope
- type Located
- type Need
- type Plan
- type Verdict
Constants ¶
const ( DefaultCardRead = 5 * time.Second DefaultCardReadRetry = 15 * time.Second )
The deadlines of a card-table read. The read is one nvidia-smi exec: a tenth of a second on a quiet box, and on a loaded one (three cards at 100 %, a model loading, a CPU with no slot for the exec) a read that answered in a second has then run out five. A read that runs out its first deadline is made once more under the longer one, so one slow read does not change a placement (F24, 2026-10-09: the allocation's re-read of the table ran out and hard-deferred a media call that its own admission read had just served).
const DisplayIdleUtilPct = 15
DisplayIdleUtilPct is the display card's utilization at or above which the card is busy, not idle: a game, a video or another application is drawing on it. A chosen figure, not a measurement: on the `blackwell-3x16` reference box the desktop alone read 0-4 % and a game 37-41 % (2026-11-07), and a 3-card job sharing the card with either is what the operator's rule keeps off it.
Variables ¶
This section is empty.
Functions ¶
func BuildInput ¶
func BuildInput(ctx context.Context, m *gpulease.Manager, cfg config.Config, need Need, deps Deps) (gpulease.AllocInput, error)
BuildInput assembles the allocator's input from live state: the card table, the live leases, quarantine sidecars, foreign compute processes, resident seats, the display card's cap and host RAM. Every read is best-effort except the card table, which is the point (a *CardTableError, after the one retry of Deps.CardTable); an unreadable extra reads as "nothing to report" (and, for foreign processes, is empty on Windows by nvidia-smi's own limit).
func Claims ¶
Claims reads what is taken, without the card table: whether a whole-node lease is live (it claims every card) and the lease ids of the cards a live lease claims, plus the ones the caller claims for work the lease directory cannot show (Need.Claimed). A caller that NAMED its cards (a pin, a pool, a declared device) has nothing to choose, so this is all it asks of the allocator's input: it never needs nvidia-smi for it.
func DisplayBusy ¶ added in v0.209.0
DisplayBusy is the production idle reader of the operator's 2026-11-07 rule ("only up to 60% of the 5070ti card WHEN IDLE so i can always keep it interactive"): "" when every display card in cards is idle, else why not. Idle is BOTH readings at once, because "idle" can name the desk or the card and either one at the desk is a reason to keep off it: (1) the card is not busy, its utilization known and under DisplayIdleUtilPct; (2) the operator is away by the presence probe in cfg.AllocatorPresenceMode() (unset = auto: the console locked, or no input for operator_idle_sec with nothing fullscreen; "away" is the operator's override and "present" his word that he is at the desk). Every failure to read is busy: an unknown utilization, and a presence the probe could not establish (Known=false: off Windows, and from session 0 unless the console is locked, placement/presence_windows.go).
func EffectiveMemoryStack ¶
EffectiveMemoryStack is the memory stack a lease never unloads: the config's, else the default.
func Explain ¶
Explain turns verdicts into lines that name what was unloaded and what was left, with the reason, one line per distinct reason in the order they first appear.
func GrantCheck ¶
func GrantCheck(build func() (gpulease.AllocInput, error), ids []string) func() error
GrantCheck is the check a queued request makes when its turn comes (gpulease.Options.GrantCheck). The set it was queued on was chosen against the display card's cap and the VRAM in use as they were at the enqueue, and a place in line can be hours long: the allocator's input is built again (build, the same reader that chose the set), so the cap and the display card's free VRAM are read as they are at the grant, and the desktop rule (gpulease.DesktopRefusals) is put to ids. A card table that cannot be read refuses too: a grant that cannot be shown to keep the desktop its share is not made.
The check runs with the cards already granted to the request (gpulease.VetGrant), so the lease directory lists them as claimed; those claims are the request's own and are not read as a rival's.
func PickAuto ¶
func PickAuto(plan Plan, wait time.Duration, build func() (gpulease.AllocInput, error), out io.Writer, sleep func(time.Duration), now func() time.Time) (ids []string, free bool, err error)
PickAuto turns a Plan into a concrete set, from live state. free reports which kind of set it is: true = cards that qualify and are free right now (the caller claims them and, if another claimant got there first, picks again); false = no qualifying set is free, and ids is the fixed set to queue FIFO on (the free cards first, topped up from the cards a live lease claims). When too few cards qualify for a reason waiting for a lease does not fix (a display card, quarantine, host RAM, VRAM) it polls until they do or wait runs out.
Progress lines go to out (io.Discard is fine); the caller's clock and sleep are injected.
The poll loop is bounded twice: by the deadline on the caller's clock and by the number of polls the wait allows at the poll interval, whichever comes first. The second bound exists because both the clock and the sleep are injected, and a loop that ends only when `now()` passes the deadline is a busy-spin whenever the sleep it is handed does not advance the clock it is given (a no-op sleep with the real clock, a frozen clock): 2026-10-10, a test of exactly that shape held 52 GiB private within a minute, one AllocInput and one log line per pass, for the hour it had asked to wait. In production the two bounds are the same bound.
func QueuedClaims ¶
func QueuedClaims(m *gpulease.Manager, cards []gpuprobe.Card, ownToken string, declaresHostRAM bool) map[string]bool
QueuedClaims lists the cards callers are queued for ahead of a new arrival: live waiters and the live tokens (a place held for a caller who may come back). They are not free for a newcomer, who queues behind them (FIFO). A queued whole-node request is a barrier for every card. ownToken is the caller's own place, never counted against it.
WHY THE ALLOCATOR READS IT (register D-1xx-3, 2026-10-09). The lease directory shows only what is HELD, so a card that a registered waiter is queued for, and that nobody holds at this instant, reads as free to the allocator. A request that picks such a card and claims it through the gated Acquire is told the waiter is ahead (ErrStillQueued) and has to pick again; a request that never asked the line would have won the card ahead of the waiter, which is the starvation this closes. Both doors that allocate (the reserve verb and the media admission) add this set to the cards the allocator may not treat as free, so they choose a card nobody is queued for when one exists and queue FIFO on the busy set when none does, instead of finding out at the claim.
Merge the result into AllocInput.Claimed (Need.Claimed before BuildInput, or the map BuildInput returned): a card in it is "not free right now", and the allocator still lists it among the cards a queued request can be given.
declaresHostRAM is whether the asker declares any host RAM: a waiter that waits ONLY on host RAM does not hold its cards against one that declares none (gpulease.Waiter.HoldsItsCardsAgainst, G6 of the P0 plan), so those cards are free to it, as the gated claim will find them; without this the allocator would steer a request that passes such a waiter away from an idle card, and a call that cannot wait would be told the card is "promised to callers ahead" by a waiter it can pass.
func QueuedClaimsBefore ¶
func QueuedClaimsBefore(m *gpulease.Manager, cards []gpuprobe.Card, ownToken string, declaresHostRAM bool, since time.Time) map[string]bool
QueuedClaimsBefore is QueuedClaims for a caller that RESUMES a place in line that arrived at since: only the waiters and places that arrived strictly before it are ahead of it, because the lease queue itself serves a resumed place by arrival time (a caller behind it does not hold the card against it, and a tie is not counted: the answer errs toward free). A zero since is a new arrival, for whom everyone in line is ahead (QueuedClaims). It exists for the ticket queue: with two places on one idle card each read the other as in its way, and neither would ever be started (P0 plan S2).
func ReadCards ¶
ReadCards is the production card-table reader, and the one every caller that does not inject its own uses (the allocator's default, and the root package's cardTableFn). It is gpuprobe's one per-device query (--query-gpu fields) and nothing else: the allocation never lists processes, the slowest thing nvidia-smi does under load (the foreign-process reader is a separate, best-effort call that only the verbs which want it make). It adds NO deadline of its own and takes the one in ctx, because CardTable puts a deadline on every attempt and a reader that capped itself would cap the retry's longer deadline too: the 5 s the base kept inside the default reader made the 15 s retry a 5 s one. Only a run against a real process can tell, so TestTheProductionReaderIsNotCappedBelowTheRetryDeadline does that, with a stand-in nvidia-smi (internal/gpuprobe/smitest), and TestTheAllocationNeverListsProcesses pins what the allocation execs.
func ResidentFrom ¶
func ResidentFrom(cfg config.Config, cards []gpuprobe.Card, loaded map[string]bool) map[string]gpulease.ResidentInfo
ResidentFrom is the mapping alone: which configured layer seats, among the loaded models (lower-cased ids), sit on which card. Pure, so it is tested without llama-swap.
A seat is its model AND, for a router seat, every model_map twin: the display layer's rungs (gemma-4-e4b-display, gemma-4-e2b-display) are named only there, and a loaded twin sits on the display card as surely as the pair's seat sits on its own. Counting only s.Model left that card reading as empty, so it sorted first as the card with nothing to evict while it held a twin. The same walk over the twins is config.LayerPins's, which answers the other direction (model → pins) and is what the lease's unload list already uses.
The cost of taking the card is what the loaded models hold on it: per loaded model, footprint_gib, else for the display layer's router (which declares only display_footprint_gib) that. The footprint is declared per seat and is what ONE of its models puts on the card (the two display twins are about 6.2 GiB each), so a router with both twins loaded costs both: taking the card evicts both, and the order prices the eviction it would really make.
func ResidentSeats ¶
func ResidentSeats(ctx context.Context, cfg config.Config, cards []gpuprobe.Card, client *http.Client) map[string]gpulease.ResidentInfo
ResidentSeats maps each card to the configured layer seats that are loaded in llama-swap right now and pinned to it. Pins are read as nvidia-smi indices or UUID prefixes (the placement package's own convention). Best-effort: a pin that does not resolve contributes nothing. client, when given, reads /running through it (the reserve verb's shared maintenance client); nil reads it through the llama-swap client, with a short timeout.
An unreadable /running is not "nothing is loaded". The one card whose occupancy changes the ORDER is the display card, which a loaded twin makes a card with something to evict: read as empty it sorts first, and the allocator hands the desktop's card to a job while a twin may be sitting on it (the floor, which the allocator also applies, only holds back what does not fit). So when /running cannot be read the display layer's models are counted as loaded, each costed as a loaded twin is, and the display card sorts as occupied. Other layers' seats still contribute nothing then: nothing about them is conservative to assume, and the cost of treating a card as busy falls on the display card alone, which the allocator opens only within its cap.
func SkipSummary ¶
func SkipSummary(e *gpulease.NoCardsError) string
SkipSummary is the one line that says why cards were skipped. The operator's screen card says so beside a reason that does not (a media call refused over the display card's cap reads "card 1 vram (display card)", not a bare "card 1 vram"); the full sentence, with the cap, is the skip's Detail.
func UnloadEnv ¶
UnloadEnv renders the list as the environment variable the render lane reads (GPU_LEASE_UNLOAD_MODELS): a comma list, `-` for "unload nothing", and no variable at all when the list is unknown, which leaves the lane on its own rule.
func UnloadModels ¶
func UnloadModels(ctx context.Context, cfg config.Config, roster []string, rosterErr error, leaseIDs []string, deps Deps, warn io.Writer) ([]string, bool)
UnloadModels is the model-id list the render lane's freeLlamaSwap unloads under a lease that holds leaseIDs: every model of the roster except the memory stack and the models POSITIVELY placed on another card (register F15). A model placed on a leased card goes, and so does a model whose placement is unknown (not declared by layers, no usable pin in the serving config, a pin the card table cannot place, a card table that cannot be read): the render needs its card, and that is the direction every doubt took before F15. warn, when not nil, names what was unloaded and what was left, each with its reason.
The candidates are the llama-swap roster. When the roster was read and is empty nothing is resident, and the candidates are the models the config declares (Config.LayerSeatModels) and the serving config lists, said so.
rosterErr is the error of the roster read, nil when it was read. A roster that could NOT be read is not an empty roster: nothing says what is resident, so no candidate list built from the config can be complete (a resident model neither the layers nor the serving config name would never be judged), and on a box that declares neither the list would be empty and nothing would be unloaded. ok is then false, whatever the config declares, and the render lane keeps its own rule: every model off the memory stack, as before F15. F15's per-card judgement applies to a roster that was read.
ok is false for a whole-node lease (no ids): it holds every card, so nothing narrows and the render lane keeps its own rule. A lease that names every card the box has is the whole node too. ok is false for a card lease too when the roster could not be read (above). Otherwise a card lease always has a list, empty when nothing would be unloaded (exported as the none sentinel by UnloadEnv).
Types ¶
type CardTableError ¶
type CardTableError struct{ Err error }
CardTableError is BuildInput's failure when the card table could not be read, so a caller that can place without a fresh table (the media path keeps the one it read at admission) tells that failure from any other. The words are what they always were: "the card table: <cause>".
func (*CardTableError) Error ¶
func (e *CardTableError) Error() string
func (*CardTableError) Unwrap ¶
func (e *CardTableError) Unwrap() error
type Deps ¶
type Deps struct {
// Cards reads the card table and a warning about the declared ComfyUI order. It is ONE attempt
// and takes its deadline from ctx: CardTable sets it, and again, longer, for the one retry, so a
// reader that adds a deadline of its own would cap that retry as well.
Cards func(ctx context.Context, cfg config.Config) ([]gpuprobe.Card, string, error)
// ReadDeadline bounds the first attempt of a card-table read and RetryDeadline the one retry
// that follows an attempt which ran out of time (zero = DefaultCardRead, DefaultCardReadRetry).
ReadDeadline, RetryDeadline time.Duration
// ForeignBusy maps a card (lease id) to a description of the foreign compute process on it.
// The default sees none: foreign-busy is Linux-only evidence (WDDM lists no per-process rows),
// and the reserve verb's reader lives with its denylist in package main, which passes it in.
ForeignBusy func(ctx context.Context, cfg config.Config) map[string]string
// Resident maps a card to the configured seats loaded on it.
Resident func(ctx context.Context, cfg config.Config, cards []gpuprobe.Card) map[string]gpulease.ResidentInfo
// HostMemory reads the host's memory (physical, available, commit): the reading the host-RAM
// rule is applied to, here and at the lease grant.
HostMemory func() (gpuprobe.HostMemory, bool)
// DisplayBusy says why the display card is not idle now, "" when it is (the operator away and the
// card not busy): DisplayBusy, the production reader, by default. Asked only when the table names a
// display card and the cap is open.
DisplayBusy func(cfg config.Config, cards []gpuprobe.Card) string
}
Deps are the live reads behind the allocator's input, so a test assembles a host. A nil member uses the production reader.
func (Deps) CardTable ¶
CardTable reads the card table the way the allocator does: one attempt under ReadDeadline and, when that attempt ran out of time, ONE more under the longer RetryDeadline. Only a timeout is retried: an attempt that failed outright (nvidia-smi not on PATH, a table with no card) fails the same way again, and a caller whose own context is done has nobody left to read for. The error of a read that failed twice says so, so the answer a caller builds from it can.
type LeaseScope ¶
type LeaseScope struct {
// contains filtered or unexported fields
}
LeaseScope says which seats sit on the cards a lease holds (plan P5, register C-86): a drain and an unload under a lease clear THOSE cards, not the node. A whole-node lease (no ids) reaches every seat. A model is placed by what the box declares: its `layers` seat pin, else the device pin of its entry in the serving config (internal/servingcfg, the same reader the load fence places a model with, Config.ModelPins). A model that neither places, a pin the card table cannot place, or a card table that cannot be read leaves the placement UNKNOWN, and the direction of every doubt is the whole-node behaviour: an unknown model is on the leased cards. What a positive placement buys (register F15) is that a model placed on ANOTHER card stays where it is.
func NewLeaseScope ¶
func NewLeaseScope(ctx context.Context, cfg config.Config, ids []string, deps Deps, warn io.Writer) LeaseScope
NewLeaseScope reads the card table once (deps.CardTable, which retries a read that ran out of time) for a lease holding ids (lease ids). A table it cannot read is said once on warn (nil = silent), and every model is then treated as sitting on the leased cards.
func (LeaseScope) Bounded ¶
func (s LeaseScope) Bounded() bool
Bounded reports whether the lease holds a set of cards (false = the whole node).
func (LeaseScope) Judge ¶
func (s LeaseScope) Judge(models []string) []Verdict
Judge decides, for each model, whether a lease on these cards unloads it. A model placed on a leased card goes; a model placed on another card stays (register F15); a model that is not placed goes too, because an unknown placement is read as "on the leased cards" and the render needs its card. The memory stack is the caller's to exclude.
func (LeaseScope) Locate ¶
func (s LeaseScope) Locate(model string) Located
Locate places the model serving name: by layers when they declare it, else by its serving config pin. Unknown is not an error; it is what the callers read as "on the leased cards".
func (LeaseScope) Touches ¶
func (s LeaseScope) Touches(model string) bool
Touches reports whether the model serving name sits on the leased cards. A model placed on another card does not; one that is not placed does (the drain waits, the fence holds, the unload takes it).
func (LeaseScope) TouchesPins ¶
func (s LeaseScope) TouchesPins(pins []string) bool
TouchesPins reports whether a seat pinned to pins sits on the leased cards.
func (LeaseScope) TouchesRun ¶
func (s LeaseScope) TouchesRun(r gpuactivity.Run) bool
TouchesRun reports whether a registered run is on the leased cards: by the pins it recorded, else by the seat it runs on.
type Located ¶
Located says where one model sits. Known is false when nothing places it, and then Why says what is missing; On says whether it sits on a leased card, and By what placed it.
type Need ¶
type Need struct {
// VRAMGiB is the VRAM the job needs free on EACH card (0 = not declared).
VRAMGiB float64
// RAMGiB is the host RAM the job declares: the working set it will touch (0 = not declared).
RAMGiB float64
// RAMCommitGiB is the commit the job declares (0 = the same figure as RAMGiB).
RAMCommitGiB float64
// Claimed names cards the caller already holds on behalf of work the lease directory cannot
// show (the media path's in-process per-card slots): they are not allocatable.
Claimed map[string]bool
}
Need is what the job asks of each card and of the host.
type Plan ¶
type Plan struct {
Min, Max int
// Hint is appended to the error when too few cards qualify and the wait ran out (the reserve
// verb says which flag keeps waiting; a media call says nothing, there is no flag to pass).
Hint string
}
Plan is a request for cards the caller does not name: Min..Max of them, picked by the allocator.