Author SHA1 Message Date
Pavlo Ratushnyi 5310d7042f Merge claude/debt-final-ctx5: the architecture gate reads past cfg(test) mod declarations and finds static cells by type; 49 needless allow(unused_imports) and dead glob re-exports removed; exceptions carry kept:/debt: reasons (STRA-338)
Rust port / port-typecheck (push) Successful in 1m4s
Rust port / port-linux-tests (push) Failing after 2m52s
Rust port / port-oracles (push) Successful in 4m34s
Rust port / port-fast (push) Successful in 4m36s
Linux / verify (push) Failing after 5m14s
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Product / product (push) Failing after 14m51s
2026-11-24 08:53:08 +01:00
Pavlo Ratushnyi 75e28ca110 deploy: drop the HIDDEN flag of the supervisor, a process cell that was written by --hidden and never read (STRA-338)
The console is hidden by winsys::hide_console right where the flag was stored; nothing in the workspace loads supervisor::HIDDEN, so the cell and its exception entry go. cargo check -p leleka-deploy --all-targets passes.
2026-11-24 08:51:58 +01:00
Pavlo Ratushnyi 219238cd08 architecture gate: read the whole file after a cfg(test) mod declaration, find static cells by type, 64 new exceptions with reasons (STRA-338)
The scanner stopped at the first '#[cfg(test)] mod x;' of a file, so the code below was invisible. It now skips only the item under a test-only cfg (an inline mod body, a declaration, a fn, a use; any(test, feature) is not test-only) and reads on.

process-global counted the type name OnceLock/LazyLock/OnceCell, which also matched instance fields (six exceptions existed only for that) and missed Atomic*, Mutex, RwLock, Once, Cell and RefCell statics, thread_local! included. It now counts a static whose type is a cell or a workspace type that holds one (derived per crate and its dependencies), and static mut. Eight exceptions that only excused instance fields go; the rest of the file's hits are re-judged.

Newly visible: 123 static cells in 58 files, 15 allow(unused_imports) in 6 files and the engine settings::process() cell (read at about 78 sites). Each gets an exception whose reason starts kept: (the boundary that forces it) or debt: (what removes it); the settings cell is the largest debt and is not removed here because the engine does not compile on Windows. Entries 173 -> 229, baseline stays empty. 11 new self-tests (39 in all).
2026-11-24 08:51:58 +01:00
Pavlo Ratushnyi d9c0c87dcf Narrow the dead glob re-exports of the module splits: pub use x::* becomes use x::* or pub(crate) use x::* (STRA-338)
Where the split left pub use x::* over items that no outside module can name, the compiler said the glob re-exports nothing pub. The glob now has the visibility its items really have: plain use where they are pub(self), pub(crate) where siblings reach them (model.rs file_download, libc-shim launch_interposers). One glob of backend-api scripted.rs was dead and is deleted. 7 globs of control-plane stay with their allow: the compiler calls them unused in the lib build and the lib test build of control-plane cannot be built on Windows, so a test use cannot be ruled out.

cargo check --all-targets on backend-api, control-plane, gateway-domain, gateway-text and libc-shim: no new warning, no new error (the one control-plane lib test error is the pre-existing std::os::unix use).
2026-11-24 08:51:58 +01:00
Pavlo Ratushnyi e79179a255 cuda-driver: the copy ring asks its arena for the stage slot count by static dispatch, not through a dyn view (STRA-338)
admitted_slots coerced the read lease to &dyn RingArena only to call stage_slots on it. RingArena::stage_slots(read) is the same method of the same impl without the vtable; the Ring keeps its own dyn field, which has its exception entry.
2026-11-24 08:51:57 +01:00
Pavlo Ratushnyi c1734bc7c4 cuda-driver: the expert tier probe names what it takes from its parent instead of use super::* (STRA-338)
The probe module is compiled under cfg(any(test, feature = "expert-tier-probe")), so it is production code of that feature and the glob import counts for the gate. The 16 names it uses are listed; cargo check --all-targets with features cuda-driver,expert-tier-probe and with cuda-driver alone gives no new warning.
2026-11-24 08:51:57 +01:00
Pavlo Ratushnyi 651ed44e90 Drop 49 allow(unused_imports) that no compiler warning needs (STRA-338)
The re-exports left by the mechanical module splits carried a blanket allow(unused_imports). 49 of them cover nothing: cargo check --all-targets on backend-api, control-plane, gateway-domain, gateway-text and libc-shim gives no new unused-import or glob-import warning without them. 39 others in those crates still silence a real warning and stay; the 8 in desktop-core (engine-host) could not be checked because that crate needs the engine, which does not build on Windows (STRA-390), and stay too.
2026-11-24 08:51:57 +01:00
Pavlo Ratushnyi 682c582f8a Merge claude/debt-final-ctx4: request counters, adaptive-tier tuning and the VRAM ledger leave the process cells; vague exception reasons fixed (STRA-338)
Rust port / port-typecheck (push) Successful in 1m46s
Rust port / port-linux-tests (push) Failing after 3m30s
Rust port / port-fast (push) Successful in 6m23s
Linux / verify (push) Failing after 7m48s
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Rust port / port-oracles (push) Successful in 5m34s
Desktop foundation / core (ubuntu-latest) (push) Successful in 5m6s
Product / product (push) Failing after 30m51s
2026-11-24 07:52:28 +01:00
Pavlo Ratushnyi 4619a91367 architecture.json: the engine timer exceptions say what each reading is for (STRA-338)
Eight exceptions of the instant-now ratchet in leleka-engine-qwen35-cuda ended in a deferral ("which is the S14 follow-up"), and one of them was wrong: pcie_share_controllers.rs does not feed a log line, because PcieLag and PcieAuto read the wall-clock duration of the PCIe leg and of a round as the input of their control law. Seven reasons now say that the reading is a measurement that only feeds a log line or a counter, and the controller entry says that its timing is the control input, that both controllers are opt-in (LELEKA_PCIE_AUTO=lag|on, set by no shipped profile) and that their unit tests drive the control law through round() without the clock.
2026-11-24 03:56:38 +01:00
Pavlo Ratushnyi 4ef84275b1 cuda-driver: the VRAM allocation ledger belongs to the Context, not a process cell (STRA-338)
The per-call-site ledger of LELEKA_VRAM_LEDGER is now part of what a Context retains: Context::allocate and the DeviceBuffer free note into the ledger of their own context, and the engine reports through Context::report_vram_ledger, so the OnceLock singleton of vram_ledger.rs and its architecture.json exception are gone. The operator switch stays an EnvSwitch and the default is unchanged (off: one cached bool read per allocation); with the switch on, each context now accounts for its own allocations instead of every context of the process sharing one table.
2026-11-24 03:53:15 +01:00
Pavlo Ratushnyi 47d831ec62 engine: the adaptive-tier tuning is a field of the tier configuration, not a process cell (STRA-338)
ExpertTierConfig now carries AdaptTuning (minimum routed count, margin, decay) parsed once with the tier switches; the residency pool, the cross-layer estimate and the seed ranking take it as a value, so the OnceLock of split_group_pcie.rs and its architecture.json exception are gone. The production default is unchanged (the values still come from LELEKA_ADAPT_MIN_COUNT, _MARGIN and _DECAY with the same fallbacks), and the line for an invalid LELEKA_ADAPT_DECAY is now printed when the tier configuration is read instead of at the first adaptation.

Provenance of two comments that left ExpertTierConfig::off() so that the function stays within the 30-line limit. decode_reserve_mib 300: measured (jobs 989/990/988), the per-request verifier needs about 450 MiB, so 1024 left about 550 MiB idle (180k smoke included); 300 gives the auto-sized cache about 330 more slots. On the 5090, 5 x 245k session (speedtrain-ab), with 300 the card never had less than 563 MiB free (vanilla runs down to 315), so 130 would be safe on the card (+87 slots), but the first slots-footprint A/B showed the Context budget is a second ceiling the planner respects (usable_room); 130 stays an opt-in (LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130) until its own arm measures it. pcie_frac 0.45: the PCIe share that equalises the legs when the CPU pool and the DMA share the host's memory ceiling (P/(P+C) = 0.45, job 987-b/909; 0.45 against 0.55 gave +0.5 % / +4.7 % at the auto-sized cache and was equal at 2048 slots).
2026-11-24 03:50:37 +01:00
Pavlo Ratushnyi 51a4eceff0 control-plane: the request counters of /metrics belong to Services, not a process cell (STRA-338)
The request middleware, the backend worker and the metrics handler now share one RequestMetrics value that Services holds, so the LazyLock registry of request_log.rs and its architecture.json exception are gone. The middleware gets it through Observe, the worker through BackendWorkerConfig, and prometheus::render takes it as an argument; the counters, histograms, labels and log lines are unchanged, and the unit tests now count into a registry of their own instead of one shared by the whole test process.
2026-11-24 03:44:23 +01:00
Pavlo Ratushnyi 128a6fb18b Merge claude/debt-final-ctx3: the serving context is a value from the composition root, not a process cell; unused expert layout and GPU-wait hook removed; every remaining process-global exception says why (STRA-338) 2026-11-24 03:26:37 +01:00
Pavlo Ratushnyi e9107fe43c comments: the serving context is no longer called process-wide (STRA-338) 2026-11-24 02:01:08 +01:00
Pavlo Ratushnyi c1fa88db87 architecture.json: every remaining process-global exception says why that site keeps its cell (STRA-338)
The 32 remaining process-global exceptions are classified: instance-local OnceCell/OnceLock fields
that the gate pattern only matches by type name, pure memos of constants or embedded sealed
images, ambient immutable environment read below the Settings owner, FFI and logger-facade
boundaries, diagnostics, and three entries marked "kept for now, NOT a boundary" (request_log
counters, split_group_pcie tuning, vram_ledger) that can still take the value by argument.
2026-11-24 01:04:59 +01:00
Pavlo Ratushnyi 52abe0a21a control-plane: the gpt-oss prompt date is a field of the model view, not a process cell (STRA-338)
PromptDate was set once by serve into a process OnceLock and read by harmony_prompt::render.
It is now ModelView::prompt_date, built from the config in build_state, and prepare_input_tokens
hands it to render_prompt/render. The default of a bare AppState is still Utc, as the unset cell was.
One process-global exception deleted.
2026-11-24 01:04:43 +01:00
Pavlo Ratushnyi 5951540336 native-cpu-expert: drop the process expert layout and the GPU-wait hook nobody installs (STRA-338)
install_layout/expert_layout (a process RwLock cell) and install_release_gpu_waits (a process
OnceLock hook read on a pool stall) have no caller anywhere in the workspace, so the cells were
never written and the hook never ran. They are deleted instead of injected; the origin of the
pool's diagnostic millisecond clock is now a field of the pool's shared state (Shared::origin)
instead of a process OnceLock. Three process-global exceptions deleted.
2026-11-24 01:00:07 +01:00
Pavlo Ratushnyi 79765ac804 engine: the serving context is a value from the composition root, not a process cell (STRA-338)
ServingContext::new(cells, rope) replaces configure_serving_context and the process cell of
cuda-model; serving_context() is gone. The backend spawn makes the value once (serving::
admit_context_tokens) and hands it down: OwnerThread -> LoadEnv -> ServedArtifact (the
model binding captures it, ModelBinding::serving()) and Device::create_context_serving
(every Context of the Load). Device::create_context stays the trained default for tools and
tests. contract::serving_cells, the QSA index context()/device_peak() reads, the
native-resources size read, the memory governor, the stack config and the RoPE constants
read the binding or the Context instead; the stack open refuses a binding and a Context
made for different serving contexts. The two laptop tools build their own value.

Five process-global exceptions deleted (cuda-model serving_context, engine contract,
binding_identity, qsa_index/context, qsa_native_resources).
2026-11-24 00:59:18 +01:00
Pavlo Ratushnyi 1faee20402 Merge claude/debt-final-ctx2: positions, the resident KV window and the serving geometry belong to the model binding and the Context, not to the process (STRA-338) 2026-11-23 23:14:40 +01:00
Pavlo Ratushnyi f43aacd77d Merge claude/strata-scrub: no stale engine/strata paths in comments, sealed sources and fixtures; pins re-sealed (STRA-407) 2026-11-23 22:55:36 +01:00
Pavlo Ratushnyi a736aa03fa UPSTREAM.md: keep the checkout hint in its own paragraph (STRA-407) 2026-11-23 22:51:23 +01:00
Pavlo Ratushnyi 6c88bbc65e sm86_table: say that the digest was recomputed (STRA-407) 2026-11-23 22:37:37 +01:00
Pavlo Ratushnyi bb8ff44667 Sealed PTX: scrub engine/strata from four PTX header comments and their sm_86 companions, re-pin (STRA-407)
bf16_f32_mmvf, iq3_s_q8_1, moe_group_iq3_s, moe_group_iq3_s_nc4 (sm_120 in src/, sm_86 in ptx-sm86/) change in // header comments only (proof: identical after comment
stripping, no .file/.loc directive or string carries the path). The sm_86 companions are re-derived with sm86_assets.retarget + ptxas -arch=sm_86 (== the edited files);
MANIFEST.json (sm120/sm86 sha256 and byte counts of the four, the -I flags of the one recompiled companion) and the five-part sm86_table rows (new keys, re-sorted, same 27/27/27/27/23
layout) follow; FORMER_TABLE_DIGEST is recomputed with the algorithm of its test (reproduces the old value on main). Rust pins that cover the changed bytes:
bf16_receipt_types.rs BF16_RECEIPT (.cu source_sha256 and bf16_f32_mmvf.ptx ptx_sha256; a Receipt, not a PtxPin, so patched token by token), the frozen-artifact hash of
iq3_s_q8_1.ptx in context_handle.rs and in scripts/test-cuda-projection-family-driver.sh. Instruction streams, entry names and pinned symbol names are untouched.
2026-11-23 22:37:24 +01:00
Pavlo Ratushnyi 5e963eada5 Sealed sources: scrub engine/strata from .cu/.cuh comments, move the source pins that cover them (STRA-407)
21 .cu/.cuh files change in comments only (proof: identical after comment stripping; where the file compiles without the removed headers, nvcc 13.2.86 gives the same PTX
modulo the content-hashed symbol names, which nvcc derives from the source text and which the committed PTX keeps as sealed). Every pin that covered such a file moves:
cu_pin sha256+bytes in the seal plans of mmq_original_prefill_misc, s_gemv_legacy, experimental_keyless, experimental_cvec (no repo tool writes cu_pin; computed with sha256),
experimental.rs PINS[3] and PINS[5] and closed_kernels.rs PINS[1] .source_sha256 (rustpins.apply_field, then rustfmt as seal_pins.py does). The four experimental sources
that were already pending a reseal stay pending. Seal-plan prose and -I flags follow the same wording as the gpu-bringup data.
2026-11-23 22:37:17 +01:00
Pavlo Ratushnyi da8c974f68 Drop the stale engine/strata paths and retired generator names from comments, doc strings and generated fixtures (STRA-407)
Rust comments that named scripts/offline/*, gen_goldens.py, oracle/gen_*.{sh,cpp,py}, build_oracle.sh and similar retired generators now say where the data
came from (the Original's code, Strata 41cf05a0) or drop the sentence. The path/generator text of seven generated fixtures (sampler_oracle.json, sampling_keys.json,
memory_plan_golden.json, rope_golden.json, cvec_oracle.json, stra161 fixtures.json, commentary-tool-prompt.json) is reworded; no test reads those fields and no pin
covers their bytes. cmd_time/doc.rs: the two path texts in the format string; its lines are re-broken so they stay within 120 columns (the string is unchanged
otherwise). Comment-only except those data/string spots; no behaviour change.
2026-11-23 22:37:17 +01:00
Pavlo Ratushnyi a4afb2a182 gpu-bringup: name the include dirs of an upstream checkout strata-41cf05a0/ instead of the removed engine/strata (STRA-407)
The recipe data (sm86-recipes.json, extra-seal-plan.json, rope-regeneration.json), STANDARD_INCLUDES, the sm86 include list and the one test that asserts them
now spell the include directories as strata-41cf05a0/{include,src,third_party/ggml}; prose that named engine/strata/CMakeLists.txt or the retired
build-original-verify-ptx.sh now says Strata 41cf05a0 or the precise flags. UPSTREAM.md records where to place a restored checkout.
No pin covers these files; behaviour of the tools is unchanged (the directories did not exist before either).
2026-11-23 22:29:08 +01:00
Pavlo Ratushnyi 920be477ee Merge claude/strata-removal: remove the vendored Strata tree, keep LICENSE and the files Rust embeds in third_party/strata (STRA-406)
Rust port / port-typecheck (push) Successful in 1m10s
Rust port / port-linux-tests (push) Failing after 3m0s
Rust port / port-fast (push) Successful in 4m26s
Rust port / port-oracles (push) Successful in 4m28s
Linux / verify (push) Failing after 5m16s
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Product / product (push) Failing after 14m14s
2026-11-23 21:44:36 +01:00
Pavlo Ratushnyi 91d6a64261 UPSTREAM.md: point at the last full copy of the removed tree (STRA-406) 2026-11-23 21:24:49 +01:00
Pavlo Ratushnyi 4446f93e2e UPSTREAM.md: name the removal commit of the vendored Strata tree (STRA-406) 2026-11-23 21:24:30 +01:00
Pavlo Ratushnyi 1a4d4a737b Remove the vendored Strata tree engine/strata and its provenance files (STRA-406)
Owner decision 2026-11-23: the vendored tree is junk. Leleka never builds or runs it (no Cargo.toml or build.rs depends on it), the vanilla benchmark
builds from its own checkout on the server, the comparison measurements are finished and the CUDA ports are frozen. Strata is MIT: its licence text
stays and ships (third_party/strata/LICENSE, `leleka engine license`).

- git rm -r engine: engine/strata (upstream 41cf05a0 plus 25 locally patched files), engine/README.md, engine/upstream.md (its pin record moved to
  third_party/strata/UPSTREAM.md) and engine/upstream/ (the two local-patch diffs against the removed tree). They belong to the same vendored mechanism.
- The files Rust and the product still read were moved to third_party/strata and control-plane/tests/mcp_hub in the first commit of this branch.
- The full tree is in git history before this commit; 87e2633af is the last commit that changed it. Restore with `git archive <this commit>^ engine/strata`.
- Four doc-comment lines that the path rewrite made too wide are re-wrapped (check-limits stays at 0 errors).
2026-11-23 21:24:19 +01:00
Pavlo Ratushnyi 056ab3d689 Retire the oracles, generators and scripts that only worked against the vendored Strata tree (STRA-406)
The vendored Strata tree engine/strata is removed for good (owner decision 2026-11-23): Leleka never builds or runs it, the vanilla
benchmark builds from its own checkout, the comparison measurements are finished and the CUDA ports are frozen. Everything below
compiled or read that tree, so it cannot run without it and is retired (the tree stays in git history, see third_party/strata/UPSTREAM.md).
Checked-in fixtures, golden JSON, sealed PTX, seal plans and MANIFEST hashes are untouched and keep being replayed by the cargo tests.

Drift guard
- crates/experimental-ref/tests/literal_port.rs: include_str! of the Original .cu files compared with the checked-in experimental ports.

Oracle generators and builders (they compile or extract from the Strata C++/Python sources; their outputs are the checked-in goldens)
- crates/experimental-ref/oracle/gen_{cvec,kv,remote,stream}_golden.{cpp,sh}, gen_seal_additions.py and the cuda_runtime stub they used
- crates/sampler-ref/oracle/build_oracle.sh, gen_fixtures.cpp, gen_sampling_keys.py, stub/ (run_port_host_tests.sh and the fixtures stay)
- crates/serving-policy/oracle/ (build_oracle.sh, gen_{host,cvec,vision}_fixtures.cpp)
- crates/context/tests/rope_plan_golden/gen_* (plan, rope, kv pool)
- crates/engine-core/src/conversation/golden/gen*.{sh,cpp} and stub/
- crates/cuda-driver/oracle/gen_prefill_ring_trace.py and drivers/prefill_ring_trace.cpp (extracted prefill.cpp), check_cu_syntax.sh
- crates/engine-qwen35-cuda/tests/stra161_reference/reference.py (fixtures.json and the Rust constants stay)
- control-plane/tests/golden/gen_goldens.py, scripts/offline/ (Python differentials and golden generators against the Strata Python tools)

Source-compiling CUDA oracles and builders
- scripts/build-cuda-{projection-family,q5,q6,qsa}-oracle.sh with scripts/cuda-{projection-family,q5,q6,qsa}-oracle/ (include the Original .cu; sha256 pins of them)
- scripts/build-original-verify-ptx.sh, scripts/q8/rebuild_quantizer_ptx.sh, scripts/decode-sm120/make_iq_prefix.py (needs engine/strata/include)
- scripts/cuda-stubs/ (check-cu.py and literal_diff.py need the strata headers and the Original sources; the stub headers served only them)
- tools/chain-probe/build.sh, tools/kernel-ab/{cpp,aa.sh,smoke.sh,time_smoke.sh} (the C++ comparator is built from the Strata CPU kernels; verify_manifest.py stays)
- scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/ (compiles the upstream kernel from the tree)

Engine builds and Python smokes that need the tree
- scripts/build-cpu.sh, scripts/build-static-cuda.sh, scripts/check-keyless-gpu.sh, scripts/test-static-cuda-profile.py (CMake of engine/strata)
- scripts/compare-real-tokenizer.py, scripts/smoke-mtp-pack.py (reads src/core/mtp.cpp and a bench manifest), scripts/prepare-keyless-routing.py and its test
- scripts/smoke-native-pack.py became scripts/native-pack-fixture.py: the synthetic GGUF fixtures the four other smokes import stay, the iq_pack.py oracle comparison goes

Gates and CI
- scripts/check-local.sh: no live Python oracle differentials, no literal_port note, no check-cu, no build-cpu, no retired test scripts
- .github/workflows/linux.yml: the keyless-cuda, static-cuda-package and hosted-cuda-package jobs (they built the engine from the tree) and their dispatch
  inputs, and the two oracle smoke steps; .github/workflows/port.yml: the Python oracle environment and the llama.cpp fetch of port-oracles
  (the sampler host shim still runs)
- limits.json and scripts/check_limits_test.py exclude third_party/strata/ instead of engine/strata/

Documentation and comments: README.md names third_party/strata and the pin; deploy/README.md marks the retired build and smoke commands; comments
in Rust, Python and Markdown that named engine/strata/... now name "Strata 41cf05a0, ..."; the gpu-bringup scratch-copy test no longer copies the
removed include directories. Stale engine/strata paths in sealed .cu, .ptx, seal-plan and MANIFEST files are left as they are (hashes may depend on the bytes).
2026-11-23 21:19:11 +01:00
Pavlo Ratushnyi b4db01728c Keep the Strata files Rust and the product read in third_party/strata (STRA-406)
Owner decision 2026-11-23: the vendored Strata tree engine/strata is removed for good. This first step moves what is still read
at build, test or ship time into one small directory, byte for byte:

- third_party/strata/LICENSE (MIT; `leleka engine license` embeds it, the packagers ship it)
- third_party/strata/ggml/LICENSE, project-maya/LICENSE, project-maya/NOTICE.md (licence texts the release packager ships)
- third_party/strata/serve/chat_template.jinja (one copy, embedded by control-plane server_api.rs and gateway-text prompt.rs)
- third_party/strata/serve/chat_golden.json (gateway-text prompt tests)
- third_party/strata/tests/data/native_experts/*.txt (control-plane native_pack tests)
- control-plane/tests/mcp_hub/mcp_fake_server.py next to its test harness
- third_party/strata/UPSTREAM.md replaces engine/upstream.md: pin 41cf05a0, URL, the 25 locally patched files, where the removed tree is in history

include_str! paths, deploy/build.rs (the `leleka version` Strata pin now reads third_party/strata/UPSTREAM.md), Dockerfile.static-cli,
.dockerignore, .gitattributes, the release packagers (package-5090.sh, package-release.py: the subtree facts of the removed tree are
dropped from PROVENANCE) and the evidence capture scripts follow the move. The tree itself is deleted in a later commit.
2026-11-23 21:11:53 +01:00
3191 changed files with 2573 additions and 808748 deletions
+8 -8
View File
@@ -4,14 +4,14 @@ models/
captures/
logs/
control-plane/target/
engine/*
!engine/strata/
engine/strata/*
!engine/strata/LICENSE
# prompt.rs embeds the pinned chat template at compile time
!engine/strata/serve/
engine/strata/serve/*
!engine/strata/serve/chat_template.jinja
third_party/*
!third_party/strata/
third_party/strata/*
!third_party/strata/LICENSE
# prompt.rs and server_api.rs embed the pinned chat template at compile time
!third_party/strata/serve/
third_party/strata/serve/*
!third_party/strata/serve/chat_template.jinja
benchmarks/
target/
dist/
+3
View File
@@ -27,3 +27,6 @@ scripts/check-ci-coverage.py text eol=lf
scripts/install-pinned-rustup.sh text eol=lf
scripts/test-cuda-fixed-ptx.sh text eol=lf
.github/workflows/*.yml text eol=lf
# Strata files kept for the shipped product and the Rust tests (third_party/strata/UPSTREAM.md): embedded and hashed byte for byte, never converted.
third_party/strata/** -text
-311
View File
@@ -6,23 +6,6 @@ on:
tags: ['v*']
pull_request:
workflow_dispatch:
inputs:
keyless_gpu:
description: Run synthetic Keyless CUDA tests on the private GPU runner
type: boolean
default: false
hosted_cuda_package:
description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact)
type: boolean
default: false
hosted_cuda_ple:
description: Build the hosted package with experimental KAR PLE compiled (serving remains explicit and off by default)
type: boolean
default: false
static_cuda_package:
description: Build and audit static CUDA toolkit linkage on the private Linux runner (no inference)
type: boolean
default: false
permissions:
contents: read
@@ -41,296 +24,6 @@ jobs:
- name: GPU-hidden fixed PTX assembly
run: scripts/test-cuda-fixed-ptx.sh
keyless-cuda-gate:
if: gitea.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
outputs:
enabled: ${{ steps.select.outputs.enabled }}
steps:
- id: select
env:
KEYLESS_GPU: ${{ gitea.event.inputs.keyless_gpu }}
run: |
case "${KEYLESS_GPU:-false}" in
true) echo 'enabled=true' >> "$GITHUB_OUTPUT" ;;
false|'') echo 'enabled=false' >> "$GITHUB_OUTPUT" ;;
*) echo 'keyless_gpu must be a boolean input' >&2; exit 2 ;;
esac
keyless-cuda:
needs: [verify, keyless-cuda-gate]
if: needs.keyless-cuda-gate.outputs.enabled == 'true'
runs-on: [self-hosted, linux, x64, strata-gpu]
steps:
- uses: actions/checkout@v4
- name: Query-routing, streaming and snapshot GPU tests
run: scripts/check-keyless-gpu.sh
- name: Bounded KAR expert component GPU tests
run: scripts/check-kar-expert-gpu.sh
static-cuda-package:
permissions:
contents: read
releases: write
if: gitea.event_name == 'workflow_dispatch' && gitea.event.inputs.static_cuda_package == 'true' && gitea.event.repository.private
needs: verify
runs-on: [self-hosted, linux, x64, strata-gpu]
steps:
- uses: actions/checkout@v4
- name: Build and audit engine without GPU inference
env:
CUDA_VISIBLE_DEVICES: ''
BUILD_JOBS: '2'
STRATA_BUILD_DIR: ${{ runner.temp }}/strata-static-cuda-${{ github.run_id }}
run: nice -n 10 scripts/build-static-cuda.sh
- name: Install pinned Rust and musl target
run: |
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
command -v musl-gcc
- name: Assemble combined private package
run: |
engine="${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/strata"
python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
--build-features "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/BUILD-FEATURES.json" \
--cargo-target-dir "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" \
--output "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Build compatible private runtime image without GPU inference
run: |
package="${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
python3 scripts/build-runtime-image.py --package "$package" \
--receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \
> "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json"
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json")"
docker save --output "$package/runtime-image.tar" "$image"
cp "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" "$package/IMAGE-PROVENANCE.json"
(cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json > IMAGE-SHA256SUMS)
- name: Publish exact six-file static CUDA preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile static-cuda \
--tag "static-cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \
--title "Static CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'Private build-only six-file preview. No hosted compiler/license receipt, GPU or model qualification.' \
--directory "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Remove uploaded package copy
if: always()
run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Remove owned runtime image
if: always()
run: |
receipt="${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json"
if test -s "$receipt"; then
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")"
docker image rm "$image"
rm "$receipt"
fi
- name: Remove private build intermediates
if: always()
run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}"
hosted-cuda-package:
permissions:
contents: read
releases: write
if: gitea.event_name == 'workflow_dispatch' && (gitea.event.inputs.hosted_cuda_package == 'true' || gitea.event.inputs.hosted_cuda_ple == 'true') && gitea.event.repository.private
needs: verify
runs-on: ubuntu-latest
timeout-minutes: 150
env:
CUDA_VISIBLE_DEVICES: ''
NVIDIA_VISIBLE_DEVICES: void
BUILD_JOBS: '1'
CARGO_BUILD_JOBS: '2'
CUDA_ARCHITECTURES: '120'
STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }}
steps:
- uses: actions/checkout@v4
- name: Install compatible host tools (no drivers)
run: |
echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV"
echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV"
echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV"
apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates musl-tools binutils docker.io python3 time
- name: Actual runtime-image loader boundary without GPU
run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-package-loader-container.py
- name: Assemble pinned build-only CUDA components
run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT"
- name: Build pinned GPU-hidden compiler image
env:
CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
run: |
context="$RUNNER_TEMP/strata-cuda-builder-context"
mkdir -p "$context"
cp deploy/Dockerfile.cuda-builder "$context/Dockerfile"
cp /etc/ssl/certs/ca-certificates.crt "$context/runner-ca-bundle.crt"
docker build --platform linux/amd64 --build-arg "BUILDER_BASE=$CUDA_BUILDER_BASE" \
--tag "$CUDA_BUILDER_IMAGE" "$context"
docker image inspect --format '{{.Id}}' "$CUDA_BUILDER_IMAGE" > "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID"
- name: Record actual toolchain
env:
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
run: |
"$CUDACXX" --version
docker run --rm --platform linux/amd64 --network none "$CUDA_BUILDER_IMAGE" g++-13 --version
df -h "$RUNNER_TEMP"
free -h
python3 - <<'PYTOOL'
import json, os, platform, subprocess
from pathlib import Path
info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text())
packages=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none',
os.environ['CUDA_BUILDER_IMAGE'],'dpkg-query','-W','-f=${binary:Package}=${Version}'+chr(10),
'binutils','ca-certificates','cmake','gcc-13','g++-13','git','make','python3'],text=True).splitlines()
gcc=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none',
os.environ['CUDA_BUILDER_IMAGE'],'g++-13','--version'],text=True)
info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(),
builder_base=os.environ['CUDA_BUILDER_BASE'],
builder_image_id=Path(os.environ['RUNNER_TEMP'],'CUDA-BUILDER-IMAGE-ID').read_text().strip(),
builder_packages=packages,
gcc=gcc,
nvcc=subprocess.check_output([os.environ['CUDACXX'],'--version'],text=True),
cuda_architectures=os.environ['CUDA_ARCHITECTURES'], driver_tested=False, model_tested=False)
(Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json').write_text(json.dumps(info,indent=2)+'\n')
PYTOOL
- name: Build actual static CUDA engine and audit without GPU
env:
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }}
run: |
mkdir -p "$STRATA_BUILD_DIR"
container="leleka-cuda-build-${GITHUB_RUN_ID}"
volume="leleka-cuda-build-${GITHUB_RUN_ID}"
source_archive="$RUNNER_TEMP/strata-cuda-source.tar"
cleanup() {
docker rm -f "$container" >/dev/null 2>&1 || true
docker volume rm "$volume" >/dev/null 2>&1 || true
rm -f -- "$source_archive"
}
trap cleanup EXIT
git -C "$GITHUB_WORKSPACE" archive --format=tar "$GITHUB_SHA" > "$source_archive"
docker volume create "$volume" >/dev/null
docker create --name "$container" --platform linux/amd64 --network bridge --read-only \
--cap-drop ALL --security-opt no-new-privileges \
--tmpfs /tmp:rw,nosuid,size=2g --mount "type=volume,src=$volume,dst=/work" \
-e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \
"$CUDA_BUILDER_IMAGE" /bin/bash -euc 'sleep infinity' >/dev/null
docker start "$container" >/dev/null
docker exec "$container" mkdir -p /work/workspace /work/toolkit /work/build
docker exec "$container" chmod 0777 /work/build
# Stage tracked source only. docker cp streams the archive from the
# runner container; bind mounts cannot use its path on the daemon host.
docker cp "$source_archive" "$container:/work/source.tar"
docker exec "$container" tar -xf /work/source.tar -C /work/workspace
docker exec "$container" rm /work/source.tar
docker cp "$CUDAToolkit_ROOT/." "$container:/work/toolkit/"
docker exec --user "$(id -u):$(id -g)" \
-e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \
-e CUDACXX=/work/toolkit/bin/nvcc -e CUDAToolkit_ROOT=/work/toolkit \
-e CC=/usr/bin/gcc-13 -e CXX=/usr/bin/g++-13 -e CUDAHOSTCXX=/usr/bin/g++-13 \
-e BUILD_JOBS="$BUILD_JOBS" -e CUDA_ARCHITECTURES="$CUDA_ARCHITECTURES" \
-e STRATA_KAR_PLE="$STRATA_KAR_PLE" -e STRATA_BUILD_DIR=/work/build \
-e SOURCE_REVISION="$GITHUB_SHA" \
"$container" /bin/bash -euo pipefail -c '
if compgen -G "/dev/nvidia*" >/dev/null; then
echo "NVIDIA devices unexpectedly visible in build container" >&2
exit 1
fi
cd /work/workspace
scripts/build-static-cuda.sh
'
docker cp "$container:/work/build/strata" "$STRATA_BUILD_DIR/strata"
docker cp "$container:/work/build/BUILD-FEATURES.json" "$STRATA_BUILD_DIR/BUILD-FEATURES.json"
- name: Bind compile capability to CUDA toolchain provenance
run: |
python3 - <<'PYFEATURES'
import hashlib, json, os
from pathlib import Path
features_path=Path(os.environ['STRATA_BUILD_DIR'])/'BUILD-FEATURES.json'
features=json.loads(features_path.read_text())
toolchain_path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json'
info=json.loads(toolchain_path.read_text())
info['build_features']=features['features']
info['build_features_sha256']=hashlib.sha256(features_path.read_bytes()).hexdigest()
toolchain_path.write_text(json.dumps(info,indent=2)+'\n')
PYFEATURES
- name: Install pinned Rust and musl target
run: |
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
- name: Assemble actual combined executable and runtime image
run: |
# Keep resource evidence even if the hosted runner terminates this job.
(while sleep 20; do
date -u
free -m
df -m "$RUNNER_TEMP"
test ! -r /sys/fs/cgroup/memory.events || cat /sys/fs/cgroup/memory.events
done) &
resource_sampler=$!
trap 'kill "$resource_sampler" 2>/dev/null || true; wait "$resource_sampler" 2>/dev/null || true' EXIT
engine="$STRATA_BUILD_DIR/strata"
package="$RUNNER_TEMP/strata-hosted-cuda-package"
/usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
--build-features "$STRATA_BUILD_DIR/BUILD-FEATURES.json" \
--cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package"
python3 scripts/build-runtime-image.py --package "$package" \
--receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \
> "$RUNNER_TEMP/strata-hosted-image.json"
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$RUNNER_TEMP/strata-hosted-image.json")"
docker save --output "$package/runtime-image.tar" "$image"
cp "$RUNNER_TEMP/strata-hosted-image.json" "$package/IMAGE-PROVENANCE.json"
python3 - <<'PYBIND'
import hashlib, json, os
from pathlib import Path
package=Path(os.environ['RUNNER_TEMP'])/'strata-hosted-cuda-package'
receipt=json.loads((package/'PROVENANCE.json').read_text())
image=json.loads((package/'IMAGE-PROVENANCE.json').read_text())
path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json'
toolchain=json.loads(path.read_text())
with (package/'runtime-image.tar').open('rb') as archive:
archive_sha=hashlib.file_digest(archive, 'sha256').hexdigest()
toolchain['docker_builder']={
'source_commit': os.environ['GITHUB_SHA'],
'image_id': toolchain['builder_image_id'],
'engine_sha256': receipt['engine']['sha256'],
'build_features_sha256': receipt['build_features_sha256'],
'runtime_image_id': image['image'],
'runtime_archive_sha256': archive_sha}
path.write_text(json.dumps(toolchain,indent=2)+'\n')
PYBIND
cp "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$package/CUDA-TOOLCHAIN.json"
tar -C "$CUDAToolkit_ROOT" -cf "$package/CUDA-LICENSES.tar" licenses
(cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json CUDA-TOOLCHAIN.json CUDA-LICENSES.tar > IMAGE-SHA256SUMS)
- name: Publish exact eight-file hosted CUDA preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile cuda \
--tag "cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \
--title "Hosted CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'Private build-only preview. GPU-hidden loader identity and help passed; no GPU/model inference or performance qualification.' \
--directory "$RUNNER_TEMP/strata-hosted-cuda-package"
- name: Remove uploaded package copy
if: always()
run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package"
- name: Remove owned intermediate image and build files
if: always()
run: |
receipt="$RUNNER_TEMP/strata-hosted-image.json"
if test -s "$receipt"; then
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")"
docker image rm "$image"
fi
rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-package-build"
docker image rm "leleka-cuda-builder:${GITHUB_RUN_ID}" 2>/dev/null || true
rm -rf -- "$RUNNER_TEMP/strata-cuda-builder-context" "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID"
linux-static-cli:
permissions:
contents: read
@@ -387,12 +80,8 @@ jobs:
run: python3 scripts/smoke-cuda-memory.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Atomic pinned assets before native serving
run: python3 scripts/smoke-asset-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Native GGUF pack preparation against upstream oracle
run: python3 scripts/smoke-native-pack.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Native fetch prepare serve and verified offline reuse
run: python3 scripts/smoke-native-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Pinned MTP structural preflight and native bootstrap
run: python3 scripts/smoke-mtp-pack.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Native runtime profile metadata admission
run: python3 scripts/smoke-runtime-profile.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Native systemd unit syntax and path safety
+6 -32
View File
@@ -4,7 +4,8 @@ name: Rust port
# weights or tokens. The existing "Linux" workflow is unchanged; the jobs below add the port-specific gates:
# port-fast fmt, Clippy and tests on the host-buildable crates (scripts/check-local.sh --fast)
# port-typecheck Linux-only crates (cuda-driver with the cuda-driver feature, leleka-runtime) type-checked, not run
# port-oracles CPU oracle differentials against the unmodified Python tools (needs pip and a pinned llama.cpp gguf-py)
# port-oracles the sampler host shim over the checked-in oracle fixtures (the live Python differentials and the oracle
# generators needed the vendored Strata tree, removed in STRA-406)
# port-linux-tests Docker Linux harness (scripts/linux-tests/run.sh); optional until branch claude/port-linux-tests merges
# Type-checking is not execution: nothing here runs the Linux-gated tests or any GPU smoke.
@@ -54,45 +55,18 @@ jobs:
cargo clippy --locked --target x86_64-unknown-linux-gnu --no-deps -p leleka-cuda-model -p leleka-cuda-driver --features cuda-driver -p leleka-engine-qwen35-cuda -p leleka-runtime --all-targets -- -D warnings
port-oracles:
# CPU oracle differentials: the Rust side against the UNMODIFIED Python tools and the
# sampler host shim. Optional until it has run green on the hosted runner; the committed goldens are replayed by
# port-fast regardless.
# The sampler host shim over the checked-in oracle fixtures. Optional until it has run green on the hosted runner;
# the committed goldens are replayed by port-fast regardless.
runs-on: ubuntu-latest
continue-on-error: true
steps:
- uses: actions/checkout@v4
- name: Install build tools
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential cmake git python3 python3-venv
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential cmake git python3
- name: Install pinned Rust
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
- name: Oracle Python environment (no model data)
# numpy 2.5.x needs Python >= 3.12 and the runner's distro Python is older, so the numpy pin follows the
# interpreter exactly as engine/strata/requirements.txt does (2.5.4 on 3.12+, 2.4.6 on 3.11, 2.2.6 below).
# The oracle differentials compare against recorded goldens with tolerances, not against a numpy build.
run: |
python3 -m venv "$RUNNER_TEMP/oracle-venv"
cat > "$RUNNER_TEMP/oracle-requirements.txt" <<'EOF'
numpy==2.5.4; python_version >= "3.12"
numpy==2.4.6; python_version == "3.11"
numpy==2.2.6; python_version < "3.11"
PyYAML==6.0.3
tqdm==4.70.1
Jinja2==3.1.6
regex==2026.9.10
EOF
"$RUNNER_TEMP/oracle-venv/bin/python" --version
"$RUNNER_TEMP/oracle-venv/bin/pip" install --disable-pip-version-check -r "$RUNNER_TEMP/oracle-requirements.txt"
- name: Fetch the pinned llama.cpp gguf-py
run: |
commit="$(sed -n 's/^LLAMA_CPP_COMMIT = "\(.*\)"$/\1/p' engine/strata/setup.py)"
test -n "$commit"
git init -q "$RUNNER_TEMP/llama.cpp"
git -C "$RUNNER_TEMP/llama.cpp" fetch --depth 1 https://github.com/ggml-org/llama.cpp "$commit"
git -C "$RUNNER_TEMP/llama.cpp" checkout -q FETCH_HEAD
- name: Port oracles (sampler shim and live Python differentials)
- name: Port oracles (sampler host shim over the checked-in fixtures)
env:
OFFLINE_ORACLE_PYTHON: ${{ runner.temp }}/oracle-venv/bin/python
STRATA_GGUF_PY: ${{ runner.temp }}/llama.cpp/gguf-py
SKIP_LINUX_TYPECHECK: '1'
run: scripts/check-local.sh --port
+1 -1
View File
@@ -2,7 +2,7 @@
Read-only snapshot, 2026-10-12. Audit artifact only; no builds, tests, GPU,
Strata, model or daemon execution. Paths below are relative to this source-port
tree or to the imported `engine/strata/`. Root integration remains mutable.
tree or to the Strata tree that was imported (removed, see `third_party/strata/UPSTREAM.md`). Root integration remains mutable.
This is a bounded core-path ledger, not a whole-project completion certificate.
## Actionable remaining boundaries
+4 -4
View File
@@ -2,8 +2,8 @@
Leleka is a Rust/CUDA inference runtime for coding agents. Release **0.1** serves one model, **Qwen3.8-Flash-Next IQ3_S** (KAR level-2 PLE, MTP speculative
decode), on **one RTX 5090 (32 GB)** at **262,144 tokens of context**, to Codex CLI and other clients over the Responses, Chat Completions and Messages APIs.
It is a Rust/CUDA port of the Original mode17 serve path of [Strata](https://github.com/Niko1221/Strata) (reference copy in `engine/strata/`, pinned at
upstream `41cf05a0`, see `engine/upstream.md`). Serving needs no Python and no CUDA toolkit on the host.
It is a Rust/CUDA port of the Original mode17 serve path of [Strata](https://github.com/Niko1221/Strata) (pinned at upstream `41cf05a0`; the vendored copy was removed, see
`third_party/strata/UPSTREAM.md`). Serving needs no Python and no CUDA toolkit on the host.
**Status of 0.1.** It runs real Codex sessions to completion and decodes about 155 tok/s on the 245k-token benchmark of the 5090 server (section "Numbers").
It is **not a formally quality-gated profile**, only the RTX 5090 is supported, and the limits below are real. Release notes: `spec node release/RELEASE-NOTES-5090-v0.1.md`;
@@ -76,7 +76,7 @@ What the service is doing, and why a request was slow or failed, is in its logs;
- `crates/` — the runtime: `engine-qwen35-cuda` (the engine; `leleka-runtime` is its facade), `engine-core` (pure engine domain), `cuda-driver` (CUDA Driver API, sealed PTX), `leleka-memory` (memory governor), `obs` (logging), `deploy` (the `leleka` binary), model-format, tokenizer, sampler and CPU kernels.
- `control-plane/`, `desktop-core/` — the HTTP/Responses gateway (`leleka-api`) and the engine/daemon processes.
- `engine/strata/` — the pinned upstream Strata, the reference (unmodified by Leleka).
- `third_party/strata/` — the Strata MIT licence texts, the pinned chat template and golden, and `UPSTREAM.md` (pin `41cf05a0`, local patches, where the removed vendored tree is in history). The Strata source tree itself is not in the repository.
- `deploy/`, `scripts/` — profiles, service templates, release packager (`scripts/release/`), test and measurement tooling (Python is allowed there, never in serving).
- `PROJECT_CHARTER.md`, the LeaseVibe spec (imported repository documentation) — requirements, provenance, decisions, gates and measurements. Architecture: spec node `architecture/hexagonal.md`.
@@ -92,4 +92,4 @@ scripts/release/package-5090.sh check # the release gates; `package` buil
## Licence
MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `spec node release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`engine/strata/LICENSE`).
MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `spec node release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`third_party/strata/LICENSE`, printed by `leleka engine license`).
+94 -51
View File
@@ -49,11 +49,9 @@
"patterns": ["^impl_.*\\.rs$", "_fn\\.rs$", "_[0-9]+(_[0-9]+)*\\.rs$"],
"allow": ["^(quantize_)?q[0-9]_[0-9k]\\.rs$"]
},
"_exceptions": "Sites that must stay, so the ratchet is zero outside this list (STRA-338 stage 10). Each entry: crate, file (relative to the crate directory), ratchet (a source_patterns id), reason. The file's hits of that ratchet are not counted; an entry that excuses nothing is an error.",
"_exceptions": "Sites that must stay, so the ratchet is zero outside this list (STRA-338 stage 10). Each entry: crate, file (relative to the crate directory), ratchet (a source_patterns id), reason. The reason starts with `kept:` (the site must stay, and the boundary that forces it) or `debt:` (a real remaining owner problem, and what removes it). The file's hits of that ratchet are not counted; an entry that excuses nothing is an error.",
"exceptions": [
{"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "env-read", "reason": "EnvSwitch is the one reader of the operator environment in this crate: it reads one named variable on the first get() and applies a typed rule"},
{"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "process-global", "reason": "the OnceLock inside EnvSwitch caches the switch position for the process life (an immutable operator setting; a hot path pays one atomic load)"},
{"crate": "leleka-cuda-model", "file": "src/serving_context.rs", "ratchet": "process-global", "reason": "the serving context is fixed once at engine start (configure_serving_context); the driver copies it into each Context when the Context is created and every kernel geometry reads it from the Context, so this cell is read at one place (create_context). The engine composition still reads it for the bind-time cell count; handing the value down from the config is the follow-up of S13. The resident KV window is not here: it belongs to the driver Context"},
{"crate": "leleka-cpu-worker", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
{"crate": "leleka-tokenizer", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
{"crate": "leleka-gptoss-npu", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
@@ -71,7 +69,7 @@
{"crate": "leleka-memory-os", "file": "src/heap.rs", "ratchet": "env-read", "reason": "platform adapter (glibc heap): reads its own LELEKA_MEMORY_NO_TRIM switch once"},
{"crate": "leleka-native-parity-bench", "file": "src/lib.rs", "ratchet": "env-read", "reason": "benchmark host (L4): reads the operator's STRATA_IQ_MT_MIN override to report which value it measured"},
{"crate": "leleka-npu-worker", "file": "src/main.rs", "ratchet": "env-read", "reason": "worker binary (composition root): reads LELEKA_OPENVINO_ROOT into its configuration"},
{"crate": "leleka-memory", "file": "src/settings.rs", "ratchet": "process-global", "reason": "the cached LELEKA_NO_TRIM_FILE path: an immutable operator setting read once by the crate's one environment reader"},
{"crate": "leleka-memory", "file": "src/settings.rs", "ratchet": "process-global", "reason": "kept: the LELEKA_NO_TRIM_FILE path is ambient process environment, immutable after start (a cached read equals a fresh one); this crate is below the engine Settings owner and MemoryServices carries the governor, not the environment, so no settings value reaches the reader"},
{"crate": "leleka-memory", "file": "src/governor.rs", "ratchet": "dyn-trait", "reason": "port boundary: the Governor holds its MemoryPressure adapter as Arc<dyn MemoryPressure>, chosen at start-up (hexagonal.md, ports table)"},
{"crate": "leleka-memory", "file": "src/governor/operations/setup.rs", "ratchet": "dyn-trait", "reason": "port boundary: Governor::new takes the host as Arc<dyn ProcSource + Send + Sync> (the adapter is chosen by the composition root) and source() hands it back"},
{"crate": "leleka-memory", "file": "src/lock/page_locking.rs", "ratchet": "dyn-trait", "reason": "port boundary: SharedPageLocking = Arc<dyn PageLocking>, the OS adapter of mmap/mlock chosen by the composition root"},
@@ -99,12 +97,12 @@
{"crate": "leleka-model-format", "file": "src/ple_reader/read_queue.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: readings of the per-row read queue's latency window, inside the reader loop"},
{"crate": "leleka-model-format", "file": "src/ple_reader/row_reading.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: latency measurement of one PLE row read, inside the reader loop"},
{"crate": "leleka-obs", "file": "src/time/clock.rs", "ratchet": "instant-now", "reason": "the clock adapter itself: SystemClock, AnyClock and ManualClock are the one place that reads the monotonic clock"},
{"crate": "leleka-memory-os", "file": "src/heap.rs", "ratchet": "process-global", "reason": "platform adapter (glibc heap): the LELEKA_MEMORY_NO_TRIM switch is read once and cached"},
{"crate": "leleka-libc-shim", "file": "src/cuda_trace/trace_state.rs", "ratchet": "process-global", "reason": "Windows interposer (FFI): the CUDA call tracer is process-wide state behind C-ABI hooks that carry no context pointer"},
{"crate": "leleka-obs", "file": "src/lib.rs", "ratchet": "process-global", "reason": "the logger is process-wide: its Settings, rate limiter and request sink are built once from the environment"},
{"crate": "leleka-obs", "file": "src/write_stderr.rs", "ratchet": "process-global", "reason": "the request-log sink of the process-wide logger (see lib.rs)"},
{"crate": "leleka-tokenizer", "file": "src/lib.rs", "ratchet": "process-global", "reason": "immutable constant tables built once: the pre-tokenizer regex and the character classes"},
{"crate": "leleka-gptoss-npu", "file": "src/half.rs", "ratchet": "process-global", "reason": "immutable constant table: the half-to-float conversion table, built once"},
{"crate": "leleka-memory-os", "file": "src/heap.rs", "ratchet": "process-global", "reason": "kept: platform adapter over the glibc heap, which is itself process-wide; the LELEKA_MEMORY_NO_TRIM switch is ambient immutable environment read once, and the adapter is below the Settings owner"},
{"crate": "leleka-libc-shim", "file": "src/cuda_trace/trace_state.rs", "ratchet": "process-global", "reason": "kept: FFI interposer boundary. The CUDA call tracer is state behind C-ABI hooks that the dynamic loader calls with no context pointer and no way to carry an argument; the process is the only scope that exists there"},
{"crate": "leleka-obs", "file": "src/lib.rs", "ratchet": "process-global", "reason": "kept: the logger facade, like the `log` crate, is process-wide by contract: elog! and request logging are called from every crate without a handle; its Settings, rate limiter and request sink are built once from the environment"},
{"crate": "leleka-obs", "file": "src/write_stderr.rs", "ratchet": "process-global", "reason": "kept: the request-log sink of the process-wide logger facade of lib.rs (same reason: written by every thread, no handle at the call sites)"},
{"crate": "leleka-tokenizer", "file": "src/lib.rs", "ratchet": "process-global", "reason": "kept: immutable constant tables (the pre-tokenizer regex and the character classes) compiled on first use; a pure function of constants, a memo no caller can observe"},
{"crate": "leleka-gptoss-npu", "file": "src/half.rs", "ratchet": "process-global", "reason": "kept: immutable constant table (half-to-float conversion), a pure function of constants built once; no caller can observe the memo"},
{"crate": "leleka-cuda-model", "file": "src/original_prefill_schedule.rs", "ratchet": "dyn-trait", "reason": "parameter struct SourceView borrows three residency queries (resident, pinned, transient) from the caller's tables; a generic parameter per closure would make the type unnameable in the callers' signatures"},
{"crate": "leleka-experimental-ref", "file": "src/remote_experts.rs", "ratchet": "dyn-trait", "reason": "parameter struct Candidates borrows the primary's residency test from the caller's table; generic parameters would leak into every caller's signature"},
{"crate": "leleka-cpu-worker", "file": "src/engine.rs", "ratchet": "dyn-trait", "reason": "port boundary: the engine holds the prefill accelerator (iGPU, NPU or split) as Box<dyn PrefillAccelerator + Send>, chosen by the worker binary"},
@@ -124,10 +122,9 @@
{"crate": "leleka-model-format", "file": "src/qwen4exp/binding_topology.rs", "ratchet": "dyn-trait", "reason": "std::error::Error::source() returns &(dyn Error + 'static) by the trait's own signature"},
{"crate": "leleka-model-format", "file": "src/ple_reader.rs", "ratchet": "dyn-trait", "reason": "port boundary: the PLE reader holds its PageSource (file, direct-IO file or test double) as Arc<dyn PageSource>"},
{"crate": "leleka-model-format", "file": "src/ple_reader/row_reading.rs", "ratchet": "dyn-trait", "reason": "port boundary: PleReader::open takes the PageSource as Arc<dyn PageSource>"},
{"crate": "leleka-model-format", "file": "src/huge_pages.rs", "ratchet": "process-global", "reason": "the huge-page mode is an operator setting parsed once from LELEKA_HUGEPAGES and cached for the process"},
{"crate": "leleka-model-format", "file": "src/kar/independent_handles.rs", "ratchet": "process-global", "reason": "the identity-recheck switch is an operator setting parsed once and cached for the process"},
{"crate": "leleka-model-format", "file": "src/kar.rs", "ratchet": "process-global", "reason": "a per-instance lazily opened set of file handles (a OnceLock field of the archive), not a process global"},
{"crate": "leleka-model-format", "file": "src/kar/verified_kar_ple_artifact.rs", "ratchet": "process-global", "reason": "constructs the per-instance lazy handle cell of kar.rs, not a process global"},
{"crate": "leleka-model-format", "file": "src/huge_pages.rs", "ratchet": "process-global", "reason": "kept: ambient environment and the mapping registry. The huge-page mode (LELEKA_HUGEPAGES, MODE) is immutable after start so the cache equals a fresh read, and model-format is below the engine Settings owner (dependency direction); LIVE is the registry of the live huge-page mappings that the release path needs, a process-wide fact of the allocator"},
{"crate": "leleka-model-format", "file": "src/kar/independent_handles.rs", "ratchet": "process-global", "reason": "kept: ambient environment. The identity-recheck switch is immutable after start so the cache equals a fresh read; model-format is below the engine Settings owner (dependency direction)"},
{"crate": "leleka-model-format", "file": "src/kar.rs", "ratchet": "process-global", "reason": "kept: COLD_SKIP, the number of upcoming calls that read in parallel without probing after a cold verdict (a cold file would pay the probe's latency each time); a read-path heuristic of the process's one archive reader, output-neutral. The OnceLock field of the archive is an instance field and no longer counted"},
{"crate": "leleka-control-plane", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate: every variable is parsed here into a typed value (number, path, flag, mode)"},
{"crate": "leleka-deploy", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate: every variable is parsed here into a typed value (path, flag, text)"},
{"crate": "leleka-engine-host", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate and its binaries: credentials by name, the evaluation switches, the inherited child variables"},
@@ -151,20 +148,18 @@
{"crate": "leleka-engine-host", "file": "src/node.rs", "ratchet": "dyn-trait", "reason": "tonic server-streaming response type: the generated trait wants a boxed stream"},
{"crate": "leleka-engine-host", "file": "src/runtime_rpc.rs", "ratchet": "dyn-trait", "reason": "tonic server-streaming response type: the generated trait wants a boxed stream"},
{"crate": "leleka-backend-api", "file": "src/scripted.rs", "ratchet": "dyn-trait", "reason": "the scripted test engine stores the test's responder closure"},
{"crate": "leleka-gateway-domain", "file": "src/responses/schema.rs", "ratchet": "process-global", "reason": "pure cache: the validity of a tool schema by its compact text, so the dozen schemas of a coding agent are compiled once, not three times per request"},
{"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "the compiled pinned chat template: immutable, built on first use, read by every request"},
{"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "the process-wide request counters and histograms that /metrics renders; written by every request"},
{"crate": "leleka-control-plane", "file": "src/responses/harmony_prompt.rs", "ratchet": "process-global", "reason": "the gpt-oss prompt date: configuration set once by serve before the first request"},
{"crate": "leleka-control-plane", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "diagnostic stage table of the replay harness and STRATA_STAGE_TRACE: one table per process by design"},
{"crate": "leleka-gateway-domain", "file": "src/responses/schema.rs", "ratchet": "process-global", "reason": "kept: pure memo (not state): the validity of a tool schema keyed by its compact text, so the dozen schemas of a coding agent compile once, not three times per request; the result depends on the key alone, so no caller can observe the cache; a per-request owner would defeat it"},
{"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "kept: the compiled pinned chat template is an immutable constant of the build, compiled on first use and read by every request; a pure memo of a constant"},
{"crate": "leleka-control-plane", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "kept: diagnostic stage table of the replay harness and STRATA_STAGE_TRACE; time() and span() are called from deep helpers (render, tokenize) that carry no state argument, and the output is diagnostic only, never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/settings/source.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the engine: ProcessEnv is the adapter of the EnvSource port, and Settings parses every variable into typed fields there (S13)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_engine/round_tally/serve_rounds.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per traced port call, only when the bring-up trace is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_lookahead.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per routing prediction on the lookahead thread); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_group_steps.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per CPU expert group of a decode round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_tier.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per eager admission, once at start-up); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per pool phase lap of a decode round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/pcie_share_controllers.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per PCIe lag probe and adaptation round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prefill_profile.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per prefill stage span, only when the profile switch is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prompt_device_rows/prompt_device_read/produce_original_gdn.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per GDN layer producer lap, only when the command profile is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_engine/round_tally/serve_rounds.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per traced port call, only when the bring-up trace is on; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_lookahead.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per routing prediction on the lookahead thread; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_group_steps.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per CPU expert group of a decode round; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_tier.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per eager admission, once at start-up; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per pool phase lap of a decode round; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/pcie_share_controllers.rs", "ratchet": "instant-now", "reason": "control input, not a log line: PcieLag spins until the PCIe copies of a group have landed and PcieAuto times a round from one apply_pending to the next, and the control law reads those wall-clock durations to move the PCIe share; both controllers are opt-in experiments (LELEKA_PCIE_AUTO=lag|on, off in every shipped profile) and their unit tests drive the control law through round() without the clock"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prefill_profile.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per prefill stage span, only when the profile switch is on; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prompt_device_rows/prompt_device_read/produce_original_gdn.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per GDN layer producer lap, only when the command profile is on; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-core", "file": "src/family.rs", "ratchet": "dyn-trait", "reason": "EngineFamily::spawn returns Box<dyn Backend>: the family seam is the process boundary of the engine, called once at start-up"},
{"crate": "leleka-engine-fake", "file": "src/lib.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/family.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
@@ -174,16 +169,7 @@
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/spawn_preview.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/measurement.rs", "ratchet": "dyn-trait", "reason": "the evaluation measurement sink is a stored callback handed in by the host (observer port, called once per request)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "dyn-trait", "reason": "the GPU telemetry probe is a stored callback handed in by the host at load (port, sampled by the telemetry tick, not per token)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/binding_identity.rs", "ratchet": "process-global", "reason": "the model binding captures the serving context in cells once, when it is made (the driver's context is configured before the engine binds a model); the validators read the bound from the binding, not from the process"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/model_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/contract.rs", "ratchet": "process-global", "reason": "the engine's one reader of the driver's serving context (cells): contract::serving_cells() is called where a model is bound (InputConstants::from_artifact) and by sizing code that has no binding; every validator takes the bound from the binding"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/split_group_pcie.rs", "ratchet": "process-global", "reason": "the adaptive-tier tuning constants, derived once from the settings capture (immutable after the first read)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "the epoch of the bring-up trace timestamps (DBG_T0), set once; diagnostics only"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_index/context.rs", "ratchet": "process-global", "reason": "the QSA index owner bounds positions and sizes its pages by the process geometry in about ten places (validate_ids, pending rows, native state, max rows, index image sizes) that are reached without a model binding; carrying the bound in QsaOwner is the next step. Same value as the driver's serving context, read through the engine's contract::serving_cells"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_native_resources.rs", "ratchet": "process-global", "reason": "the byte sizes of a layer's host image come from the process geometry (QsaGeometry over the serving cells) when the resource set is built, before any binding is passed in; they follow the QSA owner's bound (see qsa_index/context.rs)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "kept: DBG_T0, the epoch of the bring-up trace timestamps (dbg_el()); diagnostics only, called from trace macros in many files that hold no common owner, never read by serving logic"},
{"crate": "leleka-cuda-driver", "file": "src/compute_drain.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: stall span of one timed drain, reported by the prefill stall trace"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/chunk_stream/chunk_issuing.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one chunk issue, summed into the copy-ring profile"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/original_mmq_copy_schedule/stream_start.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: start of the copy-ring stream, read once per stream for the profile"},
@@ -223,25 +209,82 @@
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/gdn_native_batch/context.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/moe_prefill_batch.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/moe_prefill_batch/moe_prefill_batch_lifecycle.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/asset.rs", "ratchet": "process-global", "reason": "the verdict of the immutable MMQ artifact check, computed once"},
{"crate": "leleka-cuda-driver", "file": "src/prefill_stage.rs", "ratchet": "process-global", "reason": "the usability of the kh recurrence on this device: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_index_ffi.rs", "ratchet": "process-global", "reason": "the RoPE ABI of the loaded index module: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_resolver.rs", "ratchet": "process-global", "reason": "the resolver ABI of the loaded module: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/asset_admission.rs", "ratchet": "process-global", "reason": "per-operation memo of the PTX proof: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/n_types.rs", "ratchet": "process-global", "reason": "the table of PTX proof memos, one cell per operation: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/vram_ledger.rs", "ratchet": "process-global", "reason": "the process-wide VRAM ledger (LELEKA_VRAM_LEDGER): a diagnostic singleton fed by every allocation site"},
{"crate": "leleka-cuda-driver", "file": "src/marker_files.rs", "ratchet": "process-global", "reason": "the marker files of the A/B controls: the paths named by the operator are read once and the time of the first look is kept (OnceLock), so a hot path looks at the disk at most every 250 ms; one type serves the three controls"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend.rs", "ratchet": "process-global", "reason": "FFI: `static mut stdout` is libc's C stream, declared in an extern block"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_expert_layout.rs", "ratchet": "process-global", "reason": "the process-wide expert layout the pool threads read; it is set at load time by the engine"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/job_default.rs", "ratchet": "process-global", "reason": "the origin instant of the pool's job timestamps"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool.rs", "ratchet": "process-global", "reason": "the hook that releases the GPU waits, installed once by the engine (a function pointer)"},
{"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "process-global", "reason": "the cell of a Setting: the operator's switches and the CPU probes the kernels dispatch on are computed on the first read and kept for the process life (immutable; a hot path pays one atomic load, and kernel code carries no context to pass a settings value through)"}
{"crate": "leleka-cuda-driver", "file": "src/mmq/asset.rs", "ratchet": "process-global", "reason": "kept: pure memo of the verdict of the immutable embedded MMQ artifact check (a function of the embedded bytes alone), so no caller can observe the cache; a Context-owned copy would re-prove the same bytes per Context"},
{"crate": "leleka-cuda-driver", "file": "src/prefill_stage.rs", "ratchet": "process-global", "reason": "kept: pure memo of a proof about an embedded sealed image (usability of the kh recurrence), a result per device that no caller can observe as state; and two per-arm A/B overrides (GDN_OVERRIDE, NOSTORE_OVERRIDE) of the prefill GDN switches, written by the test harness for paired passes in one process"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_index_ffi.rs", "ratchet": "process-global", "reason": "kept: pure memo of the RoPE ABI proof of the embedded index module, a function of the embedded bytes alone"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_resolver.rs", "ratchet": "process-global", "reason": "kept: pure memo of the resolver ABI proof of the embedded module, a function of the embedded bytes alone"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/n_types.rs", "ratchet": "process-global", "reason": "kept: the table of the PTX proof memos of asset_admission.rs, one cell per operation; pure functions of embedded bytes"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend.rs", "ratchet": "process-global", "reason": "kept: FFI. `static mut stdout` is libc's C stream, declared in an extern block; it is the C library's own global, not ours"},
{"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "process-global", "reason": "kept: the cell of each `static Setting` (operator switches and the CPU probes the kernels dispatch on), computed on first read from the immutable environment and the CPU; the kernels are free functions called from pool worker threads that carry no context to pass a value through, and a hot path pays one atomic load"},
{"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "kept: `tokio::task_local! CURRENT`, the request context (ReqCtx) of the running request, read without a request argument by code that holds no handle; it is scoped to one task, not to the process"},
{"crate": "leleka-control-plane", "file": "src/responses.rs", "ratchet": "process-global", "reason": "kept: NEXT_RESPONSE_ID, the counter in the `resp_<time>_<n>` id of a response: unique across every request of the process by definition, so it has no narrower owner than the process"},
{"crate": "leleka-control-plane", "file": "src/responses/tool_recovery.rs", "ratchet": "process-global", "reason": "debt: the EXPERIMENTAL tool_call_recovery flag, set once by `main` from the config file or STRATA_TOOL_CALL_RECOVERY and read by the response decoder. It belongs on the Services/config value the handlers already receive; it stays a cell until the decoder takes it by argument"},
{"crate": "leleka-control-plane", "file": "src/vision.rs", "ratchet": "process-global", "reason": "kept: NEXT_DIR numbers the scratch directories of vision requests so two requests of one process never share a directory; uniqueness across the process is its job"},
{"crate": "leleka-cuda-driver", "file": "src/arch_ptx.rs", "ratchet": "process-global", "reason": "debt: STREAM_K_AVOIDED, the fact that the sm_86 companion image was chosen so the stream-K kernels stay off, set in stream_k_off when the module loads and read by the same decision; a fact about the loaded device image that belongs on the Context"},
{"crate": "leleka-cuda-driver", "file": "src/compute_drain.rs", "ratchet": "process-global", "reason": "kept: the registry of every stream the crate creates (STREAMS) and the id of the registered background copy stream (BACKGROUND), which `Api::synchronize` consults in all of the crate's producers (blas, Original schedule, owned copy, swap) that have no common owner; plus the diagnostic counters and per-site table of the drains (SEEN, SHOWN, SITES, BLOCK_*, thread-local LOCAL_DRAINS) and two A/B overrides (ZERO_MEMSET, DEPTH_OVERRIDE). Moving the registry into the Context needs the Api handle in every producer"},
{"crate": "leleka-cuda-driver", "file": "src/deferred_status.rs", "ratchet": "process-global", "reason": "kept: per-thread queue of the deferred status read-backs, bound to the context that created it (the contexts are single-thread owners); one state per thread by design, like the thread that owns the Context"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/chunk_stream.rs", "ratchet": "process-global", "reason": "kept: the thread's active inline-mode chunk stream, which `prefetch_point` finds without a handle (its doc comment: the producers have no handle to the stream)"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule.rs", "ratchet": "process-global", "reason": "debt: SIDE_STREAMS_WANTED is stored by `set_side_streams_wanted` and read by the capture phases; the thread-local SUMS of `capture_timing` is the serve profile's per-thread diagnostic. The flag belongs on the schedule value; it stays a cell until the capture call takes it"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/abi/platform/api.rs", "ratchet": "process-global", "reason": "kept: WARMED, once per process: the first graph callback thread is started pinned (Linux); a failure is ignored and the first real callback creates the thread"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/transport.rs", "ratchet": "process-global", "reason": "kept: SEEN counts the verifier-window graph instantiations of the process for the test hook LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT=N (the N-th instantiation of the process fails once); a process-wide count is what the hook means"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/chain.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/combine_head.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/diag.rs", "ratchet": "process-global", "reason": "kept: REGISTRY of the live verifier diagnostics, read by `original_verify_diagnostics` and the release hooks from the operator and shutdown paths that hold no verifier handle; diagnostics only"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/gdn_fused.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/gr/fused_down.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/gr/head_chain.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/qsa/fused_prelude.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/sm120.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/window_ops/original_verifier.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_cluster.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_late.rs", "ratchet": "process-global", "reason": "debt: per-arm overrides (OVERRIDE, TOPK_OVERRIDE) for paired A/B passes in one process, plus a once-per-process notice (SAID). The overrides belong in the arm configuration handed to the recording call; they stay cells until it is threaded through"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_kv/resident_transport.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-cuda-driver", "file": "src/settings.rs", "ratchet": "process-global", "reason": "kept: operator environment switches of the CUDA driver, one `static EnvSwitch/EnvSetting/LazySetting/MarkerFiles` per variable, computed on first read from the process environment, which cannot change after start, so a cached read equals a fresh one; they are read from free functions deep in the launch and prefill paths that carry no settings argument, and the driver sits below the engine Settings owner (dependency direction). A driver settings struct on the Context would remove them (follow-up of STRA-338)"},
{"crate": "leleka-cuda-model", "file": "src/bringup_trace.rs", "ratchet": "process-global", "reason": "kept: the LELEKA_BRINGUP_TRACE switch, an `EnvSwitch` declared where it is read (same reason as env_switch.rs: immutable environment, and the crate is below the engine Settings owner)"},
{"crate": "leleka-cuda-model", "file": "src/command_profile.rs", "ratchet": "process-global", "reason": "kept: the LELEKA_PREFILL_PROFILE_SYNC switch (an `EnvSwitch`, reason of env_switch.rs) and TOTALS, the table of per-command timings that the profile report prints; diagnostics only, recorded from command wrappers that hold no profile handle"},
{"crate": "leleka-cuda-model", "file": "src/host_profile.rs", "ratchet": "process-global", "reason": "kept: the LELEKA_SERVE_PROFILE switch (an `EnvSwitch`, reason of env_switch.rs) and the thread-local SUMS of the host profile; diagnostics only"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/config.rs", "ratchet": "process-global", "reason": "kept: RECONFIGURING (a reconfigure is reopening the serve stack, new generations are refused and retryable meanwhile) and INSTANCE (the number of the backend instance, taken by each spawn). Both describe the one engine of the process and are touched from the control thread and the request threads; open item: move them next to the backend handle when the engine builds on Windows (STRA-390) and can be compiled"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve.rs", "ratchet": "process-global", "reason": "kept: PREFIX_SUMMARY, the prefix cache's pool summary that the owner thread publishes after each request and any status thread reads; its doc comment: one backend per process, so one cell"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "process-global", "reason": "debt: PREVIOUS_TIER, the expert tier counters after the previous request, to turn stack-lifetime figures into a request's share; it belongs to the runner that reports each request, and stays a cell until the runner owns it (needs the engine to compile, STRA-390)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner/stack_reports.rs", "ratchet": "process-global", "reason": "kept: NEXT numbers the per-request id dump files of the process so that two dumps never share a name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/load_clock.rs", "ratchet": "process-global", "reason": "kept: CLOCK, the start and last-lap time of the one model load of the process, written by `lap` and `span` from the loading thread and the parallel verification threads; the output is the `leleka-load-time` log line only"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/memory_governor.rs", "ratchet": "process-global", "reason": "debt: MAPPED_WORKING_SET is the RAM kept for the hot part of a file-mapped expert bank, set by `startup` and read when the prefix budget is resolved at open; a value that should travel in the memory settings handed to open. It stays a cell until the engine compiles on Windows (STRA-390) and the plumbing can be verified"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/kar_ple_source/private_copy.rs", "ratchet": "process-global", "reason": "kept: SEQUENCE numbers the temporary private copies of a source file, so two copies of one process never collide on a name (macOS and test builds only)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/mtp/backing.rs", "ratchet": "process-global", "reason": "kept: SERIAL numbers the temporary backing files of the process (`tiny-<pid>-<serial>`), so two never collide"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/gdn.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/moe_weight_cache/cache_original_prompt.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_cache_startup.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_host/ple_on_chain.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_native/native_window.rs", "ratchet": "process-global", "reason": "kept: WINDOW_SEQ numbers the residual trace files of a window (diagnostic trace output, LELEKA trace directory only)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool.rs", "ratchet": "process-global", "reason": "kept: thread-local diagnostic accumulator of the serve profile (written from deep helpers that hold no profile handle, drained by the profile report on the same thread); never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_profile.rs", "ratchet": "process-global", "reason": "kept: thread-local diagnostic accumulator of the serve profile (written from deep helpers that hold no profile handle, drained by the profile report on the same thread); never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency.rs", "ratchet": "process-global", "reason": "debt: TAIL_SKIP_RANK, the route-tail skip rank resolved once from the settings and the cache on first use and read by the router each round. It belongs to the residency state of the serve stack; it stays a cell until that owner exists and the engine compiles on Windows (STRA-390)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/source_spans.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/tail_skip_rank.rs", "ratchet": "process-global", "reason": "kept: ANNOUNCED, the effective tail-skip rank last printed, so the operator log prints a change once; output only"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/prompt_chunk.rs", "ratchet": "process-global", "reason": "kept: LOWEST_FREE, the low-water mark of the card's free VRAM over every note of the process (diagnostic print when the serve profile is on; the number the reserve must cover)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prefill_profile.rs", "ratchet": "process-global", "reason": "kept: thread-local diagnostic accumulator of the serve profile (written from deep helpers that hold no profile handle, drained by the profile report on the same thread); never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/quality_force.rs", "ratchet": "process-global", "reason": "kept: FORCED, the teacher-forcing sequence of the model quality gate; production code never installs one (the only caller is the Original serve smoke) and with nothing installed `apply` is one uncontended lock and an empty check"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/settings.rs", "ratchet": "process-global", "reason": "debt (the largest remaining process cell): `settings::process()` holds the engine Settings in a OnceLock captured from the real environment on first ask, and is read at about 78 sites. It must become a value built once by the composition root and passed through the Context/ModelBinding/config structs, as the serving context was in phase 2c. Not done in phase 2e: leleka-engine-qwen35-cuda does not compile on Windows at the base (std::os::unix in model_binding/weight_binding/mtp, STRA-390), and no uncompiled code is committed"},
{"crate": "leleka-gptoss-npu", "file": "src/par.rs", "ratchet": "process-global", "reason": "debt: LIMIT, the thread budget of the parallel helpers, set once by the NPU prefill setup (`set_threads`) and read by every helper; it belongs to the setup value the helpers are called with"},
{"crate": "leleka-libc-shim", "file": "src/cuda_trace.rs", "ratchet": "process-global", "reason": "kept: FFI interposer boundary (same reason as trace_state.rs): the real entry points, launch counters and stream sync marks live in statics because the CUDA call wrappers are C-ABI functions the loader calls with no context pointer and no way to carry an argument"},
{"crate": "leleka-libc-shim", "file": "src/lib.rs", "ratchet": "process-global", "reason": "kept: the loader hook that registers the extra DLL directories is `Once`-guarded, once per process, because it changes the process-wide DLL search path"},
{"crate": "leleka-memory", "file": "src/telemetry.rs", "ratchet": "process-global", "reason": "kept: the telemetry state (STATE, PUBLISHED, SETTINGS): the serve loop calls the `record_*` functions from many places that hold no common handle, one sampler thread publishes once a second; process-wide by contract like the obs logger. Diagnostics only (rides the runtime snapshot), never read by serving logic"},
{"crate": "leleka-model-format", "file": "src/gguf/resident.rs", "ratchet": "process-global", "reason": "kept: NEXT_SOURCE_ID mints the private source-owner identity after an admitted file fill; unique across the process by definition, checked exhaustion refuses rather than wraps"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_legacy.rs", "ratchet": "process-global", "reason": "kept: ORACLE, the q8-zero oracle switch of the legacy kernel (`set_oracle_q8_zero`), a test hook read by the kernel free functions that pool worker threads call with no context argument"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_weight_iq.rs", "ratchet": "process-global", "reason": "kept: pure memo of the IQ quantizer grids (one slot per grid kind, built on first use from constant tables, dropped by the release call), shared by the pool worker threads that call the quantizers as free functions; no caller can observe the cache"},
{"crate": "leleka-obs", "file": "src/redact.rs", "ratchet": "process-global", "reason": "kept: the secret values registered for scrubbing: the logger facade is process-wide by contract (same reason as lib.rs) and `scrub` runs on every log line of every thread"},
{"crate": "leleka-control-plane", "file": "src/config.rs", "ratchet": "allow-unused-imports", "reason": "debt: two glob re-exports of the config split that the compiler reports unused in the lib build; they stay because the lib test build of control-plane cannot be compiled on Windows (std::os::unix), so a use from a test module cannot be ruled out. Delete or narrow them on a Linux compile"},
{"crate": "leleka-control-plane", "file": "src/mcp.rs", "ratchet": "allow-unused-imports", "reason": "debt: three glob re-exports of the mcp split that the compiler reports unused in the lib build; kept because the lib test build of control-plane cannot be compiled on Windows (std::os::unix) and a test use cannot be ruled out. Delete or narrow them on a Linux compile"},
{"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "allow-unused-imports", "reason": "debt: one glob re-export (metrics_text) that the compiler reports unused in the lib build; kept because the lib test build of control-plane cannot be compiled on Windows and a test use cannot be ruled out"},
{"crate": "leleka-control-plane", "file": "src/request_monitor.rs", "ratchet": "allow-unused-imports", "reason": "debt: one glob re-export (record) that the compiler reports unused in the lib build; kept because the lib test build of control-plane cannot be compiled on Windows and a test use cannot be ruled out"},
{"crate": "leleka-engine-host", "file": "src/runtime_gateway.rs", "ratchet": "allow-unused-imports", "reason": "debt: four glob re-exports of the gateway split; not checked, because leleka-engine-host needs the engine, which does not compile on Windows (STRA-390). Narrow or delete them with the compiler once it does"},
{"crate": "leleka-engine-host", "file": "src/runtime_rpc.rs", "ratchet": "allow-unused-imports", "reason": "debt: four glob re-exports of the rpc split; not checked, because leleka-engine-host needs the engine, which does not compile on Windows (STRA-390). Narrow or delete them with the compiler once it does"}
],
"source_patterns": [
{"id": "env-read", "regex": "\\benv::var(_os)?\\(", "why": "configuration must be parsed once into a Settings struct (S13), not read all over the code"},
{"id": "instant-now", "regex": "\\bInstant::now\\(\\)", "why": "time must come from an injected Clock in core logic (S14)"},
{"id": "path-include", "regex": "#\\[path\\s*=\\s*\"(?![^\"]*tests\\.rs\")(?![A-Za-z0-9_]+/[A-Za-z0-9_]+\\.rs\")", "why": "a file compiled into two crates must be one crate (S8); a tests.rs or a child module file of the form dir/name.rs is not an include"},
{"id": "process-global", "ignore_imports": true, "regex": "\\b(OnceLock|LazyLock|OnceCell)\\b|\\bstatic\\s+mut\\b|Governor::global\\(|serving_cells\\(\\)", "why": "process globals make core logic untestable without a GPU (S14)"},
{"id": "process-global", "ignore_imports": true, "regex": "\\bstatic\\s+mut\\b|\\bstatic\\s+[A-Z_][A-Z0-9_]*\\s*:[^=;]*{cell_types}|\\blazy_static!|Governor::global\\(|serving_cells\\(\\)", "why": "process globals make core logic untestable without a GPU (S14). Counted: a `static` (also inside thread_local!) whose type is a cell (Atomic*, Mutex, RwLock, Once, OnceLock, LazyLock, Cell, RefCell, ...) or a workspace type that holds one, and `static mut`; an instance field of those types is not a global"},
{"id": "dyn-trait", "regex": "\\bdyn\\s+[A-Z]", "why": "no dynamic dispatch per round or token; dyn is for startup composition only"},
{"id": "glob-super-import", "regex": "^use super::\\*;", "why": "a glob import of the parent hides what a module needs; name the items (use super::{A, B}); scripts/dev/explicit_imports.py does it for the files rustsplit leaves"},
{"id": "allow-unused-imports", "regex": "#\\[allow\\(unused_imports\\)\\]", "why": "a blanket allow hides imports that are really unused; it belongs on re-exports and on names that only some cargo features use"}
@@ -1,5 +1,5 @@
{
"provenance": "Pinned engine/strata/serve/chat_template.jinja rendered with Jinja2 3.1.6; sanitized fixture",
"provenance": "Pinned third_party/strata/serve/chat_template.jinja rendered with Jinja2 3.1.6; sanitized fixture",
"request": {
"model": "strata-local",
"reasoning": {
@@ -29,6 +29,7 @@ fn worker_config(tokenizer: Arc<Tokenizer>) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
+2 -6
View File
@@ -38,14 +38,10 @@ mod tests;
mod state;
pub use state::{AppState, EngineLink, HttpPolicy, ModelView, Services};
mod routes;
#[allow(unused_imports)]
pub use routes::*;
mod admin_routes;
#[allow(unused_imports)]
pub use admin_routes::*;
use admin_routes::*;
mod readiness;
#[allow(unused_imports)]
pub use readiness::*;
use readiness::*;
mod metrics_document;
#[allow(unused_imports)]
pub use metrics_document::*;
+1 -1
View File
@@ -77,7 +77,7 @@ pub(super) async fn metrics(State(state): State<AppState>, RawQuery(query): RawQ
let all = query.as_deref().is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document).into_response();
let mut response = crate::prometheus::render(&document, &state.services.request_metrics).into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE),
+1
View File
@@ -87,6 +87,7 @@ pub fn router(state: AppState) -> Router {
model: state.model.name.clone(),
memory: state.model.memory.clone(),
clock: state.services.clock.clone(),
metrics: state.services.request_metrics.clone(),
};
let routes = model_routes(server_routes(Router::new()));
let routes = chat_routes(response_routes(routes, &state, &observe), &state, &observe);
+6
View File
@@ -66,6 +66,8 @@ pub struct ModelView {
pub prefix_cache: Arc<crate::prefix_view::PrefixView>,
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory`.
pub memory: Arc<crate::memory_view::MemoryView>,
/// What a gpt-oss system message says about the date (`prompt_date` in the config).
pub prompt_date: crate::responses::PromptDate,
}
/// Stores and process-wide services.
@@ -78,6 +80,8 @@ pub struct Services {
/// The MCP servers configured for the operator (`GET /mcp`).
pub mcp: Option<SharedToolHub>,
pub settings: Arc<crate::settings::Settings>,
/// The request counters and histograms that `/metrics` renders: written by the request middleware and the worker.
pub request_metrics: Arc<crate::request_log::RequestMetrics>,
/// Wall and monotonic time: queue deadlines, uptime, response timestamps.
pub clock: SharedClock,
pub started_at: SystemTime,
@@ -120,6 +124,7 @@ impl Default for ModelView {
vision: None,
prefix_cache: Arc::new(Default::default()),
memory: Arc::new(Default::default()),
prompt_date: crate::responses::PromptDate::Utc,
}
}
}
@@ -132,6 +137,7 @@ impl Default for Services {
monitor: Arc::new(Default::default()),
mcp: None,
settings: Arc::new(crate::settings::Settings::default()),
request_metrics: Arc::default(),
started_at: clock.system_time(),
clock,
}
+2
View File
@@ -74,6 +74,8 @@ pub struct BackendWorkerConfig {
/// Where the engine's memory-governor report is copied (health tick and after every request); `None` = not shown,
/// no gate.
pub memory_view: Option<Arc<crate::memory_view::MemoryView>>,
/// Where the worker counts the engine attaches and losses that `/metrics` renders.
pub request_metrics: Arc<crate::request_log::RequestMetrics>,
}
type Engine = Arc<Mutex<Box<dyn api::Backend>>>;
+2 -2
View File
@@ -167,7 +167,7 @@ impl AttachLoop {
/// The engine has the model: report ready and answer the `Load` requests that waited.
async fn become_ready(&mut self) {
self.attached_before = true;
crate::request_log::note_engine_attached();
self.config.request_metrics.note_engine_attached();
self.publish_ready_status().await;
self.answer_waiting_loads();
}
@@ -238,7 +238,7 @@ impl AttachLoop {
/// The engine is gone: record why and fail the worker.
async fn report_engine_lost(&self, reason: &str) {
crate::request_log::note_engine_lost(reason);
self.config.request_metrics.note_engine_lost(reason);
update(&self.status, WorkerState::Failed, None).await;
}
+2 -2
View File
@@ -35,7 +35,7 @@ fn single_commands(action: &str, rest: &[String]) -> Outcome {
fn batch_commands(action: &str, rest: &[String]) -> Outcome {
match (action, rest) {
// Batch forms for the differential harness (scripts/offline/diff_tokenizer.py): one JSON value per line.
// Batch forms for the differential harness: one JSON value per line.
("pre-tokenize-batch", []) => Some(pre_tokenize_batch()),
("tokenize-batch", [path, flags_rest @ ..]) if flags_rest.iter().all(|flag| flag == "--special") => {
Some(tokenize_batch(path, !flags_rest.is_empty()))
@@ -122,7 +122,7 @@ fn request_kwargs(request: &Json) -> Vec<(&str, Json)> {
}
/// JSON lines {"messages": [...], "tools": [...]|null, "add_generation_prompt": true, "kwargs": {...}} ->
/// {"ok": "<prompt>"} or {"error": "<message>"}: the pinned chat template, for scripts/offline/diff_chat_template.py.
/// {"ok": "<prompt>"} or {"error": "<message>"}: the pinned chat template.
fn render_chat() -> Result<(), BoxError> {
for line in std::io::stdin().lines() {
let request: Json = serde_json::from_str(&line?)?;
+1 -1
View File
@@ -201,7 +201,7 @@ fn engine_info() -> Result<(), BoxError> {
}
fn engine_license() -> Result<(), BoxError> {
print!("{}", include_str!("../../../engine/strata/LICENSE"));
print!("{}", include_str!("../../../third_party/strata/LICENSE"));
Ok(())
}
+1 -1
View File
@@ -1,5 +1,5 @@
//! The hardware half of `GET /metrics`, in the member names of the Python service's Monitor (`hardware`,
//! `hardware_static`, `history`; `engine/strata/serve/telemetry.py`), built from the engine's telemetry document
//! `hardware_static`, `history`; `Strata 41cf05a0, serve/telemetry.py`), built from the engine's telemetry document
//! (`leleka-memory`'s `telemetry.rs`, copied here by the worker on its health tick).
//!
//! Units follow the Python service: memory in bytes, utilisation and CPU in percent, power in watts, temperature in
-2
View File
@@ -98,8 +98,6 @@ mod tests;
mod analyze;
mod previous;
mod sample;
#[allow(unused_imports)]
pub use analyze::*;
mod sample_records;
#[allow(unused_imports)]
pub use sample_records::*;
+3 -8
View File
@@ -103,17 +103,12 @@ mod tests;
mod archive_entry_points;
mod archive_file;
mod archive_plan;
#[allow(unused_imports)]
pub use archive_entry_points::*;
mod archive_write_steps;
#[allow(unused_imports)]
pub use archive_write_steps::*;
use archive_write_steps::*;
mod nested_layout;
#[allow(unused_imports)]
pub use nested_layout::*;
mod section_payload;
#[allow(unused_imports)]
pub use section_payload::*;
use section_payload::*;
mod directory_record;
#[allow(unused_imports)]
pub use directory_record::*;
use directory_record::*;
+5 -11
View File
@@ -1,5 +1,5 @@
//! MCP (Model Context Protocol) hub: tools from MCP servers, namespaced `<server>__<tool>`, called
//! on behalf of an agent. Port of `engine/strata/serve/mcp.py`.
//! on behalf of an agent. Port of `Strata 41cf05a0, serve/mcp.py`.
//!
//! The operator lists servers in the run config (`mcp_servers`, or Claude Desktop's `mcpServers`
//! block as is, or a separate `mcp_config_file`): a program Strata starts (`command`, `args`,
@@ -146,17 +146,14 @@ pub struct Hub {
mod tests;
mod mcp_settings_errors;
#[allow(unused_imports)]
pub use mcp_settings_errors::*;
use mcp_settings_errors::*;
mod stdio_transport;
#[allow(unused_imports)]
pub use stdio_transport::*;
mod stdio_message_routing;
#[allow(unused_imports)]
pub use stdio_message_routing::*;
use stdio_message_routing::*;
mod http_transport;
#[allow(unused_imports)]
pub use http_transport::*;
use http_transport::*;
mod transport;
#[allow(unused_imports)]
pub use transport::*;
@@ -164,11 +161,8 @@ mod server;
#[allow(unused_imports)]
pub use server::*;
mod tool_result_text;
#[allow(unused_imports)]
pub use tool_result_text::*;
mod hub;
#[allow(unused_imports)]
pub use hub::*;
use hub::*;
mod parse_config;
#[allow(unused_imports)]
pub use parse_config::*;
+1 -4
View File
@@ -30,11 +30,8 @@ struct Events(mpsc::Receiver<Event>);
mod tests;
mod count_tokens;
#[allow(unused_imports)]
pub use count_tokens::*;
mod error_type;
#[allow(unused_imports)]
pub use error_type::*;
mod messages_stream;
#[allow(unused_imports)]
pub use messages_stream::*;
use messages_stream::*;
+1 -3
View File
@@ -44,8 +44,6 @@ pub struct ModelFile {
mod tests;
mod manifest_fetch;
#[allow(unused_imports)]
pub use manifest_fetch::*;
mod file_download;
#[allow(unused_imports)]
pub use file_download::*;
pub(crate) use file_download::*;
+2 -2
View File
@@ -8,10 +8,10 @@ use std::{
};
const INDEX_LIMIT: u64 = 64 * 1024;
// engine/strata/include/strata/kernels/cpu/expert.hpp: NE * BLOB.
// Strata 41cf05a0, include/strata/kernels/cpu/expert.hpp: NE * BLOB.
const EXPERT_BYTES: u64 = 512 * 1_382_400;
// Shapes from pinned upstream mtp-manifest.json, normalized by tools/mtp_rt.py.
// Consumer: engine/strata/src/core/mtp.cpp (N=2560, HC=4, NH=24, HD=256).
// Consumer: Strata 41cf05a0, src/core/mtp.cpp (N=2560, HC=4, NH=24, HD=256).
const REQUIRED: &[(&str, &str, u64, u64)] = &[
("fc_embedding.weight", "q8_0", 2560, 2560),
("fc_hidden.weight", "q8_0", 2560, 2560),
+5 -12
View File
@@ -70,23 +70,16 @@ pub struct Options {
mod tests;
mod pack_rules;
#[allow(unused_imports)]
pub use pack_rules::*;
use pack_rules::*;
mod expert_layout;
#[allow(unused_imports)]
pub use expert_layout::*;
use expert_layout::*;
mod convert_tensor;
#[allow(unused_imports)]
pub use convert_tensor::*;
use convert_tensor::*;
mod dense_files;
#[allow(unused_imports)]
pub use dense_files::*;
use dense_files::*;
mod pack_publication;
#[allow(unused_imports)]
pub use pack_publication::*;
mod pack_outputs;
#[allow(unused_imports)]
pub use pack_outputs::*;
mod same_bytes;
#[allow(unused_imports)]
pub use same_bytes::*;
use same_bytes::*;
+7 -7
View File
@@ -65,7 +65,7 @@ fn the_native_ple_key_encodings_are_the_originals() {
}
/// Numpy (`astype(float16)`) and gguf-py (`BF16.quantize_blocks`) answers for 4096 f32 bit patterns, from
/// `scripts/offline/gen_goldens.py`. The packer's F32 -> F16 / BF16 helpers must match bit for bit.
/// the Original's offline tooling (Strata 41cf05a0). The packer's F32 -> F16 / BF16 helpers must match bit for bit.
#[test]
fn f16_and_bf16_rounding_match_numpy_and_gguf_py() {
let vectors = include_bytes!("../../tests/fixtures/offline/f16_bf16_vectors.golden");
@@ -236,12 +236,12 @@ fn shards_for(golden: &Golden) -> Vec<Shard> {
#[test]
fn real_golden_expert_tables_are_reproduced() {
let goldens = [
include_str!("../../../engine/strata/tests/data/native_experts/iq3_s.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/iq3_xxs.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/iq2_xs.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/q2_0.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/coder-iq1_m.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/swift-iq2_xs.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/iq3_s.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/iq3_xxs.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/iq2_xs.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/q2_0.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/coder-iq1_m.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/swift-iq2_xs.txt"),
];
for text in goldens {
let golden = parse_golden(text);
+4 -11
View File
@@ -79,26 +79,19 @@ struct StagingDir(PathBuf);
mod tests;
mod preview_entry_points;
#[allow(unused_imports)]
pub use preview_entry_points::*;
mod prepare_sharded;
#[allow(unused_imports)]
pub use prepare_sharded::*;
mod streamed_sharded_prepare;
#[allow(unused_imports)]
pub use streamed_sharded_prepare::*;
use streamed_sharded_prepare::*;
mod spool_raw_f32;
#[allow(unused_imports)]
pub use spool_raw_f32::*;
use spool_raw_f32::*;
mod prepare_single_file;
#[allow(unused_imports)]
pub use prepare_single_file::*;
use prepare_single_file::*;
mod tensor_encoding;
#[allow(unused_imports)]
pub use tensor_encoding::*;
mod derived_verification;
#[allow(unused_imports)]
pub use derived_verification::*;
use derived_verification::*;
mod preview_tensor_io;
use preview_tensor_io::*;
mod sharded_encode;
-1
View File
@@ -41,5 +41,4 @@ mod tests;
mod series;
use series::SERIES;
mod render;
#[allow(unused_imports)]
pub use render::*;
+2 -2
View File
@@ -35,7 +35,7 @@ pub(super) fn format_value(value: f64) -> String {
}
/// Render the `/metrics` document. `model` (when the document has one) labels `leleka_info`.
pub fn render(document: &Value) -> String {
pub fn render(document: &Value, requests: &crate::request_log::RequestMetrics) -> String {
let mut out = String::new();
let mut described: Vec<&str> = Vec::new();
for series in SERIES {
@@ -54,7 +54,7 @@ pub fn render(document: &Value) -> String {
let _ = writeln!(out, "# TYPE leleka_info gauge");
let model = document.get("model").and_then(Value::as_str).unwrap_or("");
let _ = writeln!(out, "leleka_info{{model=\"{}\"}} 1", escape(model));
crate::request_log::render_prometheus(&mut out);
requests.render_prometheus(&mut out);
out
}
+5 -4
View File
@@ -2,6 +2,7 @@
//! their fixed labels, unmeasured figures left out, and the choice of format by query or `Accept` header.
use super::*;
use crate::request_log::RequestMetrics;
use serde_json::json;
fn document() -> Value {
@@ -27,7 +28,7 @@ fn document() -> Value {
#[test]
fn counters_gauges_and_labels_render_in_the_text_format() {
let text = render(&document());
let text = render(&document(), &RequestMetrics::default());
assert!(text.contains("# TYPE leleka_generations_started_total counter\nleleka_generations_started_total 5\n"));
assert!(text.contains("leleka_prefill_seconds_total 2.5\n"));
assert!(text.contains("leleka_decode_seconds_total 1.25\n"));
@@ -85,7 +86,7 @@ const ENGINE_LINES: [&str; 16] = [
#[test]
fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() {
let text = render(&engine_document());
let text = render(&engine_document(), &RequestMetrics::default());
for expected in ENGINE_LINES {
assert!(text.contains(expected), "{expected} missing:\n{text}");
}
@@ -108,11 +109,11 @@ fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() {
#[test]
fn unmeasured_figures_are_not_exposed() {
let text = render(&document());
let text = render(&document(), &RequestMetrics::default());
// null in the document: no lifetime decode rate, no GPU clock, no swap
assert!(!text.contains("window=\"lifetime\""));
assert!(!text.contains("leleka_gpu_sm_clock_megahertz"));
let bare = render(&json!({"model": "m", "up": false}));
let bare = render(&json!({"model": "m", "up": false}), &RequestMetrics::default());
assert!(bare.contains("leleka_up 0\n"));
assert!(!bare.contains("leleka_gpu_") && !bare.contains("leleka_engine_phase"));
// every line is HELP, TYPE or a sample
+23 -19
View File
@@ -11,10 +11,10 @@
//! finalises the request, or, for a request that never reached the engine (a rejection, a client that left the queue),
//! when the last reference is dropped.
//!
//! The same moment feeds the Prometheus histograms and counters of [`render_prometheus`], whose labels are enums of
//! The same moment feeds the Prometheus histograms and counters of [`RequestMetrics`], whose labels are enums of
//! fixed size (endpoint x outcome, error class): there is no label whose value comes from a client.
use std::sync::{
Arc, LazyLock, Mutex,
Arc, Mutex,
atomic::{AtomicU64, Ordering},
};
@@ -85,6 +85,7 @@ struct Live {
pub struct ReqCtx {
state: Mutex<Live>,
clock: crate::ports::SharedClock,
metrics: Arc<RequestMetrics>,
}
/// What the request middleware leaves for the handler and the worker.
@@ -101,6 +102,7 @@ pub struct Observe {
pub model: Option<String>,
pub memory: Arc<crate::memory_view::MemoryView>,
pub clock: crate::ports::SharedClock,
pub metrics: Arc<RequestMetrics>,
}
/// Everything the line says, resolved.
@@ -128,7 +130,7 @@ pub struct Record {
pub hardware: Option<crate::memory_view::Brief>,
}
struct Registry {
pub struct RequestMetrics {
requests: Vec<AtomicU64>,
errors: Vec<AtomicU64>,
restarts: AtomicU64,
@@ -143,29 +145,31 @@ struct Registry {
prefill_tps: Histogram,
}
static REGISTRY: LazyLock<Registry> = LazyLock::new(|| Registry {
requests: (0..ENDPOINTS.len() * OUTCOMES.len()).map(|_| AtomicU64::new(0)).collect(),
errors: (0..ERROR_CLASSES.len()).map(|_| AtomicU64::new(0)).collect(),
restarts: AtomicU64::new(0),
engine_lost: AtomicU64::new(0),
engine_attached: AtomicU64::new(0),
ttft: Histogram::new(&[0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0]),
duration: Histogram::new(&[0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0]),
queue: Histogram::new(&[0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 15.0, 60.0]),
prompt_tokens: Histogram::new(&[256.0, 1024.0, 4096.0, 16384.0, 65536.0, 131072.0, 262144.0]),
output_tokens: Histogram::new(&[16.0, 64.0, 256.0, 1024.0, 4096.0, 16384.0, 65536.0]),
decode_tps: Histogram::new(&[5.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0, 150.0]),
prefill_tps: Histogram::new(&[100.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0]),
});
impl Default for RequestMetrics {
fn default() -> Self {
Self {
requests: (0..ENDPOINTS.len() * OUTCOMES.len()).map(|_| AtomicU64::new(0)).collect(),
errors: (0..ERROR_CLASSES.len()).map(|_| AtomicU64::new(0)).collect(),
restarts: AtomicU64::new(0),
engine_lost: AtomicU64::new(0),
engine_attached: AtomicU64::new(0),
ttft: Histogram::new(&[0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0]),
duration: Histogram::new(&[0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0]),
queue: Histogram::new(&[0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 15.0, 60.0]),
prompt_tokens: Histogram::new(&[256.0, 1024.0, 4096.0, 16384.0, 65536.0, 131072.0, 262144.0]),
output_tokens: Histogram::new(&[16.0, 64.0, 256.0, 1024.0, 4096.0, 16384.0, 65536.0]),
decode_tps: Histogram::new(&[5.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0, 150.0]),
prefill_tps: Histogram::new(&[100.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0]),
}
}
}
#[cfg(test)]
mod tests;
mod request_context;
#[allow(unused_imports)]
pub use request_context::*;
mod observation;
#[allow(unused_imports)]
pub use observation::*;
mod metrics_text;
#[allow(unused_imports)]
+97 -95
View File
@@ -1,107 +1,109 @@
//! The request metrics in the Prometheus text format (requests by endpoint and outcome, errors by class, engine lost,
//! attached and restart counters, time and token histograms) and the note that a worker attached to a loaded engine.
use super::{ENDPOINTS, ERROR_CLASSES, OUTCOMES, Ordering, REGISTRY};
use super::{ENDPOINTS, ERROR_CLASSES, OUTCOMES, Ordering, RequestMetrics};
use std::fmt::Write as _;
/// The worker attached to a loaded engine (at start and after every restart).
pub fn note_engine_attached() {
let n = REGISTRY.engine_attached.fetch_add(1, Ordering::Relaxed) + 1;
leleka_obs::emit_always(leleka_obs::Level::Info, "api", "engine_attached", &[("attaches", n.into())]);
}
impl RequestMetrics {
/// The worker attached to a loaded engine (at start and after every restart).
pub fn note_engine_attached(&self) {
let n = self.engine_attached.fetch_add(1, Ordering::Relaxed) + 1;
leleka_obs::emit_always(leleka_obs::Level::Info, "api", "engine_attached", &[("attaches", n.into())]);
}
/// Append the request metrics in the Prometheus text format.
pub fn render_prometheus(out: &mut String) {
render_requests(out);
render_errors(out);
render_engine_counters(out);
render_histograms(out);
}
/// Append the request metrics in the Prometheus text format.
pub fn render_prometheus(&self, out: &mut String) {
self.render_requests(out);
self.render_errors(out);
self.render_engine_counters(out);
self.render_histograms(out);
}
/// `leleka_requests_total` by endpoint and outcome (a zero line when there is none).
fn render_requests(out: &mut String) {
let reg = &*REGISTRY;
leleka_obs::hist::header(
"leleka_requests_total",
"Generation requests by endpoint and how they ended.",
"counter",
out,
);
let mut any = false;
for (e, endpoint) in ENDPOINTS.iter().enumerate() {
for (o, outcome) in OUTCOMES.iter().enumerate() {
let n = reg.requests[e * OUTCOMES.len() + o].load(Ordering::Relaxed);
if n > 0 {
any = true;
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} {n}");
/// `leleka_requests_total` by endpoint and outcome (a zero line when there is none).
fn render_requests(&self, out: &mut String) {
let reg = self;
leleka_obs::hist::header(
"leleka_requests_total",
"Generation requests by endpoint and how they ended.",
"counter",
out,
);
let mut any = false;
for (e, endpoint) in ENDPOINTS.iter().enumerate() {
for (o, outcome) in OUTCOMES.iter().enumerate() {
let n = reg.requests[e * OUTCOMES.len() + o].load(Ordering::Relaxed);
if n > 0 {
any = true;
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} {n}");
}
}
}
if !any {
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"responses\",outcome=\"stop\"}} 0");
}
}
if !any {
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"responses\",outcome=\"stop\"}} 0");
/// `leleka_request_errors_total` by error class.
fn render_errors(&self, out: &mut String) {
let reg = self;
leleka_obs::hist::header(
"leleka_request_errors_total",
"Failed or rejected requests by error class.",
"counter",
out,
);
for (c, class) in ERROR_CLASSES.iter().enumerate().skip(1) {
let n = reg.errors[c].load(Ordering::Relaxed);
let _ = writeln!(out, "leleka_request_errors_total{{class=\"{class}\"}} {n}");
}
}
/// The engine lost, attached and restart-request counters.
fn render_engine_counters(&self, out: &mut String) {
let reg = self;
let counters = [
(
"leleka_engine_lost_total",
"Times the API lost the engine (it restarted, hung or stopped answering).",
&reg.engine_lost,
),
(
"leleka_engine_attached_total",
"Times the API attached to a loaded engine (the first start counts).",
&reg.engine_attached,
),
("leleka_requests_engine_restart_total", "Requests during which the engine was lost.", &reg.restarts),
];
for (name, help, value) in counters {
leleka_obs::hist::header(name, help, "counter", out);
let _ = writeln!(out, "{name} {}", value.load(Ordering::Relaxed));
}
}
/// The time, token and rate histograms of the requests.
fn render_histograms(&self, out: &mut String) {
self.render_time_histograms(out);
self.render_size_histograms(out);
}
/// The time histograms: first token, duration and queue wait.
fn render_time_histograms(&self, out: &mut String) {
let reg = self;
reg.ttft.render("leleka_request_ttft_seconds", "Time from arrival to the first generated token.", out);
reg.duration.render("leleka_request_duration_seconds", "Time from arrival to the end of the request.", out);
reg.queue.render("leleka_request_queue_wait_seconds", "Time a request waited before the engine took it.", out);
}
/// The token-count and token-rate histograms.
fn render_size_histograms(&self, out: &mut String) {
let reg = self;
reg.prompt_tokens.render("leleka_request_prompt_tokens", "Prompt tokens per request.", out);
reg.output_tokens.render("leleka_request_output_tokens", "Output tokens per request.", out);
reg.decode_tps.render("leleka_request_decode_tokens_per_second", "Decode rate per request.", out);
reg.prefill_tps.render(
"leleka_request_prefill_tokens_per_second",
"Prefill rate per request (uncached prompt tokens).",
out,
);
}
}
/// `leleka_request_errors_total` by error class.
fn render_errors(out: &mut String) {
let reg = &*REGISTRY;
leleka_obs::hist::header(
"leleka_request_errors_total",
"Failed or rejected requests by error class.",
"counter",
out,
);
for (c, class) in ERROR_CLASSES.iter().enumerate().skip(1) {
let n = reg.errors[c].load(Ordering::Relaxed);
let _ = writeln!(out, "leleka_request_errors_total{{class=\"{class}\"}} {n}");
}
}
/// The engine lost, attached and restart-request counters.
fn render_engine_counters(out: &mut String) {
let reg = &*REGISTRY;
let counters = [
(
"leleka_engine_lost_total",
"Times the API lost the engine (it restarted, hung or stopped answering).",
&reg.engine_lost,
),
(
"leleka_engine_attached_total",
"Times the API attached to a loaded engine (the first start counts).",
&reg.engine_attached,
),
("leleka_requests_engine_restart_total", "Requests during which the engine was lost.", &reg.restarts),
];
for (name, help, value) in counters {
leleka_obs::hist::header(name, help, "counter", out);
let _ = writeln!(out, "{name} {}", value.load(Ordering::Relaxed));
}
}
/// The time, token and rate histograms of the requests.
fn render_histograms(out: &mut String) {
render_time_histograms(out);
render_size_histograms(out);
}
/// The time histograms: first token, duration and queue wait.
fn render_time_histograms(out: &mut String) {
let reg = &*REGISTRY;
reg.ttft.render("leleka_request_ttft_seconds", "Time from arrival to the first generated token.", out);
reg.duration.render("leleka_request_duration_seconds", "Time from arrival to the end of the request.", out);
reg.queue.render("leleka_request_queue_wait_seconds", "Time a request waited before the engine took it.", out);
}
/// The token-count and token-rate histograms.
fn render_size_histograms(out: &mut String) {
let reg = &*REGISTRY;
reg.prompt_tokens.render("leleka_request_prompt_tokens", "Prompt tokens per request.", out);
reg.output_tokens.render("leleka_request_output_tokens", "Output tokens per request.", out);
reg.decode_tps.render("leleka_request_decode_tokens_per_second", "Decode rate per request.", out);
reg.prefill_tps.render(
"leleka_request_prefill_tokens_per_second",
"Prefill rate per request (uncached prompt tokens).",
out,
);
}
+12 -9
View File
@@ -3,7 +3,7 @@
use super::{
Arc, CURRENT, Done, ENDPOINTS, ERROR_CLASSES, HeaderValue, Instant, Live, Next, OUTCOMES, ObsHandle, Observe,
Ordering, REGISTRY, REQUEST_ID_HEADER, Record, Registry, ReqCtx, ReqIdentity, Request, Response, State, V,
Ordering, REQUEST_ID_HEADER, Record, ReqCtx, ReqIdentity, Request, RequestMetrics, Response, State, V,
class_of_status, endpoint_index, session_tag,
};
@@ -69,7 +69,8 @@ pub async fn observe(State(observe): State<Observe>, request: Request, next: Nex
sid: session_tag(request.headers()),
model: observe.model.clone(),
};
let ctx = Arc::new(ReqCtx::new(identity, Some(observe.memory.clone()), observe.clock.clone()));
let ctx =
Arc::new(ReqCtx::new(identity, Some(observe.memory.clone()), observe.clock.clone(), observe.metrics.clone()));
let id = ctx.id();
let mut response = CURRENT.scope(ctx.clone(), next.run(request)).await;
ctx.set_http_status(response.status().as_u16());
@@ -224,13 +225,13 @@ impl Record {
}
}
pub(super) fn publish(&self) {
REGISTRY.observe(self);
pub(super) fn publish(&self, metrics: &RequestMetrics) {
metrics.observe(self);
leleka_obs::record("api", "request", &self.fields());
}
}
impl Registry {
impl RequestMetrics {
pub(super) fn observe(&self, r: &Record) {
let outcome = OUTCOMES.iter().position(|o| *o == r.outcome).unwrap_or(OUTCOMES.len() - 1);
self.requests[r.endpoint * OUTCOMES.len() + outcome].fetch_add(1, Ordering::Relaxed);
@@ -268,8 +269,10 @@ impl Registry {
}
}
/// The worker lost the engine (a structured warning is logged; the count feeds `leleka_engine_lost_total`).
pub fn note_engine_lost(reason: &str) {
REGISTRY.engine_lost.fetch_add(1, Ordering::Relaxed);
leleka_obs::warn("api", "engine_lost", &[("reason", reason.into())]);
impl RequestMetrics {
/// The worker lost the engine (a structured warning is logged; the count feeds `leleka_engine_lost_total`).
pub fn note_engine_lost(&self, reason: &str) {
self.engine_lost.fetch_add(1, Ordering::Relaxed);
leleka_obs::warn("api", "engine_lost", &[("reason", reason.into())]);
}
}
@@ -2,7 +2,8 @@
//! the classifiers that keep free text out of the line: endpoint index, session tag by digest, error class.
use super::{
Arc, Digest, Done, DoneInfo, Finish, HeaderMap, Live, Mutex, ObsHandle, Record, ReqCtx, SESSION_HEADERS, Sha256,
Arc, Digest, Done, DoneInfo, Finish, HeaderMap, Live, Mutex, ObsHandle, Record, ReqCtx, RequestMetrics,
SESSION_HEADERS, Sha256,
};
pub fn endpoint_index(path: &str) -> usize {
@@ -76,6 +77,7 @@ impl ReqCtx {
identity: ReqIdentity,
memory: Option<Arc<crate::memory_view::MemoryView>>,
clock: crate::ports::SharedClock,
metrics: Arc<RequestMetrics>,
) -> Self {
Self {
state: Mutex::new(Live {
@@ -96,6 +98,7 @@ impl ReqCtx {
memory,
}),
clock,
metrics,
}
}
@@ -171,7 +174,7 @@ impl ReqCtx {
Some(Record::from_state(s, self.clock.now()))
});
if let Some(Some(record)) = record {
record.publish();
record.publish(&self.metrics);
}
}
}
@@ -186,7 +189,7 @@ impl Drop for ReqCtx {
_ => None,
};
if let Some(record) = record {
record.publish();
record.publish(&self.metrics);
}
}
}
+18 -14
View File
@@ -34,14 +34,14 @@ fn ctx() -> ReqCtx {
sid: Some("s-0123456789".into()),
model: Some("qwen-iq3".into()),
};
ReqCtx::new(identity, None, crate::adapters::SystemClock::shared())
ReqCtx::new(identity, None, crate::adapters::SystemClock::shared(), Arc::default())
}
#[test]
fn the_record_stamps_come_from_the_injected_clock() {
let clock = crate::ports::fakes::ManualClock::new(1_700_000_000);
let identity = ReqIdentity { id: "rid".into(), endpoint: 0, sid: None, model: None };
let c = ReqCtx::new(identity, None, clock.clone());
let c = ReqCtx::new(identity, None, clock.clone(), Arc::default());
clock.advance(std::time::Duration::from_millis(40));
c.engine_start();
clock.advance(std::time::Duration::from_millis(60));
@@ -189,19 +189,20 @@ fn the_session_header_is_hashed_not_copied() {
assert_eq!(session_tag(&headers).unwrap(), tag);
}
fn counted(endpoint: &str, outcome: &str) -> u64 {
fn counted(metrics: &RequestMetrics, endpoint: &str, outcome: &str) -> u64 {
let mut text = String::new();
render_prometheus(&mut text);
metrics.render_prometheus(&mut text);
let prefix = format!("leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} ");
text.lines().find_map(|l| l.strip_prefix(prefix.as_str())).and_then(|n| n.parse().ok()).unwrap_or(0)
}
/// A router whose handler asserts it sees the request's record and answers 503, behind the `observe` middleware.
fn rejecting_router() -> axum::Router {
fn rejecting_router(metrics: Arc<RequestMetrics>) -> axum::Router {
let observe = Observe {
model: Some("m".into()),
memory: Arc::new(Default::default()),
clock: crate::adapters::SystemClock::shared(),
metrics,
};
axum::Router::new()
.route(
@@ -217,8 +218,10 @@ fn rejecting_router() -> axum::Router {
}
/// Serves `rejecting_router` on a free port; returns its URL and the server task.
async fn serve_rejecting_handler() -> (String, tokio::task::JoinHandle<std::io::Result<()>>) {
let app = rejecting_router();
async fn serve_rejecting_handler(
metrics: Arc<RequestMetrics>,
) -> (String, tokio::task::JoinHandle<std::io::Result<()>>) {
let app = rejecting_router(metrics);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/v1/chat/completions", listener.local_addr().unwrap());
let server = tokio::spawn(async move { axum::serve(listener, app).await });
@@ -227,10 +230,10 @@ async fn serve_rejecting_handler() -> (String, tokio::task::JoinHandle<std::io::
/// The rejected-chat count once it rises above `before`. The record is written when the last reference to it is gone,
/// just after the response.
async fn counted_after(before: u64) -> u64 {
async fn counted_after(metrics: &RequestMetrics, before: u64) -> u64 {
let mut after = before;
for _ in 0..50 {
after = counted("chat", "rejected");
after = counted(metrics, "chat", "rejected");
if after > before {
break;
}
@@ -241,14 +244,15 @@ async fn counted_after(before: u64) -> u64 {
#[tokio::test]
async fn the_middleware_names_the_request_hands_it_to_the_handler_and_records_a_rejection() {
let (url, server) = serve_rejecting_handler().await;
let before = counted("chat", "rejected");
let metrics = Arc::<RequestMetrics>::default();
let (url, server) = serve_rejecting_handler(metrics.clone()).await;
let before = counted(&metrics, "chat", "rejected");
let response = reqwest::Client::new().post(url).header("session_id", "conv-4417").body("{}").send().await.unwrap();
assert_eq!(response.status(), 503);
let id = response.headers()[REQUEST_ID_HEADER].to_str().unwrap().to_owned();
assert!(uuid::Uuid::parse_str(&id).is_ok(), "{id}");
assert!(!id.contains("4417"));
let after = counted_after(before).await;
let after = counted_after(&metrics, before).await;
assert!(after > before, "the rejection must be counted: {before} -> {after}");
server.abort();
}
@@ -259,9 +263,9 @@ fn the_prometheus_text_has_fixed_labels_and_valid_lines() {
c.engine_start();
c.first_token();
c.done(&done("DONE 10 100 5.0 100.0 length"), false);
record_of(&c).publish();
record_of(&c).publish(&c.metrics);
let mut text = String::new();
render_prometheus(&mut text);
c.metrics.render_prometheus(&mut text);
assert!(text.contains("leleka_requests_total{endpoint=\"responses\",outcome=\"length\"}"), "{text}");
assert!(text.contains("# TYPE leleka_request_ttft_seconds histogram"));
for line in text.lines() {
+2 -4
View File
@@ -1,5 +1,5 @@
//! The API request monitor: `GET /api/requests`, the opt-in inspection of the last requests' prompts and answers of the
//! Python service (`api_monitor` in its config; `engine/strata/serve/server.py` `begin_request` / `request_records`,
//! Python service (`api_monitor` in its config; `Strata 41cf05a0, serve/server.py` `begin_request` / `request_records`,
//! tests in `serve/test_monitor.py`).
//!
//! It keeps the last [`RETENTION`] requests of the three generation dialects (`/v1/chat/completions`, `/v1/messages`,
@@ -93,11 +93,9 @@ struct Tap {
mod tests;
mod captured_text;
#[allow(unused_imports)]
pub use captured_text::*;
use captured_text::*;
mod record;
#[allow(unused_imports)]
pub use record::*;
mod capture;
#[allow(unused_imports)]
pub use capture::*;
+1 -1
View File
@@ -54,7 +54,7 @@ use serde_json::Map;
type SharedCodec = Arc<dyn TextCodec>;
static NEXT_RESPONSE_ID: AtomicU64 = AtomicU64::new(0);
mod harmony_prompt;
pub use harmony_prompt::{PromptDate, set_prompt_date};
pub use harmony_prompt::PromptDate;
mod create;
pub use create::create;
mod errors;
+5 -13
View File
@@ -7,7 +7,6 @@
//! developer message; reasoning of earlier turns is not replayed (the template drops it), except for a
//! tool-call message where the template keeps it; custom tools are not supported.
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};
pub use leleka_gateway_domain::responses::PromptDate;
@@ -19,22 +18,15 @@ use serde_json::Value;
use super::CreateRequest;
static PROMPT_DATE: OnceLock<PromptDate> = OnceLock::new();
/// Choose the date mode for the rest of the process (once, at start; later calls are ignored).
pub fn set_prompt_date(mode: PromptDate) {
let _ = PROMPT_DATE.set(mode);
}
pub(super) fn today() -> String {
civil_date(SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs())
}
/// Render the Harmony prompt for `request` with today's date. The special markers are written as
/// sentinel characters, which the gpt-oss codec turns into the special tokens: text from the client can
/// never forge a marker.
pub(super) fn render(request: &CreateRequest) -> Result<String, String> {
match PROMPT_DATE.get().unwrap_or(&PromptDate::Utc) {
/// Render the Harmony prompt for `request` with the date `mode` says (the model view's `prompt_date`). The special
/// markers are written as sentinel characters, which the gpt-oss codec turns into the special tokens: text from the
/// client can never forge a marker.
pub(super) fn render(request: &CreateRequest, mode: &PromptDate) -> Result<String, String> {
match mode {
PromptDate::Utc => render_dated(request, Some(&today()), true),
PromptDate::Fixed(date) => render_dated(request, Some(date), true),
PromptDate::None => render_dated(request, None, true),
+1 -1
View File
@@ -90,7 +90,7 @@ pub(super) async fn prepare_input_tokens(
encode_images: bool,
) -> Result<Prepared, Box<Response>> {
resolve_previous(state, request).await?;
let (prompt, images) = render_prompt(&tokenizer, request)?;
let (prompt, images) = render_prompt(&tokenizer, request, &state.model.prompt_date)?;
let (token_ids, prompt) = tokenize_prompt(tokenizer.clone(), prompt).await?;
if images.is_empty() || !encode_images {
return Ok(Prepared {
@@ -74,13 +74,14 @@ pub(super) async fn resolve_previous(state: &AppState, request: &mut CreateReque
pub(super) fn render_prompt(
tokenizer: &SharedCodec,
request: &CreateRequest,
date: &crate::responses::PromptDate,
) -> Result<(String, Vec<String>), Box<Response>> {
let rendered = crate::stage_trace::time("render", || match tokenizer.family() {
Family::Qwen35 => {
let qwen = tokenizer.qwen().ok_or_else(|| "the Qwen family needs the Qwen tokenizer".to_owned())?;
render_request(request, qwen.marks())
}
Family::GptOss => harmony_prompt::render(request).map(|prompt| (prompt, Vec::new())),
Family::GptOss => harmony_prompt::render(request, date).map(|prompt| (prompt, Vec::new())),
});
rendered.map_err(|message| {
refuse(StatusCode::BAD_REQUEST, "invalid_request_error", "invalid_prompt", Some("input"), &message)
+1
View File
@@ -51,6 +51,7 @@ pub(super) fn worker_config(
cancel_drain_timeout: Duration::from_secs(20),
prefix_view: Some(state.model.prefix_cache.clone()),
memory_view: Some(state.model.memory.clone()),
request_metrics: state.services.request_metrics.clone(),
}
}
+1 -1
View File
@@ -48,6 +48,7 @@ pub(super) fn build_state(config: &Config, history: ResponseHistory) -> Result<a
model: app::ModelView {
name: config.model.clone(),
aliases: Arc::new(config.aliases.clone()),
prompt_date: config.prompt_date.clone(),
..Default::default()
},
services: services(config, history),
@@ -108,7 +109,6 @@ pub(super) fn apply_prompt_settings(config: &Config) {
config.prompt_date
);
}
leleka_control_plane::responses::set_prompt_date(config.prompt_date.clone());
if config.tool_call_recovery {
leleka_control_plane::elog!(
"tool_call_recovery is ON (experimental): a declared tool's call written in a drifted form is run as \
+3 -3
View File
@@ -1,8 +1,8 @@
//! The operational HTTP surface of the Original's Python server (`engine/strata/serve/server.py`)
//! The operational HTTP surface of the Original's Python server (`Strata 41cf05a0, serve/server.py`)
//! that is not an inference API: `GET /props`, `GET /slots`, `GET /v1/status`, `GET /api/health`,
//! `GET|POST /settings`, `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload`, CORS and
//! the own-page guard. Behaviour is checked against the real Python handlers in
//! `tests/http_surface.rs` (fixtures from `tests/golden/gen_goldens.py http`).
//! `tests/http_surface.rs` (fixtures recorded from the Original's Python server).
//!
//! One engine at a time: `total_slots` is 1 and `/slots` lists one slot while the engine is loaded.
@@ -32,7 +32,7 @@ use crate::{
};
/// The chat template the Original serves in `/props` when the model ships none.
pub const DEFAULT_CHAT_TEMPLATE: &str = include_str!("../../engine/strata/serve/chat_template.jinja");
pub const DEFAULT_CHAT_TEMPLATE: &str = include_str!("../../third_party/strata/serve/chat_template.jinja");
mod engine_lifecycle;
pub use engine_lifecycle::*;
+1 -3
View File
@@ -28,8 +28,6 @@ mod unix;
mod tests;
mod command_line;
#[allow(unused_imports)]
pub use command_line::*;
use command_line::*;
mod control;
#[allow(unused_imports)]
pub use control::*;
+2 -5
View File
@@ -188,13 +188,10 @@ mod storage {
mod tests;
mod switch_profiles;
#[allow(unused_imports)]
pub use switch_profiles::*;
use switch_profiles::*;
mod run;
#[allow(unused_imports)]
pub use run::*;
mod reconcile;
#[cfg(unix)]
mod transaction;
#[allow(unused_imports)]
pub use reconcile::*;
use reconcile::*;
+1 -1
View File
@@ -184,7 +184,7 @@ mod tests {
}
/// Every GEN/GENI line equals what the Original's `StrataEngine.generate` writes to the pipe
/// (fixture from `tests/golden/gen_goldens.py`, which runs that real code with a fake pipe).
/// (fixture recorded by running that real code with a fake pipe).
#[test]
fn gen_lines_equal_the_python_servers_for_every_sampling_key() {
let fixture: serde_json::Value =
@@ -102,6 +102,7 @@ fn default_worker_config(tokenizer: Arc<Tokenizer>) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
@@ -32,6 +32,7 @@ fn worker_config(stack: &Stack) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(1),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
+1 -2
View File
@@ -1,10 +1,9 @@
//! The native Jinja renderer against the Python server's `ChatTemplate` (jinja2) on generated conversations.
//!
//! `tests/fixtures/offline/chat_template_oracle.json` comes from `scripts/offline/gen_goldens.py chat_template_oracle`:
//! `tests/fixtures/offline/chat_template_oracle.json` was recorded from the Original's Python code (Strata 41cf05a0):
//! 90 renders (every role incl. developer and tool, list content with image/video parts, assistant `tool_calls`
//! with mapping arguments, tools, `enable_thinking` / `reasoning_effort` / `preserve_thinking`, no generation
//! prompt) and 25 conversations the template refuses, with the exact `raise_exception` message.
//! `scripts/offline/diff_chat_template.py` runs the same generator live over thousands of cases.
use leleka_control_plane::prompt::{ChatInput, Json, pinned};
use serde::Deserialize;
+2 -2
View File
@@ -1,8 +1,8 @@
//! Dequantization versus the pinned gguf-py (`quants.dequantize`, llama.cpp 3cf03257) and `tools/iq_fixture.py`.
//!
//! `tests/fixtures/offline/dequant_oracle.json` holds one seeded 256-value row of each of 23 block types and the
//! oracle's float32 bits (`scripts/offline/gen_goldens.py dequant_oracle`; `scripts/offline/diff_dequant.py` runs
//! 32 rows x 3 seeds live). The production visitor (`gguf_f32_stream::visit`: independent Rust decoders where they
//! oracle's float32 bits (recorded from the Original's Python code, Strata 41cf05a0). The production
//! visitor (`gguf_f32_stream::visit`: independent Rust decoders where they
//! exist, the pinned ggml C bridge otherwise) must reproduce every float bit for bit. Q8_K has no gguf-py
//! dequantizer; its reference is `d * qs`.
use leleka_control_plane::{gguf, gguf_f32_stream};
@@ -1,10 +1,9 @@
//! GGUF header reader versus `engine/strata/tools/gguf_reader.py`.
//! GGUF header reader versus `Strata 41cf05a0, tools/gguf_reader.py`.
//!
//! `tests/fixtures/offline/gguf_headers.json` is generated by `scripts/offline/gen_goldens.py` from the unmodified
//! `tests/fixtures/offline/gguf_headers.json` was recorded offline from the unmodified
//! Python reader: random GGUF v3 headers (all 13 metadata value types, arrays, unicode, alignment, split keys,
//! 1-4 dimensional tensors of every block geometry) with the metadata and tensor directory it parses from each, and
//! its `BLOCK_GEOMETRY` table. The live differential over thousands of files is
//! `scripts/offline/diff_gguf_header.py`.
//! its `BLOCK_GEOMETRY` table.
use leleka_control_plane::{gguf, gguf_json};
use serde_json::Value;
use std::{fs, path::PathBuf};
-617
View File
@@ -1,617 +0,0 @@
"""Offline golden generator for the control-plane serving surface (Python is allowed for fixtures only).
Runs the REAL Python handlers of the pinned Strata (`engine/strata/serve/*.py`, mock engine, no GPU) over tables
of inputs and records what they answer. The Rust tests in `control-plane/tests/golden_*.rs` and the unit tests of
`crates/serving-policy` compare against these files.
python3 -I control-plane/tests/golden/gen_goldens.py [section ...]
Needs the packages in engine/strata/requirements.txt (jinja2, jsonschema, regex). The scratchpad venv has them.
Sections: gen_lines, shared, props_slots, cors, ...
"""
import json
import os
import queue
import sys
import threading
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.normpath(os.path.join(HERE, "..", "..", ".."))
ENGINE = os.path.join(REPO, "engine", "strata")
sys.path.insert(0, ENGINE)
sys.path.insert(0, os.path.join(ENGINE, "tools"))
OUT_CONTROL = os.path.join(HERE, "..", "fixtures", "golden")
OUT_POLICY = os.path.join(REPO, "crates", "serving-policy", "tests", "fixtures")
def write(name, obj, dest="control"):
out = OUT_POLICY if dest == "policy" else OUT_CONTROL
os.makedirs(out, exist_ok=True)
path = os.path.join(out, name + ".json")
with open(path, "w", encoding="utf-8") as f:
json.dump(obj, f, indent=1, ensure_ascii=False, sort_keys=False)
f.write("\n")
print("wrote", os.path.relpath(path, REPO), file=sys.stderr)
# ------------------------------------------------------------------------------------------------ gen_lines
def gen_lines():
from serve.server import StrataEngine
class Pipe:
def __init__(self):
self.sent = []
def write(self, text):
self.sent.append(text)
def flush(self):
pass
def capture(ids, max_new, sampling, embeddings=None):
eng = object.__new__(StrataEngine)
eng.proc = type("P", (), {"stdin": Pipe()})()
eng.lines = queue.Queue()
eng.lines.put("DONE 1 1 1.0 1.0 stop\n")
eng.can_stop = False
eng.progress = None
eng.prefill_tok_s_mean = None
eng.last = {}
list(eng.generate(ids, max_new, sampling, threading.Event(), embeddings=embeddings))
return "".join(eng.proc.stdin.sent)
cases = []
sampling_tables = [
{},
{"temperature": 0.0},
{"temperature": 0.7},
{"temperature": 0.7, "top_p": 0.9},
{"temperature": 1, "top_p": 1.0},
{"temperature": 0.8, "top_k": 40, "min_p": 0.05},
{"temperature": 0.8, "top_k": 0},
{"temperature": 0.8, "top_k": 1000},
{"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.0},
{"repetition_penalty": 1.1},
{"repetition_penalty": 1.1, "penalty_last_n": 256},
{"presence_penalty": 0.5, "frequency_penalty": 0.25},
{"presence_penalty": -0.5},
{"frequency_penalty": 1.5, "penalty_last_n": 0},
{"temperature": 0.7, "seed": 42},
{"temperature": 0.7, "seed": 0},
{"temperature": 0.7, "seed": 18446744073709551615},
{"temperature": 0.9, "top_p": 0.8, "top_k": 33, "min_p": 0.02, "repetition_penalty": 1.05,
"presence_penalty": 0.1, "frequency_penalty": 0.2, "penalty_last_n": 128, "seed": 7},
{"strata_tune": {"pcie_frac": 0.0}},
{"strata_tune": {"pcie_frac": 0.35, "spec_min_p": 0.2}},
{"strata_tune": {"spec_min_p": 1.0}},
{"experimental_speed_projection": True},
{"experimental_speed_projection": False},
{"temperature": 0.5, "strata_tune": {"pcie_frac": 0.5}, "experimental_speed_projection": False},
]
for ids, max_new, emb in (([1, 2, 3], 16, None), ([248045, 872, 198, 9707], 4096, None),
([5, 248056, 248056, 6], 32, "/tmp/req-abc123.sve")):
for sampling in sampling_tables:
cases.append({"token_ids": ids, "max_new": max_new, "embeddings": emb, "sampling": sampling,
"line": capture(ids, max_new, sampling, emb)})
write("gen_lines", {"source": "serve/server.py StrataEngine.generate (real code, fake pipe)", "cases": cases})
# ------------------------------------------------------------------------------------------------ shared
def shared():
from serve.server import clean_shared_defaults, sampling_defaults_from_config
clean_cases = [
None, {}, [], "x", 5,
{"temperature": 0.7}, {"temperature": 1}, {"temperature": 0}, {"temperature": 2}, {"temperature": 2.5},
{"temperature": -0.1}, {"temperature": True}, {"temperature": "0.5"},
{"top_p": 0.9}, {"top_p": 1}, {"top_p": 0}, {"top_p": 1.5}, {"top_p": False},
{"top_k": 40}, {"top_k": 40.0}, {"top_k": 40.5}, {"top_k": 0}, {"top_k": 64}, {"top_k": 65}, {"top_k": "40"},
{"seed": 7}, {"seed": 7.0}, {"seed": 0}, {"seed": -3}, {"seed": 1.5}, {"seed": 18446744073709551615},
{"max_tokens": 512}, {"max_tokens": 0}, {"max_tokens": "10"},
{"reasoning_effort": "none"}, {"reasoning_effort": "low"}, {"reasoning_effort": "medium"},
{"reasoning_effort": "high"}, {"reasoning_effort": "xhigh"}, {"reasoning_effort": 3},
{"experimental_speed_projection": True}, {"experimental_speed_projection": False},
{"experimental_speed_projection": 1},
{"temperature": None, "top_p": "", "top_k": None}, {"unknown": 1}, {"unknown": None}, {"min_p": 0.1},
{"temperature": 0.7, "top_p": 0.9, "top_k": 20, "seed": 11, "max_tokens": 100,
"reasoning_effort": "medium", "experimental_speed_projection": False},
]
clean = []
for case in clean_cases:
try:
clean.append({"input": case, "ok": clean_shared_defaults(case)})
except ValueError as e:
clean.append({"input": case, "error": str(e)})
config_cases = [
None, {}, {"temperature": 0.7}, {"temperature": 0}, {"temperature": -1}, {"temperature": True},
{"top_p": 0.95}, {"top_p": 0}, {"top_p": 1.01}, {"min_p": 0.05}, {"min_p": 0}, {"min_p": 2},
{"top_k": 40}, {"top_k": 0}, {"top_k": 65}, {"top_k": 20.0}, {"top_k": 1.5},
{"presence_penalty": 0.5}, {"presence_penalty": -0.5}, {"frequency_penalty": 0.25},
{"frequency_penalty": -1}, {"repetition_penalty": 1.1}, {"repetition_penalty": 0},
{"penalty_last_n": 128}, {"penalty_last_n": 0}, {"penalty_last_n": -2}, {"penalty_last_n": 1.5},
{"seed": 5}, {"seed": 0}, {"seed": 5.5}, {"seed": "5"},
{"experimental_speed_projection": True}, {"experimental_speed_projection": "yes"},
{"temperature": None, "top_p": None}, {"nonsense": 3}, {"temperature": 0.6, "nonsense": 3},
{"temperature": 0.6, "top_p": 0.9, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.1,
"frequency_penalty": 0.1, "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 9},
]
import contextlib
import io
config = []
for case in config_cases:
out = io.StringIO()
try:
with contextlib.redirect_stdout(out):
ok = sampling_defaults_from_config({"sampling": case} if case is not None else {})
config.append({"input": case, "ok": ok, "ignored": [ln for ln in out.getvalue().splitlines()
if "unknown key" in ln]})
except SystemExit as e:
config.append({"input": case, "error": str(e)})
write("shared", {"source": "serve/server.py clean_shared_defaults / sampling_defaults_from_config (real code)",
"clean": clean, "config": config}, dest="policy")
# ------------------------------------------------------------------------------------------------ reasoning
def reasoning():
import random
from serve.frontend import OutputParser
from serve.server import Detokenizer, Service, ByteTokenizer
class BytesTok:
"""Token i's bytes are the table's entry; what Detokenizer needs from the real tokenizer."""
def __init__(self, table):
self.table = table
def token_bytes(self, t):
return self.table[t]
pieces = [b"a", b"b", b" so ", b"think", b"</", b"/think>", b"</think>", b"</thi", b"nk>", b"<", b"/", b"\n",
b"\xc3", b"\xa9", "\u65e5".encode()[:1], "\u65e5".encode()[1:], b"\xff", b"\xe2\x82", b"\xac", b"<t",
b"hink>", b"x"]
rng = random.Random(1234)
seqs = [[0, 1, 2, 3], [4, 5], [6, 0, 1], [0, 4, 0, 1], [11, 12, 0, 0, 0], [13, 14, 0, 0], [16, 0, 0], [17, 18, 0],
[3, 4, 5, 3, 3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
for _ in range(120):
seqs.append([rng.randrange(len(pieces)) for _ in range(rng.randrange(1, 14))])
cases = []
for seq in seqs:
row = {"pieces_hex": [pieces[i].hex() for i in seq], "wrap_at": {}}
for budget in (1, 2, 3, 5, 8):
parser = OutputParser(thinking=True, tools=None, stream_tools=True)
detok = Detokenizer(BytesTok(pieces))
thought, wrap_at = 0, None
for i, t in enumerate(seq):
parser.feed(detok.push(t))
if parser.state == "reasoning":
thought += 1
if thought >= budget and not parser.buf and not detok.pending():
wrap_at = i
break
row["wrap_at"][str(budget)] = wrap_at
cases.append(row)
parse = []
svc = Service.__new__(Service)
for req, default in [(None, 0), ({}, 0), ({"reasoning_budget_tokens": 20}, 0), ({"reasoning_budget_tokens": 20.0}, 0),
({"reasoning_budget_tokens": 0}, 50), ({"reasoning_budget_tokens": -1}, 50),
({}, 50), ({"reasoning_budget_tokens": None}, 50), ({"reasoning_budget_tokens": True}, 0),
({"reasoning_budget_tokens": "5"}, 0), ({"reasoning_budget_tokens": 2.5}, 0),
({"reasoning_budget_tokens": [1]}, 0), ({"reasoning_budget_tokens": 10000}, 0)]:
svc.reasoning_budget_tokens = default
try:
parse.append({"request": req, "default": default, "ok": svc.reasoning_budget(req)})
except ValueError as e:
parse.append({"request": req, "default": default, "error": str(e)})
from serve.server import REASONING_WRAP_UP
write("reasoning", {"source": "serve/server.py Service.reasoning_budget + Service.run budget branch (real "
"Detokenizer/OutputParser)", "wrap_up": REASONING_WRAP_UP, "cases": cases,
"parse": parse}, dest="policy")
# ------------------------------------------------------------------------------------------------ http
def http_surface():
"""The operational HTTP surface of the real Python server, scenario by scenario (fake resident engine)."""
import http.client
from pathlib import Path
from serve.frontend import ChatTemplate
from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve
class Resident(StrataEngine):
def __init__(self, tok, loaded, max_context):
self.reply = MockEngine(tok, "Hello.", max_context=max_context)
self.max_context, self.info, self.last = max_context, {"version": "9.9.9"}, {}
self.loaded, self.unloaded, self.progress = loaded, not loaded, None
def alive(self):
return self.loaded
def exit_code(self):
return None
def restart(self):
self.loaded, self.unloaded = True, False
def close(self):
self.loaded = False
def unload(self):
self.close()
self.unloaded = True
def generate(self, *args, **kwargs):
yield from self.reply.generate(*args, **kwargs)
def run(setup, steps):
tok = ByteTokenizer()
engine = Resident(tok, setup.get("loaded", True), setup.get("max_context", 4096))
svc = Service(engine, tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"),
model_name=setup.get("model", "strata-test"),
sampling_defaults=setup.get("config_sampling") or {})
svc.set_aliases(setup.get("aliases"))
svc.api_key = setup.get("api_key", "")
svc.cors_origins = setup.get("cors_origins", [])
svc.trusted_origins = setup.get("trusted_origins", [])
if setup.get("shared"):
svc.shared = dict(setup["shared"])
svc.idle_unload_s = setup.get("idle_unload_s", 0)
for key, value in (setup.get("status") or {}).items():
svc.status[key] = value
httpd = serve(svc, port=0)
port = httpd.server_address[1]
out = []
try:
for step in steps:
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
headers = dict(step.get("headers") or {})
body = step.get("body")
if body is not None and not isinstance(body, str):
body = json.dumps(body)
headers.setdefault("Content-Type", "application/json")
if body is not None:
headers.setdefault("Content-Length", str(len(body.encode())))
conn.request(step["method"], step["path"], body=body.encode() if body is not None else None,
headers=headers)
response = conn.getresponse()
raw = response.read().decode()
selected = {k.lower(): v for k, v in response.getheaders()
if k.lower().startswith("access-control-") or k.lower() == "vary"}
try:
parsed = json.loads(raw) if raw else None
except ValueError:
parsed = raw
out.append({"request": {"method": step["method"], "path": step["path"],
"headers": step.get("headers") or {}, "body": step.get("body")},
"status": response.status, "headers": selected, "body": parsed,
"state": {"loaded": engine.loaded, "shared": svc.shared}})
conn.close()
finally:
httpd.shutdown()
httpd.server_close()
return {"setup": setup, "steps": out}
scenarios = {}
# ---- CORS
cors_steps = [
{"method": "OPTIONS", "path": "/v1/chat/completions",
"headers": {"Origin": "https://a.example", "Access-Control-Request-Headers": "authorization,content-type"}},
{"method": "OPTIONS", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}},
{"method": "OPTIONS", "path": "/v1/models"},
{"method": "OPTIONS", "path": "/health", "headers": {"Origin": "https://a.example"}},
{"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://a.example/"}},
{"method": "GET", "path": "/v1/status?x=1", "headers": {"Origin": "https://b.example"}},
{"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}},
{"method": "GET", "path": "/v1/models"},
{"method": "GET", "path": "/health", "headers": {"Origin": "https://a.example"}},
{"method": "GET", "path": "/props", "headers": {"Origin": "https://a.example"}},
{"method": "GET", "path": "/v1/nothing", "headers": {"Origin": "https://a.example"}},
]
for name, origins in (("off", []), ("any", ["*"]), ("listed", ["https://a.example", "https://b.example"])):
scenarios[f"cors_{name}"] = run({"cors_origins": origins}, cors_steps)
# (an unknown path answers 404 before authentication in the Python server; the Rust server
# authenticates every path first, so that one step is left out here)
scenarios[f"cors_{name}_with_key"] = run({"cors_origins": origins, "api_key": "k" * 40}, cors_steps[:-1])
# ---- own page
page = {"defaults": {"temperature": 0.5}}
own = [
{"method": "POST", "path": "/settings", "body": page},
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "http://127.0.0.1:1"}},
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example"}},
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com/"}},
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com",
"Host": "proxy.internal"}},
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example",
"X-Forwarded-Host": "evil.example",
"CF-Ray": "1"}},
{"method": "POST", "path": "/settings", "body": json.dumps(page), "headers": {"Content-Type": "text/plain"}},
{"method": "POST", "path": "/settings", "body": json.dumps(page),
"headers": {"Content-Type": "application/x-www-form-urlencoded"}},
{"method": "POST", "path": "/settings", "body": json.dumps(page),
"headers": {"Content-Type": "application/json; charset=utf-8"}},
{"method": "GET", "path": "/settings"},
]
scenarios["own_page"] = run({"trusted_origins": ["https://strata.example.com"]}, own)
# ---- settings
settings = [
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.7, "top_k": 40, "seed": 3}}},
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 9}}},
{"method": "POST", "path": "/settings", "body": {"defaults": {"nonsense": 1}}},
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_p": 0, "temperature": 1}}},
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": {"defaults": {"max_tokens": 128, "reasoning_effort": "low",
"experimental_speed_projection": True}}},
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": [1, 2]},
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.5}}},
{"method": "POST", "path": "/settings", "body": {}},
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": {"defaults": 5}},
]
scenarios["settings"] = run({}, settings)
scenarios["settings_with_key"] = run({"api_key": "k" * 40}, [
{"method": "GET", "path": "/settings"},
{"method": "GET", "path": "/settings", "headers": {"Authorization": "Bearer " + "k" * 40}},
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}}},
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}},
"headers": {"Authorization": "Bearer " + "k" * 40}},
])
# ---- props, slots, health, status
reads = [
{"method": "GET", "path": "/props"},
{"method": "GET", "path": "/props?model=strata-test"},
{"method": "GET", "path": "/props?model=alias-one"},
{"method": "GET", "path": "/props?model=nope"},
{"method": "GET", "path": "/props?model="},
{"method": "GET", "path": "/slots"},
{"method": "GET", "path": "/api/health"},
{"method": "GET", "path": "/v1/status"},
]
scenarios["reads_loaded"] = run({"aliases": ["alias-one", "alias-two"]}, reads)
scenarios["reads_loaded_with_defaults"] = run(
{"config_sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.2,
"repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 8},
"shared": {"temperature": 0.9, "max_tokens": 256}, "max_context": 32768}, reads)
scenarios["reads_unloaded"] = run({"loaded": False, "aliases": ["alias-one"]}, reads)
scenarios["reads_busy"] = run({"status": {"busy": True, "queued": 2}}, [
{"method": "GET", "path": "/slots"}, {"method": "GET", "path": "/v1/status"}])
scenarios["reads_with_key"] = run({"api_key": "k" * 40}, [
{"method": "GET", "path": "/props"}, {"method": "GET", "path": "/slots"},
{"method": "GET", "path": "/v1/status"}, {"method": "GET", "path": "/api/health"},
{"method": "GET", "path": "/health"}])
# ---- load / unload
lifecycle = [
{"method": "POST", "path": "/unload"},
{"method": "POST", "path": "/unload"},
{"method": "GET", "path": "/slots"},
{"method": "POST", "path": "/load"},
{"method": "POST", "path": "/load"},
{"method": "POST", "path": "/v1/unload", "body": {}},
{"method": "POST", "path": "/v1/unload", "body": {}},
{"method": "POST", "path": "/v1/load", "body": {"model": "other-model"}},
{"method": "POST", "path": "/v1/load", "body": {"model": "strata-test"}},
{"method": "POST", "path": "/v1/load", "body": {}},
{"method": "POST", "path": "/v1/load", "body": "{}", "headers": {"Content-Type": "text/plain"}},
{"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Origin": "https://other.example"}},
{"method": "POST", "path": "/v1/unload", "body": [1]},
{"method": "POST", "path": "/v1/unload", "body": "not json", "headers": {"Content-Type": "application/json"}},
{"method": "POST", "path": "/v1/unload", "body": {"model": None}},
{"method": "GET", "path": "/props"},
]
scenarios["lifecycle"] = run({}, lifecycle)
scenarios["lifecycle_busy"] = run({"status": {"queued": 1}}, [
{"method": "POST", "path": "/v1/unload", "body": {}},
{"method": "POST", "path": "/v1/load", "body": {}},
{"method": "POST", "path": "/unload"},
{"method": "POST", "path": "/load"},
])
scenarios["lifecycle_unloaded_then_busy"] = run({"loaded": False, "status": {"busy": True}}, [
{"method": "POST", "path": "/v1/load", "body": {}},
{"method": "POST", "path": "/unload"},
{"method": "POST", "path": "/load"},
])
scenarios["lifecycle_with_key"] = run({"api_key": "k" * 40}, [
{"method": "POST", "path": "/unload"},
{"method": "POST", "path": "/v1/unload", "body": {}},
{"method": "POST", "path": "/v1/unload", "body": {},
"headers": {"Authorization": "Bearer " + "k" * 40, "Origin": "https://other.example"}},
{"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Authorization": "Bearer " + "k" * 40}},
{"method": "POST", "path": "/load", "headers": {"x-api-key": "k" * 40}},
])
write("http_surface", {"source": "serve/server.py Handler (real code, resident fake engine)",
"scenarios": scenarios})
# ------------------------------------------------------------------------------------------------ timings
def timings():
from serve.server import ByteTokenizer, MockEngine, Service, request_timings
from serve.frontend import ChatTemplate
from pathlib import Path
cases = []
lasts = [
{"prompt_ms": 250.0, "decode_ms": 1000.0, "generated": 50, "reused": 60},
{"prompt_ms": 0.0, "decode_ms": 0.0, "generated": 0, "reused": 0},
{"prompt_ms": 12.34567, "decode_ms": 98.7654, "generated": 7, "reused": None},
{"prompt_ms": 0.25, "decode_ms": 0.05, "generated": 3},
{"prompt_ms": 2.675, "decode_ms": 1234.55, "generated": 11, "reused": 5, "drafts_offered": 20, "drafts_accepted": 15},
{"prompt_ms": 100.0, "decode_ms": 333.3333, "generated": 0, "reused": 200},
{"prompt_ms": 1e-9, "decode_ms": 5e-5, "generated": 9, "reused": 0, "drafts_offered": 0, "drafts_accepted": 0},
{"prompt_ms": 12345.678, "decode_ms": 87654.321, "generated": 4096, "reused": 1},
]
for last in lasts:
for prompt_tokens, generated in ((300, last.get("generated") or 5), (10, 10), (0, 0), (50, 7)):
cases.append({"last": last, "prompt_tokens": prompt_tokens, "generated": generated,
"timings": request_timings(prompt_tokens, generated, last)})
cases.append({"last": {}, "prompt_tokens": 5, "generated": 5, "timings": request_timings(5, 5, {})})
aliases = []
tok = ByteTokenizer()
for value in (None, [], ["a"], [" a ", "a", "", "m", "b"], "a, b ,a,,m", ["a", 1], 5, {"a": 1}, "", [""]):
svc = Service(MockEngine(tok, "x"), tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"),
model_name="m")
try:
svc.set_aliases(value)
aliases.append({"input": value, "ok": svc.aliases})
except ValueError as e:
aliases.append({"input": value, "error": str(e)})
write("timings", {"source": "serve/server.py request_timings + Service.set_aliases (real code)",
"timings": cases, "aliases": aliases}, dest="policy")
# ------------------------------------------------------------------------------------------------ vision
def vision():
import base64
import tempfile
from pathlib import Path
from serve.frontend import ChatTemplate, _image_source, images_of, openai_to_messages
from serve.server import IMAGE_PAD, VISION_START, ByteTokenizer, MockEngine, Service, Vision
# base64 as Vision.load decodes data: URLs
b64 = []
for text in ["QQ==", "QUI=", "QUJD", "QU\nJD", "", "QQ", "Q", "QUJDRA==", "QUJDRA=", "QUJDRA", "QU JD", "QQ==QQ==",
"Q=Q=", "!!!!", "QUJD\n", "//8=", "-_8=", "QUJD=", "====", "QUJDREVG", "QUJDREVGRw", "QUJDREVGRw=="]:
try:
b64.append({"text": text, "ok": Vision.load("data:image/png;base64," + text).hex()})
except Exception as e: # binascii.Error and friends
b64.append({"text": text, "error": type(e).__name__ + ": " + str(e)})
sources = [
{"type": "image_url", "image_url": {"url": "https://x/y.png"}}, {"type": "image_url", "image_url": "data:abc"},
{"type": "input_image", "image_url": "file:///a.png"}, {"type": "image_url"}, {"type": "image_url", "image_url": {}},
{"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}},
{"type": "image", "source": {"type": "base64", "data": "QQ=="}},
{"type": "image", "source": {"type": "url", "url": "http://u"}}, {"type": "image", "source": {"path": "/p.png"}},
{"type": "image", "source": {"url": "", "path": "/q.png"}}, {"type": "image"}, {"type": "image", "source": None},
]
src = [{"part": part, "source": _image_source(part)} for part in sources]
tok = ByteTokenizer()
class FakeVision:
def __init__(self, counts):
self.counts, self.dir = counts, Path(tempfile.mkdtemp(prefix="strata-golden-"))
def encode(self, source):
path = self.dir / (str(abs(hash(source)) % 10**8) + ".sve")
path.write_bytes(source.encode())
return path, self.counts[source]
template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja")
prepared = []
cases = [
([{"role": "user", "content": "hello"}], {}),
([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": "A"}}]}],
{"A": 3}),
([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}},
{"type": "image_url", "image_url": {"url": "B"}},
{"type": "text", "text": "compare"}]}], {"A": 2, "B": 5}),
([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}}]},
{"role": "assistant", "content": "ok"},
{"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": "C"}}]}],
{"A": 1, "C": 4}),
([{"role": "user", "content": [{"type": "text", "text": "literal " + IMAGE_PAD + " in text"},
{"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}),
([{"role": "user", "content": "just text " + IMAGE_PAD + " again"}], {}),
([{"role": "user", "content": [{"type": "text", "text": VISION_START + IMAGE_PAD + " fake"},
{"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}),
]
for messages, counts in cases:
req = {"messages": messages}
norm, tools, kw = openai_to_messages(req)
prompt = template.render(norm, tools=tools, **kw)
ids_before = tok.encode(prompt, parse_special=True)
svc = Service(MockEngine(tok, "x", max_context=100000), tok, template, vision=FakeVision(counts) if counts else None)
entry = {"messages": messages, "counts": counts, "ids_before": ids_before,
"images": images_of(norm), "pad": tok.encode(IMAGE_PAD, parse_special=True)[0],
"start": tok.encode(VISION_START, parse_special=True)[0],
"literal": tok.encode(IMAGE_PAD, parse_special=False)}
try:
ids, thinking, max_new = svc.prepare(norm, tools, kw, 10)
entry["ids_after"] = ids
entry["combined_hex"] = Path(svc.embeddings.path).read_bytes().hex() if getattr(svc.embeddings, "path", None) else None
except ValueError as e:
entry["error"] = str(e)
prepared.append(entry)
write("vision", {"source": "serve/server.py Service.prepare, Vision.load, frontend._image_source (real code)",
"base64": b64, "sources": src, "prepare": prepared}, dest="policy")
def vision_dialects():
"""Chat and Messages requests that carry pictures, through the real `openai_to_messages` / `anthropic_to_messages`
and the real chat template: the prompt text and the picture sources in prompt order."""
import base64
from pathlib import Path
from serve.frontend import ChatTemplate, anthropic_to_messages, images_of, openai_to_messages
template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja")
counter = iter(range(1, 250))
def url():
# a PNG signature and one tag byte: the tests find the picture again by its last byte
return "data:image/png;base64," + base64.b64encode(b"\x89PNG\r\n\x1a\n" + bytes([next(counter)])).decode()
def chat(messages):
return {"dialect": "chat", "request": {"messages": messages, "reasoning_effort": "none"}}
def claude(messages, system=None):
request = {"messages": messages, "thinking": {"type": "disabled"}}
if system:
request["system"] = system
return {"dialect": "messages", "request": request}
def b64(media="image/png"):
data = url().split(",", 1)[1]
return {"type": "image", "source": {"type": "base64", "media_type": media, "data": data}}
cases = [
chat([{"role": "user", "content": [{"type": "text", "text": "what is this?"},
{"type": "image_url", "image_url": {"url": url(), "detail": "high"}}]}]),
chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]}]),
chat([{"role": "user", "content": [{"type": "image_url", "image_url": url()}, {"type": "text", "text": "after"}]}]),
chat([{"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "image_url", "image_url": {"url": url()}},
{"type": "text", "text": "b"}, {"type": "image_url", "image_url": url()},
{"type": "text", "text": "c"}]}]),
chat([{"role": "system", "content": "be brief"},
{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "x"}]}]),
chat([{"role": "user", "content": "first"}, {"role": "assistant", "content": "ok"},
{"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": url()}}]}]),
chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]},
{"role": "assistant", "content": "a cat"},
{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "and?"}]}]),
chat([{"role": "user", "content": [{"type": "text", "text": "the docs say <|image_pad|> marks an image"},
{"type": "image_url", "image_url": {"url": url()}}]}]),
claude([{"role": "user", "content": [b64(), {"type": "text", "text": "describe"}]}]),
claude([{"role": "user", "content": [{"type": "text", "text": "describe"}, b64("image/jpeg")]}], system="be brief"),
claude([{"role": "user", "content": [b64(), b64(), {"type": "text", "text": "compare"}]}]),
claude([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image", "source": {"type": "url", "url": url()}}]}]),
claude([{"role": "user", "content": [{"type": "image", "source": {"type": "url", "url": url()}}]}]),
claude([{"role": "user", "content": "first"}, {"role": "assistant", "content": [{"type": "text", "text": "ok"}]},
{"role": "user", "content": [b64(), {"type": "text", "text": "now this"}]}]),
]
out = []
for case in cases:
req = case["request"]
if case["dialect"] == "chat":
messages, tools, kw = openai_to_messages(req)
else:
messages, tools, kw = anthropic_to_messages(req)
out.append({**case, "prompt": template.render(messages, tools=tools, **kw), "images": images_of(messages)})
write("vision_dialects", {"source": "serve/frontend.py openai_to_messages / anthropic_to_messages + chat_template.jinja",
"cases": out})
SECTIONS = {"gen_lines": gen_lines, "shared": shared, "reasoning": reasoning, "http": http_surface,
"timings": timings, "vision": vision, "vision_dialects": vision_dialects}
def main(argv):
names = argv or list(SECTIONS)
for name in names:
SECTIONS[name]()
if __name__ == "__main__":
main(sys.argv[1:])
+1 -1
View File
@@ -2,7 +2,7 @@
//! The operational HTTP surface (`/props`, `/slots`, `/settings`, `/load`, `/unload`, `/v1/load`,
//! `/v1/unload`, `/v1/status`, `/api/health`, CORS, own-page guard) against the real Python
//! handlers: every scenario in `tests/fixtures/golden/http_surface.json` was recorded from
//! `engine/strata/serve/server.py` by `tests/golden/gen_goldens.py http`, and is replayed here
//! `Strata 41cf05a0, serve/server.py`, and is replayed here
//! against the Rust router with a real worker supervisor and the mock engine.
//!
//! Deliberate differences, skipped in the comparison: the chat template text, the build/version
+1 -1
View File
@@ -7,7 +7,7 @@ use std::path::PathBuf;
use std::process::{Command, Stdio};
pub(super) fn fake_path() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../engine/strata/serve/mcp_fake_server.py")
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/mcp_hub/mcp_fake_server.py")
}
pub(super) fn python() -> Option<&'static str> {
+3 -3
View File
@@ -1,6 +1,6 @@
//! The MCP hub against the Python fake server of the Original (`engine/strata/serve/mcp_fake_server.py`,
//! standard library only; a test double, not part of serving): stdio and Streamable HTTP clients,
//! paging, namespacing, errors as text, timeouts, the result cap, restart on demand, cancellation.
//! The MCP hub against the Python fake server of the Original (`mcp_fake_server.py` next to this test, from
//! Strata 41cf05a0 `serve/`, standard library only; a test double, not part of serving): stdio and Streamable
//! HTTP clients, paging, namespacing, errors as text, timeouts, the result cap, restart on demand, cancellation.
//! The tests are skipped (with a message) when `python3` is not installed.
mod harness;
@@ -54,6 +54,7 @@ fn worker_config(tokenizer: Arc<Tokenizer>, memory: &Arc<MemoryView>) -> Backend
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: Some(memory.clone()),
request_metrics: Default::default(),
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
//! `mtp_fetch` against a local HTTP mirror of a fake checkpoint: the behavioural spec is
//! `engine/strata/tools/test_mtp_fetch.py` (#327), ported case for case. Nothing leaves the machine.
//! `Strata 41cf05a0, tools/test_mtp_fetch.py` (#327), ported case for case. Nothing leaves the machine.
use std::{
collections::BTreeMap,
fs,
@@ -1,7 +1,7 @@
//! The reasoning-budget logic against the Python server's `Service.reasoning_budget` and `Service.run` (#123).
//!
//! `tests/fixtures/offline/reasoning_budget_oracle.json` comes from `scripts/offline/gen_goldens.py
//! reasoning_budget_oracle`: 247 budget lookups (request and configured values of every JSON type, with the message
//! `tests/fixtures/offline/reasoning_budget_oracle.json` was recorded from the Original's Python
//! code (Strata 41cf05a0): 247 budget lookups (request and configured values of every JSON type, with the message
//! of the 400) and 400 generations of the unmodified `Service.run` over a scripted engine and a byte-level toy
//! vocabulary, recording each engine call (prompt, max_new), the finish reason, the completion tokens and the text
//! the output parser was fed.
+1 -1
View File
@@ -2,7 +2,7 @@
These unmodified source and header files come from `ggml-org/llama.cpp` commit
`3cf03257f219afbe7334045ff7c6a06ac68c627d`, the same commit pinned by
the imported Strata engine in `engine/strata/third_party/ggml/VERSION.txt`.
the Strata engine pinned in `third_party/strata/UPSTREAM.md` (its `third_party/ggml/VERSION.txt`).
Their original repository paths are under `ggml/src/` or `ggml/include/`;
`ggml-cpu-impl.h` came from `ggml/src/ggml-cpu/`. `SHA256SUMS` records every
vendored file. The upstream MIT license is in `LICENSE`.
-22
View File
@@ -21,50 +21,28 @@ pub use recent_ids::{DEFAULT_RECENT_IDS, RecentIds};
mod tests;
mod backend_contract;
#[allow(unused_imports)]
pub use backend_contract::BACKEND_API_VERSION;
#[allow(unused_imports)]
pub use backend_contract::Backend;
#[allow(unused_imports)]
pub use backend_contract::BackendCapabilities;
#[allow(unused_imports)]
pub use backend_contract::BackendError;
#[allow(unused_imports)]
pub use backend_contract::BackendIdentity;
#[allow(unused_imports)]
pub use backend_contract::ContractError;
#[allow(unused_imports)]
pub use backend_contract::ErrorCode;
#[allow(unused_imports)]
pub use backend_contract::FinishReason;
#[allow(unused_imports)]
pub use backend_contract::GenerationEvent;
#[allow(unused_imports)]
pub use backend_contract::GenerationRequest;
#[allow(unused_imports)]
pub use backend_contract::GenerationSink;
#[allow(unused_imports)]
pub use backend_contract::GenerationTerminal;
#[allow(unused_imports)]
pub use backend_contract::LoadedModel;
#[allow(unused_imports)]
pub use backend_contract::MAX_OUTPUT_TOKENS;
#[allow(unused_imports)]
pub use backend_contract::ModelDescriptor;
#[allow(unused_imports)]
pub use backend_contract::RuntimeConfig;
#[allow(unused_imports)]
pub use backend_contract::SamplingOptions;
#[allow(unused_imports)]
pub use backend_contract::SupportedModelTuple;
#[allow(unused_imports)]
pub use backend_contract::Usage;
mod generation_stream;
#[allow(unused_imports)]
use generation_stream::EventSender;
#[allow(unused_imports)]
pub use generation_stream::GenerationStream;
#[allow(unused_imports)]
pub use generation_stream::StreamError;
mod contract_rules;
+2 -6
View File
@@ -103,12 +103,8 @@ pub struct ScriptedEngine {
mod tests;
mod scripted_handle;
#[allow(unused_imports)]
pub use scripted_handle::*;
use scripted_handle::*;
mod backend_port;
#[allow(unused_imports)]
pub use backend_port::*;
mod play;
#[allow(unused_imports)]
pub use play::*;
use play::*;
mod shared_ops;
+1 -1
View File
@@ -1,6 +1,6 @@
//! RoPE scaling (none / linear / YaRN) and the host-side cos/sin table builder.
//!
//! Literal port of the Original (pinned Strata under `engine/strata/`):
//! Literal port of the Original (pinned Strata, upstream commit 41cf05a0):
//! - `include/strata/kernels/rope_scaling.hpp` (`RopeScaling`, `rope_yarn_ramp`, `rope_scaled_angle`,
//! `rope_scaling_invalid`, `RopeKernelArgs`),
//! - `src/kernels/cuda/rope.cu` (`build_rope_table`, both overloads),
+2 -2
View File
@@ -1,10 +1,10 @@
//! `engine/strata/setup.py`'s pure RAM / VRAM / context sizing rules, ported function for function.
//! `Strata 41cf05a0, setup.py`'s pure RAM / VRAM / context sizing rules, ported function for function.
//!
//! The rope half of `setup.py` (`derived_factor`, `resolve_rope`) lives in [`crate::rope_scaling`]
//! (`derived_factor`, `setup_resolve_rope`); this module holds the rest: which contexts the RAM allows
//! ([`ram_ctx`], [`ctx_ram_need`]), how many GiB of experts to keep resident ([`resident_budget_gib`]) and the
//! low-RAM mode's arithmetic (`low_ram_*`). Every function is checked against `import setup` over a grid by
//! `tests/setup_policy_oracle.rs` (golden from `scripts/offline/gen_goldens.py setup_policy`).
//! `tests/setup_policy_oracle.rs` (golden recorded from the Original's `setup.py`).
//!
//! Floating point is IEEE double on both sides, evaluated in the same order; Python's `round()` is round-half-even
//! (`f64::round_ties_even`).
+1 -1
View File
@@ -1,5 +1,5 @@
//! Golden tests for `rope_scaling` and `memory_plan` against fixtures produced by the ORIGINAL's host code
//! (see `rope_plan_golden/gen_rope_golden.sh` and `gen_plan_golden.sh`; clang++ on macOS, arm64).
//! (clang++ on macOS, arm64).
//!
//! Rope: the C++ side links `rope_scaling.hpp` unmodified and the two `build_rope_table` definitions extracted
//! verbatim from `rope.cu`, compiled `-O2 -ffp-contract=off`. Tables are checked bit-for-bit through FNV-1a 64
@@ -1,49 +0,0 @@
// gen_kv_pool_golden.cpp - prints the Original's `kv_pool_bytes` (src/core/layer.cpp, extracted verbatim by
// gen_plan_golden.py into kv_pool_bytes.inc) for every KV format on several shapes. Output: JSON array.
#include "strata/kernels/kv_q4.hpp"
#include "strata/kernels/kv_q8.hpp"
#include "strata/kernels/qsa.hpp"
#include <cstdint>
#include <cstdio>
using strata::kernels::QsaShapes;
static bool g_without_key = false; // layer.cpp globals the extracted function reads
static bool g_kv_q4 = false;
#include "kv_pool_bytes.inc"
int main() {
struct Shape { int64_t kv, dim, page; };
const Shape shapes[] = {{2, 256, 4}, {4, 128, 1}, {2, 256, 1}, {1, 64, 8}};
const int64_t pages[] = {1, 7, 131072, 262144};
struct Fmt { const char* name; bool without_key, q4, hybrid, int8; };
// the flag combinations qsa_state_bytes passes: kv_pool_bytes(s, slots, g_kv_hybrid, g_kv_int8 || g_kv_hybrid)
const Fmt fmts[] = {{"fp16", false, false, false, false},
{"int8", false, false, false, true},
{"q4_0", false, true, false, false},
{"k8v4", false, false, true, true},
{"int8-keyless", true, false, false, true}};
std::printf("[");
bool first = true;
for (const Shape& sh : shapes) {
QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head_kv = sh.kv;
s.head_dim = sh.dim;
s.page_size = sh.page;
for (const Fmt& f : fmts) {
g_without_key = f.without_key;
g_kv_q4 = f.q4;
for (int64_t p : pages) {
std::printf("%s\n {\"n_head_kv\": %lld, \"head_dim\": %lld, \"page_size\": %lld, \"format\": \"%s\", "
"\"pages\": %lld, \"bytes\": %llu}",
first ? "" : ",", (long long) sh.kv, (long long) sh.dim, (long long) sh.page, f.name,
(long long) p, (unsigned long long) kv_pool_bytes(s, p, f.hybrid, f.int8));
first = false;
}
}
}
std::printf("\n]\n");
return 0;
}
@@ -1,62 +0,0 @@
#!/usr/bin/env python3
"""Offline fixture generator (Python is allowed for offline tooling, AGENTS.md): builds the Original's
`strata-plan` CLI (header-only) and the `kv_pool_bytes` harness, runs a table of configurations and writes
memory_plan_golden.json. Usage: gen_plan_golden.py <out.json> <engine/strata dir> <work dir>."""
import json, subprocess, sys, os, re
out, strata, work = sys.argv[1:4]
cxx = os.environ.get("CXX", "clang++")
here = os.path.dirname(os.path.abspath(__file__))
flags = ["-std=c++17", "-O2", "-I" + os.path.join(strata, "include"), "-I" + work]
subprocess.check_call([cxx, *flags, os.path.join(strata, "src/plan/plan_main.cpp"), "-o", os.path.join(work, "strata-plan")])
with open(os.path.join(strata, "src/core/layer.cpp")) as f:
src = f.read().split("\n")
start = next(i for i, l in enumerate(src) if l.startswith("uint64_t kv_pool_bytes("))
end = next(i for i in range(start, len(src)) if src[i].startswith("}"))
with open(os.path.join(work, "kv_pool_bytes.inc"), "w") as f:
f.write("\n".join(src[start:end + 1]) + "\n")
subprocess.check_call([cxx, *flags, os.path.join(here, "gen_kv_pool_golden.cpp"), "-o", os.path.join(work, "kvgen")])
kv_pool = json.loads(subprocess.check_output([os.path.join(work, "kvgen")]))
G = 1000 ** 3
GIB = 1024 ** 3
state_default = 36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4)
cases = []
def add(*args): cases.append([str(a) for a in args])
for ctx in (20480, 65536, 131072, 262144, 393216, 524288):
for vram in (12 * G, 16 * G, 24 * G, 32 * G, 32 * GIB, 48 * G):
add("--max-context", ctx, "--vram", vram)
# charter profiles with their state (x2 slots for 2x256K), on 32 GiB with and without resident weights
for (ctx, slots) in ((524288, 1), (524288, 2), (262144, 1), (262144, 2)):
st = state_default * slots
for vram in (16 * G, 24 * G, 32 * GIB):
add("--max-context", ctx, "--vram", vram, "--state", st)
add("--max-context", ctx, "--vram", vram, "--state", st, "--dense", 4 * G, "--embd", 500_000_000, "--workspace", 300_000_000)
# small cards: the planner must refuse
for ctx in (262144, 524288):
for vram in (3 * G, 4 * G, 6 * G, 7 * G):
add("--max-context", ctx, "--vram", vram)
# resident weights larger than the card: derived pool 0 falls back to the default pool
add("--max-context", 4096, "--vram", 5 * G, "--dense", 6 * G)
add("--max-context", 20480) # CLI defaults
add("--pool", 5943000000, "--max-context", 20480)
add("--pool", 3 * G, "--max-context", 100000)
add("--pool", 20 * G, "--max-context", 100000, "--dense", 5 * G, "--embd", G) # --pool still subtracts dense/embd
add("--max-context", 1000, "--vram", 1_000_000) # does not close
add("--max-context", 1, "--vram", 13056 + 117_669_888 + 1_382_399) # no room for one slot (default state)
add("--max-context", 1, "--vram", 13056 + 117_669_888 + 1_382_400) # exactly one slot
add("--max-context", 100, "--vram", 10 * G, "--state", 0)
add("--max-context", 100, "--vram", 10 * G, "--workspace", 123456789)
add("--help")
add("--bogus")
add("--max-context")
runs = []
for args in cases:
p = subprocess.run([os.path.join(work, "strata-plan"), *args], capture_output=True, text=True)
runs.append({"args": args, "exit": p.returncode, "stdout": p.stdout, "stderr": p.stderr})
json.dump({"generator": "strata-plan built from engine/strata/src/plan/plan_main.cpp (unmodified) + extracted layer.cpp kv_pool_bytes",
"state_bytes_default": state_default, "cli": runs, "kv_pool": kv_pool}, open(out, "w"), indent=1)
@@ -1,7 +0,0 @@
#!/bin/sh
# Regenerates memory_plan_golden.json from the Original (macOS or Linux, any C++17 compiler + python3).
set -eu
here=$(cd "$(dirname "$0")" && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
python3 -I "$here/gen_plan_golden.py" "$here/memory_plan_golden.json" "$here/../../../../engine/strata" "$work"
@@ -1,196 +0,0 @@
// gen_rope_golden.cpp - golden-fixture generator for the Rust rope port (leleka-runtime::rope_scaling).
//
// It links the ORIGINAL host-side code: `include/strata/kernels/rope_scaling.hpp` is included unmodified, and the
// two `build_rope_table` definitions are extracted VERBATIM from `src/kernels/cuda/rope.cu` by `gen_rope_golden.sh`
// into a generated include (`rope_table_original.inc`). Nothing from the Original is re-typed here.
//
// Every double/float is printed as its IEEE bit pattern in hex so the fixture is exact (serde_json's default
// float parser is not guaranteed correctly rounded). Tables are summarised by FNV-1a 64 over the little-endian
// f32 bytes of the whole cos table and of the whole sin table, plus full rows at selected positions.
#include "strata/kernels/rope_scaling.hpp"
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
namespace strata::kernels {
// the engine's other definitions live in the .cu next to the extracted functions; only the table builders are needed
void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab);
void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab);
} // namespace strata::kernels
namespace strata::kernels {
#include "rope_table_original.inc"
} // namespace strata::kernels
using namespace strata::kernels;
static std::string hex64(double d) {
uint64_t u;
std::memcpy(&u, &d, 8);
char b[32];
std::snprintf(b, sizeof b, "0x%016llx", (unsigned long long) u);
return b;
}
static std::string hex32(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
char b[32];
std::snprintf(b, sizeof b, "0x%08x", u);
return b;
}
static uint64_t fnv(const float* p, size_t n) {
uint64_t h = 0xcbf29ce484222325ull;
for (size_t i = 0; i < n; ++i) {
uint32_t u;
std::memcpy(&u, p + i, 4);
for (int k = 0; k < 4; ++k) {
h ^= (uint8_t) (u >> (8 * k));
h *= 0x100000001b3ull;
}
}
return h;
}
struct Case {
const char* name;
const char* desc;
int n_rot;
RopeScaling sc;
bool tables; // build the 524288-position tables (skipped for invalid configs)
};
static RopeScaling mk(RopeScalingType t, double fb, double factor, double fsi, double orig, double ext, double attn,
double bf, double bs) {
RopeScaling s;
s.type = t;
s.freq_base = fb;
s.factor = factor;
s.freq_scale_in = fsi;
s.orig_ctx = orig;
s.ext_factor = ext;
s.attn_factor = attn;
s.beta_fast = bf;
s.beta_slow = bs;
return s;
}
int main() {
using T = RopeScalingType;
const double B = 1e7, O = 262144;
std::vector<Case> cases = {
{"none_default", "default-constructed RopeScaling (today's engine)", 64, RopeScaling{}, true},
{"none_junk_knobs", "type none with every scaling knob set: knobs must be inert", 64,
mk(T::None, B, 4.0, 0.25, 4096, 1.0, 0.5, 20, 2), true},
{"linear_2", "linear factor 2 (512K over 262144)", 64, mk(T::Linear, B, 2.0, 0, O, 0, 1.0, 32, 1), true},
{"linear_1_5", "linear factor 1.5 (393216 over 262144)", 64, mk(T::Linear, B, 1.5, 0, O, 0, 1.0, 32, 1), true},
{"linear_freq_scale_in", "linear with the raw ggml freq_scale 0.25 overriding 1/factor", 64,
mk(T::Linear, B, 2.0, 0.25, O, 0, 1.0, 32, 1), true},
{"linear_attn_factor", "linear with attn_factor 0.9 and no correction: mscale = attn_factor", 64,
mk(T::Linear, B, 2.0, 0, O, 0, 0.9, 32, 1), true},
{"yarn_2", "yarn factor 2 (setup.py default for 512K), ext 1, betas 32/1", 64,
mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_1_5", "yarn factor 1.5 (setup.py default for 393216)", 64,
mk(T::YaRN, B, 1.5, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_1", "yarn factor 1 (inside trained range): ramp active, mscale 1", 64,
mk(T::YaRN, B, 1.0, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_4", "yarn factor 4 (1M context)", 64, mk(T::YaRN, B, 4.0, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_2_betas", "yarn factor 2 with attn 1.1, betas 16/2", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.1, 16, 2), true},
{"yarn_2_ext_half", "yarn factor 2 with ext_factor 0.5", 64, mk(T::YaRN, B, 2.0, 0, O, 0.5, 1.0, 32, 1), true},
{"yarn_orig_131072", "yarn factor 4 against a 131072 trained context", 64,
mk(T::YaRN, B, 4.0, 0, 131072, 1.0, 1.0, 32, 1), true},
{"yarn_ext0", "yarn type with ext_factor 0: correction off, behaves as linear", 64,
mk(T::YaRN, B, 2.0, 0, O, 0.0, 1.0, 32, 1), true},
{"yarn_n_rot128", "yarn n_rot 128, base 1e6, orig 4096, factor 8", 128,
mk(T::YaRN, 1e6, 8.0, 0, 4096, 1.0, 1.0, 32, 1), true},
{"yarn_n_rot4", "yarn n_rot 4: corr_dims clamps to n_rot-1", 4, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, 1), true},
// invalid (finite) configurations: only the validity message and the scalar resolutions are recorded
{"bad_factor_below_1", "factor 0.5", 64, mk(T::Linear, B, 0.5, 0, O, 0, 1.0, 32, 1), false},
{"bad_freq_base_1", "freq_base 1 (none)", 64, mk(T::None, 1.0, 1.0, 0, O, 0, 1.0, 32, 1), false},
{"bad_orig_ctx_0", "orig_ctx 0", 64, mk(T::YaRN, B, 2.0, 0, 0.0, 1.0, 1.0, 32, 1), false},
{"bad_ext_negative", "ext_factor -1", 64, mk(T::YaRN, B, 2.0, 0, O, -1.0, 1.0, 32, 1), false},
{"bad_attn_0", "attn_factor 0", 64, mk(T::Linear, B, 2.0, 0, O, 0, 0.0, 32, 1), false},
{"bad_beta_fast_0", "beta_fast 0", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 0, 1), false},
{"bad_beta_slow_neg", "beta_slow -1", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, -1), false},
{"bad_freq_scale_in_neg", "freq_scale_in -0.1", 64, mk(T::Linear, B, 2.0, -0.1, O, 0, 1.0, 32, 1), false},
{"bad_mscale_negative", "freq_scale_in 1e6 with ext 1: the log term drives mscale negative", 64,
mk(T::YaRN, B, 2.0, 1e6, O, 1.0, 1.0, 32, 1), false},
};
const int NMAX = 524288;
const int NS[2] = {262144, 524288};
const int SAMPLE_POS[] = {0, 1, 2, 4095, 4096, 65535, 131071, 262143, 262144, 524287};
const int AN_POS[] = {1, 4096, 262143, 524287};
std::printf("{\n \"generator\": \"gen_rope_golden.cpp over rope_scaling.hpp + rope.cu build_rope_table (verbatim)\",\n");
std::printf(" \"cases\": [\n");
std::vector<float> cs, sn;
for (size_t ci = 0; ci < cases.size(); ++ci) {
const Case& c = cases[ci];
const RopeScaling& s = c.sc;
const int half = c.n_rot / 2;
std::printf(" {\n \"name\": \"%s\", \"desc\": \"%s\", \"n_rot\": %d,\n", c.name, c.desc, c.n_rot);
const char* tn = s.type == T::YaRN ? "yarn" : s.type == T::Linear ? "linear" : "none";
std::printf(" \"type\": \"%s\",\n", tn);
std::printf(" \"freq_base\": \"%s\", \"factor\": \"%s\", \"freq_scale_in\": \"%s\", \"orig_ctx\": \"%s\",\n",
hex64(s.freq_base).c_str(), hex64(s.factor).c_str(), hex64(s.freq_scale_in).c_str(),
hex64(s.orig_ctx).c_str());
std::printf(" \"ext_factor\": \"%s\", \"attn_factor\": \"%s\", \"beta_fast\": \"%s\", \"beta_slow\": \"%s\",\n",
hex64(s.ext_factor).c_str(), hex64(s.attn_factor).c_str(), hex64(s.beta_fast).c_str(),
hex64(s.beta_slow).c_str());
const char* bad = rope_scaling_invalid(s);
if (bad) std::printf(" \"invalid\": \"%s\",\n", bad);
else std::printf(" \"invalid\": null,\n");
std::printf(" \"freq_scale\": \"%s\", \"mscale\": \"%s\",\n", hex64(s.freq_scale()).c_str(),
hex64(s.mscale()).c_str());
double cd[2];
s.corr_dims(c.n_rot, cd);
std::printf(" \"corr_dims\": [\"%s\", \"%s\"],\n", hex64(cd[0]).c_str(), hex64(cd[1]).c_str());
const RopeKernelArgs a = s.kernel_args(c.n_rot);
std::printf(" \"kernel_args\": {\"freq_scale\": \"%s\", \"corr_low\": \"%s\", \"corr_high\": \"%s\", "
"\"ext_factor\": \"%s\", \"attn_factor\": \"%s\"},\n",
hex32(a.freq_scale).c_str(), hex32(a.corr_low).c_str(), hex32(a.corr_high).c_str(),
hex32(a.ext_factor).c_str(), hex32(a.attn_factor).c_str());
// analytic path (float32 rope_scaled_angle): theta_extrap = (float)(p * inv_i)
std::printf(" \"analytic\": [");
bool first = true;
const int pairs[] = {0, 1, 7, 15, 16, 31};
for (int pair : pairs) {
if (pair >= half) continue;
for (int p : AN_POS) {
const double inv = std::pow(s.freq_base, -2.0 * (double) pair / (double) c.n_rot);
const float te = (float) ((double) p * inv);
float co, si;
rope_scaled_angle(te, a.freq_scale, a.corr_low, a.corr_high, a.ext_factor, a.attn_factor, pair, co, si);
std::printf("%s\n {\"theta_extrap\": \"%s\", \"pair\": %d, \"cos\": \"%s\", \"sin\": \"%s\"}",
first ? "" : ",", hex32(te).c_str(), pair, hex32(co).c_str(), hex32(si).c_str());
first = false;
}
}
std::printf("\n ]");
if (c.tables) {
cs.assign((size_t) NMAX * half, 0.f);
sn.assign((size_t) NMAX * half, 0.f);
build_rope_table(c.n_rot, s, NMAX, cs.data(), sn.data());
std::printf(",\n \"tables\": [");
for (int k = 0; k < 2; ++k)
std::printf("%s\n {\"n_pos\": %d, \"cos_fnv1a64\": \"0x%016llx\", \"sin_fnv1a64\": \"0x%016llx\"}",
k ? "," : "", NS[k], (unsigned long long) fnv(cs.data(), (size_t) NS[k] * half),
(unsigned long long) fnv(sn.data(), (size_t) NS[k] * half));
std::printf("\n ],\n \"rows\": [");
for (size_t k = 0; k < sizeof SAMPLE_POS / sizeof *SAMPLE_POS; ++k) {
const int p = SAMPLE_POS[k];
std::printf("%s\n {\"pos\": %d, \"cos\": [", k ? "," : "", p);
for (int i = 0; i < half; ++i) std::printf("%s\"%s\"", i ? "," : "", hex32(cs[(size_t) p * half + i]).c_str());
std::printf("], \"sin\": [");
for (int i = 0; i < half; ++i) std::printf("%s\"%s\"", i ? "," : "", hex32(sn[(size_t) p * half + i]).c_str());
std::printf("]}");
}
std::printf("\n ]");
}
std::printf("\n }%s\n", ci + 1 < cases.size() ? "," : "");
}
std::printf(" ]\n}\n");
return 0;
}
@@ -1,19 +0,0 @@
#!/bin/sh
# Regenerates rope_golden.json from the Original's host code (macOS or Linux, any C++17 compiler).
# usage: gen_rope_golden.sh [extra compiler flags]
# The committed fixture is built with -O2 -ffp-contract=off (Rust never fuses multiply-adds) and
# -fno-builtin-sinf/-cosf: Apple clang otherwise merges a sinf+cosf pair into __sincosf_stret, whose sinf
# differs from a separate sinf call by 1-2 ULP, and Rust (like the CUDA device code) calls them separately.
# Only the float32 analytic path is affected; the float64 tables are identical either way.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
strata="$here/../../../../engine/strata"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
# extract the two build_rope_table definitions from rope.cu verbatim (up to the next anonymous namespace)
awk '/^void build_rope_table\(int n_rot, double theta/ {on=1} on && /^namespace \{/ {exit} on {print}' \
"$strata/src/kernels/cuda/rope.cu" > "$work/rope_table_original.inc"
test -s "$work/rope_table_original.inc"
${CXX:-clang++} -std=c++17 -O2 -ffp-contract=off -fno-builtin-sinf -fno-builtin-cosf "$@" -I"$strata/include" -I"$work" \
"$here/gen_rope_golden.cpp" -o "$work/gen_rope_golden"
"$work/gen_rope_golden" > "$here/rope_golden.json"
@@ -1,5 +1,5 @@
{
"generator": "strata-plan built from engine/strata/src/plan/plan_main.cpp (unmodified) + extracted layer.cpp kv_pool_bytes",
"generator": "strata-plan built from Strata 41cf05a0, src/plan/plan_main.cpp (unmodified) + extracted layer.cpp kv_pool_bytes",
"state_bytes_default": 117669888,
"cli": [
{
@@ -1,5 +1,5 @@
{
"generator": "gen_rope_golden.cpp over rope_scaling.hpp + rope.cu build_rope_table (verbatim)",
"generator": "host build over rope_scaling.hpp + rope.cu build_rope_table (verbatim)",
"cases": [
{
"name": "none_default", "desc": "default-constructed RopeScaling (today's engine)", "n_rot": 64,
+1 -1
View File
@@ -1,5 +1,5 @@
//! `setup.py` sizing rules versus `import setup` (the unmodified oracle), over the grid in
//! `tests/fixtures/setup_policy_oracle.json` (`scripts/offline/gen_goldens.py setup_policy`). Floats are compared
//! `tests/fixtures/setup_policy_oracle.json`. Floats are compared
//! bit for bit.
use leleka_context::{
rope_scaling::{RopeScalingType, derived_factor, setup_resolve_rope},
@@ -1,5 +1,5 @@
// Original Strata fetch_blobs_kernel; arithmetic-free uint4 copy.
// engine/strata/src/kernels/cuda/verify_kernels.cu, pinned upstream provenance.
// Strata 41cf05a0, src/kernels/cuda/verify_kernels.cu, pinned upstream provenance.
#include <cuda_runtime.h>
#include <cstdint>
extern "C" __global__ void fetch_blobs_kernel(const unsigned long long* __restrict__ src, const int32_t* __restrict__ n,
@@ -1,7 +0,0 @@
#!/bin/sh
# Syntax-check ported .cu files without nvcc. Superseded by the unified stub set under scripts/cuda-stubs/ (clang's CUDA
# frontend against stub headers; covers every .cu, not only the ones the host shim can execute). The EXECUTING emulation
# (shim/cuda_host_shim.h, run_shim_oracles.sh) is a different tool and stays.
# usage: check_cu_syntax.sh [file.cu ...] (no argument: every crates/cuda-driver/src/*.cu)
here=$(cd "$(dirname "$0")" && pwd)
exec python3 "$here/../../../scripts/cuda-stubs/check-cu.py" "$@"
@@ -1,463 +0,0 @@
// GENERATED by oracle/gen_prefill_ring_trace.py from engine/strata/src/prefill/prefill.cpp
// (sha256 1d18288208debcf1d26021ed8bdfc2633db6dcbd88d899c76d1f628b57838c91). The code between the VERBATIM markers is copied from that file (lines 1170-1228, 1279-1287, 1692-1743, 1806-1853);
// everything else stubs the cuda* calls and records them. Issue is inline (STRATA_PREFILL_ISSUER=0): the threaded issuer
// makes the same copy-stream calls in the same order, gated by the same consumed + ring rule.
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <thread>
#include <string>
#include <vector>
using cudaStream_t = int;
using cudaEvent_t = int;
enum { cudaMemcpyHostToDevice = 1, cudaSuccess = 0 };
constexpr int STAGE = 8, RING_MAX = 512, DQ = 2;
static std::vector<std::string> g_ops;
static void op(const std::string& s) { g_ops.push_back(s); }
static const char* sname(cudaStream_t s) { return s == 1 ? "C" : "K"; }
static int slot_of_dev(const void* p) { return (int) (((uintptr_t) p - 0x10000000u) / 0x1000u); }
static std::string src_of_host(const void* p) {
const uintptr_t v = (uintptr_t) p;
if (v >= 0x40000000u) return "stage " + std::to_string((v - 0x40000000u) / 0x1000u);
return "blob " + std::to_string((v - 0x20000000u) / 0x10000u) + " " + std::to_string(((v - 0x20000000u) % 0x10000u) / 0x10u);
}
static int cudaMemcpyAsync(void* dst, const void* src, size_t, int, cudaStream_t s) {
op(std::string(sname(s)) + " h2d " + std::to_string(slot_of_dev(dst)) + " " + src_of_host(src));
return 0;
}
static std::string ev_name(cudaEvent_t e) {
if (e >= 4000) return "ple_copied " + std::to_string(e - 4000);
if (e >= 3000) return "dma " + std::to_string(e - 3000);
return (e >= 2000 ? "used " + std::to_string(e - 2000) : "copied " + std::to_string(e - 1000));
}
static int cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned) { op(std::string(sname(s)) + " wait " + ev_name(e)); return 0; }
static int cudaEventRecord(cudaEvent_t e, cudaStream_t s) { op(std::string(sname(s)) + " record " + ev_name(e)); return 0; }
struct Clock { struct time_point {}; static time_point now() { return {}; } };
static double ms_since(Clock::time_point) { return 0.0; }
struct ExpertLayoutStub { size_t blob_bytes(int64_t) const { return 4096; } };
namespace strata { namespace kernels { namespace cpu {
using ExpertLayout = ExpertLayoutStub;
inline const ExpertLayout& expert_layout() { static ExpertLayout l; return l; }
} } }
struct ModelGeom { int64_t n_expert; int64_t n_layers; };
struct Scenario {
const char* name;
int n_layers, n_expert, lb, le, ring, stager_ring;
int64_t T; // rows of the chunk (stream_all needs T >= 1024)
std::vector<std::vector<int32_t>> orders; // per layer in [lb, le): routed experts, ascending
int resident_mod, resident_rem; // cache-resident when e % mod == rem (mod 0: none)
bool cache_present;
int pinned_mod, transient_mod; // pinned: e % pinned_mod == 0; transient: (e+l) % transient_mod == 0
int chunks;
};
static const Scenario* g_sc = nullptr;
struct Src {
bool pinned(int64_t, int64_t e) const { return g_sc->pinned_mod != 0 && e % g_sc->pinned_mod == 0; }
bool transient(int64_t l, int64_t e) const { return !pinned(l, e) && g_sc->transient_mod != 0 && (e + l) % g_sc->transient_mod == 0; }
const uint8_t* blob(int64_t l, int64_t e) const { return (const uint8_t*) (0x20000000u + (uintptr_t) l * 0x10000u + (uintptr_t) e * 0x10u); }
};
struct Stager {
struct Job { const uint8_t* src; size_t bytes; Src* from = nullptr; int32_t l = 0, e = 0; };
int kRing = 16;
void start(std::vector<Job>&& js) {
if (js.empty()) return; // Stager::start
std::string d = "H stager_start";
for (auto& j : js) d += j.from ? " T" + std::to_string(j.l) + "." + std::to_string(j.e) : " U";
op(d + " n=" + std::to_string(js.size()));
}
const uint8_t* wait(int j) { op("H stager_wait " + std::to_string(j)); return (const uint8_t*) (0x40000000u + (uintptr_t) (j % kRing) * 0x1000u); }
void issued_one(int j, cudaStream_t copy) { cudaEventRecord(3000 + j % kRing, copy); }
void finish() { op("H stager_finish"); }
};
struct Cache { const uint8_t* device_slot(int s) const { return (const uint8_t*) (0x50000000u + (uintptr_t) s * 0x1000u); } };
struct Stats { int64_t experts_dma = 0, experts_streamed = 0, experts_resident = 0; double ms_experts_host = 0, ms_ple = 0; };
constexpr int64_t N = 2560;
struct PT { void mark(int, cudaStream_t) {} };
enum { kPfWaitCopy = 0, kPfDequant = 1 };
inline int64_t stream_all_min() { return 1024; }
// ---- PLE read-ahead stubs
#include <future>
static std::string ple_buf_of(const void* p, uintptr_t base) { return std::to_string(((uintptr_t) p - base) / 0x1000u); }
static int cudaMemcpyAsync(float* dst, const float* src, size_t, int, cudaStream_t) {
(void) dst;
op("K upload ple_emb " + ple_buf_of(src, 0x60000000u));
return 0;
}
static int cudaEventSynchronize(cudaEvent_t e) { op("H sync ple_copied " + std::to_string(e - 4000)); return 0; }
template <class F> static std::future<bool> shim_async(F f) { op("H ple_async"); return std::async(std::launch::deferred, f); }
struct PleTable {
bool gather_batch_device(const uint32_t*, size_t, float*, cudaStream_t, std::string&) { op("K ple_gather_device"); return true; }
};
struct PleState { PleTable* table; };
struct SessionStub { struct { PleTable* table; } ple; };
struct Impl {
Src* src = nullptr; const Cache* cache = nullptr; const int32_t* host_res = nullptr; const ModelGeom* g = nullptr;
int ring = STAGE; cudaStream_t cs = 2, copy = 1;
std::unique_ptr<Stager> stager;
uint8_t* stage_dev[RING_MAX] = {};
cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {};
bool stage_live[RING_MAX] = {};
float* ple_emb = nullptr;
float* ple_emb_host[2] = {};
cudaEvent_t ple_copied[2] = {};
std::vector<uint32_t> ple_rows[2];
int64_t T = 0;
};
static void run_scenario(const Scenario& sc) {
g_sc = &sc;
g_ops.clear();
Impl m;
ModelGeom geom{sc.n_expert, sc.n_layers};
const ModelGeom& g = geom;
Src src_obj; Cache cache_obj;
m.src = &src_obj;
m.g = &geom;
m.ring = sc.ring;
m.stager.reset(new Stager());
m.stager->kRing = sc.stager_ring;
for (int i = 0; i < RING_MAX; ++i) {
m.stage_dev[i] = (uint8_t*) (0x10000000u + (uintptr_t) i * 0x1000u);
m.copied[i] = 1000 + i; m.used[i] = 2000 + i;
}
std::vector<int32_t> host_res_table((size_t) sc.n_layers * sc.n_expert, -1);
if (sc.cache_present) {
int next_slot = 0;
for (int l = 0; l < sc.n_layers; ++l)
for (int e = 0; e < sc.n_expert; ++e)
if (sc.resident_mod != 0 && e % sc.resident_mod == sc.resident_rem) host_res_table[(size_t) l * sc.n_expert + e] = next_slot++;
m.host_res = host_res_table.data();
m.cache = &cache_obj;
}
Stats stats_;
PT pt;
cudaStream_t cs = m.cs;
const int64_t LB = sc.lb, LE = sc.le, T = sc.T;
std::string err;
for (int chunk = 0; chunk < sc.chunks; ++chunk) {
op("H chunk " + std::to_string(chunk));
auto chunk_fn = [&]() -> bool {
// ---- VERBATIM prefill.cpp (sequence, issue_until) ----
const strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout();
const bool stream_all = m.ring > STAGE && T >= stream_all_min() && m.src != nullptr;
struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; };
std::vector<StreamEntry> seq;
std::vector<size_t> seq_start;
size_t issued = 0, consumed = 0;
if (stream_all) {
seq_start.assign((size_t) g.n_layers + 1, 0);
std::vector<Stager::Job> js;
for (int64_t l = LB; l < LE; ++l) {
seq_start[(size_t) l] = seq.size();
for (int32_t e = 0; e < m.g->n_expert; ++e) {
if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
int job = -1;
const uint8_t* b = nullptr;
if (m.src->transient(l, e)) { // CS-T: copied by the source into the stager's buffer
job = (int) js.size();
js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e});
} else {
b = m.src->blob(l, e);
if (!b) { err = "prefill: expert source has no blob"; return false; }
if (!m.src->pinned(l, e)) {
job = (int) js.size();
js.push_back({b, (size_t) lay0.blob_bytes(l)});
}
}
seq.push_back({(int32_t) l, e, b, job});
}
}
for (int64_t l = LE; l <= g.n_layers; ++l) seq_start[(size_t) l] = seq.size();
m.stager->start(std::move(js));
}
struct StagerDone {
Stager* st;
~StagerDone() { if (st) st->finish(); }
} chunk_stager_done{stream_all ? m.stager.get() : nullptr};
auto issue_until = [&](size_t limit) {
limit = std::min(limit, seq.size());
while (issued < limit) {
const StreamEntry& en = seq[issued];
const int sl = (int) (issued % (size_t) m.ring);
const auto th = Clock::now();
const size_t bytes = (size_t) lay0.blob_bytes(en.l);
if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
if (en.job < 0) {
cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy);
++stats_.experts_dma;
} else {
const uint8_t* hb = m.stager->wait(en.job);
cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy);
m.stager->issued_one(en.job, m.copy);
}
cudaEventRecord(m.copied[sl], m.copy);
m.stage_live[sl] = true;
stats_.ms_experts_host += ms_since(th);
++stats_.experts_streamed;
++issued;
}
};
// ---- end VERBATIM ----
const bool threaded_issue = false;
std::atomic<size_t> a_issued{0}, a_consumed{0};
// ---- VERBATIM prefill.cpp (wait_issued, give_back) ----
// the consumer's side: entry k's copy is on the copy stream (the thread issued it), then k is given back
auto wait_issued = [&](size_t k) {
if (!threaded_issue) return;
while (a_issued.load(std::memory_order_acquire) <= k) std::this_thread::yield();
};
auto give_back = [&](size_t upto) {
if (threaded_issue) a_consumed.store(upto, std::memory_order_release);
else issue_until(upto + (size_t) m.ring);
};
// ---- end VERBATIM ----
if (stream_all) issue_until((size_t) m.ring); // prefill.cpp: else if (stream_all) { issue_until((size_t) m.ring); }
for (int64_t l = LB; l < LE; ++l) {
const std::vector<int32_t>& order = sc.orders[(size_t) (l - LB)];
op("H layer " + std::to_string(l));
const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
// ---- VERBATIM prefill.cpp (staging setup, stage_one) ----
// Stage ahead: the copy stream moves blobs host -> device while the compute stream works.
int stage_next = 0;
std::vector<int> stage_of(order.size(), -1);
// the unpinned ones are copied to pinned buffers by the stager's threads, in this order
std::vector<int> job_of(order.size(), -1);
if (!stream_all) {
std::vector<Stager::Job> js;
for (size_t j = 0; j < order.size(); ++j) {
const int32_t e = order[j];
if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
if (m.src->pinned(l, e)) continue;
job_of[j] = (int) js.size();
if (m.src->transient(l, e)) { // CS-T: copied by the source
js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
continue;
}
const uint8_t* b = m.src->blob(l, e);
if (!b) { err = "prefill: expert source has no blob"; return false; }
js.push_back({b, (size_t) lay.blob_bytes(l)});
}
m.stager->start(std::move(js));
}
StagerDone stager_done{stream_all ? nullptr : m.stager.get()};
auto stage_one = [&](size_t j) -> bool {
const int32_t e = order[j];
const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
if (resident) return true;
const int sl = stage_next;
stage_next = (stage_next + 1) % STAGE;
const auto th = Clock::now();
const bool pinned = m.src->pinned(l, e); // pinned: never transient
const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr;
if (pinned && !b) { err = "prefill: expert source has no blob"; return false; }
if (pinned) {
// DMA straight from the page-locked arena: the copy stream only waits for the slot
if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
++stats_.experts_dma;
} else {
// copied to a pinned buffer by the stager (waits only if it is behind), then DMA
const uint8_t* hb = m.stager->wait(job_of[j]);
if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
m.stager->issued_one(job_of[j], m.copy);
}
cudaEventRecord(m.copied[sl], m.copy);
m.stage_live[sl] = true;
stage_of[j] = sl;
stats_.ms_experts_host += ms_since(th);
++stats_.experts_streamed;
return true;
};
// ---- end VERBATIM ----
auto compute = [&](size_t j, const uint8_t*, int slot) -> bool {
op("K compute " + std::to_string(order[j]) + " " + (slot >= 0 ? std::to_string(slot) : std::string("-")));
if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); // prefill.cpp: after the gather / dequant read of the blob
return true;
};
// ---- VERBATIM prefill.cpp (the walks) ----
if (!stream_all) {
size_t staged = 0;
const size_t lookahead = STAGE - 1;
for (size_t j = 0; j < order.size(); ++j) {
while (staged < order.size() && staged <= j + lookahead) {
if (!stage_one(staged)) return false;
++staged;
}
const int32_t e = order[j];
if (stage_of[j] < 0) {
++stats_.experts_resident;
if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
} else {
pt.mark(kPfWaitCopy, cs);
cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0);
if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false;
}
}
} else {
// the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not
// pick only gives its slot back
size_t k = seq_start[(size_t) l];
const size_t kend = seq_start[(size_t) l + 1];
auto release_to = [&](int32_t e_stop) {
while (k < kend && seq[k].e < e_stop) {
cudaEventRecord(m.used[k % (size_t) m.ring], m.cs);
consumed = ++k;
give_back(consumed);
}
};
for (size_t j = 0; j < order.size(); ++j) {
const int32_t e = order[j];
release_to(e);
if (k < kend && seq[k].e == e) {
const int sl = (int) (k % (size_t) m.ring);
pt.mark(kPfWaitCopy, cs);
wait_issued(k);
cudaStreamWaitEvent(m.cs, m.copied[sl], 0);
if (!compute(j, m.stage_dev[sl], sl)) return false;
consumed = ++k;
give_back(consumed);
} else {
++stats_.experts_resident;
if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
}
}
release_to(m.g->n_expert);
}
// ---- end VERBATIM ----
op("K combine");
}
return true;
};
if (!chunk_fn()) { std::fprintf(stderr, "scenario %s failed: %s\n", sc.name, err.c_str()); std::exit(2); }
}
std::printf("{\"name\":\"%s\",\"p\":{\"n_layers\":%d,\"n_expert\":%d,\"lb\":%d,\"le\":%d,\"ring\":%d,\"stager_ring\":%d,\"rows\":%lld,"
"\"resident_mod\":%d,\"resident_rem\":%d,\"cache_present\":%d,\"pinned_mod\":%d,\"transient_mod\":%d,\"chunks\":%d,\"orders\":[",
sc.name, sc.n_layers, sc.n_expert, sc.lb, sc.le, sc.ring, sc.stager_ring, (long long) T, sc.resident_mod, sc.resident_rem,
(int) sc.cache_present, sc.pinned_mod, sc.transient_mod, sc.chunks);
for (size_t li = 0; li < sc.orders.size(); ++li) {
std::printf("%s[", li ? "," : "");
for (size_t k = 0; k < sc.orders[li].size(); ++k) std::printf("%s%d", k ? "," : "", sc.orders[li][k]);
std::printf("]");
}
std::printf("]},\"stats\":[%lld,%lld,%lld],\"ops\":[", (long long) stats_.experts_dma, (long long) stats_.experts_streamed, (long long) stats_.experts_resident);
for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str());
std::printf("]}");
}
struct PleScenario { const char* name; int64_t n, T; bool gpu_cache; };
static void run_ple_scenario(const PleScenario& sc) {
g_ops.clear();
Impl m;
m.T = sc.T;
PleTable table;
SessionStub ss;
ss.ple.table = &table;
for (int b = 0; b < 2; ++b) { m.ple_emb_host[b] = (float*) (0x60000000u + (uintptr_t) b * 0x1000u); m.ple_copied[b] = 4000 + b; m.ple_rows[b].assign(4, 0); }
m.ple_emb = (float*) 0x70000000u;
Stats stats_;
std::string err;
const int64_t n = sc.n;
const bool ple_on = true, ple_gpu_cache = sc.gpu_cache;
std::string ple_next_err;
std::future<bool> ple_next;
int ple_buf = 0;
auto ple_gather = [&](int64_t c0, int buf, std::string&) -> bool { op("H ple_gather " + std::to_string(c0) + " " + std::to_string(buf)); return true; };
for (int64_t c0 = 0; c0 < n; c0 += m.T) {
const int64_t T = std::min(m.T, n - c0);
op("H ple_chunk " + std::to_string(c0));
cudaStream_t cs = 2; (void) cs;
auto ple_fn = [&]() -> bool {
// ---- VERBATIM prefill.cpp (the PLE row read-ahead) ----
if (ple_on) {
const auto tp = Clock::now();
if (ple_gpu_cache) {
if (!ple_gather(c0, 0, err) ||
!ss.ple.table->gather_batch_device(m.ple_rows[0].data(), (size_t) T,
m.ple_emb, m.cs, err)) return false;
} else if (!ple_next.valid()) {
if (!ple_gather(c0, ple_buf, err)) return false;
} else if (!ple_next.get()) {
err = ple_next_err;
return false;
}
if (!ple_gpu_cache) {
cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs);
cudaEventRecord(m.ple_copied[ple_buf], m.cs);
if (c0 + m.T < n) {
cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]); // the other buffer's upload (a chunk ago) is done
ple_next = shim_async( [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] {
return ple_gather(c1, b, ple_next_err);
});
}
ple_buf ^= 1;
}
stats_.ms_ple += ms_since(tp);
}
// ---- end VERBATIM ----
return true;
};
if (!ple_fn()) { std::fprintf(stderr, "ple scenario failed\n"); std::exit(2); }
}
std::printf("{\"name\":\"%s\",\"ple\":[%lld,%lld,%d],\"ops\":[", sc.name, (long long) sc.n, (long long) sc.T, (int) sc.gpu_cache);
for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str());
std::printf("]}");
}
// ---- the GR write fusion decision of one half
namespace strata { namespace kernels { struct CvecStub { bool cover; bool covers(int64_t) const { return cover; } }; inline CvecStub& cvec() { static CvecStub c; return c; } } }
static bool g_gr_unfused = false;
static bool gr_unfused() { return g_gr_unfused; }
static bool fuse_of(int64_t l, int half, int64_t LE, bool ple_on, bool unfused, bool cvec_covers) {
g_gr_unfused = unfused;
strata::kernels::cvec().cover = cvec_covers;
const int64_t nl = half == 0 ? l : l + 1;
const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) &&
!(half == 1 && strata::kernels::cvec().covers(l));
return fuse;
}
static std::vector<int32_t> iota_vec(int n, int step = 1, int from = 0) {
std::vector<int32_t> v;
for (int i = from; i < n; i += step) v.push_back(i);
return v;
}
int main() {
std::vector<Scenario> sc;
// fields: name, n_layers, n_expert, lb, le, ring, stager_ring, T, orders, resident_mod, resident_rem, cache_present, pinned_mod, transient_mod, chunks
sc.push_back({"stream_basic", 6, 24, 1, 4, 16, 16, 1024,
{iota_vec(24, 2), iota_vec(24, 3, 1), {0, 1, 2, 5, 23}}, 5, 0, true, 3, 4, 2});
sc.push_back({"stream_ring_wrap", 4, 40, 0, 3, 16, 16, 2048,
{iota_vec(40), iota_vec(40), iota_vec(40, 7)}, 0, 0, true, 2, 0, 2});
sc.push_back({"stream_no_cache_all_pinned", 3, 20, 0, 3, 16, 16, 1024,
{iota_vec(20), iota_vec(20, 2), {19}}, 0, 0, false, 1, 0, 1});
sc.push_back({"stream_sparse_release", 5, 40, 1, 4, 16, 4, 4096,
{{39}, {0}, {5, 6, 7, 30}}, 0, 0, true, 5, 3, 2});
sc.push_back({"staged_under_threshold", 4, 32, 0, 3, 384, 16, 512,
{iota_vec(32), iota_vec(32, 3), {2, 4}}, 4, 1, true, 3, 5, 2});
sc.push_back({"staged_ring8", 3, 12, 0, 2, 8, 16, 4096,
{iota_vec(12), iota_vec(12, 2)}, 0, 0, false, 2, 3, 1});
sc.push_back({"staged_few_experts", 3, 10, 0, 2, 16, 16, 100,
{{1, 3, 4}, {9}}, 3, 0, true, 0, 0, 1});
std::printf("{\"ring\":[");
for (size_t i = 0; i < sc.size(); ++i) { if (i) std::printf(",\n"); run_scenario(sc[i]); }
std::printf("],\n");
std::vector<PleScenario> ples = {{"ple_two_chunks_gather", 2000, 1024, false}, {"ple_single_chunk", 100, 256, false},
{"ple_gpu_cache", 3000, 1024, true}, {"ple_four_chunks", 4096, 1024, false},
{"ple_exact_multiple", 2048, 1024, false}};
std::printf("\"ple\":[");
for (size_t i = 0; i < ples.size(); ++i) { if (i) std::printf(",\n"); run_ple_scenario(ples[i]); }
std::printf("],\n\"fuse\":[");
bool first = true;
for (int le : {48, 16}) for (int ple_on = 0; ple_on < 2; ++ple_on) for (int unfused = 0; unfused < 2; ++unfused)
for (int cv = 0; cv < 2; ++cv) for (int l : {0, 1, 2, 14, 15, 46, 47}) for (int half = 0; half < 2; ++half) {
if (l >= le) continue;
std::printf("%s[%d,%d,%d,%d,%d,%d,%d]", first ? "" : ",", le, ple_on, unfused, cv, l, half, (int) fuse_of(l, half, le, ple_on != 0, unfused != 0, cv != 0));
first = false;
}
std::printf("]}\n");
return 0;
}
@@ -1,321 +0,0 @@
#!/usr/bin/env python3
"""Builds drivers/prefill_ring_trace.cpp by EXTRACTING the expert-stream scheduling code of the Original
engine/strata/src/prefill/prefill.cpp (the sequence builder + issue_until, wait_issued / give_back, the staged
stage_one lambda, and the two per-layer expert walks) verbatim between textual markers, wrapped in a host harness whose
cuda* calls only append to a trace. usage: gen_prefill_ring_trace.py [prefill.cpp] > drivers/prefill_ring_trace.cpp
The trace line format is the golden-fixture format read by original_prefill_schedule.rs."""
import hashlib, os, sys
here = os.path.dirname(os.path.abspath(__file__))
path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(here, '../../../engine/strata/src/prefill/prefill.cpp')
text = open(path).read()
lines = text.split('\n')
def find(marker, start=0):
for i in range(start, len(lines)):
if marker in lines[i]:
return i
raise SystemExit('marker not found: ' + marker)
def cut(first, last_exclusive, start=0):
a = find(first, start)
b = find(last_exclusive, a + 1)
return '\n'.join(lines[a:b]), a + 1, b
seq_build, a1, b1 = cut('const strata::kernels::cpu::ExpertLayout& lay0', '// D-5: the stream is issued by its own host thread')
consumer, a2, b2 = cut("// the consumer's side:", 'host_setup_ms += ms_since(tsetup);')
staged, a3, b3 = cut('// Stage ahead: the copy stream moves blobs host -> device', "// one expert's products from its blob on the device")
w_first = find('auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool {')
a4 = find('if (!stream_all) {', w_first)
b4 = find('pt.mark(kPfCombine, cs);', a4)
walks = '\n'.join(lines[a4:b4])
ple_a = find('// ---- the PLE rows of the whole chunk')
ple_first = find('if (ple_on) {', ple_a)
ple_last = find('for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1];', ple_first)
ple_block = '\n'.join(lines[ple_first:ple_last])
assert 'std::async(std::launch::async,' in ple_block
ple_block = ple_block.replace('std::async(std::launch::async,', 'shim_async(') # the one documented edit: deferred, logged
fuse_a = find('const int64_t nl = half == 0 ? l : l + 1;')
fuse_b = find('const core::WeightRef* wnn = nullptr;', fuse_a)
fuse_block = '\n'.join(lines[fuse_a:fuse_b])
digest = hashlib.sha256(text.encode()).hexdigest()
template = r'''// GENERATED by oracle/gen_prefill_ring_trace.py from engine/strata/src/prefill/prefill.cpp
// (sha256 __DIGEST__). The code between the VERBATIM markers is copied from that file (lines __R1__, __R2__, __R3__, __R4__);
// everything else stubs the cuda* calls and records them. Issue is inline (STRATA_PREFILL_ISSUER=0): the threaded issuer
// makes the same copy-stream calls in the same order, gated by the same consumed + ring rule.
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <thread>
#include <string>
#include <vector>
using cudaStream_t = int;
using cudaEvent_t = int;
enum { cudaMemcpyHostToDevice = 1, cudaSuccess = 0 };
constexpr int STAGE = 8, RING_MAX = 512, DQ = 2;
static std::vector<std::string> g_ops;
static void op(const std::string& s) { g_ops.push_back(s); }
static const char* sname(cudaStream_t s) { return s == 1 ? "C" : "K"; }
static int slot_of_dev(const void* p) { return (int) (((uintptr_t) p - 0x10000000u) / 0x1000u); }
static std::string src_of_host(const void* p) {
const uintptr_t v = (uintptr_t) p;
if (v >= 0x40000000u) return "stage " + std::to_string((v - 0x40000000u) / 0x1000u);
return "blob " + std::to_string((v - 0x20000000u) / 0x10000u) + " " + std::to_string(((v - 0x20000000u) % 0x10000u) / 0x10u);
}
static int cudaMemcpyAsync(void* dst, const void* src, size_t, int, cudaStream_t s) {
op(std::string(sname(s)) + " h2d " + std::to_string(slot_of_dev(dst)) + " " + src_of_host(src));
return 0;
}
static std::string ev_name(cudaEvent_t e) {
if (e >= 4000) return "ple_copied " + std::to_string(e - 4000);
if (e >= 3000) return "dma " + std::to_string(e - 3000);
return (e >= 2000 ? "used " + std::to_string(e - 2000) : "copied " + std::to_string(e - 1000));
}
static int cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned) { op(std::string(sname(s)) + " wait " + ev_name(e)); return 0; }
static int cudaEventRecord(cudaEvent_t e, cudaStream_t s) { op(std::string(sname(s)) + " record " + ev_name(e)); return 0; }
struct Clock { struct time_point {}; static time_point now() { return {}; } };
static double ms_since(Clock::time_point) { return 0.0; }
struct ExpertLayoutStub { size_t blob_bytes(int64_t) const { return 4096; } };
namespace strata { namespace kernels { namespace cpu {
using ExpertLayout = ExpertLayoutStub;
inline const ExpertLayout& expert_layout() { static ExpertLayout l; return l; }
} } }
struct ModelGeom { int64_t n_expert; int64_t n_layers; };
struct Scenario {
const char* name;
int n_layers, n_expert, lb, le, ring, stager_ring;
int64_t T; // rows of the chunk (stream_all needs T >= 1024)
std::vector<std::vector<int32_t>> orders; // per layer in [lb, le): routed experts, ascending
int resident_mod, resident_rem; // cache-resident when e %% mod == rem (mod 0: none)
bool cache_present;
int pinned_mod, transient_mod; // pinned: e %% pinned_mod == 0; transient: (e+l) %% transient_mod == 0
int chunks;
};
static const Scenario* g_sc = nullptr;
struct Src {
bool pinned(int64_t, int64_t e) const { return g_sc->pinned_mod != 0 && e %% g_sc->pinned_mod == 0; }
bool transient(int64_t l, int64_t e) const { return !pinned(l, e) && g_sc->transient_mod != 0 && (e + l) %% g_sc->transient_mod == 0; }
const uint8_t* blob(int64_t l, int64_t e) const { return (const uint8_t*) (0x20000000u + (uintptr_t) l * 0x10000u + (uintptr_t) e * 0x10u); }
};
struct Stager {
struct Job { const uint8_t* src; size_t bytes; Src* from = nullptr; int32_t l = 0, e = 0; };
int kRing = 16;
void start(std::vector<Job>&& js) {
if (js.empty()) return; // Stager::start
std::string d = "H stager_start";
for (auto& j : js) d += j.from ? " T" + std::to_string(j.l) + "." + std::to_string(j.e) : " U";
op(d + " n=" + std::to_string(js.size()));
}
const uint8_t* wait(int j) { op("H stager_wait " + std::to_string(j)); return (const uint8_t*) (0x40000000u + (uintptr_t) (j %% kRing) * 0x1000u); }
void issued_one(int j, cudaStream_t copy) { cudaEventRecord(3000 + j %% kRing, copy); }
void finish() { op("H stager_finish"); }
};
struct Cache { const uint8_t* device_slot(int s) const { return (const uint8_t*) (0x50000000u + (uintptr_t) s * 0x1000u); } };
struct Stats { int64_t experts_dma = 0, experts_streamed = 0, experts_resident = 0; double ms_experts_host = 0, ms_ple = 0; };
constexpr int64_t N = 2560;
struct PT { void mark(int, cudaStream_t) {} };
enum { kPfWaitCopy = 0, kPfDequant = 1 };
inline int64_t stream_all_min() { return 1024; }
// ---- PLE read-ahead stubs
#include <future>
static std::string ple_buf_of(const void* p, uintptr_t base) { return std::to_string(((uintptr_t) p - base) / 0x1000u); }
static int cudaMemcpyAsync(float* dst, const float* src, size_t, int, cudaStream_t) {
(void) dst;
op("K upload ple_emb " + ple_buf_of(src, 0x60000000u));
return 0;
}
static int cudaEventSynchronize(cudaEvent_t e) { op("H sync ple_copied " + std::to_string(e - 4000)); return 0; }
template <class F> static std::future<bool> shim_async(F f) { op("H ple_async"); return std::async(std::launch::deferred, f); }
struct PleTable {
bool gather_batch_device(const uint32_t*, size_t, float*, cudaStream_t, std::string&) { op("K ple_gather_device"); return true; }
};
struct PleState { PleTable* table; };
struct SessionStub { struct { PleTable* table; } ple; };
struct Impl {
Src* src = nullptr; const Cache* cache = nullptr; const int32_t* host_res = nullptr; const ModelGeom* g = nullptr;
int ring = STAGE; cudaStream_t cs = 2, copy = 1;
std::unique_ptr<Stager> stager;
uint8_t* stage_dev[RING_MAX] = {};
cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {};
bool stage_live[RING_MAX] = {};
float* ple_emb = nullptr;
float* ple_emb_host[2] = {};
cudaEvent_t ple_copied[2] = {};
std::vector<uint32_t> ple_rows[2];
int64_t T = 0;
};
static void run_scenario(const Scenario& sc) {
g_sc = &sc;
g_ops.clear();
Impl m;
ModelGeom geom{sc.n_expert, sc.n_layers};
const ModelGeom& g = geom;
Src src_obj; Cache cache_obj;
m.src = &src_obj;
m.g = &geom;
m.ring = sc.ring;
m.stager.reset(new Stager());
m.stager->kRing = sc.stager_ring;
for (int i = 0; i < RING_MAX; ++i) {
m.stage_dev[i] = (uint8_t*) (0x10000000u + (uintptr_t) i * 0x1000u);
m.copied[i] = 1000 + i; m.used[i] = 2000 + i;
}
std::vector<int32_t> host_res_table((size_t) sc.n_layers * sc.n_expert, -1);
if (sc.cache_present) {
int next_slot = 0;
for (int l = 0; l < sc.n_layers; ++l)
for (int e = 0; e < sc.n_expert; ++e)
if (sc.resident_mod != 0 && e %% sc.resident_mod == sc.resident_rem) host_res_table[(size_t) l * sc.n_expert + e] = next_slot++;
m.host_res = host_res_table.data();
m.cache = &cache_obj;
}
Stats stats_;
PT pt;
cudaStream_t cs = m.cs;
const int64_t LB = sc.lb, LE = sc.le, T = sc.T;
std::string err;
for (int chunk = 0; chunk < sc.chunks; ++chunk) {
op("H chunk " + std::to_string(chunk));
auto chunk_fn = [&]() -> bool {
// ---- VERBATIM prefill.cpp (sequence, issue_until) ----
__SEQ_BUILD__
// ---- end VERBATIM ----
const bool threaded_issue = false;
std::atomic<size_t> a_issued{0}, a_consumed{0};
// ---- VERBATIM prefill.cpp (wait_issued, give_back) ----
__CONSUMER__
// ---- end VERBATIM ----
if (stream_all) issue_until((size_t) m.ring); // prefill.cpp: else if (stream_all) { issue_until((size_t) m.ring); }
for (int64_t l = LB; l < LE; ++l) {
const std::vector<int32_t>& order = sc.orders[(size_t) (l - LB)];
op("H layer " + std::to_string(l));
const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
// ---- VERBATIM prefill.cpp (staging setup, stage_one) ----
__STAGED__
// ---- end VERBATIM ----
auto compute = [&](size_t j, const uint8_t*, int slot) -> bool {
op("K compute " + std::to_string(order[j]) + " " + (slot >= 0 ? std::to_string(slot) : std::string("-")));
if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); // prefill.cpp: after the gather / dequant read of the blob
return true;
};
// ---- VERBATIM prefill.cpp (the walks) ----
__WALKS__
// ---- end VERBATIM ----
op("K combine");
}
return true;
};
if (!chunk_fn()) { std::fprintf(stderr, "scenario %%s failed: %%s\n", sc.name, err.c_str()); std::exit(2); }
}
std::printf("{\"name\":\"%%s\",\"p\":{\"n_layers\":%%d,\"n_expert\":%%d,\"lb\":%%d,\"le\":%%d,\"ring\":%%d,\"stager_ring\":%%d,\"rows\":%%lld,"
"\"resident_mod\":%%d,\"resident_rem\":%%d,\"cache_present\":%%d,\"pinned_mod\":%%d,\"transient_mod\":%%d,\"chunks\":%%d,\"orders\":[",
sc.name, sc.n_layers, sc.n_expert, sc.lb, sc.le, sc.ring, sc.stager_ring, (long long) T, sc.resident_mod, sc.resident_rem,
(int) sc.cache_present, sc.pinned_mod, sc.transient_mod, sc.chunks);
for (size_t li = 0; li < sc.orders.size(); ++li) {
std::printf("%%s[", li ? "," : "");
for (size_t k = 0; k < sc.orders[li].size(); ++k) std::printf("%%s%%d", k ? "," : "", sc.orders[li][k]);
std::printf("]");
}
std::printf("]},\"stats\":[%%lld,%%lld,%%lld],\"ops\":[", (long long) stats_.experts_dma, (long long) stats_.experts_streamed, (long long) stats_.experts_resident);
for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%%s\"%%s\"", i ? "," : "", g_ops[i].c_str());
std::printf("]}");
}
struct PleScenario { const char* name; int64_t n, T; bool gpu_cache; };
static void run_ple_scenario(const PleScenario& sc) {
g_ops.clear();
Impl m;
m.T = sc.T;
PleTable table;
SessionStub ss;
ss.ple.table = &table;
for (int b = 0; b < 2; ++b) { m.ple_emb_host[b] = (float*) (0x60000000u + (uintptr_t) b * 0x1000u); m.ple_copied[b] = 4000 + b; m.ple_rows[b].assign(4, 0); }
m.ple_emb = (float*) 0x70000000u;
Stats stats_;
std::string err;
const int64_t n = sc.n;
const bool ple_on = true, ple_gpu_cache = sc.gpu_cache;
std::string ple_next_err;
std::future<bool> ple_next;
int ple_buf = 0;
auto ple_gather = [&](int64_t c0, int buf, std::string&) -> bool { op("H ple_gather " + std::to_string(c0) + " " + std::to_string(buf)); return true; };
for (int64_t c0 = 0; c0 < n; c0 += m.T) {
const int64_t T = std::min(m.T, n - c0);
op("H ple_chunk " + std::to_string(c0));
cudaStream_t cs = 2; (void) cs;
auto ple_fn = [&]() -> bool {
// ---- VERBATIM prefill.cpp (the PLE row read-ahead) ----
__PLE__
// ---- end VERBATIM ----
return true;
};
if (!ple_fn()) { std::fprintf(stderr, "ple scenario failed\n"); std::exit(2); }
}
std::printf("{\"name\":\"%s\",\"ple\":[%lld,%lld,%d],\"ops\":[", sc.name, (long long) sc.n, (long long) sc.T, (int) sc.gpu_cache);
for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str());
std::printf("]}");
}
// ---- the GR write fusion decision of one half
namespace strata { namespace kernels { struct CvecStub { bool cover; bool covers(int64_t) const { return cover; } }; inline CvecStub& cvec() { static CvecStub c; return c; } } }
static bool g_gr_unfused = false;
static bool gr_unfused() { return g_gr_unfused; }
static bool fuse_of(int64_t l, int half, int64_t LE, bool ple_on, bool unfused, bool cvec_covers) {
g_gr_unfused = unfused;
strata::kernels::cvec().cover = cvec_covers;
__FUSE__
return fuse;
}
static std::vector<int32_t> iota_vec(int n, int step = 1, int from = 0) {
std::vector<int32_t> v;
for (int i = from; i < n; i += step) v.push_back(i);
return v;
}
int main() {
std::vector<Scenario> sc;
// fields: name, n_layers, n_expert, lb, le, ring, stager_ring, T, orders, resident_mod, resident_rem, cache_present, pinned_mod, transient_mod, chunks
sc.push_back({"stream_basic", 6, 24, 1, 4, 16, 16, 1024,
{iota_vec(24, 2), iota_vec(24, 3, 1), {0, 1, 2, 5, 23}}, 5, 0, true, 3, 4, 2});
sc.push_back({"stream_ring_wrap", 4, 40, 0, 3, 16, 16, 2048,
{iota_vec(40), iota_vec(40), iota_vec(40, 7)}, 0, 0, true, 2, 0, 2});
sc.push_back({"stream_no_cache_all_pinned", 3, 20, 0, 3, 16, 16, 1024,
{iota_vec(20), iota_vec(20, 2), {19}}, 0, 0, false, 1, 0, 1});
sc.push_back({"stream_sparse_release", 5, 40, 1, 4, 16, 4, 4096,
{{39}, {0}, {5, 6, 7, 30}}, 0, 0, true, 5, 3, 2});
sc.push_back({"staged_under_threshold", 4, 32, 0, 3, 384, 16, 512,
{iota_vec(32), iota_vec(32, 3), {2, 4}}, 4, 1, true, 3, 5, 2});
sc.push_back({"staged_ring8", 3, 12, 0, 2, 8, 16, 4096,
{iota_vec(12), iota_vec(12, 2)}, 0, 0, false, 2, 3, 1});
sc.push_back({"staged_few_experts", 3, 10, 0, 2, 16, 16, 100,
{{1, 3, 4}, {9}}, 3, 0, true, 0, 0, 1});
std::printf("{\"ring\":[");
for (size_t i = 0; i < sc.size(); ++i) { if (i) std::printf(",\n"); run_scenario(sc[i]); }
std::printf("],\n");
std::vector<PleScenario> ples = {{"ple_two_chunks_gather", 2000, 1024, false}, {"ple_single_chunk", 100, 256, false},
{"ple_gpu_cache", 3000, 1024, true}, {"ple_four_chunks", 4096, 1024, false},
{"ple_exact_multiple", 2048, 1024, false}};
std::printf("\"ple\":[");
for (size_t i = 0; i < ples.size(); ++i) { if (i) std::printf(",\n"); run_ple_scenario(ples[i]); }
std::printf("],\n\"fuse\":[");
bool first = true;
for (int le : {48, 16}) for (int ple_on = 0; ple_on < 2; ++ple_on) for (int unfused = 0; unfused < 2; ++unfused)
for (int cv = 0; cv < 2; ++cv) for (int l : {0, 1, 2, 14, 15, 46, 47}) for (int half = 0; half < 2; ++half) {
if (l >= le) continue;
std::printf("%s[%d,%d,%d,%d,%d,%d,%d]", first ? "" : ",", le, ple_on, unfused, cv, l, half, (int) fuse_of(l, half, le, ple_on != 0, unfused != 0, cv != 0));
first = false;
}
std::printf("]}\n");
return 0;
}
'''
out = (template.replace('__DIGEST__', digest)
.replace('__R1__', f'{a1}-{b1}').replace('__R2__', f'{a2}-{b2}').replace('__R3__', f'{a3}-{b3}').replace('__R4__', f'{a4+1}-{b4}')
.replace('__SEQ_BUILD__', seq_build).replace('__CONSUMER__', consumer).replace('__STAGED__', staged).replace('__WALKS__', walks).replace('__PLE__', ple_block).replace('__FUSE__', fuse_block))
out = out.replace('%%', '%')
sys.stdout.write(out)
+19 -19
View File
@@ -124,13 +124,13 @@
"count": 3
}
],
"sm120_bytes": 5980,
"sm120_bytes": 5983,
"sm120_nvcc": null,
"sm120_path": "crates/cuda-driver/src/bf16_f32_mmvf.ptx",
"sm120_sha256": "044543f681bb23eb9cae602b1a16aa7b2386d6d5c3b15cc41987338bd613b1c3",
"sm120_sha256": "8b0d71f343f2b2b34b0e742e3bb08c2192be33e8016c2136e63fc7f34f477aaa",
"sm120_stored_nul": false,
"sm86_bytes": 5874,
"sm86_sha256": "54a33146558ef76c817fc8e556f709228f90e2ccd6565f57c4f8ec4646e6c442"
"sm86_bytes": 5877,
"sm86_sha256": "29e6a266d9608df5ff00c87ca8296c55f4ea53ed4d1fe01f0b785b76984d4318"
},
{
"entries": 19,
@@ -476,13 +476,13 @@
"count": 1
}
],
"sm120_bytes": 24712,
"sm120_bytes": 24718,
"sm120_nvcc": "13.0.88",
"sm120_path": "crates/cuda-driver/src/iq3_s_q8_1.ptx",
"sm120_sha256": "94f798c00813c2fb860b4bf77be9225767d408955e3421330ac34a4ebd43978f",
"sm120_sha256": "ebfcabd456b8cf16608c529b906849e4391096322a88e5a665ac87657a91dde6",
"sm120_stored_nul": false,
"sm86_bytes": 24711,
"sm86_sha256": "b19860070e69dccd5e98d1e6bc7cddcda2928efbd3f0bd21568fd1ae7d4ae927"
"sm86_bytes": 24717,
"sm86_sha256": "46a64e151bbdfe0e5b3a4b36e6abab396aeed026872b608e76b9a482bea8240a"
},
{
"entries": 1,
@@ -916,13 +916,13 @@
"count": 1
}
],
"sm120_bytes": 25114,
"sm120_bytes": 25120,
"sm120_nvcc": "13.0.88",
"sm120_path": "crates/cuda-driver/src/moe_group_iq3_s.ptx",
"sm120_sha256": "58d068ff3acc4211614f70ab04703a40858e148f9aef8503ed66f7640ae2e2aa",
"sm120_sha256": "46b0d5365a1529c65f478aa5335089e56eb624370f9c17c87e79b7369f0e7b8a",
"sm120_stored_nul": false,
"sm86_bytes": 25113,
"sm86_sha256": "36c2f68c0d3a3c524787ecf03a1f33e2da930a4917419ea5893ccaa28c33a88c"
"sm86_bytes": 25119,
"sm86_sha256": "0e5e0434421077516213079c02d9f98ff4bcfa46347903786e1decd520bbfd14"
},
{
"entries": 2,
@@ -936,13 +936,13 @@
"count": 1
}
],
"sm120_bytes": 36382,
"sm120_bytes": 36388,
"sm120_nvcc": "13.0.88",
"sm120_path": "crates/cuda-driver/src/moe_group_iq3_s_nc4.ptx",
"sm120_sha256": "be6ee907c0b370cb99894a03419466f1aa465ba9b8e2e8cf603887f534450d0c",
"sm120_sha256": "7a13911f998d38bba5c52862f92799d17a662e8427c1cdff24f01c1f30a7fd94",
"sm120_stored_nul": false,
"sm86_bytes": 36381,
"sm86_sha256": "23b702aaf1278dd3d436142b9c27321921f36dda7606d1f756973e5dfcbd4537"
"sm86_bytes": 36387,
"sm86_sha256": "e12dea8f921efd99c9483012f8da00c5ba1ba66b0444ff4ba98fed4903ed51e5"
},
{
"entries": 1,
@@ -1635,12 +1635,12 @@
"-std=c++17",
"--fmad=true",
"--ftz=false",
"-Iengine/strata/include",
"-Iengine/strata/third_party/ggml",
"-Istrata-41cf05a0/include",
"-Istrata-41cf05a0/third_party/ggml",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-cuda",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-include",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-src",
"-Iengine/strata/src"
"-Istrata-41cf05a0/src"
],
"isa": "9.2",
"method": "recompile",
@@ -1,5 +1,5 @@
// Adapted from the pinned native operation:
// engine/strata/src/kernels/cuda/native_bf16.cu
// Strata 41cf05a0, src/kernels/cuda/native_bf16.cu
// SHA-256 70b44795528fb73d636be5914d60f0adaa849a48cc38f309d327a2976c3ed3da
// and exact BF16 bit expansion in bf16_bits.hpp
// SHA-256 813b51f17c5c264d642f4d77b3d6e5f35e7ea7310ba87b18b3a2a5bc9185198f.
+2 -2
View File
@@ -1,7 +1,7 @@
// IQ3_S Q8_1 routed projection; derived from llama.cpp/ggml native Fmt21.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// Native source: engine/strata/src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: engine/strata/third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Native source: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: Strata 41cf05a0, third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Full MIT notice is retained in crates/quant-core/LICENSE-GGML.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -1,7 +1,7 @@
// IQ3_S Q8_1 routed projection; derived from llama.cpp/ggml native Fmt21.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// Native source: engine/strata/src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: engine/strata/third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Native source: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: Strata 41cf05a0, third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Full MIT notice is retained in crates/quant-core/LICENSE-GGML.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -5,8 +5,8 @@
// Tail activation loads clamp to last genuine pointer; only live stores write.
// IQ3_S Q8_1 routed projection; derived from llama.cpp/ggml native Fmt21.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// Native source: engine/strata/src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: engine/strata/third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Native source: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: Strata 41cf05a0, third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Full MIT notice is retained in crates/quant-core/LICENSE-GGML.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -1,6 +1,6 @@
{
"schema": 1,
"note": "Additions for the experimental Strata modes. None of these six .cu files has been compiled; PINS in experimental.rs are all zero and admit_ptx refuses every asset until Root builds the PTX and freezes the digests. Flags follow engine/strata/CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list (native_* only) and the strata_kernels target adds no other CUDA flag besides CUDA_STANDARD 17, so the build is precise (no --use_fast_math) with default -fmad contraction.",
"note": "Additions for the experimental Strata modes. None of these six .cu files has been compiled; PINS in experimental.rs are all zero and admit_ptx refuses every asset until Root builds the PTX and freezes the digests. Flags follow Strata 41cf05a0, CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list (native_* only) and the strata_kernels target adds no other CUDA flag besides CUDA_STANDARD 17, so the build is precise (no --use_fast_math) with default -fmad contraction.",
"assets": [
{
"cu": "crates/cuda-driver/src/experimental_kv_q4.cu",
@@ -17,7 +17,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). FWHT-256 + Q4_0 append (step/batched) + gather; Original kv_q4.cu precise (default flags, not in the fast-math list); K8V4's Q4_0 V half and rotated INT8's FWHT",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/kv_q4.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/kv_q4.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -53,7 +53,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). INT8 append (K+V, K8V4 K half, V-only) + gather; Original kv_q8.cu precise",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/kv_q8.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/kv_q8.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -89,7 +89,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). CLOCK residency resolver, block copy, ring table, u4 copy; Original kv_stream.cu precise; integer only",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/kv_stream.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/kv_stream.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -113,8 +113,8 @@
{
"cu": "crates/cuda-driver/src/experimental_keyless.cu",
"cu_pin": {
"sha256": "77c50e5baff842e31f0d71624a5706f46ed74a56cdfc5e4211086d2ef08671c5",
"bytes": 1987
"sha256": "44304e967dc68e92233f6b78c25e6d80475ea4c0e94262cf928f7405cd553733",
"bytes": 1990
},
"ptx": "crates/cuda-driver/src/experimental_keyless.ptx",
"flags": [
@@ -125,7 +125,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). per-head query routing (fmaf-ordered 256x256); Original keyless.cu precise",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/keyless.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/keyless.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -161,7 +161,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). experimental attention modes 2/3/4 + merge; Original qsa_decode_attn.cu precise (expf/exp2f exact, not in the fast-math list)",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/qsa_decode_attn.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/qsa_decode_attn.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -185,8 +185,8 @@
{
"cu": "crates/cuda-driver/src/experimental_cvec.cu",
"cu_pin": {
"sha256": "d4fe221b11569db73247644bb79118b34d040b49c14897e0bac158dcd4ca356e",
"bytes": 4783
"sha256": "89038128664ea4688e20de69eb32f55dd17c3a51bb1d67ec7774cba97ec70686",
"bytes": 4786
},
"ptx": "crates/cuda-driver/src/experimental_cvec.ptx",
"flags": [
@@ -197,7 +197,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). control-vector apply; Original cvec.cu default flags (its own __expf in sigmoidf_ is explicit in the source)",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/cvec.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/cvec.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -1,7 +1,7 @@
{
"schema": 1,
"purpose": "Assets Root must seal for the literal Verifier window recorder (OriginalVerifyWindowOps). Everything not listed under new_sources is an already sealed asset that the window producers merely bind (SHA-256 pinned in the AssetSpec constants of crates/cuda-driver/src/original_verify_window_*.rs).",
"toolkit": "deploy/cuda-toolkit.lock.json (CUDA 13.0.88), built through scripts/build-original-verify-ptx.sh",
"toolkit": "deploy/cuda-toolkit.lock.json (CUDA 13.0.88), built with the precise nvcc flags (--fmad=true --ftz=false)",
"new_sources": [
{
"source": "crates/cuda-driver/src/original_verify_window_moe_experts.cu",
@@ -13,8 +13,8 @@
"-arch=sm_120",
"--fmad=true",
"--ftz=false",
"-Iengine/strata/include",
"-Iengine/strata/third_party/ggml",
"-Istrata-41cf05a0/include",
"-Istrata-41cf05a0/third_party/ggml",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-cuda",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-include",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-src"
@@ -37,7 +37,7 @@
"window_moe_down_7",
"window_moe_down_8"
],
"derived_from": "engine/strata/src/kernels/cuda/iq_kernels.cu (native_gu_kernel, native_gu_multi_kernel, native_down_kernel, native_down_multi_kernel via native_expert_grouped / launch_gu / launch_down; textually includes crates/cuda-driver/src/mtp_original_full_head_iq.cu, the sealed copy of iq_kernels.cu; engine/strata/CMakeLists.txt gives iq_kernels.cu no per-source COMPILE_OPTIONS)",
"derived_from": "Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu (native_gu_kernel, native_gu_multi_kernel, native_down_kernel, native_down_multi_kernel via native_expert_grouped / launch_gu / launch_down; textually includes crates/cuda-driver/src/mtp_original_full_head_iq.cu, the sealed copy of iq_kernels.cu; Strata 41cf05a0, CMakeLists.txt gives iq_kernels.cu no per-source COMPILE_OPTIONS)",
"notes": "NEW source: no sealed PTX instantiates the grouped gate/up and down templates for the target's formats. The rest of native_expert_grouped (swiglu_entries_kernel, quantize_q8_1_kernel) is sealed in mtp_original_full_head_iq.ptx under mangled names. The PTX will also carry the unused head_* / dequant entries of the included file. Update EXPERTS.sha in original_verify_window_moe.rs after sealing; the build script's required-exports check should list the exports above.",
"install": "Compile, append exactly ONE terminal NUL byte (like the other sealed MTP assets), write over the placeholder .ptx, then replace the all-zero `sha` of the matching AssetSpec by sha256 of the bytes BEFORE the NUL."
},
@@ -51,8 +51,8 @@
"-arch=sm_120",
"--fmad=true",
"--use_fast_math",
"-Iengine/strata/include",
"-Iengine/strata/third_party/ggml",
"-Istrata-41cf05a0/include",
"-Istrata-41cf05a0/third_party/ggml",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-cuda",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-include",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-src"
@@ -60,8 +60,8 @@
"exports": [
"verify_window_qsa_gate"
],
"derived_from": "engine/strata/src/kernels/cuda/native_qsa.cu (kernel `gate`; CMakeLists.txt compiles native_qsa.cu with --use_fast_math)",
"nvcc_note": "--use_fast_math (as engine/strata/CMakeLists.txt compiles native_qsa.cu) implies --ftz=true --prec-div=false --prec-sqrt=false --fmad=true; --ftz=false is deliberately NOT passed.",
"derived_from": "Strata 41cf05a0, src/kernels/cuda/native_qsa.cu (kernel `gate`; CMakeLists.txt compiles native_qsa.cu with --use_fast_math)",
"nvcc_note": "--use_fast_math (as Strata 41cf05a0, CMakeLists.txt compiles native_qsa.cu) implies --ftz=true --prec-div=false --prec-sqrt=false --fmad=true; --ftz=false is deliberately NOT passed.",
"install": "Compile, append exactly ONE terminal NUL byte (like the other sealed MTP assets), write over the placeholder .ptx, then replace the all-zero `sha` of the matching AssetSpec by sha256 of the bytes BEFORE the NUL."
}
],
@@ -160,7 +160,7 @@
"native_qsa_indexer",
"native_qsa_score"
],
"note": "engine/strata/CMakeLists.txt compiles these Original sources with --use_fast_math. The sealed Rust copies below were built with the precise flags of scripts/build-original-verify-ptx.sh (--fmad=true --ftz=false). Some copies reproduce the fast-math operations with explicit intrinsics in the .cu (e.g. mtp_original_full_shared.cu: __fdividef/__expf); the others are a numerics risk for bit-exact parity with the Original window until a per-kernel golden comparison on the GPU (or a re-seal with --use_fast_math) proves otherwise.",
"note": "Strata 41cf05a0, CMakeLists.txt compiles these Original sources with --use_fast_math. The sealed Rust copies below were built with the precise flags (--fmad=true --ftz=false). Some copies reproduce the fast-math operations with explicit intrinsics in the .cu (e.g. mtp_original_full_shared.cu: __fdividef/__expf); the others are a numerics risk for bit-exact parity with the Original window until a per-kernel golden comparison on the GPU (or a re-seal with --use_fast_math) proves otherwise.",
"candidate_resealed_assets": [
{
"ptx": "mtp_original_full_head_native.ptx / mtp_original_tail.ptx / mtp_original_full_checks.ptx",
@@ -204,7 +204,7 @@
}
],
"audit": {
"method": "For each Original source in the fast-math list that the window launches, the fast-math-sensitive operations (/ , expf, sqrtf, powf, sinf, cosf, logf) were listed from engine/strata/src/kernels/cuda/*.cu and compared with the instruction mix of the sealed PTX. A precise nvcc compile emits div.rn/rcp.rn/sqrt.rn and the multi-instruction expf sequence (fma.rn + ex2.approx.ftz + mul); --use_fast_math emits div.full, rcp.approx.ftz, sqrt.approx.ftz, ex2.approx.ftz(x*log2e), sin/cos.approx.ftz and .ftz on the arithmetic. Only qsa_decode_postops.ptx carries .ftz on its arithmetic.",
"method": "For each Original source in the fast-math list that the window launches, the fast-math-sensitive operations (/ , expf, sqrtf, powf, sinf, cosf, logf) were listed from Strata 41cf05a0, src/kernels/cuda/*.cu and compared with the instruction mix of the sealed PTX. A precise nvcc compile emits div.rn/rcp.rn/sqrt.rn and the multi-instruction expf sequence (fma.rn + ex2.approx.ftz + mul); --use_fast_math emits div.full, rcp.approx.ftz, sqrt.approx.ftz, ex2.approx.ftz(x*log2e), sin/cos.approx.ftz and .ftz on the arithmetic. Only qsa_decode_postops.ptx carries .ftz on its arithmetic.",
"sealed_precise_but_original_fast_math": [
{
"ptx": "mtp_original_full_head_native.ptx",
@@ -257,7 +257,7 @@
"original_verify.ptx, mtp_original_full_fused_gr.ptx, mtp_original_kv.ptx, qsa_prompt_select.ptx, qsa_prompt_resolver.ptx, mtp_original_full_element.ptx, mtp_original_full_s2.ptx, mtp_original_full_head_iq.ptx, mtp_original_full_router_legacy.ptx (all precise in the Original)"
],
"not_in_verify_window": "native_flash_attn.cu and native_qsa_score.cu are launched only by the single-token layer.cpp path, never by verify.cpp (qsa_decode_attn_batch / qsa_block_scores are precise)",
"action": "Re-seal the six assets above from their existing .cu with --use_fast_math (scripts/build-original-verify-ptx.sh compiles every source with the precise flags) and update their SHA pins; none of those sources contains hand-written intrinsics that a fast-math build would double-apply. The same assets back the MTP path, so the MTP golden comparisons must be redone after the re-seal."
"action": "Re-seal the six assets above from their existing .cu with --use_fast_math (every source was sealed with the precise flags) and update their SHA pins; none of those sources contains hand-written intrinsics that a fast-math build would double-apply. The same assets back the MTP path, so the MTP golden comparisons must be redone after the re-seal."
},
"not_candidates_original_is_precise": [
{
@@ -1,6 +1,6 @@
{
"schema": 1,
"note": "Additions to CUDA-SEAL-PLAN.json (schema 1, see stra169 plan) for the .cu assets added on claude/port-forward-leaves. Same fields; seal_sha256/seal_length are filled by the sealing session after nvcc. None of these needs -I/work/include (they include only cuda_fp16.h/cuda_runtime.h/libc headers). Verify each compiled entry list with `cuobjdump -sass`/`grep .entry` against `entries` before pinning. Flags follow engine/strata/CMakeLists.txt: --use_fast_math only for files in the native_* fast-math list.",
"note": "Additions to CUDA-SEAL-PLAN.json (schema 1, see stra169 plan) for the .cu assets added on claude/port-forward-leaves. Same fields; seal_sha256/seal_length are filled by the sealing session after nvcc. None of these needs -I/work/include (they include only cuda_fp16.h/cuda_runtime.h/libc headers). Verify each compiled entry list with `cuobjdump -sass`/`grep .entry` against `entries` before pinning. Flags follow Strata 41cf05a0, CMakeLists.txt: --use_fast_math only for files in the native_* fast-math list.",
"assets": [
{
"cu": "crates/cuda-driver/src/qsa_prompt_attention_variants.cu",
@@ -81,8 +81,8 @@
{
"cu": "crates/cuda-driver/src/mmq_original_prefill_misc.cu",
"cu_pin": {
"sha256": "da4cc72e19ca1ad694f4be807d6c0c1337ecfd8ca553fe31dd4c5185ed24cf4a",
"bytes": 3072
"sha256": "c5b2242dd01a48168052e4dd42ed5ab37bf44bd1bcc47a9bccb8f4ab7460faad",
"bytes": 3075
},
"ptx": "crates/cuda-driver/src/mmq_original_prefill_misc.ptx",
"flags": [
@@ -154,8 +154,8 @@
{
"cu": "crates/cuda-driver/src/s_gemv_legacy.cu",
"cu_pin": {
"sha256": "0922bb96ca3b2f1110509adab242cf76fa1f910cde859d1e4e4150c607b51952",
"bytes": 51423
"sha256": "0476de35304abd5149fc3b123e2a81855d79b37d36e0f4022433732fe94090ca",
"bytes": 51401
},
"ptx": "crates/cuda-driver/src/s_gemv_legacy.ptx",
"flags": [
@@ -211,7 +211,7 @@
}
],
"flags_policy_audit": {
"audited": "2026-10-14 with scripts/cuda-stubs/literal_diff.py (SOURCES=1) over every crates/cuda-driver/src/*.cu, against engine/strata/CMakeLists.txt",
"audited": "2026-10-14 with a literal-diff check (SOURCES=1) over every crates/cuda-driver/src/*.cu, against Strata 41cf05a0, CMakeLists.txt",
"cmake_policy": {
"per_source_use_fast_math": [
"native_mmvq",
@@ -229,7 +229,7 @@
"native_qsa_indexer",
"native_qsa_score"
],
"cmake_lines": "engine/strata/CMakeLists.txt:340-352 (strata_kernels), :965 (strata_mmq)",
"cmake_lines": "Strata 41cf05a0, CMakeLists.txt:340-352 (strata_kernels), :965 (strata_mmq)",
"strata_mmq_extended_lambda_use_fast_math": [
"src/prefill/moe_mmq.cu",
"src/prefill/ggml_cuda_host.cu",
@@ -320,6 +320,6 @@
"mtp_original_full_fused_gr (fused_gr)",
"mtp_original_full_s2 / mtp_original_full_shared / mtp_original_full_verify / mtp_original_full_element / mtp_original_full_gr_write / mtp_original_full_head_iq / mtp_original_full_head_sampler / mtp_original_full_coupled / mtp_original_full_quant80"
],
"stale_toolkit_comments": "kar_decode_levels.cu, experimental_*.cu, mmq_original_group_*.cu, mmq_original_formats*.cu say nvcc 12.8.93; deploy/cuda-toolkit.lock.json and scripts/build-original-verify-ptx.sh pin 13.0.88"
"stale_toolkit_comments": "kar_decode_levels.cu, experimental_*.cu, mmq_original_group_*.cu, mmq_original_formats*.cu say nvcc 12.8.93; deploy/cuda-toolkit.lock.json pins 13.0.88"
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
// Adapted from the pinned native operation:
// engine/strata/src/kernels/cuda/native_bf16.cu
// Strata 41cf05a0, src/kernels/cuda/native_bf16.cu
// SHA-256 70b44795528fb73d636be5914d60f0adaa849a48cc38f309d327a2976c3ed3da
// and exact BF16 bit expansion in bf16_bits.hpp
// SHA-256 813b51f17c5c264d642f4d77b3d6e5f35e7ea7310ba87b18b3a2a5bc9185198f.
@@ -51,9 +51,10 @@ impl Driver {
}
}
impl<'driver> Device<'driver> {
/// A context for the serving context the process configured (the trained default when none was).
/// A context of the trained serving context (262144 cells, identity RoPE); the serving engine creates its
/// contexts with [`Device::create_context_serving`].
pub fn create_context(&self, byte_budget: usize) -> Result<Context<'driver>> {
self.create_context_serving(byte_budget, crate::serving_context::serving_context())
self.create_context_serving(byte_budget, ServingContext::trained())
}
/// A context whose buffers are sized and whose rotating kernels are parameterized for `serving`.
pub fn create_context_serving(&self, byte_budget: usize, serving: ServingContext) -> Result<Context<'driver>> {
+2 -2
View File
@@ -54,8 +54,8 @@ pub const PINS: [PtxPin; 3] = [
},
PtxPin {
source_sha256: [
9, 34, 187, 150, 202, 59, 47, 17, 16, 80, 154, 218, 178, 66, 207, 118, 250, 31, 145, 12, 222, 133, 157, 30,
78, 65, 80, 198, 7, 181, 25, 82,
4, 118, 222, 53, 48, 74, 189, 81, 73, 252, 59, 18, 62, 42, 129, 133, 93, 121, 179, 125, 54, 224, 244, 2,
36, 51, 115, 47, 233, 64, 144, 202,
],
ptx_sha256: [
58, 180, 209, 42, 94, 151, 196, 226, 244, 96, 44, 108, 135, 35, 114, 197, 192, 104, 93, 140, 241, 162, 2,
+6 -1
View File
@@ -54,6 +54,11 @@ impl Context<'_> {
}
Ok(CurrentGuard { context: self, active: true })
}
/// Print the allocation sites of this context that changed since the last report (nothing while
/// `LELEKA_VRAM_LEDGER` is off).
pub fn report_vram_ledger(&self, label: &str) {
vram_ledger::report(&self.retained.vram_ledger, label);
}
pub fn allocate(&self, bytes: usize) -> Result<DeviceBuffer<'_>> {
valid_size(bytes)?;
let total = self.allocated.get().checked_add(bytes).ok_or(Error::BudgetExceeded)?;
@@ -68,7 +73,7 @@ impl Context<'_> {
// A successful allocation whose pop fails stays charged. The poisoned
// context owns that allocation until destruction, so no unguarded free.
let handle = combine(allocation, guard.finish())?;
vram_ledger::note_alloc(handle.qwen_address(), bytes);
vram_ledger::note_alloc(&self.retained.vram_ledger, handle.qwen_address(), bytes);
Ok(DeviceBuffer { context: self, handle: Some(handle), bytes, _thread: PhantomData, borrowed: false })
}
/// Queue a buffer's release for after the chunk's expert stream (it stays charged until then); when the
+2 -2
View File
@@ -1,9 +1,9 @@
//! DeviceBuffer host/device copies (whole buffer and ranges, staged through a host Vec, synchronised) and its release
//! and Drop, plus the LELEKA_CHAIN 'mtp' selector chain_selects_mtp with its no-driver stubs.
use super::{DeviceBuffer, Error, Result, combine, compute_drain, vram_ledger};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
use super::original_verify;
use super::{DeviceBuffer, Error, Result, combine, compute_drain, vram_ledger};
impl DeviceBuffer<'_> {
pub fn len(&self) -> usize {
@@ -153,7 +153,7 @@ impl DeviceBuffer<'_> {
if self.borrowed {
return Ok(());
}
vram_ledger::note_free(handle.qwen_address());
vram_ledger::note_free(&self.context.retained.vram_ledger, handle.qwen_address());
if compute_drain::background() != 0 && !self.context.poisoned.get() {
// a chunk expert stream is in flight: do not synchronize the device now
return self.context.defer_free(handle, self.bytes);
+4 -4
View File
@@ -136,8 +136,8 @@ pub const PINS: [PtxPin; 6] = [
},
PtxPin {
source_sha256: [
119, 197, 14, 91, 175, 248, 66, 227, 31, 13, 113, 98, 74, 87, 6, 244, 110, 215, 74, 86, 205, 252, 94, 66,
17, 8, 109, 46, 240, 134, 113, 197,
68, 48, 78, 150, 125, 198, 142, 146, 35, 63, 107, 120, 194, 94, 109, 128, 71, 94, 164, 192, 233, 66, 98,
207, 146, 143, 116, 5, 205, 85, 55, 51,
],
ptx_sha256: [
26, 184, 184, 21, 110, 140, 130, 65, 49, 192, 12, 236, 218, 23, 127, 229, 125, 116, 178, 134, 160, 43, 126,
@@ -156,8 +156,8 @@ pub const PINS: [PtxPin; 6] = [
},
PtxPin {
source_sha256: [
212, 254, 34, 27, 17, 86, 157, 183, 50, 71, 100, 75, 183, 145, 24, 179, 77, 4, 11, 73, 193, 72, 151, 224,
186, 193, 88, 220, 212, 202, 53, 110,
137, 3, 129, 40, 102, 78, 164, 104, 142, 32, 222, 105, 235, 50, 245, 93, 209, 124, 58, 81, 187, 29, 103,
236, 119, 116, 203, 169, 126, 199, 6, 134,
],
ptx_sha256: [
25, 58, 221, 92, 180, 72, 245, 225, 147, 242, 15, 242, 72, 202, 68, 89, 171, 185, 98, 180, 114, 102, 60, 0,
+1 -1
View File
@@ -6,7 +6,7 @@
// an explicit ExperimentalOptIn (experimental.rs). With the flag off and no pending write the kernel is a no-op;
// with a pending write it applies the fused hyper-connection read's own arithmetic.
//
// LITERAL PORT of engine/strata/src/kernels/cuda/cvec.cu: `cvec_kernel`'s BODY and `sigmoidf_` are
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/cvec.cu: `cvec_kernel`'s BODY and `sigmoidf_` are
// byte-identical to the Original's (experimental_cvec.rs::literal_bodies_match_the_original). Edits:
// `__global__ cvec_kernel` became the `__device__ cvec_kernel_body` function called by the `extern "C" __global__`
// entry; the host tables (g_dev, cvec_upload, cvec_apply) are Rust. A null `bo`/`inj` is a 64-bit zero argument.
@@ -5,7 +5,7 @@
// model-quality gate (docs/keyless-runtime.md): this is an unqualified experiment, off by default, and the driver
// refuses the program without an explicit ExperimentalOptIn (experimental.rs).
//
// LITERAL PORT of engine/strata/src/kernels/cuda/keyless.cu: the kernel BODY is byte-identical to the Original's
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/keyless.cu: the kernel BODY is byte-identical to the Original's
// (experimental_attn.rs::literal_bodies_match_the_original). Edits: `__global__ route_kernel` became the
// `__device__ route_kernel_body` function called by the `extern "C" __global__` entry; the host wrapper
// `keyless_route_query` (argument checks and launch geometry) is Rust.
+1 -1
View File
@@ -3,7 +3,7 @@
// 256-point Walsh-Hadamard transform they rely on. Off by default; the driver refuses to open this program
// without an explicit ExperimentalOptIn for a mode that needs it (experimental.rs).
//
// LITERAL PORT of engine/strata/src/kernels/cuda/kv_q4.cu (Original, PR #21). Every kernel BODY below is
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/kv_q4.cu (Original, PR #21). Every kernel BODY below is
// byte-identical to the Original's (experimental_kv.rs::literal_bodies_match_the_original compares them).
// The only edits:
// 1. each `__global__` kernel became a `__device__ ..._body` function with the same parameters, called by
+2 -2
View File
@@ -8,7 +8,7 @@
// Both are lossy/unqualified and off by default; the driver refuses this program without an explicit
// ExperimentalOptIn (experimental.rs). The production INT8 path of the Rust runtime does not use this file.
//
// LITERAL PORT of engine/strata/src/kernels/cuda/kv_q8.cu. Kernel BODIES are byte-identical to the Original's
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/kv_q8.cu. Kernel BODIES are byte-identical to the Original's
// (experimental_kv.rs::literal_bodies_match_the_original). Edits: each `__global__` kernel became a
// `__device__ ..._body` function with the same parameters called by an `extern "C" __global__` entry with a
// flat pointer/integer ABI (KvHostPools rebuilt from pointers; a null pointer argument is a 64-bit zero);
@@ -22,7 +22,7 @@
// `cur_stride` (the Original's S26 multi-token append); the body is copied verbatim and the entry instantiates the
// single-token form (MULTI = false, strides 0), the old behaviour bit for bit, with its ABI unchanged. The MULTI
// branch is therefore not instantiated here. The Original's 8-wide gather (kv_gather_q8_wide_kernel) exists only
// under STRATA_EXPERIMENTAL_SM60 and is not part of this sm_120 program (tests/literal_port.rs lists it as excluded).
// under STRATA_EXPERIMENTAL_SM60 and is not part of this sm_120 program.
// Not compiled after the re-sync (no nvcc on that host): the sealed PTX is the 2026-10-15 build of the previous source
// and experimental::PENDING_RESEAL makes the program refuse to open until the server reseals it.
// Sealed 2026-10-15 with nvcc 13.2.86 -ptx -O3 -arch=sm_120 -std=c++17, precise math (the Original builds kv_q8.cu with
@@ -5,7 +5,7 @@
// bitwise equal to resident attention), but it is unqualified in this port and off by default; the driver
// refuses this program without an explicit ExperimentalOptIn (experimental.rs).
//
// LITERAL PORT of engine/strata/src/kernels/cuda/kv_stream.cu (resolve_kernel, copy_kernel, reset_kernel,
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/kv_stream.cu (resolve_kernel, copy_kernel, reset_kernel,
// ring_kernel, block_scan, Runs, RT). Bodies are byte-identical to the Original's
// (experimental_stream.rs::literal_bodies_match_the_original). Edits: `__global__` kernels became
// `__device__ ..._body` functions with the same parameters called by `extern "C" __global__` entries with a flat
@@ -7,7 +7,7 @@
// ExperimentalOptIn (experimental.rs). The fp16 and INT8 modes of the Original kernel are NOT instantiated here
// (INT8 is qsa_native_decode.cu; fp16 is not part of the Rust runtime).
//
// LITERAL PORT of engine/strata/src/kernels/cuda/qsa_decode_attn.cu: warp_sum, warp_max, load8_*, load8<>,
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/qsa_decode_attn.cu: warp_sum, warp_max, load8_*, load8<>,
// attn_chunk_kernel<> and attn_merge_kernel BODIES are byte-identical to the Original's
// (experimental_attn.rs::literal_bodies_match_the_original), as are the constants and mrope_pos. Edits: the
// `__global__` kernels became `__device__ ..._body` functions with the same parameters, called by
@@ -24,7 +24,7 @@
// LANE_CELL, QUERY_SWIZZLE, REDUCE12>` (with reduce12_gfx906 / reduce12_head_of_lane), copied verbatim; the entries
// instantiate it with the three flags off, which is the previous kernel's arithmetic. The Original's alternate
// schedules and batch variants (attn_chunk_kernel_pre75 and its helpers, attn_merge_v2_kernel, the INT8 v3 kernel,
// the slot / row kernels) are not part of this program: tests/literal_port.rs lists each as excluded with its reason.
// the slot / row kernels) are not part of this program.
// Not compiled after the re-sync (no nvcc on that host): the sealed PTX is the 2026-10-15 build of the previous
// source and experimental::PENDING_RESEAL makes the program refuse to open until the server reseals it.
// Sealed 2026-10-15 with nvcc 13.2.86 -ptx -O3 -arch=sm_120 -std=c++17, precise math (the Original builds
+1 -1
View File
@@ -121,7 +121,7 @@ fn routed_ptx(format: RoutedFormat) -> &'static [u8] {
// standalone installed-Driver proof is distinct from composition.
RoutedFormat::IQ3_XXS => concat!(include_str!("../iq3_xxs_q8_1.ptx"), "\0").as_bytes(),
// Root-delivered STRA-149 frozen routed artifact
// 94f798c00813c2fb860b4bf77be9225767d408955e3421330ac34a4ebd43978f.
// ebfcabd456b8cf16608c529b906849e4391096322a88e5a665ac87657a91dde6.
RoutedFormat::IQ3_S => concat!(include_str!("../iq3_s_q8_1.ptx"), "\0").as_bytes(),
// Root-delivered STRA-150 frozen routed artifact a31e653d.
RoutedFormat::IQ2_S => concat!(include_str!("../iq2_s_q8_1.ptx"), "\0").as_bytes(),
+2 -2
View File
@@ -1,7 +1,7 @@
// IQ3_S Q8_1 routed projection; derived from llama.cpp/ggml native Fmt21.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// Native source: engine/strata/src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: engine/strata/third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Native source: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: Strata 41cf05a0, third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Full MIT notice is retained in crates/quant-core/LICENSE-GGML.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -59,8 +59,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
schedule: &OriginalMmqCopySchedule<'ctx>,
layer: usize,
) -> Result<usize> {
let admitted: &dyn RingArena = read;
let count = admitted.stage_slots()?;
let count = RingArena::stage_slots(read)?;
schedule.validate_context(context)?;
if !schedule_serves_ring(schedule.ring_slots(), count) {
let e = Error::InvalidProjectionShape;

Some files were not shown because too many files have changed in this diff Show More