Files
leleka/docs/architecture/independent-nvidia-engine.md
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

20 KiB

Independent NVIDIA engine: architecture handoff

Status: architecture proposal, awaiting Tech Lead review. This is a source inventory and migration design; it does not claim a working inference engine.

Decision already made by the project owner: Rust owns the runtime. Strata is an upstream source for selected behavior and algorithms, not a build, runtime, or deployment dependency. The new implementation repository is the private Gitea repository git@vezha.io:para/leleka.git; its remote is reachable and was empty when checked on 2026-10-05. Keep this architecture record and the existing Strata provenance in strata-next; implement the replacement in Leleka.

1. Options and recommendation

Option Benefits Costs and risks Decision
Keep the current C++ Strata engine and Rust control plane Reuses the most inference code; shortest path to the existing Qwen setup Production remains coupled to Strata's executable, --serve wire format, build and model profile Reject as the target; preserve only as the behavior/reference baseline
Rust-owned engine and scheduler, with CUDA C++ kernels behind a narrow internal ABI Rust owns model loading, tensors, routing, KV, admission, scheduling, lifecycle and API integration; existing CUDA kernels can be ported in measured steps Initial CUDA kernels still need the CUDA build toolchain; FFI ownership, shape and stream contracts need tests Recommend. This meets the owner's independence goal without pretending CUDA kernels can be safely rewritten in one pass
Rewrite all runtime and kernels in Rust immediately One main language and fewer long-term language boundaries Rust does not remove the need for CUDA/PTX; kernel parity and performance need separate proofs, and a big-bang rewrite delays a usable runtime Reject as the first migration stage; replace individual kernels only after parity and paired performance gates
Rust host with a separate Python/C++ serving engine Can compose existing libraries quickly Keeps a second runtime, protocol bridge, process lifecycle and extra packaging dependencies; violates the desired self-contained production runtime Reject for production. Python remains allowed only for offline research/evaluation where useful

This is a staged C++/Python-to-Rust migration, not a literal syntax translation. Move ownership of serving behavior first. Keep CUDA C++ only at a small kernel boundary while each kernel is ported or replaced against a numeric oracle. The shipped Linux runtime should need an installed NVIDIA driver, not the CUDA toolkit, a compiler, Python, or a Strata installation. Build-time CUDA toolkit use is acceptable. The release gate must inspect the final artifact's ELF dependencies to prove the driver-only installation claim.

2. Existing coupling inventory

The current repository is an intermediate product. These references explain what Leleka must replace; they are not a requirement to copy the imported tree.

Area Current source What it means for independence
CPU engine build scripts/build-cpu.sh configures CMake from engine/strata/ Remove this from the Leleka build and release path
CUDA engine build scripts/build-static-cuda.sh compiles target strata; its checks run the imported engine's ELF audit and --help Replace the engine source and qualify the new binary; do not call --help an inference test
Hosted CUDA package workflow .github/workflows/linux.yml builds the actual Strata engine; later steps combine and package it Leleka CI must build its own runtime from pinned sources and retain build provenance
CLI image license deploy/Dockerfile.static-cli copies the imported engine license into the CLI-only image Preserve required notices for any source actually reused; remove the Strata license copy only when no Strata code is shipped
Worker process boundary worker.rs accepts an executable and arguments; the worker process is supervised and generation is sent to it Replace the serving child process with an in-process Rust InferenceBackend; keep process isolation as an optional later boundary
Strata serving wire wire.rs explicitly implements the resident Strata --serve stdin/stdout protocol Delete this adapter from the replacement path; the public API must not inherit this private wire protocol
Embedded engine package embedded_engine.rs stores and starts a separately built engine executable, and says model/shared libraries are not bundled Package the Rust engine directly; model assets remain independently acquired and SHA-verified
Qwen-only model prep native_model.rs has one RuntimeProfile::Qwen4expFlashNext; GGUF/native pack helpers are preparation code, not an inference implementation Keep Qwen import/preparation behind a model adapter or offline tool; define a versioned model descriptor instead of extending a single-profile enum
Build-time GGML C code build.rs compiles a vendored pinned ggml-quants.c plus ggml_bridge.c; ggml_bridge.rs uses it for GGUF quant conversion This is a preprocessing dependency rather than serving inference. Move it to an optional offline packer crate so the shipped serving CLI does not need a C compiler or GGML bridge
Offline scripts compare-real-tokenizer.py, prepare-keyless-routing.py, and pack smoke scripts import Strata tools or inspect Strata sources Replace or retire them one at a time; keep them out of serving and never silently treat their output as production support
KAR experimental adapters gpu/kar/README.md documents a narrow experimental expert component and explicit limits Port the file/container concepts and proven kernels selectively; do not port the Strata callback as the new runtime boundary
Provenance docs/upstream.md pins the imported Strata SHA and describes subtree update procedure Preserve this historical record unchanged. Add a separate Leleka source/provenance manifest; do not rewrite the old upstream identity

responses.rs is a Rust protocol layer that currently consumes worker/tokenizer types. Its role can remain in the Rust control plane, but it must call the new backend API rather than depend on Strata's tokenizer, worker executable or wire format. The public /v1/responses, SSE, cancellation, auth and health contracts need their own replay tests; the model engine should not implement HTTP semantics.

3. Leleka backend boundary

Ownership

Leleka is a Rust workspace with at least these logical crates:

  1. leleka-api: versioned request, model descriptor, capability, memory-plan, error and event types. No CUDA or model implementation dependency.
  2. leleka-engine: Rust-owned model loader, tensor/layout registry, tokenizer integration, router, KV allocator, scheduler, sampling and lifecycle.
  3. leleka-cuda: safe Rust wrappers over a narrow private CUDA C ABI. It owns device/context/stream/event/buffer lifetimes; kernels cannot retain pointers after the wrapper's borrow or stream completion.
  4. leleka-server: HTTP/API translation, SSE, auth, cancellation and observability. It talks to leleka-api, not to model-specific tensor layouts.
  5. leleka-tools: offline conversion/evaluation only. It is not a dependency of the serving binary and may contain Python during the transition.

The initial backend is compiled into the process. Rust trait objects are not a stable cross-version plugin ABI; if external native plugins are needed later, define a layout-safe C ABI with explicit size/version fields and opaque handles.

Versioned contract (proposal)

leleka-api has an explicit API_MAJOR and a capability-schema version. Incompatible event, layout or error semantic changes increment the major version. Release metadata records engine commit, CUDA kernel source digests, toolchain, model adapter version and supported quantization IDs.

The backend contract contains these operations:

  • capabilities() -> CapabilitySet: architecture IDs, quantization/layout identifiers, attention/KV forms, limits, cancellation and streaming support.
  • load(ModelArtifact, ModelConfig) -> LoadedModel: validate artifact digest, descriptor, hardware/driver constraints and required tensors before publishing a ready model. Partial failure drops all owned allocations.
  • memory_plan(ModelDescriptor, RequestDemand) -> MemoryPlan and admit(MemoryPlan) -> Result<Admission, InsufficientMemory>: account for weights, cache, KV, scratch/workspace, simultaneous slots and safety margin; reject before mutation when the request cannot fit.
  • health(), readiness() and model_metadata(): readiness is false until weights, kernels, tokenizer and required runtime state are verified.
  • generate(Request, CancellationToken) -> Stream<BackendEvent>: stream token IDs and optional token bytes/diagnostics plus a single terminal result. The server maps those events to Responses/chat SSE. The stream has bounded backpressure and a request ID.
  • cancel(request_id) and drain(deadline): stop future work, cancel active work at a documented safe boundary, then release allocations exactly once.
  • unload(): reject new admissions, drain/cancel according to policy, release model/KV/cache ownership, then report unloaded.

Errors are typed: UnsupportedArchitecture, UnsupportedQuantization, UnsupportedCapability, ArtifactMismatch, InsufficientMemory, DriverIncompatible, LoadFailure, Cancelled, DeadlineExceeded, DeviceLost, BackendFault, and ProtocolViolation. No unsupported format may silently fall back to a lossy conversion. Every accepted generation emits exactly one terminal event (completed, cancelled, length, or failed); after a terminal event no more deltas for that request are legal. Error details are machine-readable and safe for API mapping; raw prompts, model tensors and secret values are never diagnostics.

The model descriptor is immutable per loaded model and includes architecture family/revision, layer and expert geometry, router semantics, attention/KV layout, tokenizer/template digests, tensor names/shapes, quantization scheme, packing schema, context bound, required auxiliary heads and artifact digest. Model-family names alone do not authorize tensor reinterpretation.

4. Capability and optimization portability

Concept Reusable part Model/quantization-specific part Safe behavior until qualified
Compressed weights resident in VRAM Block store, byte-range validation, residency planner and bounded scratch allocation Archive/tensor mapping, scale/group geometry, codebook and dequant arithmetic Accept only exact versioned pack schema and tensor digest; otherwise reject or use an explicitly supported native format
Bounded expert cache LRU/admission/eviction accounting and metrics Expert IDs, dimensions, routing semantics, packed payload size and CUDA tile geometry Cache only verified experts from the loaded descriptor; evict or fall back to a verified native path
KAR decoder Container reader and generic bounded decode orchestration after schema validation Current KAR top-down group-32 expert shape, levels, quant bytes and F32 accumulation; current code does not establish model-quality parity Experimental opt-in only; reject shape/schema mismatch; never claim full-model residency or speed from the component probe
Expert routing and scheduling Queue, batching windows, cancellation, fair admission and cost accounting Router weights, top-k, shared/routed experts, normalization, correction bias and token-to-expert mapping Use the model adapter's exact reference routing; unsupported router versions fail closed
KV allocation/streaming Page/slot allocator, budget policy, asynchronous transfer lifecycle and accounting MHA/GQA/MLA tensor layout, head sizes, position encoding, quantization, scales and block packing Select only a declared KV format supported by that adapter; otherwise reject or use its verified lossless/default format
PLE Sparse table paging/cache and row-request abstraction Table meaning, lookup geometry, packing and exact association with model layers/experts Disable unless manifest binds PLE artifact to model digest and adapter validates geometry
MTP/speculative decoding Draft/verify scheduler mechanics and accepted-token counters Trained draft heads, tokenizer, logits alignment, depth and model-specific verification semantics Disable by default; enable only for an artifact declaring compatible heads and after exact greedy/quality gates
Value-only KV / lossy KV Cache policy experiments and measurement hooks Quality behavior depends on the exact model, workload, context and cache policy Keep disabled; the existing Qwen V-only pretrained quality screen failed
Tokenizer and chat template Byte streaming and API event mapping Vocabulary, merge rules, special tokens, template and tool-call grammar Require matching digests; no approximate tokenizer/template fallback

“MoE-compatible” means the model uses sparse experts, not that its weights, router, attention, tokenizer, cache, quantization or speculative heads can be reused. Every matrix row must be keyed by a model and pack manifest, not a broad architecture label.

5. Candidate model families and evidence gaps

These are adapter/evaluation candidates, not supported models.

Candidate Public artifact and license evidence Compatibility and the first port-specific work Evaluation feasibility and blocker
Mistral Mixtral-8x7B-v0.1 Official model card lists Apache-2.0 and describes a sparse MoE; official weights are available Conventional attention plus sparse expert feed-forward gives a second-vendor router/weight-map adapter. Validate safetensors mapping and select a documented quant pack; do not reuse Qwen IQ3 conversion Public reference weights and a reference runtime make tensor/logit and greedy-token oracle generation feasible. No Mixtral tensor map, converted artifact, quality corpus, or protocol trace is currently checked in; 32-GB fit at useful context depends on quantization and remains unproven
DeepSeek-V2-Lite Official model card lists 16B total / 2.4B active parameters, safetensors and the DeepSeek model license; the paper describes MLA + DeepSeekMoE Distinct latent-attention KV state and DeepSeekMoE routing require a separate attention/KV and router adapter. Published model context is 32K; do not assume Qwen's 256K/512K profile Public reference weights/paper permit an adapter smoke and deterministic oracle suite. The model license has use-based conditions; compliance review and the exact license must accompany any distribution. No converted artifact or project quality/protocol evidence exists; 32-GB quantized launch and long-context target are unproven

If the owner wants the first extra family to be easier to serve on a 32-GB card, Qwen3 MoE is a lower-variance adapter step but does not demonstrate a second vendor or distinct attention family. Mixtral and DeepSeek-V2-Lite are therefore the stronger architecture-coverage candidates; lawful artifact selection and evaluation-data availability remain explicit gates.

6. Migration and qualification stages

  1. Repository and interface foundation (Leleka). Create a clean Rust workspace in the new Gitea repo, record licenses/provenance, pin Rust/CUDA build inputs, define the API/capability schema, and add mock-backend lifecycle/cancellation/memory-admission tests. No model or GPU is needed.
  2. Qwen correctness path. Add a Qwen adapter and one explicit lossless quant/pack path. Compare tokenizer IDs, tensor loads/dequant bytes, routing, logits and greedy token IDs against the pinned reference. Then replay sanitized real protocol traces: non-streaming, SSE terminal events, tool calls/results, cancellation, timeout, reconnect and worker/device failure.
  3. Linux NVIDIA runtime artifact. Build a reproducible self-contained executable/image in CI. On a clean Linux host with an NVIDIA driver, audit ELF dependencies, load the model, verify readiness, exercise API/cancel, stop/restart and rollback. Host installation must not need Strata, Python, CUDA toolkit or compilers. Model assets remain separately pinned and integrity-checked.
  4. Port optimizations one at a time. Start with bounded expert residency, then KV policy/streaming, then exact-format KAR work, then optional PLE/MTP. Each stage has a numeric oracle and its own isolated quality gate; lossy or experimental arms remain off by default. Port CUDA kernels only when exact output/tensor requirements pass and paired end-to-end measurements justify keeping them.
  5. Model-family expansion. Land Mixtral adapter + exact quant path and protocol/quality suite; separately land DeepSeek-V2-Lite with MLA/KV tests and license review. Passing one family does not imply support for other MoE variants.
  6. Cutover. Preserve Strata as the reference until the same sanitized API, model, quality and deployment suites pass. Run a controlled paired workload comparison with engine/model/config/cache/token counts recorded. Canary on a separate port/service with artifact rollback; keep the last accepted runtime selectable until the new build passes gates. Only after acceptance remove Strata from the Leleka production/release path; retain historical source provenance in strata-next.

No stage claims performance from compilation, synthetic kernels, mock-backend tests, source inspection, or model loading alone. Required project profiles remain 1 x 512K and 2 x 256K on the stated target; 1 x 256K is an interim local profile and cannot stand in for them.

7. Immediate implementation work breakdown

The next implementation tasks belong in Leleka, after this handoff receives Tech Lead acceptance:

  1. Establish clean repo/CI and the versioned leleka-api crate with a mock backend; verify no Strata import/build/runtime dependency.
  2. Move the Rust control-plane event/API contract behind leleka-api; add lifecycle, cancellation, single-terminal-event and admission tests.
  3. Split offline GGUF/tokenizer preparation from the serving build; pin source and artifact digests, with no production Python import.
  4. Add the Rust-owned engine/model-loader skeleton and CUDA safe-wrapper crate; first acceptance is CPU/mock behavior plus CUDA driver/toolchain contract, not GPU inference.
  5. Implement one Qwen lossless model path, exact numerical/token parity, then run its real NVIDIA/protocol/quality gates on a host explicitly reserved for qualification.
  6. Create separately scoped Mixtral and DeepSeek adapter tasks only after the corresponding legal artifact, supported quantization and evaluation corpus are pinned.

These are proposed bounded work items, not evidence that the deliverables already exist. The new repository was empty at the time of this handoff; no model files, traces, credentials, build artifacts or user workload data are copied into it.