# ModelOS design This file states the design the operator's words define. The words themselves are the raw record in the operator's instruction log (private), and they govern; the numbers below are quote numbers there. Where the code stands against this design is `docs/design-status.md`. What happens next, in order, is `docs/todo.md`. Only the coordinator edits this file (quote 37). The design adopted on 2026-11-01 and the path from it to here are kept unchanged in `docs/history/design-2026-11-01.md`. Where that record differs from this file, this file holds. ## 1. The goal and the bar - Performance first, with a significant advantage over existing systems; isolation is out of scope (41). The standard is an OSDI best paper (188). - The key scenes are Flash and the 27B (358), each built against its hardware ceiling (356, 376). - Every number has a receipt, and performance beats the best framework, built on that framework's own algorithms and policies (382, 388). No tuning before the algorithms match theirs (387). - One configuration and one shape a model, on real agent traffic, never synthetic fixed inputs alone (383). The 0.6B and 8B are not continued (383). - Built for fast change, so that agents can iterate the OS themselves: OS-level self-improvement (541, 543). ## 2. The thesis The OS is built around the execution semantics of the workload: model-specific rather than general, on real workloads, for inference and training (8, 9). The units a model runs in differ from processes and pages, and they change with load rather than being fixed (101): - work is a Request (in training, a Job) moving through Steps; - memory is tensors, KV blocks and Experts; - lifetime is a model's. A traditional OS has control but not the workload's semantics, so its policies are blind. A user-space engine has the semantics but not control of physical memory, copy engines or GPU page tables. ModelOS has both, so its policies can be richer and more precise (262, 265). Policies become functions between Steps that write tables; this is policy and mechanism separation applied to model serving. ## 3. The system: no Linux, one Rust core - ModelOS boots directly. Firmware or a bootloader loads its image and jumps into it; no Linux runs before or beside it (96, 108). - It runs in ring 0 with no process, virtual-memory, page or file abstraction (24, 96). - From the Linux source it keeps only early boot code compiled into ModelOS: the x86 boot header, the decompressor, E820 and ACPI discovery, starting the other cores. Driver code brought from Linux may stay as it is; the abstractions it brings that this design does not need are removed: processes, VFS and the page cache, sockets, the scheduler, kthreads, softirq and timers (269). - The runtime core is Rust wherever possible: the owner loop, Step engine, GPU control, memory and tiers, offload, policies, network and text (268). C stays only at the early-boot interface and where a vendor ABI header requires it. Python is for build-time tools, capture and evaluation, never the runtime. - Every device that takes part in inference runs under one mechanism, not only the GPU (5, 47, 66, 98). | Traditional abstraction | ModelOS | |---|---| | Process, thread | A Request (in training, a Job) is the unit of admission, scheduling, memory and cancellation. A Step is one round over a batch. Cores run Ops, and the owner changes what each core does between Steps. No threads, no context switch. | | CPU scheduler | At each Step the owner decides from load which Requests enter, how they are chunked, and which core or device runs each part. | | Virtual memory, pages, allocators | Model objects: tensors, KV blocks, Experts, gradients, Programs. The OS allocates them, moves them between VRAM, RAM and disk by load, and frees them with their Request, Step or model. Faults are a mechanism the OS may use on its model objects (169). | | File | Every model object has a current location: VRAM, RAM or disk extents. Moves are DMA Ops through polled queues. | | Socket, softirq, TCP/IP | A Request has a stream. A small TCP stack runs inside the owner's loop on a polled NIC ring. | | Interrupts, timers, RCU, workqueues | Polled completion words and rings, the TSC for time, one wake path for idle. | | GPU driver | Bring-up is captured and replayed at boot. After that, the OS drives channels and doorbells directly and manages VRAM and GPU page tables at run time; GSP stays as firmware, spoken to only where the hardware requires it. | | libcuda, Python, engine | The OS programs the GPU itself (109): it loads compiled kernels, builds launch descriptors and push buffers, maps memory through its own page tables, fences with semaphores and moves data with the copy engine. HTTP and the tokenizer run in the owner's loop. | ## 4. Objects and how they run - An **Image** is what a model starts from: Programs, CPU kernels, weights, tokenizer and an initial placement. - An **Instance** is a running model. Its placement, Programs in use, cores and, in training, its weights change while it runs. It can be saved back as a new Image. - A **Request** holds its slots, budget and stream. A **Job** is the same for training: forward, backward and optimizer Steps, with gradients that live for a Step (9). - A **Step** is built by the owner each round from the current batch, routing and placement, as a graph of **Ops**: GPU kernel launches, CPU kernels over a row range, data moves between tiers, network frames. - Activating a model is itself one Step of disk and DMA Ops, the same path for a native and a graph Image (374, 377). What changes with load: batch membership and chunking, every Step; the graph itself, since Expert routing depends on the data and work moves between CPU and GPU as their queues grow; placement, with hot Experts and KV moving up, cold ones down, and models becoming resident or parked; how many cores do what, down to sleeping when idle; which kernels run, with what grid and arguments, for each shape. None of this creates a process, takes a page fault or wakes a thread: it is Ops the owner posts between Steps. How it runs: every device has the same two calls, post an Op and poll for its completion. The owner core loops: poll the NIC ring, then TCP, HTTP, tokenize and admit; build the next Steps from load; poll completion words and advance them, ringing the GPU doorbell, posting moves and handing CPU kernels to workers; when a Step ends, detokenize and send. Worker cores spin on descriptor rings and run CPU kernels. Small model, offload and many models are the same engine with different graphs. ## 5. The framework (170 to 177) Layers, and different scheduling policies on them (170); the best and most general design, with little per-model adaptation code and nothing ad hoc (171); better than Strata (172); hardware mechanisms used where they help (173); the algorithms first (174). A general framework that is easy to extend at run time (399): a new model is data, and new policies and kernels join a running system without a rebuild. Nothing here names a model. 1. **Requests are tokens catching up.** A Request has tokens computed and tokens including speculation. Prefill, decode, prefix reuse and speculation are one rule. Admission has two levels: capacity (who is active, with memory reserved) and rows (who runs in this Step). 2. **A Program is the canonical GPU form.** A Program is a pushbuffer template with named patch points, one per architecture and shape class. Two producers make the same artifact: capture from a production engine, and composition from registered kernels. Both GPU paths stay supported (137), and the owner picks prefill or window for each Step at run time (377). Inside a Step everything dynamic is data. 3. **A Step is a small descriptor:** row map, table pointers, table version. Rows are data, so any mix of Requests and speculative lengths runs on one Program. 4. **Join replaces Select.** `Join(group, keys, strategy, table)` works on all keys of all rows at once. Strategies: `resident` (decided on the device), `probe` (hits in VRAM, a share over PCIe, the rest on CPU workers) and `scan` (stream a whole layer behind compute). A policy picks the strategy and writes the split table; the mechanism only reads it. 5. **State has versions.** A Step writes shadow state and `Commit(n_keep)` is an Op. Verify windows, draft KV, recurrent state, prompt checkpoints and parking all use it. 6. **Memory.** Object groups are declared by the Image as data. Tiers are VRAM, pinned RAM and disk; `Move` is a batched Op overlapping compute, published at its fence. One VRAM budget arbitrates between groups, and each Instance has its own VRAM and RAM budget, so one model cannot take memory from another (186). Park goes through `Move` and `Commit`, the tiers are one service, and every disk read takes one path (377). 7. **Policies produce tables.** The hooks `fill`, `observe`, `plan`, `route` and `batch` run between Steps and write tables the mechanisms read; they run on no token path. Each Instance names its policies. Every policy goes through a table (377). **Per-model code.** One catalogue entry per checkpoint; one declarative architecture graph per new architecture: layers, Join points, state groups and commit rules, over a kernel vocabulary. One composer in the OS turns a graph into Programs for any shape; no model has a composer of its own (171, 399). **Run-time extension (399).** An Image carries its graph and kernels, so a model is loaded as data. A policy is loaded into a running Instance and attached to its hooks; it runs between Steps and only writes tables. **Kernels.** No kernel, stand-in or fusion is written by us (204, 205). Variants are registered production kernels (Strata, ggml, cuBLAS, SGLang, vLLM), used unchanged, each declaring bit-exact or a tolerance. **Hardware mechanisms.** All are supported and wired into the runtime (169, 173, 265, 377): replayable GPU faults, GPU access counters, device semaphores at every rendezvous, runlist priorities and compute preemption, large GPU pages, several copy engines, the whole of VRAM mapped through the BAR with NVMe peer-to-peer, and CPU waits on a memory address. **Agent backbone, report-only.** An Op registry with one file per backend, frozen real inputs per Op, Step replay of a recorded event log on a null GPU, one compare table, and a ledger that keeps failures. ### Serving execution and migration (511, 513, 516, 525) Serving uses the existing Image, Instance, Request, Step and Op interfaces. The object ledger, tier moves, activation, parking and wake-up retain their existing ownership rules. Capture and graph composition produce the same artifact over registered production kernels. The service prepares one Program for each supported model and shape class. Each migrated shape meets standard A. Standard B measures whether the production primitives express the whole Step as one compute submission. - **A, owner replay.** During a Step the owner supplies only row mappings, tables and patch data. It neither rebuilds the graph, records commands nor resubmits compute during execution. Every migrated shape meets A. - **B, one compute submission.** The Step submits one compute Program. Move/COPY and CPU worker dependencies are declared at recording time and progress through the original Program, device and worker without an owner round trip. A worker may read dynamically routed expert IDs, prepare sources, post COPY and publish source-ready through a declared dependency. In native hybrid MTP, when the original kernels cannot consume the accepted keep count in the same Program, a worker advances the declared promotion Move using keep and next-input data in the same fence cycle. A shape without that full chain records B as unmet and uses the existing MTP operations through the migrated interface to meet A. The shape capability table records A and B independently. For each Step record owner admission, owner round trips, compute submissions, Move/COPY and worker posts, and owner readback followed by new command generation. Intermediate consolidation may reduce staging without satisfying B. The template is built once for an Image, graph version, supported shape class and vocabulary ABI. Instance binding resolves its declared patch points in the active Space and Context. Binding borrows the original channel, Mapping objects and exclusive slot. Subsequent Steps supply row data. The CPU copy of descriptors stays stable when the device writes its copy. Capture continues to supply supported templates during and after the migration. While Step N runs, the owner prepares the known part of N+1 in a separate binding slot. This includes candidate Requests, row capacities and immutable Program references. The slot does not own N's scratch or writer. The owner seals N+1 after observing the predecessor completion and committing its state. Both slots are charged to the existing ledger. If there is room for one, the same prepare, seal and launch interface can run serially. An accepted submission retains its slot and leases through its actual device fence. The planner uses one token budget for decode and chunked prefill in the same Step. It reports useful progress separately from candidate proposal rows and the physical row allocation of each pass. Shape classes declare the existing kernel and state limits. The speculation policy supplies per-Request advice based on live demand, spare rows, observed acceptances and cost. The planner allocates those rows once. When the table disables proposals, the original target pass still serves the Request. A later draft may proceed independently of a current answer once the current answer has a proven state Commit and its remaining readers are held by the Flight. KV pages and published radix prefixes are objects in the same memory tiers. The binding presents the original kernel's page table or an equivalent contiguous virtual view over those objects. A radix entry references committed state under its Version. A private writer keeps its pages or copy-on-write state through the fence. Recurrent state and draft history have their own state groups and promotion rules. A successful Commit publishes kept rows from one completed Step. A device failure resets the affected Instance through the existing path (560). Experts also use the object ledger. The policy uses measured source, PCIe and CPU costs to choose a split between available resident experts, transfers and CPU workers, following Strata's measured miss assignment and streamed fill (F1–F10 in `docs/algorithms.md`). Each source has a lease, a producer signal and a consumer release. Prefetch takes a charged staging slot while earlier compute runs. The declared source service may exchange routed keys and ready data with the CPU workers. The serving owner does not turn that exchange into per-group graph reconstruction or a new compute launch. These contracts follow the supported-shape replay and CPU overlap of SGLang, the shared token planning, paging and load-sensitive speculation of vLLM, and the radix and expert source mechanisms above. Dense, native hybrid MTP and Flash reuse their existing kernel and state operations. Dense consolidates the private encoding and binding cache. Hybrid MTP moves promotion behind declared dependencies where the existing kernels and worker can express the chain. Flash declares router, source, expert and state dependencies and records them into the Program. A reduction in host stages during migration is counted separately from one compute submission. `docs/design-status.md` tracks the current coverage. #### Component contracts The eight components below are module boundaries. A change to a component updates its direct callers in the same change. The interfaces use existing error, Object and Mapping types. | Component | Module | Files | Interface and prerequisites | Focused host evidence | |---|---|---|---|---| | C1 Architecture data | `modelos_core::model::graph` | `os/model/graph/{mod,schema,tests}.rs`, `tools/arch/`, `os/lib.rs`, `os/Cargo.toml` | `Graph::parse`, `Graph::shape_class` and `TemplateKey` describe architecture, shape capacity and ports. | MOSARC01 parsing, shape and port resolution, unsupported generated operations. | | C2 Composition and recording | `modelos_core::gpu::program` | `os/model/graph/compose.rs`, `os/gpu/program/` | `compose_program` resolves graph operands and emits registered operations into one `Sequence`. `Sequence::import_captured` records original packets. `ProgramTemplate` retains recorded commands and their relocation sites. | Real original and composed command operands, patch bounds and dependency slots. | | C3 Program binding and launch | `modelos_core::model::program` | `os/model/{mod,runtime}.rs`, `os/model/program/`, `os/engine/{step,step_tests}.rs`, `os/gpu/{mod,execution}.rs` | `install(key: TemplateKey, template: ProgramTemplate) -> Result`. `bind(program: ProgramRef, key: BindingKey, slot: BindingSlot, deps: StepDeps<'_>) -> Result`; `launch(step: PreparedStep) -> Result`; `poll(ticket: &mut StepTicket) -> Result>`. Uses the recording contract. | One accepted compute launch, same template with multiple bindings, descriptor isolation, true ticket drainage, cancellation and invalidation. | | C4 Overlap and unified row policy | `modelos_core::engine::policy::batch` | `os/engine/{mod,objects,owner_loop,policy}.rs`, `os/engine/owner/registry*.rs`, `os/engine/policy/batch/`, `os/engine/policy/{admission,draft,loaded,schedule,speculation}.rs` | `Planner::plan_next` selects the `BatchIntent` from current requests and pass budgets. The owner carries the actual `SlotLease` alongside that intent and gives both to C8 to prepare the Program. `speculate(cap: SpecCapacity, load: Load, out: &mut [ProposalAdvice])` supplies advice. | N+1 preparation while N is pending, slot and writer separation, invalidation at state transitions, per-pass capacity, and no-spare speculation. | | C5 KV, prefix and state | `modelos_core::memory::state` | `os/memory/state/`, `os/memory/prefix/`, `os/memory/tier/prefix.rs` and its leaves, `os/memory/mod.rs` and the state layout leaf | `reserve(request: Handle, demand: KvDemand) -> Result`; `KvReservation::view(range: MappedRange) -> Result`. `acquire_prefix(cache, tokens: &[u32]) -> Result>`; `KvReservation::commit_item(done: &CompletedStep, tokens, keep)` supplies the owner's charged batch to `commit_batch`. The same terminal Step authorizes discarding a drained private append. | Original extent growth and contiguous VA, page and radix lifetime, private writes, real-fence Commit, Instance reset on device failure. | | C6 Expert objects and Flash binding | `modelos_core::model::experts` and `modelos_models::flash` | OS side: `os/memory/tier.rs` and non-prefix tier leaves, `os/model/{join,experts}.rs` and their leaves, `os/engine/policy/{pcie,adapt,join}.rs`. Model side: `models/src/flash/`, `tests/flash_*` and Flash's registration in the shared Factory. | The OS side owns expert residency, placement, PCIe and CPU assignment, source leases and completion counters. The model side declares Route, source, COPY and ready dependencies in the Program, using C1 declarations, C2 recording, C3 launch and the C8 Factory. | Fixed table offsets and layer order, CPU and COPY completion in either order, retained sources through cancel and drain, captured and composed Programs. | | C7 Resource and activation lifecycle | `modelos_core::image::activation::resources` | `os/engine/image_activation/`, `os/image/activation/`, `os/engine/owner/{mod,loading,budget_tests}.rs` and owner README, `os/engine/policy/budget.rs` | `resource_plan(asks: &Requirements, facts: &RoomFacts, table: &BudgetTable) -> Result`; `reserve(plan: &ResourcePlan) -> Result`. `activate(ticket: ActivationTicket, reserve: AdmissionReservation) -> Result`. `ready_facts() -> ReadyFacts`. Consumes C5 state and C6 `ExpertRequirements` as values in `Requirements`, alongside C7 room facts and the budget table. Returns granted expert pool and staging capacity. | Check/reserve/release the same geometry, charge each held expert backing once, preserve suspended ticket and source, let a fitting Image proceed, drain accepted I/O and Move. | | C8 Native model binding and shared registration | `modelos_models::activation` | `models/src/{lib,activation,verify}.rs`, `models/src/activation/`, `models/src/{qwen3,qwen3_5}/`, `models/Cargo.toml` and native fixtures. Flash's Factory registration is part of C6. | Existing Factory and Model ports supply `execution_graph(class: ShapeClassId) -> Result>` and `state_contract() -> StateContract`. Uses the preceding contracts. Flash registers through this shared adapter. | Actual Image and original ABI binding, generated operand roles, output and Version contract, supported per-shape availability. | C6 describes actual expert pool and staging geometry before activation: `ExpertRequirements` carries the admitted shape's staging slot count and the allocation asks by tier. C7 uses those facts for room, reserve and budget accounting in the same grant, including attach and wake. Accepted source work remains with its owner until its completion or release is collected. During a Step, `SourceLeases` takes slots from the granted pool or staging capacity. C6 owns assignment, current free slots, victims, I/O progress and release. C7 publishes granted capacity so per-layer preparation uses existing slots. It does not acquire room for each group or infer source readiness from the grant. `ReadyDependency` identifies the declared producer, release and retained row scope. A completion must carry the source and worker outcome before `observe` credits an adaptive replacement. **Execution validity (560).** The owner invalidates or rebuilds affected prepared Steps, bindings and plans in the same turn that parks, wakes, moves or cancels an Instance or Request. The GPU and declared workers return one Step ticket, their fence and one completion record with the outcome and outputs. Version identifies published KV and prefix state. Internal layouts and COPY operands follow from construction. Remove activation generations, planner epochs, duplicate binding identities and runtime Stale checks; transport handles still identify requests. A device failure resets the affected Instance through the existing path after collecting accepted work. #### Migration and confirmation Copy the existing implementation into its component module, adapt it to the new interface, switch its production and test callers, and delete the old code in the same change. No compatibility layers: callers move to the new interface in the same change and the old code is deleted. A module's `mod.rs` exposes its interface and keeps implementation leaves private. Remove forwarding layers and tests that only exercise them. Focused unit tests cover the principal behaviors and failure paths. - **Dense and overlap.** Bind the existing dense native Program to the new launch and planner. Confirm descriptor and Mapping ownership, next-Step preparation, actual launch count, cohort width and charged memory across short requests, B128, 8B and park/wake. - **KV and native hybrid.** Wire KV and radix state, per-pass row planning and MTP through the new interface. Preserve delta growth, retained activation, kept rows and promotion semantics. Record target, verify and draft counts, prefill position, state restoration and tier bytes. Advance an answer separately from a future draft after Commit. - **Flash expert dependencies.** Record resident Route/JoinRows/Tail, Probe with known sources and dynamic Probe routing using declared dependencies. The worker reads routed IDs and the Join table, writes order, bounds and counts, prepares sources, drives COPY and publishes readiness after data and table writes are visible. C3 holds sources, staging and flags through actual worker, COPY and compute drainage. Keep route output, group tables and staging at declared Program slots. A group of 16 experts can remain the unit of staging. One Program per layer is intermediate progress toward one compute submission for the whole Step. Preserve both capture and composition and the original numerical and Commit behavior. Record F4's second PCIe table, F5's tail skip and F2's landed replacements separately from owner replay and compute submissions. Record owner round trips, COPY and worker drainage, source retention, fill overlap, activation and charged bytes for each supported shape. - **Consolidation.** Remove duplicate phase construction, source lifecycle helpers, private caches and duplicate resource calculations. Each change runs the focused host tests of the modules it touches. GPU checks run at most once an hour, 30 minutes each, beside development (538, 552), with `run20.sh` on the existing scenes: coherent output, and latency and throughput against the receipts in `docs/numbers.md` and `results/index.jsonl`. Failed runs and partial results are kept. Work happens in temporary detached worktrees from `origin/main`, merged and removed within three hours (532). ## 6. The scene and the key models - **The scene (225):** a multi-model GPU host, serverless-style. At the same SLO, how many models one GPU holds, against vLLM's sleep mode, CRIU and fast loading. - **Flash** runs against Strata on Strata's own algorithms and policies (`docs/algorithms.md`): its prefill Program, device plan, the PCIe-or-CPU choice for missed Experts, the adaptive tier, the draft policy and the prompt cache. - **The 27B** runs against the better of vLLM and SGLang, starting from their MTP speculative decoding and their prefix cache for agent sessions. - ModelOS then adds what only it has: one VRAM budget across models, copy engines beside compute, Commit-based checkpoints, fast park and wake. - **Budget first (182).** Each scene gets a budget per phase from its strongest baseline and the hardware floor before code; the ceilings are in `docs/design-status.md` part 11. ## 7. Engineering form and how the work runs - No compatibility layers: callers move to the new interface in the same change and the old code is deleted. - One execution path at any time, and the code base only shrinks (549): a change that adds a path switches every caller and deletes the path it replaces in the same change. - The code base goes to half of its 2026-11-30 size (226,857 lines of Rust in os and models) with complete function (558). Checks stay only on data that enters from outside, HTTP requests and device results; COPY ranges and ownership are not checked. - Adding a model and optimizing performance are easy (162). No unnecessary gate, check or refusal (157). What does not fit the design, and old code that misleads, is removed at once (293, 304). The code is organized as the best open-source projects are, with mature kernels and no confusion (371, 386). The form is `docs/engineering.md`. - One deployed image and base and one test framework (105, 106). The execution-layer migration uses the temporary detached worktrees specified above (532). No extra clone, branch, stash or revert (321). Every step is committed and pushed on its own (141). - The coordinator does the design work itself (375). The execution-layer migration follows the component ownership above. - The order: the design matches the operator's words first, with nothing measured until it does (370); then the algorithms match the best framework's (387); then every number gets its receipt; optimization comes last (366). Every hour the coordinator reports the full current design and its gaps (370).