Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion coordinator/api/billing_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ func TestIntegration_ReservationRefundedOnCompletion(t *testing.T) {
defer conn.Close(websocket.StatusNormalClosure, "")

// Short generation — completion_tokens (10) is far below the reservation
// based on default max_tokens=8192.
// based on the implicit default max_tokens bound.
usage := protocol.UsageInfo{PromptTokens: 5, CompletionTokens: 10}
providerDone := serveOneInference(ctx, t, conn, pubKey, usage)

Expand Down
41 changes: 22 additions & 19 deletions coordinator/api/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -999,15 +999,22 @@ func bodyForProvider(rawBody []byte, requiresVision bool, provider *registry.Pro
return rawBody
}

// defaultMaxOutputTokens is the ceiling injected into requests that don't set
// max_tokens. It bounds the worst-case cost of a single inference so the
// defaultMaxOutputTokens is the generation bound injected into requests that
// don't set max_tokens. It bounds the worst-case cost of a single inference so the
// pre-flight balance reservation covers the entire generation; without this
// cap a consumer could stream output exceeding their reservation and the
// post-inference charge would fail silently (see GitHub issue #33). Consumers
// who need longer generations must set max_tokens explicitly and carry the
// balance to cover it.
Comment thread
anupsv marked this conversation as resolved.
Resolved
const defaultMaxOutputTokens = 8192

func implicitMaxTokensBound(modelMaxOutputLength int) int {
if modelMaxOutputLength > 0 && modelMaxOutputLength < defaultMaxOutputTokens {
return modelMaxOutputLength
}
return defaultMaxOutputTokens
Comment thread
anupsv marked this conversation as resolved.
Resolved
}
Comment thread
anupsv marked this conversation as resolved.
Resolved
Comment thread
anupsv marked this conversation as resolved.
Resolved

Comment thread
anupsv marked this conversation as resolved.
Resolved
// explicitMaxTokens returns the consumer-specified max output tokens from any
// of the recognized field names, or 0 if none were set.
func explicitMaxTokens(parsed map[string]any) int {
Expand Down Expand Up @@ -1176,11 +1183,10 @@ func (s *Server) reserveAdditionalForProvider(pr *registry.PendingRequest, provi
// ensureMaxTokensBound injects a max-tokens bound into parsed when the
// consumer didn't specify any max-tokens field, so the outgoing request to
// the provider is bounded by the amount we reserve upfront. The bound is
// the model's max_output_length from the registry (or defaultMaxOutputTokens
// as fallback). The injected field name depends on the API flavor: Responses
// API uses max_output_tokens, everything else uses max_tokens. Returns true
// when an injection occurred, so the caller can re-marshal the outgoing body
// if needed.
// the platform default clamped by the model's max_output_length when lower.
// The injected field name depends on the API flavor: Responses API uses
// max_output_tokens, everything else uses max_tokens. Returns true when an
Comment thread
anupsv marked this conversation as resolved.
Resolved
Comment thread
anupsv marked this conversation as resolved.
Resolved
// injection occurred, so the caller can re-marshal the outgoing body if needed.
func ensureMaxTokensBound(parsed map[string]any, isResponsesAPI bool, bound int) bool {
if n := explicitMaxTokens(parsed); n > 0 {
// Normalize alias fields the provider engine doesn't read: a chat
Expand Down Expand Up @@ -1532,7 +1538,7 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {

// Inject model-specific defaults from the registry: reasoning_parser
// and max_tokens bound. Single DB lookup (cached for platform prices).
maxOutputBound := defaultMaxOutputTokens
maxOutputBound := implicitMaxTokensBound(0)
if rec, err := s.store.GetModelRegistryRecord(model); err == nil {
Comment thread
anupsv marked this conversation as resolved.
Resolved
// Reasoning parser from runtime_parameters.
if _, hasRP := parsed["reasoning_parser"]; !hasRP && rec.RuntimeParameters != nil {
Expand All @@ -1541,18 +1547,15 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
rawBody, _ = marshalForwardBody(parsed)
}
}
// Use the registry's max_output_length as the default max_tokens
// bound instead of the hardcoded 8192. This lets models like
// GPT-OSS 20B (32K output) generate longer responses when the
// consumer omits max_tokens.
if rec.MaxOutputLength > 0 {
maxOutputBound = rec.MaxOutputLength
}
// max_output_length is an advertised maximum, not the implicit default.
// Omitted max_tokens stays on the safer platform default; models with a
// lower published max still clamp the injected bound to their maximum.
maxOutputBound = implicitMaxTokensBound(rec.MaxOutputLength)
}

// Bound the generation so the pre-flight reservation covers it. If the
// consumer didn't set max_tokens, inject the model's max_output_length
// (or defaultMaxOutputTokens as fallback). Without this bound the
// consumer didn't set max_tokens, inject the platform default clamped by
// the model's max_output_length when lower. Without this bound the
// provider could return more tokens than we reserved for, and the
// silent post-inference charge failure would hand the consumer free
// inference (GitHub issue #33).
Expand Down Expand Up @@ -4100,9 +4103,9 @@ func (s *Server) handleGenericInference(w http.ResponseWriter, r *http.Request,
// Completions and Anthropic messages both use the max_tokens field (never
// max_output_tokens, which is Responses API only). Inject a default if
// unset so the pre-flight reservation bounds the generation.
genericMaxOutput := defaultMaxOutputTokens
genericMaxOutput := implicitMaxTokensBound(0)
if rec, err := s.store.GetModelRegistryRecord(model); err == nil && rec.MaxOutputLength > 0 {
genericMaxOutput = rec.MaxOutputLength
genericMaxOutput = implicitMaxTokensBound(rec.MaxOutputLength)
Comment thread
anupsv marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🏷️ handleGenericInference uses map[string]any for JSON parsing

💡 Suggestion: Consider defining a typed struct for generic inference requests with proper field tags

📊 Score: 2×2 = 4 · Category: map[string]any usage

}
ensureMaxTokensBound(parsed, false, genericMaxOutput)

Expand Down
25 changes: 25 additions & 0 deletions coordinator/api/consumer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1032,6 +1032,31 @@ func TestResponsesRequestToChatCompletions(t *testing.T) {
}
}

func TestImplicitMaxTokensBoundUsesSafeDefaultBelowModelMaximum(t *testing.T) {
if got := implicitMaxTokensBound(8192); got != defaultMaxOutputTokens {
t.Fatalf("implicitMaxTokensBound(8192) = %d, want %d", got, defaultMaxOutputTokens)
}
}

func TestImplicitMaxTokensBoundClampsToLowerModelMaximum(t *testing.T) {
if got := implicitMaxTokensBound(256); got != 256 {
t.Fatalf("implicitMaxTokensBound(256) = %d, want 256", got)
}
}

func TestEnsureMaxTokensBoundInjectsImplicitDefault(t *testing.T) {
parsed := map[string]any{
"model": "gemma-4-26b",
"messages": []any{map[string]any{"role": "user", "content": "hello"}},
}
Comment thread
anupsv marked this conversation as resolved.
Resolved
if !ensureMaxTokensBound(parsed, false, implicitMaxTokensBound(8192)) {
t.Fatal("ensureMaxTokensBound did not report injection")
}
if got := parsed["max_tokens"]; got != defaultMaxOutputTokens {
t.Fatalf("max_tokens = %v, want %d", got, defaultMaxOutputTokens)
}
}

func TestResponsesInputToolTranscriptToChatMessages(t *testing.T) {
input := []any{
map[string]any{
Expand Down
2 changes: 1 addition & 1 deletion coordinator/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func keyLimitResetFromContext(ctx context.Context) string {
// 0.6.0 is the APNs code-identity / VLM-routing / graceful-update release.
// Keep this fallback in sync with ProviderCore.version so dev/in-memory
// coordinators advertise the same floor as the Swift binary they expect.
var LatestProviderVersion = "0.6.10"
var LatestProviderVersion = "0.6.11"

// minProviderVersionForDesiredModels is the first provider version whose Swift
// runtime understands the desired_models message. The coordinator must NOT send
Expand Down
56 changes: 50 additions & 6 deletions coordinator/registry/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ type routingSnapshot struct {
prefillTPS float64
systemMetrics protocol.SystemMetrics
gpuMemoryActiveGB float64
gpuMemoryCacheGB float64
totalMemoryGB float64
modelSizeGB float64 // catalog-reported weight footprint (0 = unknown, gate disabled)
minRAMGb int // catalog authoritative min RAM (GB) to run the model (0 = unknown)
Expand Down Expand Up @@ -133,6 +134,14 @@ const (
// gemma-4-26b min_ram_gb=36 vs 28*2.x rejecting the whole 64 GB tier).
const modelMemoryHeadroomFactor = 2.0

const (
providerMemoryCapFraction = 0.90
providerMinimumReserveGB = 2.0
providerModelMemoryOverheadFactor = 1.2
providerActivationReserveGB = 3.0
providerMinimumLoadKVGB = 1.0
Comment thread
anupsv marked this conversation as resolved.
Resolved
Comment thread
anupsv marked this conversation as resolved.
Resolved
)

// modelFitsHardware reports whether a model can run on a node with the given
// total unified memory (GB). It prefers the catalog's authoritative min_ram_gb
// (the operator-published requirement) and only falls back to a heuristic
Expand All @@ -153,6 +162,28 @@ func modelFitsHardware(minRAMGb int, modelSizeGB, totalMemoryGB float64) bool {
return true
}

func providerHardMemoryCapGB(totalMemoryGB float64) float64 {
if totalMemoryGB <= 0 {
return 0
}
byFraction := totalMemoryGB * providerMemoryCapFraction
byFloor := 0.0
if totalMemoryGB > providerMinimumReserveGB {
byFloor = totalMemoryGB - providerMinimumReserveGB
}
if byFraction < byFloor {
return byFraction
}
return byFloor
Comment thread
anupsv marked this conversation as resolved.
Resolved
}

func providerEstimatedModelLoadGB(modelSizeGB float64) float64 {
if modelSizeGB <= 0 {
return 0
}
return modelSizeGB * providerModelMemoryOverheadFactor
Comment thread
anupsv marked this conversation as resolved.
Resolved
Comment thread
anupsv marked this conversation as resolved.
Resolved
}

// costBreakdown decomposes the routing cost so callers can log or
// expose individual contributions. The numeric values match the terms
// added in buildCandidate; total should equal costMs (modulo float
Expand Down Expand Up @@ -760,6 +791,7 @@ func (r *Registry) snapshotProviderLocked(p *Provider, model string, traits Requ

if p.BackendCapacity != nil {
snap.gpuMemoryActiveGB = p.BackendCapacity.GPUMemoryActiveGB
snap.gpuMemoryCacheGB = p.BackendCapacity.GPUMemoryCacheGB
if p.BackendCapacity.TotalMemoryGB > 0 {
snap.totalMemoryGB = p.BackendCapacity.TotalMemoryGB
}
Expand Down Expand Up @@ -805,7 +837,8 @@ func freeMemoryAdmits(snap routingSnapshot, reqPromptTokens, reqMaxTokens int) b
if snap.modelSizeGB <= 0 || snap.totalMemoryGB <= 0 {
return true
}
required := snap.modelSizeGB
modelLoadGB := providerEstimatedModelLoadGB(snap.modelSizeGB)
required := modelLoadGB
if snap.modelLoaded {
required = 0
}
Expand All @@ -818,7 +851,6 @@ func freeMemoryAdmits(snap routingSnapshot, reqPromptTokens, reqMaxTokens int) b
tokens = maxTokensForCalc
}
kvCacheGB := float64(tokens*kvCacheBytesPerToken) / float64(bytesPerGB)
required += kvCacheGB

// When the model is available on disk but not currently loaded, the
// provider will evict idle models to make room (LRU eviction). Check
Expand All @@ -831,12 +863,23 @@ func freeMemoryAdmits(snap routingSnapshot, reqPromptTokens, reqMaxTokens int) b
// through to the standard free-memory check which requires room
// alongside active models.
if snap.availableOnDisk && !snap.modelLoaded && snap.totalPending == 0 {
const osReserveGB = 4.0
return snap.modelSizeGB+kvCacheGB+osReserveGB <= snap.totalMemoryGB
requiredKVGB := kvCacheGB
if requiredKVGB < providerMinimumLoadKVGB {
requiredKVGB = providerMinimumLoadKVGB
}
required := modelLoadGB + providerActivationReserveGB + requiredKVGB
return required <= providerHardMemoryCapGB(snap.totalMemoryGB)
}

free := snap.totalMemoryGB - snap.gpuMemoryActiveGB
return free >= required
freeUnderCap := providerHardMemoryCapGB(snap.totalMemoryGB) - snap.gpuMemoryActiveGB - snap.gpuMemoryCacheGB
if freeUnderCap < 0 {
freeUnderCap = 0
}
required += kvCacheGB + providerActivationReserveGB
if !snap.modelLoaded {
required += providerMinimumLoadKVGB
}
return freeUnderCap >= required
Comment thread
anupsv marked this conversation as resolved.
Resolved
}

func pendingTokenBudget(pr *PendingRequest) int {
Expand Down Expand Up @@ -1255,6 +1298,7 @@ func (r *Registry) quickCapacityCheck(model string, estimatedPromptTokens, reque
}
if snap.hasBackendCapacity {
snap.gpuMemoryActiveGB = p.BackendCapacity.GPUMemoryActiveGB
snap.gpuMemoryCacheGB = p.BackendCapacity.GPUMemoryCacheGB
if p.BackendCapacity.TotalMemoryGB > 0 {
snap.totalMemoryGB = p.BackendCapacity.TotalMemoryGB
}
Expand Down
24 changes: 24 additions & 0 deletions coordinator/registry/scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1423,6 +1423,30 @@ func TestFreeMemoryAdmitsFallsBackWithoutBudget(t *testing.T) {
}
}

func TestFreeMemoryAdmitsColdLoadMirrorsProviderMemoryEnvelope(t *testing.T) {
// 26 GB of raw weights looks like it fits on a 36 GB laptop under the old
// raw-size + 4 GB reserve check (30 <= 36). The provider actually loads with
// scanner overhead (1.2x), a 90% hard cap, activation reserve, and minimum KV
// headroom: 31.2 + 3 + 1 > 32.4, so the coordinator must not route it cold.
publicGemmaOnLaptop := routingSnapshot{
modelSizeGB: 26,
totalMemoryGB: 36,
availableOnDisk: true,
modelLoaded: false,
totalPending: 0,
}
if freeMemoryAdmits(publicGemmaOnLaptop, 100, 256) {
t.Fatal("should reject cold load that only fits under raw-size accounting")
}

// The QAT build's smaller raw footprint still fits the same envelope.
qatGemmaOnLaptop := publicGemmaOnLaptop
qatGemmaOnLaptop.modelSizeGB = 15
if !freeMemoryAdmits(qatGemmaOnLaptop, 100, 256) {
t.Fatal("should admit smaller QAT build under provider-equivalent accounting")
}
}

func TestSlotHeadroomWithExhaustedTokenBudgetRejectsCapacity(t *testing.T) {
reg := New(testLogger())
model := "budget-headroom-model"
Expand Down
70 changes: 55 additions & 15 deletions provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1463,6 +1463,32 @@ public actor BatchScheduler {
return n // 0 ⇒ disabled
}

static func makeSamplingParams(
maxTokens: Int,
temperature: Float,
topP: Float?,
topK: Int?,
repetitionPenalty: Float?,
presencePenalty: Float?,
frequencyPenalty: Float?,
seed: UInt64?
) -> SamplingParams {
let requestedRepetitionPenalty = repetitionPenalty ?? 1.0
let safeRepetitionPenalty =
requestedRepetitionPenalty <= 0 ? Float(1.0) : requestedRepetitionPenalty
var sp = SamplingParams(
maxTokens: maxTokens,
temperature: temperature,
repetitionPenalty: safeRepetitionPenalty,
presencePenalty: presencePenalty ?? 0.0,
frequencyPenalty: frequencyPenalty ?? 0.0
)
if let topP { sp.topP = topP }
if let topK { sp.topK = topK }
if let seed { sp.seed = seed }
return sp
Comment thread
anupsv marked this conversation as resolved.
Resolved
}
Comment thread
anupsv marked this conversation as resolved.
Resolved
Comment thread
anupsv marked this conversation as resolved.
Resolved
Comment thread
anupsv marked this conversation as resolved.
Resolved

/// Set the post-load budgets driven by architecture + physical
/// memory. Pulled out of `loadModel` so the lifecycle reads as a
/// short sequence; the arithmetic itself is unchanged.
Expand All @@ -1488,11 +1514,12 @@ public actor BatchScheduler {
// Derive context-aware limits from config.json.
self.maxContextLength = snapshot.architecture.maxContextLength ?? 0
if maxContextLength > 0 {
// Raise the default max output tokens so consumers that omit
// `max_tokens` get a reasonable budget for the model's class.
// Cap at 8192 so we don't over-reserve with very-long-context
// models (e.g. 131K Qwen).
self.defaultMaxTokens = min(maxContextLength, 8192)
// Do not auto-raise omitted `max_tokens` after model load. Runaway
// loops then run to an unexpectedly large cap and over-reserve KV.
// Only clamp downward for unusually short-context models.
self.defaultMaxTokens = min(initDefaultMaxTokens, maxContextLength)
} else {
self.defaultMaxTokens = initDefaultMaxTokens
}

self.dynamicMaxConcurrentRequests = min(4, maxConcurrentRequests)
Expand All @@ -1518,6 +1545,9 @@ public actor BatchScheduler {
temperature: Float = 0.0,
topP: Float? = nil,
topK: Int? = nil,
repetitionPenalty: Float? = nil,
presencePenalty: Float? = nil,
frequencyPenalty: Float? = nil,
seed: UInt64? = nil,
requestId: String? = nil,
cacheScope: String = ""
Expand Down Expand Up @@ -1575,10 +1605,16 @@ public actor BatchScheduler {
await refreshPendingSummaryCache()
}

var sp = SamplingParams(maxTokens: maxTokens, temperature: temperature)
if let topP { sp.topP = topP }
if let topK { sp.topK = topK }
if let seed { sp.seed = seed }
let sp = Self.makeSamplingParams(
maxTokens: maxTokens,
temperature: temperature,
topP: topP,
topK: topK,
repetitionPenalty: repetitionPenalty,
presencePenalty: presencePenalty,
frequencyPenalty: frequencyPenalty,
seed: seed
)

let req = Request(
requestId: id,
Expand Down Expand Up @@ -1752,13 +1788,17 @@ public actor BatchScheduler {
await refreshPendingSummaryCache()
}

// Greedy (temperature == 0) hits the engine's vectorized argmax
// fast path automatically; just pass the requested value through.
let temperature = request.temperature ?? 0.0
var sp = SamplingParams(maxTokens: maxTokens, temperature: temperature)
if let topP = request.top_p { sp.topP = topP }
if let topK = request.top_k { sp.topK = topK }
if let seed = request.seed { sp.seed = seed }
let sp = Self.makeSamplingParams(
maxTokens: maxTokens,
temperature: temperature,
topP: request.top_p,
topK: request.top_k,
repetitionPenalty: request.repetition_penalty,
presencePenalty: request.presence_penalty,
frequencyPenalty: request.frequency_penalty,
seed: request.seed
)

let req = Request(
requestId: id,
Expand Down
Loading
Loading