Open-source softwareApache 2.0 · Open source

Stageplane

Distributed transformer inference across a trusted, expandable worker pool.

From thesis to implementation

Reference paper

Distributed Transformer Execution: Orchestrated Inference Across Heterogeneous Devices

Read the underlying architecture and analytical model. This project page documents the implementation, its privacy boundary and the recorded experiments.

Read the thesis
Version 0.1.0Apache 2.0Research implementation

One model, an expandable worker pool

Stageplane is my open-source implementation of distributed transformer inference on a trusted, heterogeneous worker pool. It separates model preparation, execution coordination and the workers that perform computation. A worker loads its assigned model stages instead of requiring every machine to load the entire checkpoint. Requests still execute the same ordered model: the system distributes its computation, not independent guesses from different models.

The current implementation is a runnable decoder-only serving system, with native transformer blocks, versioned artifacts, direct worker-to-worker activations, session state, replica selection and bounded recovery. It also provides an OpenAI-compatible text chat interface and a dashboard with a Three.js topology. The dashboard shows actual assignments and health; the diagrams on this portfolio page are explanatory illustrations, not a connection to a running cluster.

Its principal advantage is flexible resident capacity: several qualified machines can collectively hold stages that do not fit on one participant. More eligible workers can add stage replicas, alternative routes or spare capacity without changing the model’s chunk boundaries. This is horizontal expansion of the worker plane. It does not imply linear throughput scaling, faster generation for one user, or a highly available coordinator.

  • Keep model execution inside an organization-controlled pool, with authenticated transport and explicit trust boundaries.
  • Prepare and verify a model once, then distribute reusable stage artifacts to independent executors and workers.
  • Use compatible machines of different sizes, subject to each complete stage’s memory, compute and storage requirements.
  • Inspect readiness, per-stage timing, memory usage, token commitments and recovery instead of relying only on process health.
Repository evidenceProject README ↗Implementation map ↗

Three responsibilities, one execution contract

The producer resolves an open-weight checkpoint and writes a manifest plus hashed Safetensors artifacts. The executor registers that model, receives worker heartbeats, plans assignments, admits requests, selects routes and commits output tokens. Workers download only their assigned artifacts, verify them, materialize the appropriate native layers and retain the state needed by those layers. These responsibilities can run on separate hosts; the local development launcher also allows them to run as separate processes on one computer.

Control messages carry assignments, health, resource budgets and route authority. The data path carries token IDs and activation tensors directly through successive workers. Colocated stages execute locally. The final output head returns logits and timing metadata to the executor, which performs sampling and delivers the response. The coordinator therefore remains on the token-generation path, even though intermediate activations do not all pass back through it.

Implemented responsibilities and their operating boundaries.
ComponentWhat it ownsBoundary
Producer / bundle publisherCheckpoint resolution, complete tensors, stage boundaries, manifest and file hashesPublishing weights still requires permission under the model’s license.
ExecutorRegistry, placements, admission, sampling, route epochs, committed output and dashboard eventsSingle writer with SQLite deployment persistence; no consensus failover.
WorkerAssigned stages, native attention/recurrent state, resource admission and forwardingMust fit a whole compatible stage plus runtime, cache and workspace.
TransportREST, generic unary gRPC or WebSocket using one bounded binary formatReachable advertised endpoints and correctly configured authentication/TLS are required.
Repository evidenceExecutor ↗Worker ↗Protocol ↗

Explore Stageplane’s execution model in 3D

Loading interactive 3D…

Prepare once. Publish verifiable model stages.

Distribution accepts a Hugging Face repository with an optional pinned revision, a local HF-format Safetensors checkpoint, or a trusted HTTP directory with the required inventory. The manifest identifies the resolved checkpoint, tokenizer, configuration, layer intervals, file sizes and SHA-256 digests. Stage assignments pin the manifest digest, so a worker cannot silently substitute a different checkpoint or tokenizer configuration in the route.

Chunks contain whole contiguous decoder blocks. Embedding and normalization/output stages are handled separately; auxiliary weights are retained as artifacts. Stage count is independent of worker count. For the recorded Qwen3 4B configuration, one block per chunk produces 38 executable stages: 36 decoder blocks, embedding, and norm/output. Ten workers can host those 38 stages because a worker may own several stages. Adding another worker does not require slicing the checkpoint again.

Portable .stageplane ZIP64 archives and directory/catalog formats retain the same manifest. Consumers can import a local bundle or fetch one through HTTP, Git/Git LFS/catalog sources, or a public Google Drive file. Import verifies the declared artifacts before installation; it does not fetch the original checkpoint and repartition it. The bundle can therefore be prepared on a capable producer and reused by a separate executor. On real hosts, each worker needs its own assigned files; local hardlinks are only a same-disk testing optimization.

The runtime uses native Transformers layers and retains original tensor names, positions and indices. Supported adapters cover Qwen2, Qwen3, Qwen3.5 text, Llama and Mistral. This is adapter support, not a benchmark for every checkpoint in those families. Auxiliary multimodal weights are preserved, but image/video execution is not implemented. Quantized Ollama GGUF execution is also not provided: supported aliases resolve to original open weights, with no claim of numerical parity with an Ollama quantization.

Repository evidenceDistribution and manifest generation ↗Portable bundles ↗Native stage runtime ↗

Follow a request from prompt to committed token

A client sends text messages to the executor’s chat endpoint. The executor resolves an immutable model key, applies the matching tokenizer and chat template, and checks the combined prompt/output context budget. A route is usable only when every required stage has a ready replica. A worker declares readiness after verifying artifacts, loading its stage and executing a shape/finite-output fixture; whole-route numerical parity is established separately by tests.

During prefill, the embedding stage receives token IDs and successive blocks receive hidden-state tensors. Each worker retains the native attention cache or hybrid recurrent state for its own layers. The final head returns the last-position logits. After successful execution of the complete route, the executor samples and commits a token. Decode sends the new token through that ordered route while workers reuse their retained state. A later transformer block cannot compute its result before its input arrives.

Every forward envelope includes model revision, manifest digest, tenant/session identity, route epoch, token offset, context budget, lease and the ordered route. Workers reject incompatible revisions, stale epochs, invalid token IDs, unexpected shapes, expired leases and inconsistent offsets before executing that stage. Frames use a length-prefixed JSON header and a Safetensors tensor, rather than arbitrary Python object deserialization. The frame limit is 64 MiB and the tensor batch size is one; sufficiently wide or long inputs can hit the frame limit before the nominal context limit.

  • Default context budget: 2,048 tokens including requested output, configurable through STAGEPLANE_MAX_CONTEXT.
  • Default gateway admission: four requests; each worker allows eight resident sessions and one compute operation at a time.
  • Healthy sessions keep their selected route. Cancellation and completion release cache reservations; bounded expiry cleans up abandoned state.
  • Text chat supports messages, model, max_tokens, temperature, top_p, seed and stream. Unknown chat fields are rejected; tools, Responses API, multimodal inputs and continuous batching are not implemented.
Repository evidenceExecution and session protocol ↗Wire format ↗API contract ↗

Horizontal scaling means qualifying useful capacity

A new node registers its endpoints, resource budget, placement group and declared failure domain. The planner considers memory, storage, available CPU, a speed hint and observed stage costs. Weighted rendezvous placement makes assignments stable across membership changes. With multiple placement groups, a stage maps to one group and membership changes replan affected groups. An uncovered group remains unready rather than triggering movement throughout the cluster.

Replicas are additional copies of a stage on eligible workers with distinct declared failure domains. The requested count is a target constrained by capacity, not a promise that enough replicas have been loaded. A session uses one ready replica per required stage. Extra replicas can offer capacity for different sessions and alternatives after failure; they do not combine their CPU time to accelerate the same sequential stage. Three containers on one laptop are still one physical host failure domain, regardless of their node identifiers.

For an organization with 10,000 employees, begin with a qualified pool, not a route containing 10,000 devices. Inventory available memory, supported kernels, trust, network reachability and availability. Place whole stages on suitable hosts, keep enough reserve for caches and workspace, and expand bottleneck stages before adding arbitrary nodes. A small device is useful only if it can execute an assigned stage within the service objective; it may otherwise host coordination or supporting services. The current code has no automatic battery, thermal or foreground-application eligibility policy.

Scaling has several separate dimensions. Sharding can reduce the weights resident on an individual worker. Replication can supply alternative placements and more concurrency. Both add runtime and sometimes duplicated tied-weight storage across hosts. Neither removes the slowest-stage constraint, stateful session costs, network overhead or the single executor’s limit. Multi-host concurrent-load measurements are needed before claiming a particular user count, throughput gain or availability target.

Repository evidencePlacement and replica selection ↗Resource budgets ↗Loading-aware rebalancing ↗

Replicas protect a route only when state can be rebuilt

A replacement holding the correct weights does not automatically hold a conversation’s KV cache. Stageplane’s implemented recovery mechanism is committed-prefix replay. When a forward fails, the executor identifies and temporarily excludes the failed worker, advances the route epoch, finds a complete ready replacement route and replays the original prompt plus already committed output. Workers rebuild state under the new epoch. Tokens already delivered to the client are not resampled or emitted again, although computation can repeat.

Defaults bound the attempt: three executor retries, a ten-second replacement-readiness wait, a thirty-second chunk compute/queue deadline and a 180-second transport operation timeout. Recovery can fail when no ready replacement exists or the deadline is exceeded. The recorded ten-worker 50-millicore case demonstrates this distinction: memory fit and a deployed route did not make the timed-out chunk recoverable with one replica.

Draining changes new assignments while preserving stages used by live sessions. The latest loading guard also postpones resource-driven replans while a peer in the same placement group is loading, preventing temporary headroom changes from repeatedly moving stages during bootstrap. These are worker-plane controls. SQLite preserves deployment metadata across executor restart, but in-flight streams do not transfer to a new executor. Cache snapshots, proactive state replication and consensus-based coordinator failover remain extensions.

Repository evidenceRecovery contract ↗Retry and deadline tests ↗Live worker-loss test ↗

Privacy-focused deployment on trusted infrastructure

Stageplane provides a practical implementation for keeping inference within an organization-controlled worker pool. It can run from locally prepared artifacts, without sending inference requests to an external model API. Bearer authentication protects service access, non-loopback listeners require a token, and REST, WebSocket and gRPC support mutual TLS when configured with appropriate certificates. This is a privacy-focused deployment model with explicit trusted participants, not cryptographic private computation.

The executor’s operational records describe timing, shapes, stage assignments and token commitments without recording prompt or activation contents. Sensitive material nevertheless exists during execution: the gateway receives the prompt and retains committed history for replay; the embedding worker receives token IDs; subsequent workers process activations and own session state. TLS protects these values in transit, not from the worker executing them. Splitting weights does not make prompts unreadable or guarantee protection from a compromised host.

Manifest and file hashes detect mismatched or damaged artifacts. They are integrity checks against a trusted manifest, not digital signatures, publisher attestation or proof that a remote worker executed correctly. Safetensors and disabled remote model Python code reduce unsafe deserialization/code-loading exposure. Operators must still trust artifact sources and workers, control filesystem and backup access, and decide where model weights and transient session data may reside.

The current shared token grants both control and inference access. Internal tenant/session keys scope caches, but the public gateway serves one default tenant. Per-tenant keys, role-based authorization, certificate revocation/discovery, workload attestation and encrypted computation are not implemented. Development certificates cover localhost only. A real deployment needs workload-specific certificates with valid host names and an independently reviewed access boundary.

Repository evidenceDocumented trust boundary ↗Certificate-backed TLS test ↗Authentication and TLS configuration ↗

Latency: a cost to measure, not a benefit to assume

Low per-hop overhead is a design goal on fast, uncongested links. Keeping consecutive stages together can avoid a network transfer, while direct forwarding avoids routing every activation through the executor. But a complete response includes stage computation, serialization, memory movement, link delay, queuing, sampling and any replay. Minimal network overhead would not by itself imply minimal first-token or whole-response latency.

A single-machine test is useful for correctness, protocol overhead and resource-admission behavior. It cannot establish the performance of independent physical hosts: local worker processes and containers share CPU scheduling, memory bandwidth, physical RAM and the loopback or virtual network. More processes may increase contention without creating compute capacity. Conversely, moving to separate hosts adds genuine resources but introduces real link bandwidth, jitter and failure behavior. Neither improvement nor regression can be inferred from node count alone.

The latest ten-worker successful request attributed approximately 97.6% of its recorded per-token wall time to stage trace intervals. Those intervals include scheduling and memory effects, not just CPU arithmetic. The remaining time is not a pure network measurement. The result identifies a constrained CPU-backend experiment; it does not prove negligible network cost or predict GPU and multi-host latency.

Different measures answer different performance questions.
MeasureWhat to includeWhat it establishes
Time to first tokenAdmission, prefill, transfers, sampling and response deliveryHow quickly a user begins receiving output.
Inter-token delaySequential decode work, queues and transfersWhether streaming remains usable after the first token.
Accepted-request goodputConcurrent requests that meet declared quality and latency objectivesUseful capacity rather than raw registered-node count.
Recovery interruptionDetection, replacement readiness and committed-prefix replayThe user-visible consequence of a worker failure.
Repository evidenceTen-worker timing and trace evidence ↗Benchmark methodology ↗

Recorded validation: correctness, costs and failed limits

These results come from reports retained in the Stageplane repository, not a new benchmark performed by this website. The latest retained suite records 36 passing tests. Coverage includes native prefill/decode parity for five adapters, manifest and bundle integrity, protocol rejection, mixed-transport inference, OpenAI SDK streaming, replica recovery, retry bounds, resource placement and certificate-backed mutual TLS. Passing those checks establishes the tested behaviors, not production certification or performance on every supported device.

The native macOS Qwen3 4B comparison used the full BF16 checkpoint and the explicit bounded-f32 CPU kernel in both modes. That kernel converts bounded weight tiles for FP32 linear accumulation and returns BF16 outputs; it is not a comparison of vanilla BF16 kernels. Direct execution used two compute threads; four worker processes used two threads each, REST, one replica and verified local hardlinks. Each mode had a warmup followed by five measured requests. Generated token IDs matched in every trial.

Qwen3 4B, five local trials on one Mac. These are recorded observations, not multi-host predictions.
MetricNative directFour local workers
Median first-token latency0.936 s1.512 s
Median decode interval0.651 s1.389 s
Median whole request11.310 s19.380 s
Median output rate, including prefill1.415 tokens/s0.755 tokens/s
Observed aggregate peak RSS8.201 GB8.823 GB
Largest worker / direct process peak RSS8.201 GB2.699 GB
Generated-token agreementReferenceExact in all five trials
  • Four-worker result: the largest individual process used less measured RSS, while aggregate RSS and median latency increased. One distributed trial took 133.092 seconds. Five trials and sampled RSS do not establish stable p95 latency or account for all host compression/swap effects.
  • Ten Docker workers at 50 millicores each: all ten registered, no worker was OOM-killed, but inference failed with a chunk deadline and HTTP 503. There is no successful TTFT or throughput for that case.
  • Separate ten-worker comparison at one CPU core per worker: a single nine-token request completed with exact reference token parity. Server TTFT was 92.908 seconds and generation elapsed time was 639.133 seconds. This was a very slow functional success, not evidence of low latency or a representative workload benchmark.
  • Fifty-worker attempts did not complete inference. Low-memory tiers caused admission/OOM failures; a higher-RAM retry still exhausted physical Docker VM memory. Raising aggregate container ceilings did not create RAM. The higher-RAM capture was partial and is labeled as such in the source report.
Repository evidenceNative / four-worker report and raw results ↗Ten-worker results and CPU comparison ↗Retained 36-test output ↗

What a meaningful multi-machine evaluation needs

The next performance test should use physically independent hosts and declare the actual network topology, memory budgets, CPU/GPU kernels, model revision and precision. Start with a native baseline on hardware that can hold the model, then compare a fixed distributed topology. Separately vary worker count, stage placement and replica count. A result that changes operating system, kernels, CPU allocation and topology together cannot isolate the effect of horizontal scaling.

Run representative prompt/output lengths and several concurrency levels, with warm and cold routes recorded separately. Report failures alongside TTFT, decode delay, accepted-request goodput, peak memory and total resource cost. Add controlled link delay, bandwidth limits, worker loss and executor restart. Confirm generated-token or logit agreement under a declared precision policy and verify that replay does not duplicate already delivered output.

For smaller devices, measure whether a complete stage can load and execute within a useful deadline while leaving headroom for the owner’s work. A large number of devices with insufficient per-stage memory cannot collectively execute an indivisible stage in this backend. Active network profiling, host workload policies, continuous batching and warm-state recovery are potential improvements, not capabilities established by the current reports.

Repository evidenceImplementation / extension boundary ↗Reproducible local experiments ↗

Run the offline fixture before importing a full model

The repository supports Python 3.11+ and documents uv-based setup. Start with its tiny random checkpoint to inspect partitioning, routing and the dashboard without downloading a full model. The fixture validates the machinery; its generated text is not a language-quality result. The commands below follow the repository’s local fixture workflow and start the executor/dashboard on port 8080.

Open http://127.0.0.1:8080 after the local launcher reports readiness. Its dashboard settings accept the documented local development token. That token is for loopback testing only. The launcher owns its worker processes; Ctrl-C stops those services. This portfolio preview is separate and does not start a Stageplane cluster or consume model-serving resources.

Stageplane repository · local correctness fixture · shell
git clone https://github.com/karthikrameshdev/stageplane.git
cd stageplane
uv sync --extra test
source .venv/bin/activate

python -m scripts.tiny_checkpoint data/fixture
stageplane distribute data/fixture --store data/fixture-models --layers-per-chunk 1
python -m scripts.dev_cluster --store data/fixture-models --work data/fixture-run --port 8080
Repository evidenceInstallation and full-model setup ↗Producer-to-worker deployment guide ↗

Integrate through a familiar text-chat client

Applications can use the OpenAI Python client with Stageplane’s /v1 base URL for the supported models and chat-completions subset. The example uses an explicit server URL and token from the application environment, selects a model returned by the local executor and streams a short deterministic response. Set those environment values for your own instance; the snippet does not contact OpenAI’s hosted model API.

For a real network, provision a non-development token and mutual TLS, advertise worker endpoints reachable by other workers, and configure the client’s certificate trust where required. Client-protocol compatibility is narrower than complete OpenAI API compatibility: tool calling, image input, arbitrary extension fields and the Responses API are outside the implemented contract. Keep application retries distinct from the executor’s internal recovery so an ambiguous disconnected request does not silently produce duplicate work.

Supported text-chat streaming subset · python
import os
from openai import OpenAI

client = OpenAI(
    base_url=os.environ["STAGEPLANE_BASE_URL"],  # e.g. http://127.0.0.1:8080/v1
    api_key=os.environ["STAGEPLANE_TOKEN"],
)
model = client.models.list().data[0].id
stream = client.chat.completions.create(
    model=model,
    messages=[{"role": "user", "content": "Explain distributed inference briefly."}],
    max_tokens=32, temperature=0, stream=True,
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
Repository evidenceAuthoritative API contract ↗SDK integration tests ↗

Where Stageplane fits today

Stageplane is useful for exploring controlled model distribution, heterogeneous stage placement, private-infrastructure inference and explicit stateful recovery. A lab or engineering team can inspect every layer of the serving path, reuse portable model bundles and compare alternative resource layouts. Organizations interested in repurposing existing machines have a concrete implementation to evaluate rather than only a proposed architecture.

Version 0.1.0 is a research implementation. It is not a demonstrated production replacement for an optimized GPU serving engine, an internet-wide untrusted compute network, or a high-availability enterprise service. The current executor is single-writer, worker batches contain one sequence, and state recovery replays the committed prefix. Tensor parallelism, out-of-core operators, quantization kernels, continuous batching, speculative decode, split prefill/decode, MoE execution, encoder-decoder execution and multimodal inference are not implemented.

The practical next step is to evaluate a fixed, trusted multi-host pool with a real workload and a declared service objective. Add optimizations one at a time and preserve parity, failure behavior and cost evidence as the system changes. Horizontal expansion is the architecture’s opportunity; useful throughput, low latency and operational reliability are the outcomes to establish experimentally.

Repository evidenceImplemented mechanisms and future extensions ↗Apache 2.0 license ↗

Practical guide & interpretation

Stageplane distributes the stages of one open-weight transformer across trusted workers. Its producer, executor and worker runtime provide verified artifacts, direct activation forwarding, replicas and committed-prefix recovery. It supports horizontal worker expansion; local experiments establish tested correctness and resource limits, not multi-host speedup or guaranteed low latency.

Evaluate the complete serving path

Begin with the offline fixture, then one licensed full checkpoint at a declared precision. Reproduce reference output before changing placement or adding workers. Verify stage readiness, actual memory use and route coverage: registration or a successful deployment response alone does not mean a request can complete.

Treat per-worker capacity, request concurrency and end-to-end latency as separate measurements. Keep native and Docker results separate, retain failures, and compare independent physical hosts before attributing a change to distributed execution. The thesis explains the broader architecture and analytical constraints; this page records the implemented subset.

Questions & answers

Does adding workers make generation faster?

Not automatically. Extra eligible workers can hold more stages or replicas, but one token still traverses dependent stages. Network cost, slow workers, memory pressure and the single executor can limit throughput or increase latency. Horizontal expansion is implemented; useful performance must be measured on the intended topology.

Is Stageplane privacy-preserving against untrusted workers?

No. It supports privacy-focused operation within a trusted pool, bearer authentication and configurable mutual TLS. Workers process token IDs or activations and retain session state. There is no encrypted computation, remote attestation or complete multi-tenant authorization layer.

What do the recorded experiments demonstrate?

The retained suite records 36 passing tests. Qwen3 4B local runs demonstrate generated-token agreement and measured memory/latency costs. The ten-worker one-core comparison completed one very slow request; the 50-millicore and fifty-worker attempts failed. These are single-host experiments, not multi-host scalability or production benchmarks.

About this work

Written by , an AI platform engineer and independent AI and quantum researcher. This project walkthrough includes a compact interactive explanation; the text describes its assumptions and practical limits.

First published . Explanation updated .

All projectsPython · PyTorch · Transformers · FastAPI · Safetensors · gRPC · Three.js