`fm serve` in Production: Routing Between On-Device and Private Cloud Compute
⚠️ Speculative Architecture & Preview: This article discusses future system iterations (e.g., iOS 27, Xcode 27) as conceptual planning and architectural design patterns. Technical details represent previews and proposals rather than finalized APIs.
fm serve in Production: Routing Between On-Device and Private Cloud Compute
The operational question for any fm serve production deployment is no longer whether the local endpoint works — it speaks the OpenAI protocol fluently and tools attach with a base-URL change. The deployment question is which execution tier answers each request: the on-device model or Private Cloud Compute.
The Verdict
- Build a model routing layer keyed on task class and token budget rather than selecting one default model.
- Keep the on-device model for short, structured tasks — summarization, entity extraction, classification — where it is free, private, and lower-latency than any network round trip.
- Route multi-step reasoning, large-context work, and tool-calling loops to Private Cloud Compute (PCC) despite its added latency budget and eligibility constraints.
- Hidden cost: the on-device model degrades on long-context tool use in ways toy prompts never surface — enforce the budget and instrument both paths from day one.
| Task class | Route | Why |
|---|---|---|
| Summarize / classify / extract | On-device model | Short output, rigid shape, fits the context window, ANE completes it fast |
| Multi-step reasoning | Private Cloud Compute | Bigger model, deeper reasoning levels, survives long tool loops |
| Long-context document | Private Cloud Compute | On-device window is bounded (~8K tokens per WWDC26; verify against current docs) |
| Anything near the window edge | Private Cloud Compute | The tool result you are about to append has not been counted yet |
Two Execution Tiers, One Endpoint
The fm CLI on macOS 27 introduced fm serve: an OpenAI-compatible Chat Completions server that exposes two tiers behind one port. The on-device SystemLanguageModel runs compiled to the Apple Neural Engine — no API key, no network, no marginal token cost. The PrivateCloudComputeLanguageModel runs the larger server model behind Apple’s compute grid, with strong reasoning levels and a much larger context window, at the price of a network hop, a per-user daily limit, and an entitlement.
Those tiers are not interchangeable, and fm serve will happily let you treat them as if they were — the model field is a string either way. The numbers around model size, context window, and eligibility are versioned claims that drift between releases, so verify the concrete figures against the current Foundation Models and PCC docs at publish time. What does not drift is the structural fact behind them: the two tiers have different latency, privacy, and budget profiles, and choosing between them is a policy problem, not a configuration problem.
Why a Single Default Model Is the Wrong Default
The tempting configuration is one default model with a fallback flag. In practice this fails twice:
- Default on-device, escalate on error — the on-device model does not error when it is overloaded; it produces confident, plausible output that drifts off-task once the context window fills and the key-value cache thrashes.
contextSizeExceededsurfaces late, mid-tool-loop, after several turns have already degraded. - Default PCC, fall back locally — you burn the daily per-user limit on requests the on-device model could answer in milliseconds, and you accept an unnecessary network round trip on a hot path where the user is staring at a progress spinner.
Neither approach is a policy. A routing layer that never sees a task class or a token count is guessing, and the guess is invisible because both tiers return valid-looking JSON.
The hidden cost the thesis calls out is specifically long-context tool use. A one-shot “summarize this paragraph” prompt never reveals it. An agentic loop that re-invokes the model across several tool results does: every tool response is appended to the transcript, the prompt grows each turn, and a 3B model operating near its window edge produces worse tool selections and more malformed calls before it finally throws. By the time you see the failure in your signposts, the user prompt that mattered has already scrolled out of the transcript.
Routing on Task Class and Token Budget
The FoundationModels framework provides the two primitives a policy needs: contextSize on the model and tokenCount(for:) on any prompt or transcript. That is why the policy should live against the framework rather than the HTTP surface — fm serve reports usage after the fact, but it will not tell you whether the on-device model still has headroom for the tool result you are about to append.
Use the live budget, not message counts. A one-line prompt carrying a 40-line JSON tool payload is still “one turn” — counting turns routes that straight past the window.
A RoutingClient Sketch
import Foundation
import FoundationModels
import OSLog
private let log = Logger(subsystem: "in.iosdev.intelligence", category: "ModelRouting")
/// The decision lives in one actor so the token-budget check and the request it
/// authorizes cannot interleave. We shipped the first version with two isolated
/// actors and the check raced the dispatch — a "classify" prompt ended up on PCC
/// with a 1.9s p99 we had to explain to a product owner. Routing is a policy;
/// it should read as a transaction, not a best effort.
actor RoutingClient {
struct Policy: Sendable {
/// Read live from `SystemLanguageModel.contextSize`; do not hard-code.
/// The on-device model grew its window between OS releases.
var onDeviceContext: Int
/// Headroom reserved for the tool result we are about to append.
/// 384 is what survived our 26.4-era workload; re-measure per release.
var coast: Int = 384
}
enum TaskClass: Sendable {
case summarize
case classify // guided generation, tiny schema
case extract // bounded document, structured keys
case multiStepReasoning
case longContext // transcript or doc beyond the on-device window
var label: String {
switch self {
case .summarize: "summarize"
case .classify: "classify"
case .extract: "extract"
case .multiStepReasoning: "multi-step"
case .longContext: "long-context"
}
}
}
enum Route: Sendable {
case onDevice // SystemLanguageModel
case privateCloud // PrivateCloudComputeLanguageModel
var label: String {
switch self {
case .onDevice: "on-device"
case .privateCloud: "pcc"
}
}
}
private let policy: Policy
private let onDeviceModel: SystemLanguageModel
private let sessionTools: [Tool]
init(tools: [Tool]) async throws {
let model = SystemLanguageModel()
// First cut routed on message count (< 3 turns stays on-device). That
// collapsed the day a "short" turn carried a full JSON tool payload:
// 3 turns, 2,100 tokens, wrong tier. Count tokens, never turns.
self.policy = Policy(onDeviceContext: model.contextSize)
self.onDeviceModel = model
self.sessionTools = tools
}
func respond(to prompt: String, task: TaskClass) async throws -> String {
let started = ContinuousClock.now
let route = try await decide(task: task, prompt: prompt)
// Signpost every decision: route, task, and elapsed. Without these,
// "the model was slow" is a product complaint, not a data point.
let id = OSSignpostID(log: log)
os_signpost(.begin, log: log, name: "route", signpostID: id,
"%{public}s -> %{public}s", task.label, route.label)
do {
let result = try await execute(prompt: prompt, task: task, route: route)
os_signpost(.end, log: log, name: "route", signpostID: id,
"%.1fms", started.duration(to: .now).milliseconds)
return result
} catch {
os_signpost(.end, log: log, name: "route", signpostID: id, "error")
throw error
}
}
private func decide(task: TaskClass, prompt: String) async throws -> Route {
let promptTokens = try await onDeviceModel.tokenCount(for: prompt)
let remaining = policy.onDeviceContext - policy.coast - promptTokens
switch task {
case .multiStepReasoning, .longContext:
// Each tool loop re-invokes the model; the whole transcript has to
// fit, not just this turn. The window is amortized over the loop.
return .privateCloud
case .summarize, .classify, .extract:
// Short, structured output fits on-device and completes faster than
// any network hop — but only while real headroom exists. When it
// does not, escalate before the session degrades, not after.
guard remaining > 0 else { return .privateCloud }
return .onDevice
}
}
private func execute(prompt: String, task: TaskClass, route: Route) async throws -> String {
switch route {
case .onDevice:
// Tool calling mode `.required` keeps the loop honest: every action
// is a tool call, so a transcript that silently stalls is caught by
// the tool evaluator instead of generating prose forever.
let session = LanguageModelSession(model: onDeviceModel, tools: sessionTools)
return try await session.respond(to: prompt)
case .privateCloud:
// Availability is a spectrum — entitlement, per-user daily limit,
// connectivity. Treat "limit exhausted" the same as "no entitlement"
// and you hide the approaching-limit case the simulator exists to
// exercise. Use the availability APIs and Xcode's "Simulate Apple
// Foundation Models Availability" option to test both states.
let pcc = PrivateCloudComputeLanguageModel()
let session = LanguageModelSession(model: pcc, tools: sessionTools)
return try await session.respond(to: prompt)
}
}
}
Two production notes on the code above. First, decide belongs with the session lifecycle: an agentic loop should re-check remaining between turns rather than trusting a decision made before the first tool result arrived. Second, the reasoning level for PCC is a lever worth exposing as policy data — deeper reasoning buys quality at the cost of latency and daily-limit tokens, so it is a budget decision, not a style preference.
Instrument Both Paths
The verdict is not “route to PCC for hard things.” It is: make the decision explicit, then measure both sides. The updated Foundation Models Instruments provides latency, prompts, tool calls, and token usage per session — wire your own counters on top so the data survives outside a profiling session.
Track four numbers per decision:
- Route fraction — share of requests landing on each tier, split by task class. A drift toward PCC after an OS update usually means the on-device context shrank.
- Context headroom at decision time — if this hits the coast value regularly, the policy is escalating late.
- Per-turn token growth in tool loops — the metric that surfaces the hidden cost in the thesis, before users report junk output.
- PCC daily-limit proximity — approaching the cap changes the latency budget you should be willing to trade for on-device execution.
If the on-device path degrades, you want to see it as a line on a chart with a contextSize axis — which is exactly how the degradations from long-context tool use present — rather than as a support ticket about “the model being stupid lately.”
The verdict stands: choose a routing policy keyed on task class and token budget, encode it in one serialized decision point, and instrument both tiers from the first deploy. A default model is a lazy constant; a routing layer is a measured policy.
Related Deep Dives
- The fm CLI: Apple Foundation Models from the macOS Terminal — the predecessor that introduced
fm serve, its OpenAI-compatible surface, and the unified-3b on-device model. - Private Cloud Compute: Validating Node Trust and Device Attestation — how PCC node trust and attestation work underneath the routing surface.
- Foundation Models Framework Open Source: The LanguageModel Protocol and Third-Party LLMs — where the
LanguageModelabstraction and multi-provider sessions come from.