Hybrid Edge-Cloud Inference
Design hybrid edge-cloud inference with routing, partitioning, and fallback. Learn latency accounting, privacy gates, and cost control for LLM apps.
Language AI HandbookAll chapters Hybrid Edge-Cloud Inference
A mobile writing assistant can suggest the next word on a phone and use a cloud model for an occasional rewrite. In hybrid edge-cloud inference, the application decides which side handles the work. The models can share a family or use different architectures. Making some requests local can reduce data transfer and keep those features usable during an outage, provided the model fits the device. Test handling of difficult requests, transfer policy, latency, and serving cost separately.
The gap between these two worlds is not primarily about model architecture. It is about orchestration: the control logic that sits above the models, observes what it can observe cheaply, and commits to a division of labor for each request. That control logic is the subject of this chapter. It is where the engineering difficulty lives, because the models themselves are fairly well understood, whereas the rules that decide who should run them are tied to product constraints, user expectations, network physics, and regulatory policy.
We cover three separable ideas that are easy to conflate and must be kept apart:
- Routing: pick one side (edge or cloud) to serve the whole request.
- Partitioning: split one inference pass across edge and cloud, e.g. run early layers on device and the rest remotely, or let the edge draft and the cloud verify.
- Fallback: what happens when the network, the cloud, or the device misbehaves.
We will account for transfer, offline behavior, latency and serving cost. KV Cache and Speculative Decoding explain how memory traffic and sequential decoding affect performance. On a mobile device, the route also depends on what data may be sent and how often the two sides need to communicate.
Why hybrid at all
An edge-only deployment must fit the model in device memory and stay within power and latency budgets. A cloud-only deployment needs connectivity to its inference service and sends whatever input that service requires. Running both adds orchestration work. The extra work can pay off when one path handles common requests well and the other handles a distinct set of harder requests.
Consider a concrete product: a mobile writing assistant on a smartphone.
- Most keystrokes trigger tiny suggestions (next word, grammar fix). These must appear in a few tens of milliseconds, must never leak the draft to a server, and must work on a plane. A small on-device model handles them.
- Occasionally the user asks "rewrite this paragraph to be more formal." That is longer, harder, and the user may accept a one-second delay. A cloud model handles it far better.
- When the device is offline or on a metered connection, the app must degrade gracefully to the edge model rather than fail.
That mix of cheap-frequent-easy and rare-expensive-hard is the classic case for routing. Partitioning and fallback enter when the boundary is fuzzier: when even a hard request should start on device for privacy or responsiveness, or when the edge should stay in the loop to keep the user moving while the cloud composes a better answer.
The writing assistant has many short suggestions and fewer full rewrites. Measure this mix on your workload before estimating the benefit of a router. Three forces shape the design.
- Latency. A remote request adds transfer and waiting time. Local inference still uses device compute. Compare both paths on the devices, links and request lengths you serve.
- Cost. In the worked example, each successful cloud request has a fixed fee. A different provider may bill for tokens, compute, network transfer or capacity. Local execution consumes device energy. Track those units separately.
- Privacy and availability. Local inference can keep prompts on the device when the application also excludes them from logs and telemetry. A cloud path needs connectivity and transfer approval for each workload. For a local-only request, use the approved local path or decline the request.
These three forces do not always point in the same direction. Privacy pushes toward the edge; quality pushes toward the cloud; latency can push either way depending on the network and the model sizes. A hybrid system is a policy for resolving these conflicts consistently, and the rest of this chapter builds that policy piece by piece.
The three control decisions, kept separate
The most common design error is to blur routing, partitioning, and fallback into one tangled "if the model is unsure, call the cloud" rule. That makes the system hard to reason about, test, or measure. When the three mechanisms are fused, a bug in any one of them looks like a quality problem, and you cannot tell which component to fix. Keep them as three distinct mechanisms with clear interfaces, each with its own inputs, outputs, and evaluation.
Choosing a single execution site for an entire request before generation begins. The request is fully served by either the edge model or the cloud model. Routing does not split a request across both.
Dividing one inference pass across edge and cloud. Examples: early transformer layers on device and later layers remotely; edge drafts tokens and cloud verifies them; edge handles retrieval or prefill while cloud handles decode. The output is produced by a joint computation, not one site alone.
The predetermined behavior when a primary path is unavailable or fails: network down, cloud timeout or error, device thermal throttling, quota exhausted. Fallback is about resilience, not optimization; it must be deterministic and tested.
Why separate them? Because they have different failure modes, different measurement, and different privacy implications.
| Mechanism | Decision granularity | Primary goal | Privacy exposure | When it fails |
|---|---|---|---|---|
| Routing | whole request | cost/quality tradeoff | sends the approved model input | misclassification |
| Partitioning | per layer / per token | latency + quality | sends activations or draft | coordination + network fragility |
| Fallback | on error condition | availability | depends on the fallback target | untested path returns wrong output |
When the router chooses the cloud, the application sends the approved input. A layer split instead sends the hidden activation at the split boundary. That can still disclose information about the original text. If a stream falls back to a different model after output has started, specify whether it restarts or continues and how the already displayed prefix is handled.
Routing decisions can be logged and tested per request under the applicable data policy. Partitioning adds distributed state and timing, so test prefix and cache consistency. Test fallback with deliberately injected faults as well as recorded failures.
Routing: deciding where a request runs
For whole-request routing, estimate whether the edge answer will meet the task’s quality requirement and whether the cloud improvement is worth the extra cost when transfer is allowed. A classifier can estimate edge success. You can also estimate the expected quality difference directly. Track the errors of both approaches alongside their costs on the traffic where they will run.
What signal should drive the decision
The router observes cheap, available-at-request-time features and outputs a decision. Candidate signals fall into a few families:
- Prompt-intrinsic features: length in tokens, language, presence of code or math, task-type keywords ("translate", "summarize", "prove"), readability, estimated difficulty. Cheap and privacy-preserving (computed on device). Computing these features locally requires no generation call. Measure their cost with your tokenizer and deployed request sizes.
- Edge-model confidence: an available proxy such as mean token log probability over a short local candidate, or self-reported uncertainty. Measure how it relates to task correctness and account for any local generation the score requires.
- Device and network context: battery level, thermal state, connection type (Wi-Fi vs. cellular), measured round-trip time, data-cap status. Cheap and directly actionable. These do not say anything about the request itself, but they determine the cost of the cloud path, which is half of the routing inequality.
- Learned difficulty score: a small classifier trained on (request, did-edge-succeed?) labels, where "succeed" is a judged label or a reward-model score. This requires a labeling pipeline. Compare it with inexpensive baselines on held-out traffic before committing to retraining as the model or traffic changes.
- User or policy priors: user opted into cloud for certain apps, enterprise policy forbids cloud for this document, jurisdiction rules. These are hard constraints, not soft signals. They are not evidence about difficulty at all; they are constraints on feasibility, and they override every other signal.
A router can combine a learned score with a hard transfer policy.
The hard constraints override everything: if policy says "this document may not leave the device," no score sends it to the cloud. The score only governs the discretionary middle. This two-layer structure, a hard gate followed by a soft classifier, is what lets the same codebase serve both a privacy-strict enterprise deployment and a user who has explicitly opted into cloud processing, without maintaining two divergent routing implementations.
The routing math
Let be the request and a predicted difficulty. Let and be expected quality of each path (say, a reward-model score or task success probability). Let and be expected cost (latency, dollars, battery). A reasonable routing rule is to send to cloud when the value of the quality gain exceeds the extra cost. The indicator returns 1 (route to cloud) when that inequality holds and 0 otherwise:
where:
- : the incoming request
- : the expected quality gain from serving on the cloud rather than the edge
- : the extra expected cost (latency, dollars, battery) of the cloud path
- : indicator function, equal to 1 when the condition holds (route to cloud) and 0 otherwise
- : a scalar that trades quality against cost, set by product policy (e.g., "one extra point of quality is worth one extra dollar" or, more commonly, "we will tolerate 300 ms extra for ≥5% quality gain")
The quality multiplier assigns a value to each unit of expected quality. When the cloud offers a positive quality gain and the cost and eligibility stay fixed, increasing the multiplier can only increase or preserve the set of requests selected for the cloud. The inequality has a natural interpretation as a marginal analysis. The left side is the benefit of the cloud, measured in quality units and converted to some common currency by . The right side is the extra cost in that same currency. Route to the cloud when the benefit exceeds the cost, and only then. A length or confidence cutoff can approximate this rule when that feature predicts the marginal value of the cloud path. Compare its measured weighted loss with the baseline routes.
In practice and are unknown at request time, so we proxy them. A common practical proxy is to train a router that predicts the quality gap directly by regressing on labeled comparisons, and threshold it with a latency-aware margin.
For a latency-only objective, express in milliseconds. If price or energy can alter the decision, compare the dimensions separately or choose weights to express them in a common cost unit.
Measure calibration, ranking, and routing costs
Overall routing accuracy gives each error the same weight. The costs can differ:
- Serving a hard request on edge can lower answer quality.
- Sending an easy request to the cloud can incur extra serving cost without improving the answer.
If quality loss is far more expensive than cost loss, bias toward the cloud; if cost and privacy dominate, bias toward the edge. The threshold in the rule above is how you express this, and both error types must be measured on held-out data, never just overall accuracy. Say 10 of 100 eligible requests are hard. A 90% accurate router misses all 10 hard requests. An 80% accurate router misses 2 hard requests and sends 18 easy requests to the cloud. If a hard miss costs and an unnecessary cloud trip costs , the two losses are and . The 90% router loses more when .
If the router estimates a probability, check whether requests scored near a value have the corresponding observed event rate. Check ranking separately. The cloud fraction at a threshold depends on the score distribution and its ties. Ten requests can all have score 0.7 with seven positive labels. This group is calibrated at the observed score, yet a strict threshold crossing 0.7 switches all ten decisions at once.
The deeper trap is that the errors the router cares about are unlabeled in production. When an easy request is needlessly routed to the cloud, nobody complains, because the answer was fine. When a hard request is routed to the edge and answered poorly, the user may simply abandon the app rather than report a bad answer. Both error types are silent, which means the router's offline measurements are the primary evidence you have, and they must be constructed with care: deliberate labels, deliberate slices, deliberate cost weights that reflect the product's actual priorities.
The curve of achieved quality versus fraction of requests routed to the cloud (or versus average latency/cost), traced by sweeping the routing threshold. It is the routing analog of a precision-recall curve and is the right way to choose the operating point.
Partitioning: splitting one inference pass
Routing keeps inference for a request on one side. Partitioning divides the work across endpoints. Some systems move a stage such as prefill. Others exchange intermediate results during generation. The latency ledger depends on the payload size, how often the exchange occurs, and whether compute can overlap it.
Layer-level partitioning (pipeline split)
In a two-endpoint layer split, layers run on the device and layers run on the server. The edge sends the boundary activation. When each endpoint retains state for its assigned layers, it keeps those layers’ key-value cache on that endpoint across steps. If the device starts the next decoding step, it also needs the selected token from the server. EdgeShard is a concrete system for choosing layer placement under device and network constraints.
- Serial exchanges. If each new token waits for one preceding round trip, a 100 ms round trip limits the schedule to at most 10 tokens/s even before compute. Link bandwidth and transfer size can reduce throughput further.
- Activation size. A hidden state of 4,096 bf16 values uses 8,192 bytes (8 KiB). Sending that payload at 10 Mbit/s takes about 6.55 ms of serialization before protocol overhead.
- Recovery. A transient error can delay or interrupt a step. A retry must resume from a common prefix and associated cache state or restart. Test the resume policy and its failure behavior.
Choose a placement by measuring per-layer compute, memory and transfer on the target devices and links. Evaluate prefill and single-request decode separately when the interaction needs a fast first token.
Speculative edge-cloud decoding
Speculative decoding can be partitioned so the device drafts tokens and the cloud scores them. The draft model proposes tokens, and the target model evaluates the draft prefixes in one parallel verification pass. The sampler accepts a prefix under the target-preserving rule and, on rejection, draws a correction token from the residual distribution. If every proposal is accepted, it can draw an additional token from the target.
One verification round can produce several output tokens. A sequential edge-cloud protocol pays a network round trip each round. When the very first proposal is rejected, the round emits the correction token without accepting any draft token.
The Python example below simulates request routing and offline fallback. For speculative decoding, the location of the sampler is a protocol decision. The same target distribution can be preserved on either side when the sampler uses the matching proposal and target distributions, the correct residual distribution on rejection, and a consistent prefix.
Bind each verifier response to the request, the committed prefix and the proposal it scored. Comparing an echoed accepted prefix with the device’s draft checks that they refer to the same proposed tokens. The serving path still needs an authenticated peer and a way to check or trust that it applied the correct target model and acceptance rule.
Retrieval and prefill partitioning
Local retrieval can select which approved snippets to send with a cloud request. If the application needs the full private collection for search, the index can stay on the device. The excerpts and any identifying metadata that leave the device still need transfer approval.
In another split, a prefill worker computes key-value (KV) state and a compatible decoder consumes it. DistServe studies this stage split in a serving cluster. A device-cloud variant needs compatible weights, tokenization, positions, cache layout and precision. Compare the bytes it would send with the original prompt representation. For example, an uncompressed bf16 cache for 1,024 tokens, 32 layers, eight KV heads per layer and head width 128 uses bytes (128 MiB). The two factors of 2 count key/value and bytes per scalar. The same 1,024 token IDs at four bytes each use 4 KiB. Savings from avoiding remote prefill must cover any KV transfer and compatibility costs. Cache reuse can change that tradeoff.
The choice of cut determines how often the two sides exchange data: an autoregressive layer split can require an exchange per output token, whereas a speculative protocol can amortize that exchange across output tokens when enough proposals are accepted.
Privacy boundaries
Review which data crosses the network boundary, who can read it, and how long the device and the server retain it. Model weights alone tell you little about those controls. A hybrid system has several places to enforce its policy.
- Retention: never store cloud prompts and completions, or store them for a bounded window. This is a server-side control, and it must be contractual as well as technical: a retention policy that is not enforced by the serving infrastructure is a promise, not a guarantee.
- Redaction before send: run a local PII/NER model and strip or mask sensitive spans before anything leaves the device. We covered detection strategies in PII Removal. Redaction is only as good as the detector, so its reliability must be measured and its failure modes understood.
- Hard routing exclusions: certain documents, apps, or user categories are never eligible for cloud routing, regardless of the difficulty score. These are categorical, not probabilistic, and they must be enforced in code rather than in documentation.
- On-device aggregation: send only derived features (e.g., "document is 800 tokens, legal-domain") for routing statistics, never raw text. Even derived features can expose information about a request. Minimize them and apply the same authorization and retention policy to telemetry.
- Intermediate state. Treat split activations as sensitive data. A split-inference study recovered information from hidden states under its tested model, split and attacker assumptions. Scope the transfer review to the states your protocol sends and who can access them.
The design pattern is a privacy gate that runs first, before the router. The gate classifies each request into one of: local_only, redact_then_cloud_ok, or cloud_ok. The router then operates only within what the gate permits.
Implementing the gate as an explicit, testable component (not a comment in a routing rule) is what lets you audit it. We include a minimal gate in the code below.
Run the gate before any transfer or logging that depends on its decision. For each transmitted payload, verify that the gate granted unconditional approval or that the required redaction completed. Include retries, fallback paths and telemetry in this check.
The three gate outputs are not equal in risk: a cloud_ok request is cleared exactly as written, whereas a redact_then_cloud_ok request is cleared only conditional on redaction succeeding, so the gate's output is a precondition that another component must fulfill, and the pipeline must treat a redaction failure as a fallback to local_only rather than a silent breach. A local_only request must be served on the edge or refused, and must never fall back to the cloud even under error conditions, because the most dangerous bug is a fallback path that ignores the gate.
A deterministic pre-routing component that assigns each request a transfer policy (local_only, redact_then_cloud_ok, cloud_ok) based on content type, user/app policy, and jurisdiction. It runs on-device and its output is a necessary precondition for any cloud routing.
Latency accounting
Latency in hybrid systems is deceiving because the slowest component is often the one you did not measure. We decompose end-to-end latency into additive terms and track each separately.
The discipline is to attribute every millisecond to exactly one term, so that when latency regresses you can identify the responsible component rather than guessing.
For routing:
where:
- : time for the on-device privacy gate to classify the request
- : time for the router to compute features and the difficulty score on device
- : indicator equal to 1 for the direct cloud path and 0 for the direct edge path
- : time to upload the prompt to the cloud
- : time waiting in the cloud serving queue
- : cloud prompt-prefill compute time
- : number of generated (decode) tokens
- : per-token cloud decode time, so is total cloud decode time
- : time to download the completion to the device
Here is on-device inference time. These are direct-path totals. If a cloud attempt times out before the device runs the edge model, include time spent on that attempt as well as local inference.
For a short cloud request, fixed network and queue time can be a large part of the total. For longer requests, prefill or decode can take a larger share. Measure their contributions separately and stratify the results by request length and service load. Record the gate and scoring costs on edge as well.
This is why the same routing policy can be latency-optimal for short requests and latency-pessimal for long ones, and why the router's cost estimates must be functions of request length rather than constants.
For a serialized two-endpoint layer split, count one exchange per decode step. The following ledger starts after prefill:
where:
- : compute time on the device in step
- : number of decode steps, each requiring an exchange between device and server
- : serial network delay and transfer time for the activation exchange in step
- : compute time on the server in step
With comparable exchange times, the network term grows in proportion to the number of steps in this schedule. To compare with an all-edge run of the same model, measure how much faster the relocated layers run on the server. Their compute-time saving must cover the exchanges and any other costs the split adds.
For a sequential speculative protocol with one exchange per verification round, the network term appears once per round:
where:
- : number of verify rounds, i.e., batches of draft tokens sent for verification
- : network round trip for one draft-to-verify exchange
- : total time for the cloud target model to score the drafted tokens across all rounds
- : total time for the edge draft model to propose tokens across all rounds
For a run of output tokens, is the first round by which the cumulative number of emitted tokens reaches . Over a long run with a stable average of emitted tokens per round, . For a draft of proposals, a rejection at the first proposal emits one correction token. If all proposals are accepted, the round can emit tokens with the additional target draw. A stop token or the output limit can shorten the final round. Compare the resulting exchanges, verify time and draft time on the links the service will use.
Cost accounting: separate network from serving
A recurring analysis mistake is to lump everything under one "cost" number, which hides the biggest lever. Network (egress and mobile data) and cloud serving (GPU-seconds, tokens) scale with different quantities and are optimized differently. Track them separately:
- Network. Measure transferred bytes, separately from transfer latency and the actual network bill. A serialized layer split exchanges activations each step. A sequential speculative protocol exchanges proposals and verification results each round.
- Cloud serving cost. Apply the actual fee or a measured compute and capacity cost. Tokens and compute time can help explain the bill under a specified service model. Cache reuse, batching, pricing and capacity commitments affect the relationship.
- Edge cost. Measure device energy in joules and whether sustained use fits the thermal budget. These are device costs even when the server bill stays the same.
Under a fully local route without telemetry, model traffic and remote serving charges can be zero while device energy still matters. The cloud route uploads input and returns output. A sequential speculative split exchanges proposals and verification results each round; count their actual bytes.
A router should consider the marginal cost of the alternative path, including both network and serving, and not optimize one at the expense of the other.
The separation also reveals a subtle failure mode in cost optimization. A team that optimizes only network cost may choose a partition that dramatically reduces bytes but increases cloud serving cost, or vice versa. Because the two costs have different units and different budgets, the right objective is a weighted combination whose weights are set by the business, and those weights are not interchangeable: a dollar of egress is not the same as a dollar of GPU time if the two come out of different budgets or are billed to different parties. Reporting the two costs separately makes that tradeoff visible to the people who set the weights.
Worked example: a routing decision
Let us make the routing rule concrete with numbers, then build intuition without code.
- Edge quality (mean reward score on this task), cloud .
- Edge latency ms; cloud latency ms on this network.
- Cloud monetary cost per request (raw serving + egress, aggregated) is 0.002 dollars. The edge path carries no marginal monetary charge.
Routing every request to the cloud yields a mean quality of 0.80, and routing every request to the edge yields 0.55. The difference is 0.25 across this workload. With the same cloud price on every request, sending 30% to the cloud pays 30% of the all-cloud monetary cost. How much quality that buys depends on which requests the router sends.
Start with two separate hypothetical workloads. With a uniform 0.25 cloud gain on every request, routing 30% to the cloud adds 0.075 to the edge-only mean of 0.55, giving 0.625. In a second workload, the edge scores 0.30 on the 30% sent to the cloud and 0.66 on the rest, while the cloud scores 0.80 throughout. That workload has an edge-only mean of and a hybrid mean of .
The hybrid closes about 60.5% of this workload's gap between 0.552 and 0.80.
At a fixed cloud fraction, selecting larger gains can raise mean quality relative to selecting smaller gains. If every request has the same gain, changing which requests route leaves mean quality unchanged at that fraction. Transfer eligibility, differing costs and a cloud budget can still favor serving some requests on edge and others in the cloud.
On an approved labeled sample, run both models on the same requests and plot their per-request quality differences. A large spread gives the router an opportunity to target high-gain requests if its features predict that gain. Compare each selection under the applicable costs and transfer requirements.
Implementation: a routing + fallback pipeline
The notebook simulates both model paths with controllable quality and latency. It measures routing on synthetic subgroups, gate exclusions, offline behavior, transferred bytes and remote serving spend. The code makes no model or network calls.
The simulation is deliberately simple, but its structure mirrors the production system: a gate that runs first, a router that scores within the gate's permissions, a serving step with fallback, and a logging step that records everything needed for per-slice evaluation.
Setup
PythonIn [2]Expand
import textwrap
from dataclasses import dataclass
from typing import Callable
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
rng = np.random.default_rng(7)
np.set_printoptions(precision=3, suppress=True)Simulating requests, difficulty, and both paths
The synthetic requests vary in length and difficulty. The router sees a noisy feature derived from hidden difficulty. The two generators give each request synthetic quality and latency values, with the edge score declining faster as difficulty increases.
PythonIn [3]Expand
@dataclass
class Request:
rid: int
n_tokens: int # prompt length
difficulty: float # hidden ground-truth difficulty in [0,1]
has_pii: bool # privacy-sensitive span present
language: str # 'en' or 'other'
def make_requests(n: int, rng: np.random.Generator) -> list[Request]:
reqs = []
for i in range(n):
n_tokens = int(rng.integers(20, 1200))
# difficulty increases with length and a random "hardness" trait
difficulty = np.clip(
0.15 + 0.0006 * n_tokens + rng.normal(0, 0.12), 0, 1
)
has_pii = rng.random() < 0.08
language = "en" if rng.random() < 0.85 else "other"
reqs.append(
Request(i, n_tokens, float(difficulty), bool(has_pii), language)
)
return reqs
requests = make_requests(2000, rng)ConsoleOut [4]Expand
Generated 2000 requests Mean prompt length: 605 tokens Fraction with PII: 0.066 Fraction non-English: 0.160
Our synthetic population has a spread of prompt lengths and a minority of privacy-sensitive and non-English requests. The ground-truth difficulty is hidden from the router; only the model-driven parts of the pipeline see it in simulation. This mirrors production, where difficulty is never observable directly and must always be inferred from proxies.
The two generators
Each path returns a synthetic answer score and latency. Both scores depend on difficulty, with a steeper decline on edge. The edge score includes a language penalty. Both latency expressions depend on prompt length. The cloud latency also includes a fixed network term.
PythonIn [5]Expand
def edge_generator(
req: Request, rng: np.random.Generator
) -> tuple[float, float]:
# Edge is fast, strong on easy/short, degrades on hard/long, weaker on non-English
lang_penalty = 0.05 if req.language == "other" else 0.0
base = 0.90 - 0.55 * req.difficulty - lang_penalty
quality = float(np.clip(base + rng.normal(0, 0.05), 0, 1))
latency_ms = (
20 + 0.08 * req.n_tokens + rng.normal(0, 4)
) # local prefill + decode
return quality, max(latency_ms, 5.0)
def cloud_generator(
req: Request, network_rtt_ms: float, rng: np.random.Generator
) -> tuple[float, float]:
# Cloud score has a smaller difficulty penalty and no separate language term.
base = 0.88 - 0.08 * req.difficulty
quality = float(np.clip(base + rng.normal(0, 0.04), 0, 1))
latency_ms = (
network_rtt_ms # round trip
+ 30
+ 0.05 * req.n_tokens # prefill at scale
+ rng.normal(0, 10)
) # serving jitter
return quality, max(latency_ms, 5.0)The two generators encode the core asymmetry: the edge's quality slope with respect to difficulty is steep (0.55), while the cloud's is shallow (0.08). For some easy requests, the simulated edge score is competitive. The wider gap on hard requests creates room for improvement if the router can identify them.
The privacy gate
The gate runs first and is deterministic. Here it enforces a policy rule: PII-bearing requests are redact_then_cloud_ok when redaction is enabled and local_only otherwise. Any request the gate marks local_only is ineligible for cloud routing regardless of the difficulty score.
PythonIn [6]Expand
REDACTABLE = True # PII may be eligible after redaction; no redactor runs in this example
def privacy_gate(req: Request) -> str:
if req.has_pii:
return "redact_then_cloud_ok" if REDACTABLE else "local_only"
return "cloud_ok"ConsoleOut [7]Expand
cloud_ok 1868 redact_then_cloud_ok 132
The gate count shows how many requests can be considered for cloud transfer without further action. A conditional verdict still needs verified redaction, and the simulated input contains no unconditional local-only requests with the flag enabled.
PythonIn [8]Expand
gate_order = ["cloud_ok", "redact_then_cloud_ok", "local_only"]
gate_series = (
pd.Series([privacy_gate(r) for r in requests])
.value_counts()
.reindex(gate_order, fill_value=0)
)
gate_counts_arr = gate_series.to_numpy(dtype=float)
gate_labels_arr = list(gate_series.index)
gate_frac_arr = gate_counts_arr / gate_counts_arr.sum()VisualizationOut [9]Expand

Most requests get the cloud_ok verdict. The PII-bearing requests receive a conditional verdict with REDACTABLE enabled. The notebook provides no redactor and keeps both PII-bearing categories on the device. To permit cloud transfer after redaction in a deployment, check that redaction succeeded on the actual payload.
The router: features, score, and threshold
The router uses token length, language, and a synthetic edge-confidence feature. We generate that feature by adding noise to a function of the hidden difficulty. A sigmoid maps a hand-set linear score into the unit interval. Treat it as a priority score for this simulation.
We sweep the threshold to trace the route-quality curve rather than hard-code an operating point.
PythonIn [10]Expand
def router_features(req: Request, rng: np.random.Generator) -> np.ndarray:
# Synthetic noisy confidence proxy.
edge_conf = np.clip(
0.75 - 0.35 * req.difficulty + rng.normal(0, 0.15), 0, 1
)
lang = 1.0 if req.language == "other" else 0.0
return np.array([1.0, req.n_tokens / 1000.0, lang, edge_conf])
def router_score(feats: np.ndarray) -> float:
# Hand-set weights for the example.
w = np.array(
[-1.2, 1.6, 0.7, -2.5]
) # longer, non-English, low-confidence -> cloud
logit = feats @ w
return float(1.0 / (1.0 + np.exp(-logit)))
score_rng = np.random.default_rng(42)
scores_by_request = {
r.rid: router_score(router_features(r, score_rng)) for r in requests
}ConsoleOut [11]Expand
Router score distribution: min=0.03 median=0.18 max=0.73
A higher score makes a request more likely to pass the cloud threshold. These weights assign higher scores to longer prompts, non-English prompts, and lower simulated confidence. Inspect the reported score distribution to see how many requests can be affected by changing the threshold. Whether their local answers are correct is a separate measurement.
End-to-end simulation with fallback
Apply the gate and threshold to each request. The simulation includes a pre-transfer availability check. If it declines a cloud-eligible request, the request stays on edge without an attempted upload. The notebook computes synthetic quality and latency for each path in a fixed order, and selects only the chosen path for reporting. Using the same seed for each policy gives each request the same potential outcomes and availability draw.
PythonIn [12]Expand
NETWORK_RTT_MS = 120.0 # representative mobile round trip
P_CLOUD_UNAVAILABLE = 0.02 # synthetic pre-transfer service unavailability
CLOUD_COST_PER_REQ = 0.0015 # serving $ / request in this separate simulation
BYTES_PROMPT_PER_TOKEN = 4
BYTES_COMPLETION_PER_TOKEN = 4
def simulate(
threshold: float, rng: np.random.Generator, network_up: bool = True
) -> pd.DataFrame:
rows = []
for r in requests:
g = privacy_gate(r)
score = scores_by_request[r.rid]
unavailable = rng.random() < P_CLOUD_UNAVAILABLE
edge_outcome = edge_generator(r, rng)
cloud_outcome = cloud_generator(r, NETWORK_RTT_MS, rng)
# Only unconditional approvals can leave the device.
want_cloud = g == "cloud_ok" and score > threshold
use_cloud = want_cloud and network_up and not unavailable
fallback = want_cloud and not use_cloud
if use_cloud:
q, lat = cloud_outcome
served = "cloud"
bytes_xfer = (r.n_tokens + 40) * BYTES_PROMPT_PER_TOKEN + (
50 + 20
) * BYTES_COMPLETION_PER_TOKEN
cloud_cost = CLOUD_COST_PER_REQ
else:
q, lat = edge_outcome
served = "edge"
bytes_xfer = 0
cloud_cost = 0.0
rows.append(
{
"rid": r.rid,
"difficulty": r.difficulty,
"gate": g,
"served": served,
"want_cloud": want_cloud,
"fallback": fallback,
"quality": q,
"latency_ms": lat,
"bytes": bytes_xfer,
"cloud_cost": cloud_cost,
"non_english": r.language == "other",
}
)
return pd.DataFrame(rows)ConsoleOut [13]Expand
Cloud fraction: 0.030 Mean quality: 0.624 Mean latency: 71.5 ms Cloud spend: $0.09 over 2000 requests Fallbacks: 0 requests hit the fallback path
At a 0.5 threshold, relatively few requests pass the score cutoff. The display counts successful cloud responses separately from requests that would have used the cloud but stayed on edge after the availability check. These fallback requests contribute their edge quality and latency. The simulation includes no post-upload failure or timeout costs.
Where the synthetic policy sends requests
Break down the same synthetic traffic by difficulty, language, and gate verdict to see what the aggregate hides. This exercise reuses the 2,000 generated requests. In a deployment, define the slices before evaluation and test the chosen thresholds on separate traffic.
With quality scores bounded between 0 and 1, a change confined to a slice that accounts for 5% of traffic moves the overall mean by at most 0.05, or five percentage points. A smaller shift in the mean can still hide a large loss inside the slice.
PythonIn [14]Expand
rng_rep = np.random.default_rng(11)
df = simulate(0.5, rng_rep)
hard = df.difficulty >= df.difficulty.quantile(0.75)
slices = pd.DataFrame(
{
"mean_quality": [
df.quality.mean(),
df[hard].quality.mean(),
df[df.non_english].quality.mean(),
df[df["gate"] != "cloud_ok"].quality.mean(),
],
"cloud_frac": [
np.mean(df.served == "cloud"),
np.mean(df[hard].served == "cloud"),
np.mean(df[df.non_english].served == "cloud"),
np.mean(df[df["gate"] != "cloud_ok"].served == "cloud"),
],
"p95_latency_ms": [
np.percentile(df.latency_ms, 95),
np.percentile(df[hard].latency_ms, 95),
np.percentile(df[df.non_english].latency_ms, 95),
np.percentile(df[df["gate"] != "cloud_ok"].latency_ms, 95),
],
},
index=["all", "hard (top quartile)", "non-English", "privacy-gated"],
)ConsoleOut [15]Expand
mean_quality cloud_frac p95_latency_ms all 0.624 0.030 114.733 hard (top quartile) 0.486 0.098 202.602 non-English 0.621 0.131 205.409 privacy-gated 0.620 0.000 110.288
The table shows the observed route mix for each slice. Interpret the pattern alongside the threshold, feature weights and unconditional transfer requirement.
Place each slice’s cloud fraction beside its mean quality. These describe one policy; changes in quality require a comparison on the same requests under competing policies.
PythonIn [16]Expand
slice_names_arr = list(slices.index)
cloud_frac_arr = slices["cloud_frac"].to_numpy(dtype=float)
mean_quality_arr = slices["mean_quality"].to_numpy(dtype=float)
pos_arr = np.arange(len(slice_names_arr))VisualizationOut [17]Expand

Requests can belong to several slices. A privacy-gated request stays on edge in this simulation, regardless of its score. Each displayed p95 describes its own slice under the measured policy.
The cloud path in this simulation includes a fixed 120 ms network term per cloud-served request. To estimate how routing changes a slice’s p95 latency, compare both policies on the same requests with matched simulated conditions and recompute the quantile for each policy. Path compute and request composition can also change the tails.
The route-quality curve
Sweep the threshold and plot mean quality, mean latency and serving spend against the fraction of requests served in the cloud. Compare the three plots at the same cloud fraction to choose a candidate operating point.
The curve characterizes the routing system: two systems with different routers, different edge models, or different traffic mixes will have differently shaped curves, and the shape tells you which lever to pull.
PythonIn [18]Expand
thresholds = np.linspace(
0.0, 0.30, 19
) # sweep across the region where the score distribution has mass
curve_rows = []
for t in thresholds:
local_rng = np.random.default_rng(11)
d = simulate(float(t), local_rng)
curve_rows.append(
{
"threshold": t,
"cloud_frac": float(np.mean(d.served == "cloud")),
"quality": float(d.quality.mean()),
"mean_latency_ms": float(d.latency_ms.mean()),
"cloud_spend": float(d.cloud_cost.sum()),
"bytes_mb": float(d.bytes.sum() / 1e6),
}
)
curve = pd.DataFrame(curve_rows)
plot_curve = curve.sort_values("cloud_frac", ignore_index=True)VisualizationOut [19]Expand

VisualizationOut [20]Expand

VisualizationOut [21]Expand

Across the sampled thresholds, larger cloud-served fractions correspond to higher mean quality and latency. Each successful cloud request has the same fee in this simulation, so serving spend rises proportionally.
Start with thresholds that meet the quality floor and fit the serving budget. Compare their latency, then check the candidate operating points on the traffic slices your application needs to serve. The plot uses one seeded population, and a different mix of requests can move the operating point.
Offline behavior
Simulate a full network outage using the same request scores and potential outcomes as the online run. Compare how many requests finish locally and how their mean score changes.
PythonIn [22]Expand
off = simulate(0.5, np.random.default_rng(11), network_up=False)
assert off["served"].eq("edge").all()
assert off["fallback"].equals(off["want_cloud"])ConsoleOut [23]Expand
Served on edge: 1.000 Unconditionally eligible requests above threshold: 61 Mean quality offline: 0.612
All requests are served on-device during the outage. The count in the second row measures preflight cloud intent: the gate returned cloud_ok and the score exceeded the threshold. The two assertions check that every request finishes on edge and that every request with cloud intent takes the fallback path. The intent count includes requests the online availability check might already send to the edge. Compare outcomes on this shared workload before measuring the policy on a different traffic mix.
Limitations and practical impact
A hybrid app can serve part of its workload on-device and reserve remote compute for requests that benefit from it. Measure those gains against the local-only and cloud-only baselines. Whether the combined policy meets its quality, privacy and cost requirements depends on the router, the eligible workload, and the fallback path.
But the mechanism also introduces a class of failure modes that are easy to miss in a lab demo and painful in production, and being honest about these is more valuable than the sales pitch.
The first and most under-appreciated failure is distribution shift in the router itself. The routing classifier is trained on some traffic mix (a particular app, language mix, user cohort, task distribution) and then deployed into a mix that drifts. A router has no natural feedback loop unless errors are labeled, and the errors that matter most are the ones it never sees: the hard request sent to the edge yields a quietly weak answer the user may not report.
Contamination and benchmark overfitting apply here too. The route-quality curve you measure offline is only as trustworthy as the slice coverage behind it; if the non-English slice, the privacy-gated slice, or the long-context tail is thin in your evaluation set, the deployed operating point is effectively blind there. This is why the slice-level validation above is not optional polish but central to trusting a router.
The practical remedy is continuous evaluation: sample live traffic, label it, and compare the live curve against the offline curve, treating divergence as an alarm rather than a curiosity.
Serial round trips can limit a layer split when link delay is large relative to compute and transfer time. Intermediate states also need the privacy checks described above. In a speculative split, mismatched acceptance probabilities or correction distributions can bias the generated tokens away from the target distribution.
A partitioned inference can have distributed state when a link fails. Specify which side owns committed tokens and what a retry restores. Use request routing with an edge fallback as a comparison, and test whether the partition improves your chosen latency, cost or capability metric enough to justify the extra state.
The third limit is that hybrid systems multiply the surface area you must evaluate and keep consistent: two models, two prompt formats, two decoding configs, a router, a gate, and a fallback path. Any drift between them (a prompt template update on one side, a quantization change to the edge model, a tokenizer mismatch) can silently degrade quality in ways neither model's own benchmarks will catch.
Audit the privacy gate as a security control. Test whether any path transmits documents marked local_only. Rehearse the offline path with the same transfer rules in place.
Evaluate the whole pipeline by request slice and under representative network conditions. The next chapter in Part XLIII: Small and On-Device Language Models develops this evaluation approach.
There is a final, quieter cost: hybrid systems are harder to reason about than either pure system, and that difficulty compounds over the lifetime of the product. Every new feature must answer "which side does this run on, and what happens if that side is unavailable?" Every reliability improvement to one model must be re-measured against the router's operating point.
Compare the hybrid system with both single-route baselines under the same quality, availability and transfer requirements. Then decide whether the measured gains justify maintaining the extra routing and fallback paths.
Summary
Hybrid edge-cloud inference is an orchestration problem: run a small model on the device and a large model in the cloud, and decide per request how to divide the work.
- Keep routing, partitioning, and fallback separate. Routing dispatches a whole request to one side; partitioning splits one inference pass across both; fallback defines degraded behavior when a primary path fails. They have different failure modes, privacy exposure, and evaluation.
- Route within the transfer policy. For eligible requests, compare the value of the expected quality gain with the extra service cost.
- Enforce transfer policy across the application. Check conditional redaction before sending and apply authorization and retention controls to payloads, intermediate states, logs and telemetry.
- Count network exchanges on the critical path. In the serialized layer schedule, each decode step requires an exchange. In the sequential speculative schedule, each verification round requires one. Compare total network and compute times on the target devices and links.
- Track network cost and cloud serving cost separately. They scale with different quantities (bytes vs. tokens) and are optimized differently.
- Fallback must be deterministic and tested. The offline path is what users hit when everything else is failing; rehearse it and measure the graceful quality drop.
- Validate per slice, not on averages. Route-quality curves and slice-level quality, latency, and cloud-fraction checks are the minimum evidence before trusting a router; the next chapter in Part XLIII: Small and On-Device Language Models develops that evaluation approach.
Hybrid inference does not make the small model bigger; it makes the deployment smarter than either model alone.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about hybrid edge-cloud inference.
Hybrid Edge-Cloud Inference
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!