# Remaining Strata port: status, divergences and call sites Everything here is verified without a GPU. Items are numbered as in the port brief. Oracle = the Python server and engine under `engine/strata`. ## 1. Vision over HTTP | Piece | Rust | Oracle | | --- | --- | --- | | Image parts, three dialects | `control-plane/src/chat.rs` (`image_url`), `messages.rs` (`image` blocks), `responses.rs` (`input_image`) | `serve/frontend.py` `_parts_of`, `_image_source`, `images_of` | | Template with picture items | `prompt.rs` (`Part`, `render_with_images`) | `serve/chat_template.jinja` | | Encoder client, cache, `ENC` protocol | `control-plane/src/vision.rs` | `serve/server.py` `Vision`, `tools/vision/strata_vision.cpp` | | Pad expansion, SVE1 files, M-RoPE positions | `crates/serving-policy/src/vision.rs` (existing) | `Service.prepare`, `generate.cpp` | | `GENI` line | `wire.rs` (existing) | `StrataEngine.generate` | Flow of a request with pictures: parse the part in the dialect adapter (all three reduce to a Responses `input_image`), `render_request` writes `<|vision_start|><|image_pad|><|vision_end|>` per picture and returns the sources in prompt order, the prompt is tokenized, `expand_images` encodes the pictures (holding `Vision::gate`, the mutex the worker also holds for every generation, so encoder and engine never share the GPU), turns each pad that follows `<|vision_start|>` into one pad per image token (a pad anywhere else stays literal text), concatenates the SVE1 files into a per-request `req-*.sve` and puts its path in `Generate.embeddings` (`GENI`). The reasoning-budget wrap-up pass re-sends the same embeddings. The file is removed when the last clone of the request is dropped. Configuration: a top-level `vision` object `{exe, mmproj, model, gpu, threads, max_tokens, cuda_device}` (as in the Python config). It needs an engine and refuses `lazy_load` (`lazy loading is text-only`). `strata-vision` starts before the engine, stops when the engine is unloaded and starts again before the next load. `/props`, `/v1/status`, `/api/health` and `/v1/models` report `images`/`modalities`/`architecture` accordingly. Goldens: `control-plane/tests/fixtures/golden/vision_dialects.json` is recorded from the real Python handlers and template by `gen_goldens.py vision_dialects`; `tests/vision_http.rs` replays all fourteen requests over HTTP against the mock engine and a stand-in encoder (`tests/fixtures/fake_vision.sh`) and compares prompt text and picture order. `crates/serving-policy` already golden-tests the base64 decoder, sources, expansion and position table. Deliberate divergences: 1. WebP, TIFF, AVIF and other formats `stb_image` cannot read are refused with a clear 400. Python converts them with Pillow; the Python-free serving path has no decoder for them. 2. A fetched `http(s)` image is capped at 64 MiB and a network failure is a 400 naming it (Python: no cap, an unhandled `URLError`). 3. `req-*.sve` files are deleted with the request (Python leaves them in its temp directory). 4. `count_tokens` / `input_tokens` render the prompt with one pad per picture and never start the encoder, as the Python `_count_tokens` does; the true count only exists after encoding. 5. Local file paths are accepted as image sources exactly as in Python. This lets an API client name any file the server can read as an image (the bytes only reach the encoder), so run the server behind an API key. 6. The Chat adapter is stricter than Python's: image parts only in user messages, unknown part keys rejected. An image beside a `tool_result` in a Messages user turn is kept (Python drops it). ## 2. Reasoning budget on the live path The budget was already wired when this item started (`wire::ReasoningPlan` built by `responses.rs::reasoning_plan`, executed in `worker.rs::generate`: count thinking tokens with `serving_policy::reasoning::BudgetTracker`, send `STOP` at a clean point, discard the tokens until that pass's `DONE`, deliver the wrap-up tokens, re-submit `prompt + segment + wrap-up` with `max_new - generated`, report one combined `DONE`); `docs/offline-port.md` still called it open. What was missing was evidence on that path, because `reasoning_budget_oracle.rs` replays the pure port (`reasoning_budget::run`), not the worker: * `control-plane/tests/reasoning_budget_live.rs::the_live_worker_matches_python_service_run` plays the 288 non-cancel, non-empty-prompt cases of the real-`Service.run` golden through the real worker supervisor and a scripted engine process (`tests/fixtures/scripted_engine.rs`, compiled with `rustc` at test time; it honours `STOP` between tokens) and compares every engine request (prompt, `max_new`), the finish reason, the completion tokens and the delivered text with Python. A mutation of the budget comparison fails it at case 2. * `the_budget_applies_on_the_responses_http_path` runs `/v1/responses` (buffered and streamed) through the real router, tokenizer and template: reasoning, wrap-up text, answer, `output_tokens`, and the second engine request. Not applicable: the Chat and Messages adapters pin thinking off (`reasoning: none`), so `reasoning_budget_tokens` has no effect there; the Python server accepts it in every dialect because it thinks by default. ## 3. MTP with non-greedy sampling (host side) Oracle: `engine/strata/src/program/generate.cpp` (the `--serve` request setup at 5362-5382, the verify loop at 5489-5620), `include/strata/core/coupled_draft.hpp`, `MtpDrafter::set_draft_sampling/set_draft_history`. Already in the tree (not touched): Philox, the sampler chain and the coupled draft arithmetic (`crates/sampler-ref`, fixture-tested against the Original headers), `original_sampler.rs` host helpers, the actor's `CoupledDraftHost`, `OriginalSpecController` (`coupled` flag, exact-match acceptance), `OriginalServeEngine`'s history-staged check. New: * `crates/sampler-ref/src/serve.rs` - `ServeSampling`: `req_sp` construction (greedy iff `temperature <= 0`, `seed == 0` takes one steady-clock tick, `min_p` clamped, `penalty_last_n >= 0`, `counter = 0`), `window(p, consumed, window)` (counter `p`, the `T x hist_n` literal penalty rows), `draft_history_due` (the exact `hist_n > 0 && mtp.coupled() && !eos && produced < max_new` condition), `draft_history` (ring base), `draft_params` (`coupled_ready && !greedy && temperature > 0`), `draft_counter`, plus `window_rows` (the `T` rule with the confidence floor) and `settle_window` (acceptance and the emit loop with eos and `max_new`). * `crates/sampler-ref/tests/serve_loop.rs` - the whole serve loop on a toy model with a noisy, optionally subset-headed draft: 768 combinations of sampler settings (top_k / top_p / min_p / the four penalties up to the 4096 cap), prompts, window sizes, draft chains with and without a confidence floor, coupled and argmax drafts, and the seed-0 clock fallback. The speculative token stream equals plain sampled decoding in every one; with a draft equal to the target every coupled draft is accepted and argmax drafts are not. Mutating the window counter or the draft counter (`cell + 1`) fails the suite. * `crates/leleka-runtime/src/qwen_forward/original_sampled_serve.rs` - `SampledServe`: the same for the cuda-driver types (`SamplerParams` blob, `DriverWindow` with the history to upload), cross-checked against `original_sampler.rs` (`penalty_rows`, `coupled_hist_base`, `target_params`, `request_params`). Its tests run in `crates/sampler-ref/oracle/run_port_host_tests.sh` (macOS) and as ordinary crate tests on Linux. Call sites for the serve host (nothing in `backend.rs` or `original_serve_*.rs` was edited): | Where | Call | | --- | --- | | request start, after `request_sampler(..)` | `SampledServe::new(¶ms, clock_seed(), actor.coupled())`; `verifier.set_sampling(s.driver_params())`; `verifier.set_history(s.hist_n())`; `actor.set_draft_sampling(s.driver_params())` | | `OriginalServePort::run_window` | `s.window(position, consumed, inputs)` -> `NativeHeadSampling { position, params, history, history_len: hist_n, enabled: true }` | | `OriginalServePort::stage_draft_history` | only when `s.draft_history_due(eos, produced, max_new)`: `actor.set_draft_history(consumed, next)` | | `OriginalServePort::draft_committed(.., coupled)` | `coupled = s.coupled_active()` | | `backend.rs` `generate_mtp_resume` | drop the `sampling is unavailable with MTP` branch and pass the `request_sampler` result to the port | Still GPU-bound: the device sampler and verifier assets were sealed on 2026-10-15 (nvcc 13.2.86), but nothing above has run on a device yet; the host sampler of the plain path (`step_sampler.rs`) remains the only live sampled path. ## 4. Rust owners for the kernels no Rust code launched | Kernel | Pure half (existing) | New | | --- | --- | --- | | `native_flash_attn.cu` | `native_flash_attn.rs` (admission, geometry, FP64 spec) | `ClosedKernels::native_flash_attn_short`: literal `native_flash_attn::admit` on the operands, then `<<<24, (32, 4)>>>` | | `s_gemv.cu`, `s2_gemv*.cu` (17 entries) | `s_gemv_legacy.rs` (planners, summation-order models, shim-executed golden) | `ClosedKernels::s_gemv` / `s2_gemv` over a planner `Plan`, including the dynamic shared memory of the split kernels | | `device.cu` `poison_kernel` | `device_arena.rs` (`poison_launches`) | `ClosedKernels::poison_f32`, sliced at `0x7FFFFFFF` blocks, one drain | * `crates/cuda-driver/src/closed_kernels.rs` (any host): programs, zero PTX pins (`Unpinned` refusal), the entry signature tables, argument slots (`flash_slots`, `s_gemv_slots`, `poison_slots`), operand byte counts. Tests check every entry against the checked-in `.cu` text (parameter kinds, `__launch_bounds__`, the macro-generated S-form entries) and every planner output against its entry (`crates/cuda-driver/oracle/run_closed_kernels_host_tests.sh` runs them on macOS through a shim crate; on Linux they are ordinary crate tests). * `closed_kernels_gpu.rs` (Linux + `cuda-driver`): the driver half on the generic KAR launcher. The only FFI change is `Api::launch_closed` (adds the dynamic shared-memory argument; `launch_kar_levels` calls it with 0). A block of up to three dimensions was already supported there, so the "2D block" extension in the brief reduced to this. `cargo check --target x86_64-unknown-linux-gnu --all-targets -p leleka-cuda-driver --features cuda-driver` passes. * `closed_kernels_gpu_smoke.rs`: three `#[ignore]`d smokes (`closed_gpu_*`): the poison pattern; flash attention against the FP64 specification for eleven widths with and without mask plus the invalid-step refusal; the S-form GEMVs replaying the shim-executed golden (bit-exact on the exact cases, 1e-4 relative otherwise, because nvcc may contract the multiply-adds the host shim does not). * `docs/cuda-seal-plan-additions.json`: the three entries now list `closed_kernels.rs` / `closed_kernels_gpu.rs` as consumers and `PINS[0..=2]` as the fields to fill. The recorded file hashes must be recomputed when sealing. Everything is OFF: no engine path selects these programs and every pin is zero, so the first `open` fails closed before any driver call. Not done (needs nvcc and a GPU): compiling the three `.cu` files, freezing the pins, running the smokes. The "misc" kernels of `mmq_original_prefill_misc.cu` already have their owner (`mmq_original_prefill_misc.rs`), so only the poison fill of `device.cu` was open. ## 5. KAR routed / prefill experts: feasibility note (decision: not ported) **What the brief calls them.** The Original-side local patch of 2026-10-06/07 that lets an explicit, default-off experimental arm of the C++ engine take every routed expert row from the KAR GPU component (`gpu/kar`, the "KAR miss callback") instead of from the native bank: `STRATA_NEXT_KAR_PREFILL=1` (prefill dispatches the grouped expert rows to the callback) and `STRATA_NEXT_KAR_ALL_ROUTED=1` (additionally the target's native routed storage, cache slots and staging rings are not allocated). The patch's own provenance note calls it "an experimental quality arm, not full compressed-model residency or a qualified speedup". **What is missing from the imported tree (this branch).** `engine/strata/` is the pinned upstream snapshot and has none of the patch: * `include/strata/core/experimental_routed.hpp` (the admission profile `validate_experimental_routed_profile`, `dispatch_experimental_all_routed` with its input/output validation, `dispatch_experimental_routed_window`), * `include/strata/prefill/experimental_experts.hpp` (`dispatch_grouped_experts`, the grouped, batch-of-8 prefill dispatch), * the call-site hunks: `src/core/verify.cpp` (+52 lines: the early multi-token callback before any native lookahead, an absent native tier), `src/prefill/prefill.cpp` (+123: the allocation mode that omits the routed GU/MMQ/staging buffers), `src/core/expert_source.cpp`, `src/program/generate.cpp` (+93: option parsing and admission), and the header edits (`expert_source.hpp`, `verify.hpp`, `prefill.hpp`), * the contract tests `tests/kar-all-routed-contract.cpp`, `tests/kar-prefill-contract.cpp` with their scripts, and the CI workflow. **The earlier note ("the local-patch source has to be located first") is out of date: it is located.** It exists in this repository's object store, only on the remote-tracking branch `origin/codex/stra10-bounded-kar-cache-gitea` (commits `33f075f` "explicit bounded batched prefill backend" and `b6563e3` "isolate target native routed storage in explicit mode", based on the import commit `4013e0c`; neither is an ancestor of this branch). `git show b6563e3:engine/strata/include/strata/core/experimental_routed.hpp` prints it and `git diff 4013e0c b6563e3 -- engine/strata` is the whole patch (about 230 changed lines in the four `.cpp` files plus the two headers). The Rust port has no counterpart of the `gpu/kar` miss callback either: what exists is `KarExpertSource::routed_mlp` (KAR level 2..5 decode on CUDA, `NativeBackendConfig::kar_expert_source`), which feeds the preview path's `MoeExpertStage`, not the Original serve path (verifier window MoE, grouped prefill MMQ, CPU pool). **What can be done from what exists.** Only the pure half: the two headers are about 200 lines of host-only contracts (flag parsing, the admission profile, finite/range/duplicate-expert validation, `kind == 3` ownership, grouping offsets, the batch limit of 8), and the authors' C++ contract tests can be compiled from the git objects on a dev machine to produce goldens, the way the other `experimental-ref` oracles were made. That is about a day of work with a full oracle, and it would be dead code: the consumers (a native-bank-free verifier window and a native-bank-free prefill carve) live in the sealed GPU paths and cannot be validated without a GPU run. **Decision.** Do not port. The arm is a quality experiment of the earlier Strata-next line. It requires `--expert-cache 0`, `--pcie-frac 0`, one GPU, a fixed prefill chunk and no CPU pool (each a throughput loss against the product configuration), it keeps the MTP drafter's native experts anyway (so it can claim no VRAM saving), and nothing in the charter's milestones consumes it. If a compressed-residency product is wanted later, the entry point is `KarExpertSource` plus a KAR owner in `original_verify_window_moe*.rs` and `original_moe_prompt_device.rs`, designed against the Rust owners rather than transcribed from the C++ patch; keep the patch only as a reference for the contracts above. ## 6. Multi-GPU verify stage handoff: feasibility note (decision: not done) **Scope in the Original.** `Verifier::set_stage(layer_begin, layer_end, handoff_in, handoff_out)` and `set_next` (`verify.hpp:104-118`, `verify.cpp:191,436,853,1230,1395-1423`): a verifier runs layers `[lb, le)` of every window. A stage that does not start at layer 0 reads the previous stage's residual `R` (hc x n_embd), pending write `bo` (n_embd) and `inject` (hc) per token (`handoff_floats`) from mapped pinned memory instead of embedding the tokens; one that does not end at the last layer writes them and has no head; `run`, `commit`, `wait_commit`, `window_logprobs` and `copy_logits` chain into `next_`. It is one piece of the layer split of `docs/MULTI_GPU.md`. **What the port has.** `OriginalVerifier` loops all 48 layers and has no stage bounds, no hand-off buffers and no next-stage owner (`PORT-GAPS-MODE17.md`). Around it the layer split needs the rest of that document, none of which exists in Rust: a second CUDA context with its own streams, graphs and doorbells (the driver `Context` is thread-confined and `GPU_ORDINAL` is process-global, so two contexts on one thread need explicit context switching), a session and KV per stage (`session.cpp`), a prompt pipeline across stages (a chunk flowing through the cards, 1.5 GB of prefill buffers each), an expert cache and adaptive swaps per stage, the MTP drafter and the head on the last stage, per-stage checkpoints for the conversation and prefix caches, the `--layer-split auto` placement search over the expert profile, and the WDDM pin caps. **Cost and value.** The verifier slice alone (stage bounds in the window planners, the hand-off read and write, forwarding on the last stage) is small, perhaps two days, and it has a one-GPU check: the Original runs both stages on one device (`--layer-split K --split-device 0`) and compares bit for bit with the unsplit window, so the handoff could be validated on the single RTX 5090. On its own it delivers nothing a user can run. The usable feature is the whole list above: weeks of work that can only be qualified with two cards on one host (this project has one card per machine: the 5090 server and the 3080 laptop), for a product whose targets are single-GPU hosts (the profiles are `rtx5090-32g` and `rtx3080-16g`). The Original's own measurements say a second card helps when the routed experts do not fit the faster one (+18-20 % on prompts, decode on par); the 5090 profile already keeps a 50 GB resident host bank and a VRAM expert tier. **Decision.** Nothing implemented. Revisit only if a two-card host becomes a product target; then do the verifier slice first, behind the one-device bit-exact check, before any of the surrounding work. ## 7. `/api/requests` monitor and the extra `/metrics` fields: done `control-plane/src/request_monitor.rs`, `hardware_view.rs`, `prometheus.rs` and `app.rs` `metrics_document`; the reference behaviour is `Service.begin_request` / `request_records` / `metrics` in `engine/strata/serve/server.py` and `serve/test_monitor.py`. The contract, the differences from Python and the Prometheus series are in `docs/api-contract.md` ("Monitor members, Prometheus text and `GET /api/requests`"). Tests: the `request_monitor`, `hardware_view`, `prometheus` and `metrics` unit tests and `tests/backend_worker_http.rs` (`the_request_monitor_*`, `metrics_carry_the_python_monitor_members_and_a_prometheus_view`). Not carried over: the `/api-monitor` HTML page and per-request `queue_s` / `load_s` attribution. The telemetry block comes from NVML or, where `libnvidia-ml` cannot be loaded (WSL2, containers), from polling `nvidia-smi` (`leleka-memory/src/smi.rs`). ## 8. Bring-up diagnostics are silent in production Review of every `eprintln!`/`println!` compiled into the production libraries of `leleka-runtime` and `leleka-cuda-driver` (found with `cargo clippy -p leleka-runtime -p leleka-cuda-driver --lib -- -A clippy::all -W clippy::print_stderr -W clippy::print_stdout`, which skips test code): no `DBG` / `PROBE` / `PREFILL-*` print fires without an explicit opt-in. The unconditional ones were already routed through `bringup_trace!` (`LELEKA_BRINGUP_TRACE`) by the earlier gating pass; what remains outside that macro is one of: | print | fires only under | | --- | --- | | `PREFILL-ALLOC`, `PREFILL-STALL`, `PREFILL-SITE` (`compute_drain.rs`) | `LELEKA_PREFILL_ALLOC_TRACE=1`, `LELEKA_PREFILL_STALL_TRACE=1` | | `DBG mtp ... graph`, `DBG graph window/commit` (`mtp_original_full_drafter.rs`, `original_verify_schedule.rs`) | `LELEKA_SERVE_PROFILE` (`host_profile::enabled`) | | `DBG profile`, `DBG window`, `DBG vram`, `DBG tier request` (`original_serve_profile.rs`, `original_serve_host.rs`, `original_serve_stack.rs`) | `LELEKA_SERVE_PROFILE` | | `DBG spec-stats`, `DBG spec-trace` | `LELEKA_SPEC_STATS`, `LELEKA_SPEC_TRACE` | | `DBG verify-profile` | `STRATA_VERIFY_PROFILE` | | `DBG seed`, `DBG seed-coverage` | `LELEKA_SEED_TRACE` | | `DBG ple` (`input.rs`) | `LELEKA_TRACE_PLE` | | `DBG residual*`, the logprobs line (`original_serve_native.rs`) | `LELEKA_TRACE_RESIDUAL=`, `LELEKA_TRACE_LOGPROBS=` | | `PREFILL-R` (`executor_original_prompt.rs`) | `LELEKA_TRACE_PREFILL_R` | | `driver error: ...` (nine `driver_error` helpers) | `LELEKA_TRACE_DRIVER_ERRORS` or `LELEKA_BRINGUP_TRACE` | | `CUDA-TRACE ...` (`libc-shim/src/cuda_trace.rs`, Windows), `STAGE-VERIFY` (`mmq_original_host_stage.rs`) | `LELEKA_BRINGUP_TRACE`; `LELEKA_CUDA_TRACE_SYNC`, `LELEKA_CUDA_TRACE_CALLBACKS`, `LELEKA_STAGE_VERIFY` for the heavier modes | | `LELEKA_MMQ_NO_STREAMK` / `_FILE`, `LELEKA_MMQ_STREAMK` / `_FILE`, `LELEKA_FORCE_SMS`, `LELEKA_RING_SERIALIZE` / `_FILE` / `_COPY_FILE` / `_CMD_FILE`, `LELEKA_CHUNK_DRAIN` / `_FILE` (STRA-235 diagnostics, no output) | opt-in switches of the group MMQ grid and the prompt copy ring; sm_86-class devices avoid the stream-K grid by default | | `PREFILL-PROFILE`, `PREFILL-COMMANDS` (`prefill_profile.rs`) | `LELEKA_BRINGUP_TRACE` (its own `enabled()`) | | cpu pool notices and the router-lookahead summary (`original_serve_pool.rs`) | the non-default pool modes (`LELEKA_CPU_POOL`, `LELEKA_CPU_POOL_FENCE=job`, `LELEKA_CPU_POOL_LOOKAHEAD=on`) | | `OriginalNativeOutput::load: ... refused`, `DenseWeightCache::new_original_prompt_capacity: ... refused`, `leleka-ple-reader-unavailable`, `native embedding: cannot pin`, `resident RAM budget ...` | operator-facing notices on a refusal or a fallback, not diagnostics (kept) | The test-only smokes (`backend_original_serve_*smoke*.rs`, `_replay.rs`, `_arms.rs`, `*_gpu.rs`) print `DBG`/`PROBE` lines as their evidence and are not compiled outside `cargo test`. A source scan, `crates/leleka-runtime/tests/bringup_prints_gated.rs`, now fails when a production `DBG`/`PROBE` print has neither `bringup_trace!` nor one of the opt-in switches in the lines above it. The only source change of this pass is one comment in `original_serve_stack.rs`; behaviour is unchanged.