From f78b89757c095f86a583ac58eb6ae4d8f28801e0 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 15:00:09 +0100 Subject: [PATCH] STRA-338 S12a: inline unit-test modules move to sibling tests.rs files in 118 oversize files scripts/dev/extract_tests.py moves a trailing cfg(test) mod tests block into foo/tests.rs for 118 files of leleka-runtime, cuda-driver, control-plane, gateway-text, deploy and nine smaller crates (31,000 lines), leaving production code and test ids untouched; 22 files that are themselves loaded through a path attribute carry an explicit path to their tests file. Not touched: the files the kar-off-ab branch edits (backend.rs, backend_original_serve.rs, backend_original_serve_replay.rs, qwen4exp_resident_expert_source.rs and seven deploy files). Verified: cargo check --all-targets for the whole workspace on x86_64 Linux and on the Windows host; the 2429 library unit-test ids of the workspace are identical before and after (Linux listing diff empty); the loadable sections of leleka-inference, leleka-daemon, leleka-cli and strata-next are byte-identical between a release build before and after (scripts/dev/elf-sections-equal.sh), so the shipped code is the same. The architecture ratchets exclude tests.rs from the path-include count; the baseline drops from 329 to 311 oversize files and from 302,000 to 273,600 lines. --- architecture-baseline.json | 220 ++- architecture.json | 2 +- control-plane/src/app.rs | 164 +-- control-plane/src/app/tests.rs | 163 +++ control-plane/src/config.rs | 326 +---- control-plane/src/config/tests.rs | 325 +++++ control-plane/src/ggml_bridge.rs | 1292 +---------------- control-plane/src/ggml_bridge/tests.rs | 1291 ++++++++++++++++ control-plane/src/gguf_f32_stream.rs | 918 +----------- control-plane/src/gguf_f32_stream/tests.rs | 917 ++++++++++++ control-plane/src/harmony_family.rs | 233 +-- control-plane/src/harmony_family/tests.rs | 232 +++ control-plane/src/kar.rs | 217 +-- control-plane/src/kar/tests.rs | 216 +++ control-plane/src/kar_quality.rs | 18 +- control-plane/src/kar_quality/tests.rs | 17 + control-plane/src/kar_stream_encode.rs | 153 +- control-plane/src/kar_stream_encode/tests.rs | 152 ++ control-plane/src/kar_writer.rs | 343 +---- control-plane/src/kar_writer/tests.rs | 342 +++++ control-plane/src/mcp.rs | 99 +- control-plane/src/mcp/tests.rs | 98 ++ control-plane/src/messages.rs | 90 +- control-plane/src/messages/tests.rs | 89 ++ control-plane/src/model.rs | 374 +---- control-plane/src/model/tests.rs | 373 +++++ control-plane/src/native_pack.rs | 248 +--- control-plane/src/native_pack/tests.rs | 247 ++++ control-plane/src/prepare_preview.rs | 823 +---------- control-plane/src/prepare_preview/tests.rs | 822 +++++++++++ control-plane/src/prometheus.rs | 144 +- control-plane/src/prometheus/tests.rs | 143 ++ control-plane/src/reasoning_budget.rs | 217 +-- control-plane/src/reasoning_budget/tests.rs | 216 +++ control-plane/src/request_log.rs | 301 +--- control-plane/src/request_log/tests.rs | 300 ++++ control-plane/src/request_monitor.rs | 151 +- control-plane/src/request_monitor/tests.rs | 150 ++ control-plane/src/service_install.rs | 144 +- control-plane/src/service_install/tests.rs | 143 ++ control-plane/src/service_switch.rs | 117 +- control-plane/src/service_switch/tests.rs | 116 ++ control-plane/src/wait_ready.rs | 118 +- control-plane/src/wait_ready/tests.rs | 117 ++ crates/backend-api/src/scripted.rs | 162 +-- crates/backend-api/src/scripted/tests.rs | 161 ++ crates/context/src/context_policy.rs | 135 +- crates/context/src/context_policy/tests.rs | 134 ++ crates/context/src/geometry.rs | 142 +- crates/context/src/geometry/tests.rs | 141 ++ crates/context/src/memory_plan.rs | 105 +- crates/context/src/memory_plan/tests.rs | 104 ++ crates/context/src/rope_scaling.rs | 249 +--- crates/context/src/rope_scaling/tests.rs | 248 ++++ crates/cuda-driver/src/closed_kernels.rs | 406 +----- .../cuda-driver/src/closed_kernels/tests.rs | 405 ++++++ crates/cuda-driver/src/device_slab.rs | 178 +-- crates/cuda-driver/src/device_slab/tests.rs | 177 +++ crates/cuda-driver/src/experimental.rs | 376 +---- crates/cuda-driver/src/experimental/tests.rs | 375 +++++ crates/cuda-driver/src/kar_decode_levels.rs | 339 +---- .../src/kar_decode_levels/tests.rs | 338 +++++ .../src/mmq_original_host_stage.rs | 153 +- .../src/mmq_original_host_stage/tests.rs | 151 ++ .../cuda-driver/src/mtp_original_full_ffi.rs | 23 +- .../src/mtp_original_full_ffi/tests.rs | 21 + .../src/original_conversation_state.rs | 77 +- .../src/original_conversation_state/tests.rs | 75 + .../cuda-driver/src/original_expert_stager.rs | 69 +- .../src/original_expert_stager/tests.rs | 68 + .../src/original_expert_stager_ffi.rs | 69 +- .../src/original_expert_stager_ffi/tests.rs | 67 + .../src/original_file_expert_source_ffi.rs | 67 +- .../original_file_expert_source_ffi/tests.rs | 65 + .../src/original_mtp_draft_vocab.rs | 340 +---- .../src/original_mtp_draft_vocab/tests.rs | 339 +++++ crates/cuda-driver/src/original_mtp_loader.rs | 243 +--- .../src/original_mtp_loader/tests.rs | 242 +++ crates/cuda-driver/src/original_mtp_rt.rs | 436 +----- .../cuda-driver/src/original_mtp_rt/tests.rs | 435 ++++++ .../src/original_prefill_schedule.rs | 234 +-- .../src/original_prefill_schedule/tests.rs | 233 +++ .../src/original_verify_gpu_plan.rs | 60 +- .../src/original_verify_gpu_plan/tests.rs | 58 + .../src/original_verify_window_gr.rs | 508 +------ .../src/original_verify_window_gr/tests.rs | 506 +++++++ .../src/original_verify_window_moe.rs | 722 +-------- .../src/original_verify_window_moe/tests.rs | 720 +++++++++ .../src/original_verify_window_ops.rs | 86 +- .../src/original_verify_window_ops/tests.rs | 84 ++ .../src/original_verify_window_planner.rs | 413 +----- .../original_verify_window_planner/tests.rs | 411 ++++++ .../src/original_verify_window_proj.rs | 161 +- .../src/original_verify_window_proj/tests.rs | 159 ++ .../src/original_verify_window_qsa.rs | 654 +-------- .../src/original_verify_window_qsa/tests.rs | 652 +++++++++ .../src/original_verify_window_record.rs | 319 +--- .../original_verify_window_record/tests.rs | 317 ++++ .../src/qsa_prompt_attention_select.rs | 180 +-- .../src/qsa_prompt_attention_select/tests.rs | 179 +++ crates/cuda-driver/src/s_gemv_legacy.rs | 222 +-- crates/cuda-driver/src/s_gemv_legacy/tests.rs | 221 +++ crates/deploy/src/cli.rs | 411 +----- crates/deploy/src/cli/tests.rs | 410 ++++++ crates/deploy/src/expert_profile.rs | 489 +------ crates/deploy/src/expert_profile/tests.rs | 488 +++++++ crates/deploy/src/facts.rs | 97 +- crates/deploy/src/facts/tests.rs | 96 ++ crates/deploy/src/logview.rs | 350 +---- crates/deploy/src/logview/tests.rs | 349 +++++ crates/deploy/src/preflight.rs | 478 +----- crates/deploy/src/preflight/tests.rs | 477 ++++++ crates/deploy/src/reconfigure.rs | 603 +------- crates/deploy/src/reconfigure/tests.rs | 602 ++++++++ crates/deploy/src/sealed.rs | 64 +- crates/deploy/src/sealed/tests.rs | 63 + crates/deploy/src/steps.rs | 105 +- crates/deploy/src/steps/tests.rs | 104 ++ crates/deploy/src/winfront.rs | 23 +- crates/deploy/src/winfront/tests.rs | 22 + crates/deploy/src/wsl.rs | 204 +-- crates/deploy/src/wsl/tests.rs | 203 +++ crates/experimental-ref/src/cache.rs | 98 +- crates/experimental-ref/src/cache/tests.rs | 97 ++ crates/experimental-ref/src/cvec.rs | 208 +-- crates/experimental-ref/src/cvec/tests.rs | 207 +++ crates/experimental-ref/src/keyless.rs | 205 +-- crates/experimental-ref/src/keyless/tests.rs | 204 +++ crates/experimental-ref/src/kv_stream.rs | 192 +-- .../experimental-ref/src/kv_stream/tests.rs | 191 +++ crates/experimental-ref/src/layout.rs | 132 +- crates/experimental-ref/src/layout/tests.rs | 131 ++ crates/experimental-ref/src/remote_experts.rs | 163 +-- .../src/remote_experts/tests.rs | 162 +++ crates/gateway-text/src/prompt.rs | 495 +------ crates/gateway-text/src/prompt/tests.rs | 493 +++++++ crates/gateway-text/src/tool_output.rs | 662 +-------- crates/gateway-text/src/tool_output/tests.rs | 661 +++++++++ crates/gptoss/src/ops.rs | 344 +---- crates/gptoss/src/ops/tests.rs | 343 +++++ crates/harmony/src/parse.rs | 200 +-- crates/harmony/src/parse/tests.rs | 199 +++ crates/leleka-memory/src/governor.rs | 182 +-- crates/leleka-memory/src/governor/tests.rs | 181 +++ crates/leleka-memory/src/lock.rs | 82 +- crates/leleka-memory/src/lock/tests.rs | 81 ++ crates/leleka-memory/src/plan.rs | 229 +-- crates/leleka-memory/src/plan/tests.rs | 228 +++ crates/leleka-memory/src/procfs.rs | 109 +- crates/leleka-memory/src/procfs/tests.rs | 108 ++ crates/leleka-memory/src/telemetry.rs | 179 +-- crates/leleka-memory/src/telemetry/tests.rs | 178 +++ .../leleka-runtime/src/conversation/cache.rs | 408 +----- .../src/conversation/cache/tests.rs | 407 ++++++ .../src/conversation/resident.rs | 221 +-- .../src/conversation/resident/tests.rs | 220 +++ crates/leleka-runtime/src/experimental.rs | 188 +-- .../leleka-runtime/src/experimental/tests.rs | 187 +++ .../src/model_binding/qwen4exp_gdn.rs | 48 +- .../src/model_binding/qwen4exp_gdn/tests.rs | 46 + .../src/model_binding/qwen4exp_gr.rs | 46 +- .../src/model_binding/qwen4exp_gr/tests.rs | 44 + .../src/model_binding/qwen4exp_mtp.rs | 153 +- .../src/model_binding/qwen4exp_mtp/tests.rs | 151 ++ .../leleka-runtime/src/prefix_cache/store.rs | 583 +------- .../src/prefix_cache/store/tests.rs | 582 ++++++++ .../src/qwen_forward/executor.rs | 195 +-- .../src/qwen_forward/executor/tests.rs | 194 +++ .../src/qwen_forward/moe_expert.rs | 56 +- .../src/qwen_forward/moe_expert/tests.rs | 55 + .../src/qwen_forward/moe_prefill_batch.rs | 101 +- .../qwen_forward/moe_prefill_batch/tests.rs | 100 ++ .../src/qwen_forward/mtp_attention.rs | 49 +- .../src/qwen_forward/mtp_attention/tests.rs | 48 + .../src/qwen_forward/mtp_experts.rs | 94 +- .../src/qwen_forward/mtp_experts/tests.rs | 93 ++ .../src/qwen_forward/mtp_state.rs | 286 +--- .../src/qwen_forward/mtp_state/tests.rs | 284 ++++ .../src/qwen_forward/original_serve_config.rs | 142 +- .../original_serve_config/tests.rs | 141 ++ .../original_serve_conversation.rs | 339 +---- .../original_serve_conversation/tests.rs | 337 +++++ .../src/qwen_forward/original_serve_engine.rs | 669 +-------- .../original_serve_engine/tests.rs | 668 +++++++++ .../src/qwen_forward/original_serve_host.rs | 38 +- .../qwen_forward/original_serve_host/tests.rs | 37 + .../src/qwen_forward/original_serve_pool.rs | 99 +- .../qwen_forward/original_serve_pool/tests.rs | 98 ++ .../src/qwen_forward/original_serve_prefix.rs | 676 +-------- .../original_serve_prefix/tests.rs | 674 +++++++++ .../qwen_forward/original_serve_residency.rs | 323 +---- .../original_serve_residency/tests.rs | 322 ++++ .../src/qwen_forward/original_serve_stack.rs | 72 +- .../original_serve_stack/tests.rs | 71 + .../qwen_forward/original_serve_verifier.rs | 90 +- .../original_serve_verifier/tests.rs | 89 ++ .../qwen_forward/original_spec_adaptive.rs | 399 +---- .../original_spec_adaptive/tests.rs | 398 +++++ .../qwen_forward/original_spec_controller.rs | 814 +---------- .../original_spec_controller/tests.rs | 813 +++++++++++ .../leleka-runtime/src/qwen_forward/output.rs | 91 +- .../src/qwen_forward/output/tests.rs | 90 ++ .../src/qwen_forward/session.rs | 539 +------ .../src/qwen_forward/session/tests.rs | 538 +++++++ .../src/qwen_forward/session_chunk_verify.rs | 186 +-- .../session_chunk_verify/tests.rs | 184 +++ .../qwen_forward/session_original_verified.rs | 187 +-- .../session_original_verified/tests.rs | 185 +++ crates/leleka-runtime/src/serve_meta.rs | 173 +-- crates/leleka-runtime/src/serve_meta/tests.rs | 172 +++ crates/libc-shim/src/cuda_trace.rs | 27 +- crates/libc-shim/src/cuda_trace/tests.rs | 26 + crates/model-format/src/bulk_read.rs | 155 +- crates/model-format/src/bulk_read/tests.rs | 154 ++ crates/model-format/src/native_dense_plan.rs | 139 +- .../src/native_dense_plan/tests.rs | 138 ++ crates/model-format/src/pinned_arena_plan.rs | 155 +- .../src/pinned_arena_plan/tests.rs | 154 ++ crates/runtime-client/src/client.rs | 259 +--- crates/runtime-client/src/client/tests.rs | 258 ++++ crates/sampler-ref/src/chain.rs | 170 +-- crates/sampler-ref/src/chain/tests.rs | 169 +++ crates/sampler-ref/src/params.rs | 351 +---- crates/sampler-ref/src/params/tests.rs | 350 +++++ crates/sampler-ref/src/serve.rs | 176 +-- crates/sampler-ref/src/serve/tests.rs | 175 +++ crates/serving-policy/src/cvec.rs | 152 +- crates/serving-policy/src/cvec/tests.rs | 151 ++ crates/serving-policy/src/shared.rs | 140 +- crates/serving-policy/src/shared/tests.rs | 139 ++ crates/serving-policy/src/vision.rs | 163 +-- crates/serving-policy/src/vision/tests.rs | 162 +++ crates/tokenizer/src/gguf_bpe.rs | 150 +- crates/tokenizer/src/gguf_bpe/tests.rs | 149 ++ desktop-core/src/runtime_gateway.rs | 187 +-- desktop-core/src/runtime_gateway/tests.rs | 186 +++ desktop-core/src/runtime_rpc.rs | 629 +------- desktop-core/src/runtime_rpc/tests.rs | 628 ++++++++ scripts/archcheck/baseline.py | 7 +- scripts/check_architecture_test.py | 4 + scripts/dev/elf-sections-equal.sh | 35 + scripts/dev/extract_tests.py | 106 ++ 242 files changed, 30293 insertions(+), 30021 deletions(-) create mode 100644 control-plane/src/app/tests.rs create mode 100644 control-plane/src/config/tests.rs create mode 100644 control-plane/src/ggml_bridge/tests.rs create mode 100644 control-plane/src/gguf_f32_stream/tests.rs create mode 100644 control-plane/src/harmony_family/tests.rs create mode 100644 control-plane/src/kar/tests.rs create mode 100644 control-plane/src/kar_quality/tests.rs create mode 100644 control-plane/src/kar_stream_encode/tests.rs create mode 100644 control-plane/src/kar_writer/tests.rs create mode 100644 control-plane/src/mcp/tests.rs create mode 100644 control-plane/src/messages/tests.rs create mode 100644 control-plane/src/model/tests.rs create mode 100644 control-plane/src/native_pack/tests.rs create mode 100644 control-plane/src/prepare_preview/tests.rs create mode 100644 control-plane/src/prometheus/tests.rs create mode 100644 control-plane/src/reasoning_budget/tests.rs create mode 100644 control-plane/src/request_log/tests.rs create mode 100644 control-plane/src/request_monitor/tests.rs create mode 100644 control-plane/src/service_install/tests.rs create mode 100644 control-plane/src/service_switch/tests.rs create mode 100644 control-plane/src/wait_ready/tests.rs create mode 100644 crates/backend-api/src/scripted/tests.rs create mode 100644 crates/context/src/context_policy/tests.rs create mode 100644 crates/context/src/geometry/tests.rs create mode 100644 crates/context/src/memory_plan/tests.rs create mode 100644 crates/context/src/rope_scaling/tests.rs create mode 100644 crates/cuda-driver/src/closed_kernels/tests.rs create mode 100644 crates/cuda-driver/src/device_slab/tests.rs create mode 100644 crates/cuda-driver/src/experimental/tests.rs create mode 100644 crates/cuda-driver/src/kar_decode_levels/tests.rs create mode 100644 crates/cuda-driver/src/mmq_original_host_stage/tests.rs create mode 100644 crates/cuda-driver/src/mtp_original_full_ffi/tests.rs create mode 100644 crates/cuda-driver/src/original_conversation_state/tests.rs create mode 100644 crates/cuda-driver/src/original_expert_stager/tests.rs create mode 100644 crates/cuda-driver/src/original_expert_stager_ffi/tests.rs create mode 100644 crates/cuda-driver/src/original_file_expert_source_ffi/tests.rs create mode 100644 crates/cuda-driver/src/original_mtp_draft_vocab/tests.rs create mode 100644 crates/cuda-driver/src/original_mtp_loader/tests.rs create mode 100644 crates/cuda-driver/src/original_mtp_rt/tests.rs create mode 100644 crates/cuda-driver/src/original_prefill_schedule/tests.rs create mode 100644 crates/cuda-driver/src/original_verify_gpu_plan/tests.rs create mode 100644 crates/cuda-driver/src/original_verify_window_gr/tests.rs create mode 100644 crates/cuda-driver/src/original_verify_window_moe/tests.rs create mode 100644 crates/cuda-driver/src/original_verify_window_ops/tests.rs create mode 100644 crates/cuda-driver/src/original_verify_window_planner/tests.rs create mode 100644 crates/cuda-driver/src/original_verify_window_proj/tests.rs create mode 100644 crates/cuda-driver/src/original_verify_window_qsa/tests.rs create mode 100644 crates/cuda-driver/src/original_verify_window_record/tests.rs create mode 100644 crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs create mode 100644 crates/cuda-driver/src/s_gemv_legacy/tests.rs create mode 100644 crates/deploy/src/cli/tests.rs create mode 100644 crates/deploy/src/expert_profile/tests.rs create mode 100644 crates/deploy/src/facts/tests.rs create mode 100644 crates/deploy/src/logview/tests.rs create mode 100644 crates/deploy/src/preflight/tests.rs create mode 100644 crates/deploy/src/reconfigure/tests.rs create mode 100644 crates/deploy/src/sealed/tests.rs create mode 100644 crates/deploy/src/steps/tests.rs create mode 100644 crates/deploy/src/winfront/tests.rs create mode 100644 crates/deploy/src/wsl/tests.rs create mode 100644 crates/experimental-ref/src/cache/tests.rs create mode 100644 crates/experimental-ref/src/cvec/tests.rs create mode 100644 crates/experimental-ref/src/keyless/tests.rs create mode 100644 crates/experimental-ref/src/kv_stream/tests.rs create mode 100644 crates/experimental-ref/src/layout/tests.rs create mode 100644 crates/experimental-ref/src/remote_experts/tests.rs create mode 100644 crates/gateway-text/src/prompt/tests.rs create mode 100644 crates/gateway-text/src/tool_output/tests.rs create mode 100644 crates/gptoss/src/ops/tests.rs create mode 100644 crates/harmony/src/parse/tests.rs create mode 100644 crates/leleka-memory/src/governor/tests.rs create mode 100644 crates/leleka-memory/src/lock/tests.rs create mode 100644 crates/leleka-memory/src/plan/tests.rs create mode 100644 crates/leleka-memory/src/procfs/tests.rs create mode 100644 crates/leleka-memory/src/telemetry/tests.rs create mode 100644 crates/leleka-runtime/src/conversation/cache/tests.rs create mode 100644 crates/leleka-runtime/src/conversation/resident/tests.rs create mode 100644 crates/leleka-runtime/src/experimental/tests.rs create mode 100644 crates/leleka-runtime/src/model_binding/qwen4exp_gdn/tests.rs create mode 100644 crates/leleka-runtime/src/model_binding/qwen4exp_gr/tests.rs create mode 100644 crates/leleka-runtime/src/model_binding/qwen4exp_mtp/tests.rs create mode 100644 crates/leleka-runtime/src/prefix_cache/store/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/executor/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/moe_expert/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/moe_prefill_batch/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/mtp_attention/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/mtp_experts/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/mtp_state/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_config/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_conversation/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_engine/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_host/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_pool/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_residency/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_stack/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_verifier/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_spec_adaptive/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_spec_controller/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/output/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/session/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/session_chunk_verify/tests.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/session_original_verified/tests.rs create mode 100644 crates/leleka-runtime/src/serve_meta/tests.rs create mode 100644 crates/libc-shim/src/cuda_trace/tests.rs create mode 100644 crates/model-format/src/bulk_read/tests.rs create mode 100644 crates/model-format/src/native_dense_plan/tests.rs create mode 100644 crates/model-format/src/pinned_arena_plan/tests.rs create mode 100644 crates/runtime-client/src/client/tests.rs create mode 100644 crates/sampler-ref/src/chain/tests.rs create mode 100644 crates/sampler-ref/src/params/tests.rs create mode 100644 crates/sampler-ref/src/serve/tests.rs create mode 100644 crates/serving-policy/src/cvec/tests.rs create mode 100644 crates/serving-policy/src/shared/tests.rs create mode 100644 crates/serving-policy/src/vision/tests.rs create mode 100644 crates/tokenizer/src/gguf_bpe/tests.rs create mode 100644 desktop-core/src/runtime_gateway/tests.rs create mode 100644 desktop-core/src/runtime_rpc/tests.rs create mode 100644 scripts/dev/elf-sections-equal.sh create mode 100644 scripts/dev/extract_tests.py diff --git a/architecture-baseline.json b/architecture-baseline.json index 42355e03..b8585d2a 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -6,37 +6,34 @@ ], "oversize": { "control-plane/examples/cp_replay.rs": 946, - "control-plane/src/app.rs": 636, + "control-plane/src/app.rs": 474, "control-plane/src/backend_worker.rs": 841, "control-plane/src/chat.rs": 664, - "control-plane/src/config.rs": 1112, - "control-plane/src/ggml_bridge.rs": 1354, - "control-plane/src/gguf_f32_stream.rs": 1106, - "control-plane/src/harmony_family.rs": 515, - "control-plane/src/kar.rs": 513, + "control-plane/src/config.rs": 788, + "control-plane/src/ggml_bridge/tests.rs": 1291, + "control-plane/src/gguf_f32_stream/tests.rs": 917, "control-plane/src/kar_overlay.rs": 1048, - "control-plane/src/kar_quality.rs": 518, - "control-plane/src/kar_stream_encode.rs": 405, - "control-plane/src/kar_writer.rs": 1293, + "control-plane/src/kar_quality.rs": 502, + "control-plane/src/kar_writer.rs": 952, "control-plane/src/main.rs": 1156, - "control-plane/src/mcp.rs": 1520, - "control-plane/src/messages.rs": 690, - "control-plane/src/model.rs": 827, + "control-plane/src/mcp.rs": 1423, + "control-plane/src/messages.rs": 602, + "control-plane/src/model.rs": 455, "control-plane/src/mtp_fetch.rs": 695, - "control-plane/src/native_pack.rs": 1390, - "control-plane/src/prepare_preview.rs": 2214, - "control-plane/src/prometheus.rs": 746, - "control-plane/src/reasoning_budget.rs": 617, - "control-plane/src/request_log.rs": 1031, - "control-plane/src/request_monitor.rs": 723, + "control-plane/src/native_pack.rs": 1144, + "control-plane/src/prepare_preview.rs": 1393, + "control-plane/src/prepare_preview/tests.rs": 822, + "control-plane/src/prometheus.rs": 604, + "control-plane/src/reasoning_budget.rs": 402, + "control-plane/src/request_log.rs": 732, + "control-plane/src/request_monitor.rs": 574, "control-plane/src/responses.rs": 2780, "control-plane/src/responses/harmony_prompt.rs": 621, "control-plane/src/responses/tests.rs": 2961, "control-plane/src/server_api.rs": 692, - "control-plane/src/service_install.rs": 935, - "control-plane/src/service_switch.rs": 792, + "control-plane/src/service_install.rs": 793, + "control-plane/src/service_switch.rs": 677, "control-plane/src/vision.rs": 779, - "control-plane/src/wait_ready.rs": 444, "control-plane/src/worker.rs": 2170, "control-plane/tests/backend_worker_http.rs": 1832, "control-plane/tests/mcp_hub.rs": 444, @@ -44,11 +41,9 @@ "control-plane/tests/tool_corpus.rs": 464, "control-plane/tests/vision_http.rs": 602, "crates/backend-api/src/lib.rs": 756, - "crates/backend-api/src/scripted.rs": 713, - "crates/context/src/context_policy.rs": 428, - "crates/context/src/geometry.rs": 421, - "crates/context/src/memory_plan.rs": 570, - "crates/context/src/rope_scaling.rs": 921, + "crates/backend-api/src/scripted.rs": 553, + "crates/context/src/memory_plan.rs": 467, + "crates/context/src/rope_scaling.rs": 674, "crates/context/tests/rope_plan_golden.rs": 412, "crates/cpu-kernels/src/lib.rs": 464, "crates/cpu-sys/src/c_reference.rs": 486, @@ -57,11 +52,11 @@ "crates/cpu-worker/tests/serve_loop.rs": 477, "crates/cuda-driver/src/api.rs": 529, "crates/cuda-driver/src/arch_ptx.rs": 421, - "crates/cuda-driver/src/closed_kernels.rs": 897, + "crates/cuda-driver/src/closed_kernels.rs": 493, + "crates/cuda-driver/src/closed_kernels/tests.rs": 405, "crates/cuda-driver/src/closed_kernels_gpu.rs": 491, "crates/cuda-driver/src/closed_kernels_gpu_smoke.rs": 408, - "crates/cuda-driver/src/device_slab.rs": 421, - "crates/cuda-driver/src/experimental.rs": 1136, + "crates/cuda-driver/src/experimental.rs": 762, "crates/cuda-driver/src/experimental_gpu.rs": 881, "crates/cuda-driver/src/ffi.rs": 2778, "crates/cuda-driver/src/gdn_closed_queue.rs": 1046, @@ -73,7 +68,6 @@ "crates/cuda-driver/src/gr_batch_read.rs": 870, "crates/cuda-driver/src/gr_native_batch.rs": 617, "crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu.rs": 450, - "crates/cuda-driver/src/kar_decode_levels.rs": 701, "crates/cuda-driver/src/kar_decode_levels_gpu.rs": 523, "crates/cuda-driver/src/kv_stream_gpu.rs": 431, "crates/cuda-driver/src/lib.rs": 3508, @@ -84,7 +78,7 @@ "crates/cuda-driver/src/mmq_numeric_gpu.rs": 418, "crates/cuda-driver/src/mmq_original_chunk_stream.rs": 443, "crates/cuda-driver/src/mmq_original_group.rs": 1742, - "crates/cuda-driver/src/mmq_original_host_stage.rs": 625, + "crates/cuda-driver/src/mmq_original_host_stage.rs": 476, "crates/cuda-driver/src/mmq_original_ring.rs": 1184, "crates/cuda-driver/src/mmq_original_stream_all.rs": 616, "crates/cuda-driver/src/mmq_resident.rs": 960, @@ -94,7 +88,6 @@ "crates/cuda-driver/src/mtp_input_workspace.rs": 708, "crates/cuda-driver/src/mtp_input_workspace_gpu.rs": 449, "crates/cuda-driver/src/mtp_original_full_drafter.rs": 787, - "crates/cuda-driver/src/mtp_original_full_ffi.rs": 407, "crates/cuda-driver/src/mtp_original_full_forward.rs": 2841, "crates/cuda-driver/src/mtp_original_full_symbols.rs": 445, "crates/cuda-driver/src/mtp_original_int8.rs": 1686, @@ -106,37 +99,37 @@ "crates/cuda-driver/src/native_head.rs": 2236, "crates/cuda-driver/src/native_parity.rs": 903, "crates/cuda-driver/src/native_prompt_device.rs": 1712, - "crates/cuda-driver/src/original_conversation_state.rs": 424, "crates/cuda-driver/src/original_expert_cache.rs": 964, - "crates/cuda-driver/src/original_expert_stager.rs": 1261, - "crates/cuda-driver/src/original_expert_stager_ffi.rs": 545, + "crates/cuda-driver/src/original_expert_stager.rs": 1194, + "crates/cuda-driver/src/original_expert_stager_ffi.rs": 480, "crates/cuda-driver/src/original_file_expert_source.rs": 1575, - "crates/cuda-driver/src/original_file_expert_source_ffi.rs": 518, + "crates/cuda-driver/src/original_file_expert_source_ffi.rs": 455, "crates/cuda-driver/src/original_gpu_schedule.rs": 1258, "crates/cuda-driver/src/original_gpu_schedule_ffi.rs": 539, "crates/cuda-driver/src/original_moe_prompt_device.rs": 825, "crates/cuda-driver/src/original_mtp_actor_loaded.rs": 546, - "crates/cuda-driver/src/original_mtp_draft_vocab.rs": 596, - "crates/cuda-driver/src/original_mtp_loader.rs": 745, - "crates/cuda-driver/src/original_mtp_rt.rs": 1057, - "crates/cuda-driver/src/original_prefill_schedule.rs": 855, + "crates/cuda-driver/src/original_mtp_loader.rs": 504, + "crates/cuda-driver/src/original_mtp_rt.rs": 623, + "crates/cuda-driver/src/original_mtp_rt/tests.rs": 435, + "crates/cuda-driver/src/original_prefill_schedule.rs": 623, "crates/cuda-driver/src/original_sampler.rs": 759, "crates/cuda-driver/src/original_stream_all.rs": 422, "crates/cuda-driver/src/original_verify.rs": 481, - "crates/cuda-driver/src/original_verify_gpu_plan.rs": 429, - "crates/cuda-driver/src/original_verify_window_gr.rs": 1439, - "crates/cuda-driver/src/original_verify_window_moe.rs": 1667, - "crates/cuda-driver/src/original_verify_window_ops.rs": 820, - "crates/cuda-driver/src/original_verify_window_planner.rs": 577, - "crates/cuda-driver/src/original_verify_window_proj.rs": 613, - "crates/cuda-driver/src/original_verify_window_qsa.rs": 1492, - "crates/cuda-driver/src/original_verify_window_record.rs": 640, + "crates/cuda-driver/src/original_verify_window_gr.rs": 935, + "crates/cuda-driver/src/original_verify_window_gr/tests.rs": 506, + "crates/cuda-driver/src/original_verify_window_moe.rs": 949, + "crates/cuda-driver/src/original_verify_window_moe/tests.rs": 720, + "crates/cuda-driver/src/original_verify_window_ops.rs": 738, + "crates/cuda-driver/src/original_verify_window_planner/tests.rs": 411, + "crates/cuda-driver/src/original_verify_window_proj.rs": 456, + "crates/cuda-driver/src/original_verify_window_qsa.rs": 842, + "crates/cuda-driver/src/original_verify_window_qsa/tests.rs": 652, "crates/cuda-driver/src/ple_batch_ffi.rs": 726, "crates/cuda-driver/src/ple_batch_queue.rs": 705, "crates/cuda-driver/src/prefill_stage_gdn_gpu.rs": 469, "crates/cuda-driver/src/qsa_mapped_journal.rs": 497, "crates/cuda-driver/src/qsa_prompt_attention.rs": 490, - "crates/cuda-driver/src/qsa_prompt_attention_select.rs": 627, + "crates/cuda-driver/src/qsa_prompt_attention_select.rs": 449, "crates/cuda-driver/src/qsa_prompt_kv.rs": 1016, "crates/cuda-driver/src/qsa_selected_kv.rs": 754, "crates/cuda-driver/src/qwen_dispatch.rs": 3848, @@ -146,7 +139,7 @@ "crates/cuda-driver/src/routed_group_workspace.rs": 485, "crates/cuda-driver/src/routed_resident_queue.rs": 492, "crates/cuda-driver/src/routed_resident_queue_gpu.rs": 464, - "crates/cuda-driver/src/s_gemv_legacy.rs": 788, + "crates/cuda-driver/src/s_gemv_legacy.rs": 568, "crates/cuda-driver/src/sm86_table.rs": 933, "crates/cuda-driver/tests/mock_driver.rs": 1560, "crates/cuda-driver/tests/original_serve_preflight_probe.rs": 784, @@ -154,76 +147,73 @@ "crates/cuda-driver/tests/q6_mock.rs": 463, "crates/deploy/src/app.rs": 1481, "crates/deploy/src/bin/fake_runtime.rs": 426, - "crates/deploy/src/cli.rs": 1170, + "crates/deploy/src/cli.rs": 761, + "crates/deploy/src/cli/tests.rs": 410, "crates/deploy/src/config.rs": 735, - "crates/deploy/src/expert_profile.rs": 919, - "crates/deploy/src/facts.rs": 701, - "crates/deploy/src/logview.rs": 1334, + "crates/deploy/src/expert_profile.rs": 432, + "crates/deploy/src/expert_profile/tests.rs": 488, + "crates/deploy/src/facts.rs": 606, + "crates/deploy/src/logview.rs": 986, "crates/deploy/src/plan.rs": 1470, - "crates/deploy/src/preflight.rs": 1280, + "crates/deploy/src/preflight.rs": 804, + "crates/deploy/src/preflight/tests.rs": 477, "crates/deploy/src/profile.rs": 982, - "crates/deploy/src/reconfigure.rs": 1113, + "crates/deploy/src/reconfigure.rs": 512, + "crates/deploy/src/reconfigure/tests.rs": 602, "crates/deploy/src/resources.rs": 944, - "crates/deploy/src/sealed.rs": 769, - "crates/deploy/src/steps.rs": 1350, + "crates/deploy/src/sealed.rs": 707, + "crates/deploy/src/steps.rs": 1247, "crates/deploy/src/supervisor.rs": 1849, - "crates/deploy/src/winfront.rs": 907, - "crates/deploy/src/wsl.rs": 698, + "crates/deploy/src/winfront.rs": 886, + "crates/deploy/src/wsl.rs": 496, "crates/deploy/tests/e2e.rs": 2118, - "crates/experimental-ref/src/cache.rs": 429, - "crates/experimental-ref/src/cvec.rs": 682, - "crates/experimental-ref/src/keyless.rs": 493, - "crates/experimental-ref/src/kv_stream.rs": 627, - "crates/experimental-ref/src/layout.rs": 464, - "crates/experimental-ref/src/remote_experts.rs": 536, + "crates/experimental-ref/src/cvec.rs": 476, + "crates/experimental-ref/src/kv_stream.rs": 437, "crates/experimental-ref/tests/emulated_kernels.rs": 467, - "crates/gateway-text/src/prompt.rs": 1373, - "crates/gateway-text/src/tool_output.rs": 1844, + "crates/gateway-text/src/prompt.rs": 882, + "crates/gateway-text/src/prompt/tests.rs": 493, + "crates/gateway-text/src/tool_output.rs": 1184, + "crates/gateway-text/src/tool_output/tests.rs": 661, "crates/gguf/src/lib.rs": 560, "crates/gguf/tests/synthetic.rs": 460, "crates/gptoss-igpu/src/lib.rs": 524, "crates/gptoss-npu/src/lib.rs": 809, "crates/gptoss/src/lib.rs": 1788, - "crates/gptoss/src/ops.rs": 552, "crates/gptoss/tests/synthetic_model.rs": 922, - "crates/harmony/src/parse.rs": 429, "crates/harmony/src/render.rs": 511, "crates/igpu/src/lib.rs": 1386, "crates/igpu/src/shaders.rs": 624, - "crates/leleka-memory/src/governor.rs": 1184, - "crates/leleka-memory/src/lock.rs": 598, - "crates/leleka-memory/src/plan.rs": 635, - "crates/leleka-memory/src/procfs.rs": 419, - "crates/leleka-memory/src/telemetry.rs": 807, + "crates/leleka-memory/src/governor.rs": 1004, + "crates/leleka-memory/src/lock.rs": 518, + "crates/leleka-memory/src/plan.rs": 408, + "crates/leleka-memory/src/telemetry.rs": 630, "crates/leleka-runtime/src/backend.rs": 3770, "crates/leleka-runtime/src/backend_original_prompt.rs": 529, "crates/leleka-runtime/src/backend_original_serve.rs": 1115, - "crates/leleka-runtime/src/conversation/cache.rs": 899, + "crates/leleka-runtime/src/conversation/cache.rs": 493, + "crates/leleka-runtime/src/conversation/cache/tests.rs": 407, "crates/leleka-runtime/src/conversation/kv.rs": 468, "crates/leleka-runtime/src/conversation/manager.rs": 566, "crates/leleka-runtime/src/conversation/manager_tests.rs": 1129, - "crates/leleka-runtime/src/conversation/resident.rs": 527, "crates/leleka-runtime/src/conversation/snapshot_tests.rs": 1596, - "crates/leleka-runtime/src/experimental.rs": 449, "crates/leleka-runtime/src/gpu_proofs/backend_original_serve_memory_smoke.rs": 851, "crates/leleka-runtime/src/gpu_proofs/backend_original_serve_prefix_smoke.rs": 447, "crates/leleka-runtime/src/gpu_proofs/backend_original_serve_smoke.rs": 979, "crates/leleka-runtime/src/gpu_proofs/native_down_candidate_only.rs": 1648, "crates/leleka-runtime/src/gpu_proofs/native_down_public_pair.rs": 540, - "crates/leleka-runtime/src/model_binding/qwen4exp_gdn.rs": 421, - "crates/leleka-runtime/src/model_binding/qwen4exp_gr.rs": 431, "crates/leleka-runtime/src/model_binding/qwen4exp_input.rs": 560, "crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs": 1544, "crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert.rs": 1101, - "crates/leleka-runtime/src/model_binding/qwen4exp_mtp.rs": 1755, - "crates/leleka-runtime/src/prefix_cache/store.rs": 1354, + "crates/leleka-runtime/src/model_binding/qwen4exp_mtp.rs": 1606, + "crates/leleka-runtime/src/prefix_cache/store.rs": 773, + "crates/leleka-runtime/src/prefix_cache/store/tests.rs": 582, "crates/leleka-runtime/src/qwen_forward/cache_ephemeral_routed.rs": 619, "crates/leleka-runtime/src/qwen_forward/cache_lru_index.rs": 404, "crates/leleka-runtime/src/qwen_forward/cache_profile.rs": 441, "crates/leleka-runtime/src/qwen_forward/cache_profile_fill.rs": 1110, "crates/leleka-runtime/src/qwen_forward/cache_strata_adaptive.rs": 554, "crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs": 1614, - "crates/leleka-runtime/src/qwen_forward/executor.rs": 1301, + "crates/leleka-runtime/src/qwen_forward/executor.rs": 1108, "crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs": 612, "crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk.rs": 2216, "crates/leleka-runtime/src/qwen_forward/gdn.rs": 1169, @@ -240,34 +230,33 @@ "crates/leleka-runtime/src/qwen_forward/moe_activation_reuse_gpu.rs": 435, "crates/leleka-runtime/src/qwen_forward/moe_down.rs": 699, "crates/leleka-runtime/src/qwen_forward/moe_down_reuse_gpu.rs": 410, - "crates/leleka-runtime/src/qwen_forward/moe_expert.rs": 1133, + "crates/leleka-runtime/src/qwen_forward/moe_expert.rs": 1079, "crates/leleka-runtime/src/qwen_forward/moe_group_chunk.rs": 1589, - "crates/leleka-runtime/src/qwen_forward/moe_prefill_batch.rs": 835, + "crates/leleka-runtime/src/qwen_forward/moe_prefill_batch.rs": 736, "crates/leleka-runtime/src/qwen_forward/moe_route.rs": 594, "crates/leleka-runtime/src/qwen_forward/moe_weight_cache.rs": 3142, "crates/leleka-runtime/src/qwen_forward/mtp.rs": 572, - "crates/leleka-runtime/src/qwen_forward/mtp_attention.rs": 733, + "crates/leleka-runtime/src/qwen_forward/mtp_attention.rs": 686, "crates/leleka-runtime/src/qwen_forward/mtp_decode.rs": 875, "crates/leleka-runtime/src/qwen_forward/mtp_decoder_batch_gpu.rs": 786, "crates/leleka-runtime/src/qwen_forward/mtp_expert_transport.rs": 523, "crates/leleka-runtime/src/qwen_forward/mtp_expert_transport_gpu.rs": 546, "crates/leleka-runtime/src/qwen_forward/mtp_expert_workspace.rs": 964, - "crates/leleka-runtime/src/qwen_forward/mtp_experts.rs": 457, "crates/leleka-runtime/src/qwen_forward/mtp_gr.rs": 451, - "crates/leleka-runtime/src/qwen_forward/mtp_state.rs": 813, + "crates/leleka-runtime/src/qwen_forward/mtp_state.rs": 531, "crates/leleka-runtime/src/qwen_forward/mtp_state_chunk.rs": 490, - "crates/leleka-runtime/src/qwen_forward/original_serve_config.rs": 465, - "crates/leleka-runtime/src/qwen_forward/original_serve_conversation.rs": 662, - "crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs": 1225, - "crates/leleka-runtime/src/qwen_forward/original_serve_host.rs": 627, - "crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs": 950, - "crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs": 1310, - "crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs": 1590, - "crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs": 2051, - "crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs": 476, - "crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs": 1021, - "crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs": 1294, - "crates/leleka-runtime/src/qwen_forward/output.rs": 925, + "crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs": 558, + "crates/leleka-runtime/src/qwen_forward/original_serve_engine/tests.rs": 668, + "crates/leleka-runtime/src/qwen_forward/original_serve_host.rs": 591, + "crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs": 853, + "crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs": 638, + "crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs": 674, + "crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs": 1269, + "crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs": 1981, + "crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs": 624, + "crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs": 482, + "crates/leleka-runtime/src/qwen_forward/original_spec_controller/tests.rs": 813, + "crates/leleka-runtime/src/qwen_forward/output.rs": 836, "crates/leleka-runtime/src/qwen_forward/ple_key_retained_gpu.rs": 491, "crates/leleka-runtime/src/qwen_forward/ple_transport.rs": 429, "crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs": 515, @@ -276,22 +265,19 @@ "crates/leleka-runtime/src/qwen_forward/qsa_index.rs": 1516, "crates/leleka-runtime/src/qwen_forward/qsa_index_resident.rs": 525, "crates/leleka-runtime/src/qwen_forward/router_scratch_gpu.rs": 486, - "crates/leleka-runtime/src/qwen_forward/session.rs": 1510, + "crates/leleka-runtime/src/qwen_forward/session.rs": 973, + "crates/leleka-runtime/src/qwen_forward/session/tests.rs": 538, "crates/leleka-runtime/src/qwen_forward/session_chunk.rs": 2642, - "crates/leleka-runtime/src/qwen_forward/session_chunk_verify.rs": 847, + "crates/leleka-runtime/src/qwen_forward/session_chunk_verify.rs": 665, "crates/leleka-runtime/src/qwen_forward/session_original_prompt.rs": 610, - "crates/leleka-runtime/src/qwen_forward/session_original_verified.rs": 473, - "crates/leleka-runtime/src/serve_meta.rs": 418, - "crates/libc-shim/src/cuda_trace.rs": 474, - "crates/model-format/src/bulk_read.rs": 570, + "crates/libc-shim/src/cuda_trace.rs": 449, + "crates/model-format/src/bulk_read.rs": 417, "crates/model-format/src/gguf.rs": 2285, "crates/model-format/src/gguf_resident.rs": 613, "crates/model-format/src/kar.rs": 1751, "crates/model-format/src/kar_extents.rs": 530, "crates/model-format/src/kar_kernel_model.rs": 520, "crates/model-format/src/kar_levels.rs": 666, - "crates/model-format/src/native_dense_plan.rs": 440, - "crates/model-format/src/pinned_arena_plan.rs": 551, "crates/model-format/src/ple_reader.rs": 890, "crates/model-format/src/ple_reader/tests.rs": 750, "crates/model-format/src/qwen4exp.rs": 2024, @@ -310,23 +296,19 @@ "crates/openvino/src/lib.rs": 676, "crates/quant-core/src/iq2s_grid.rs": 1032, "crates/runtime-client/src/backend.rs": 469, - "crates/runtime-client/src/client.rs": 583, "crates/runtime-client/tests/grpc_backend.rs": 689, - "crates/sampler-ref/src/chain.rs": 555, - "crates/sampler-ref/src/params.rs": 744, - "crates/sampler-ref/src/serve.rs": 408, - "crates/serving-policy/src/cvec.rs": 571, - "crates/serving-policy/src/shared.rs": 547, - "crates/serving-policy/src/vision.rs": 500, + "crates/serving-policy/src/cvec.rs": 421, + "crates/serving-policy/src/shared.rs": 409, "crates/shm/src/lib.rs": 432, "crates/tokenizer/src/fast.rs": 435, - "crates/tokenizer/src/gguf_bpe.rs": 586, + "crates/tokenizer/src/gguf_bpe.rs": 438, "crates/tokenizer/src/lib.rs": 840, "desktop-core/src/bin/leleka-inference.rs": 1487, "desktop-core/src/gateway.rs": 596, "desktop-core/src/managed_worker.rs": 476, - "desktop-core/src/runtime_gateway.rs": 1130, - "desktop-core/src/runtime_rpc.rs": 1704, + "desktop-core/src/runtime_gateway.rs": 945, + "desktop-core/src/runtime_rpc.rs": 1077, + "desktop-core/src/runtime_rpc/tests.rs": 628, "desktop-core/src/runtime_tools.rs": 724, "desktop-core/tests/api_over_runtime.rs": 638, "desktop-core/tests/gateway.rs": 403, @@ -388,7 +370,7 @@ "instant-now:leleka-runtime": 79, "instant-now:strata-control": 37, "instant-now:strata-desktop-core": 15, - "path-include:leleka-cuda-driver": 116, + "path-include:leleka-cuda-driver": 115, "path-include:leleka-model-format": 12, "path-include:leleka-native-cpu-expert": 2, "path-include:leleka-runtime": 108, diff --git a/architecture.json b/architecture.json index de3cf180..cd622785 100644 --- a/architecture.json +++ b/architecture.json @@ -41,7 +41,7 @@ "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*=", "why": "a file compiled into two crates must be one crate (S8)"}, + {"id": "path-include", "regex": "#\\[path\\s*=\\s*\"(?![^\"]*tests\\.rs\")", "why": "a file compiled into two crates must be one crate (S8); a tests.rs beside its module is not an include"}, {"id": "process-global", "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": "dyn-trait", "regex": "\\bdyn\\s+[A-Z]", "why": "no dynamic dispatch per round or token; dyn is for startup composition only"} ] diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index 4d5a99db..09b6765b 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -471,166 +471,4 @@ fn status_body( } #[cfg(test)] -mod tests { - use super::*; - - #[tokio::test] - async fn conditional_admission_rejects_stale_or_ambiguous_pid_before_mutation() { - let state = AppState::default(); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let router = router(state.clone()); - let server = tokio::spawn(async move { axum::serve(listener, router).await }); - let client = reqwest::Client::new(); - for (path, initial) in [("drain", false), ("resume", true)] { - state.lifecycle.set_draining(initial); - for (value, status) in [ - ("0".to_string(), 400), - ("bad".into(), 400), - ((std::process::id() + 1).to_string(), 409), - ] { - let response = client - .post(format!("{url}/admin/{path}")) - .header("x-strata-expected-pid", value) - .send() - .await - .unwrap(); - assert_eq!(response.status().as_u16(), status); - assert_eq!(state.lifecycle.snapshot().draining, initial); - } - let duplicate = client - .post(format!("{url}/admin/{path}")) - .header("x-strata-expected-pid", std::process::id()) - .header("x-strata-expected-pid", std::process::id()) - .send() - .await - .unwrap(); - assert_eq!(duplicate.status(), StatusCode::BAD_REQUEST); - assert_eq!(state.lifecycle.snapshot().draining, initial); - let response = client - .post(format!("{url}/admin/{path}")) - .header("x-strata-expected-pid", std::process::id()) - .send() - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::OK); - let value: serde_json::Value = - serde_json::from_str(&response.text().await.unwrap()).unwrap(); - assert_eq!(value["server_pid"], std::process::id()); - assert_eq!(value["service"], "strata-control"); - assert_eq!(value["draining"], !initial); - } - server.abort(); - let _ = server.await; - } - - #[tokio::test] - async fn drain_rejects_new_requests_before_json_parsing_and_resume_is_idempotent() { - let state = AppState::default(); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let router = router(state.clone()); - let server = tokio::spawn(async move { axum::serve(listener, router).await }); - let client = reqwest::Client::new(); - for _ in 0..2 { - let response = client - .post(format!("{url}/admin/drain")) - .send() - .await - .unwrap(); - let data: serde_json::Value = - serde_json::from_str(&response.text().await.unwrap()).unwrap(); - assert_eq!(data["draining"], true); - assert_eq!(data["drained"], true); - } - let response = client - .post(format!("{url}/v1/responses")) - .header("content-type", "application/json") - .body("invalid json") - .send() - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); - assert!(response.text().await.unwrap().contains("runtime_draining")); - assert_eq!(state.lifecycle.snapshot().requests_in_flight, 0); - let job = state.lifecycle.generation(); - assert_eq!( - lifecycle_status(State(state.clone())).await.0["drained"], - false - ); - drop(job); - state.worker.write().await.state = WorkerState::Restarting; - assert_eq!( - lifecycle_status(State(state.clone())).await.0["drained"], - false - ); - for _ in 0..2 { - let response = client - .post(format!("{url}/admin/resume")) - .send() - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::OK); - } - let response = client - .post(format!("{url}/v1/responses")) - .header("content-type", "application/json") - .body("invalid json") - .send() - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - let _ = response.text().await.unwrap(); - server.abort(); - } - - #[tokio::test] - async fn metrics_expose_activity_without_changing_discovery() { - let (sender, mut receiver) = mpsc::channel(2); - let state = AppState { - generation: Some(sender.clone()), - ..Default::default() - }; - let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap(); - let initial_metrics = metrics_document(&state, false).await; - assert_eq!(initial_metrics["active"], false); - assert!(initial_metrics["done_decode_tokens_per_second"].is_null()); - let (result, _rx) = tokio::sync::oneshot::channel(); - sender - .send(GenerationCommand { - queue: None, - activity: None, - request: crate::wire::Generate { - token_ids: vec![10], - max_new: 1, - ..Default::default() - }, - result: crate::worker::GenerationResult::Buffered(result), - }) - .await - .unwrap(); - state.worker.write().await.metrics.start(); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}/metrics", listener.local_addr().unwrap()); - let router = router(state.clone()); - let server = tokio::spawn(async move { axum::serve(listener, router).await }); - let response = reqwest::get(url).await.unwrap(); - assert_eq!(response.status(), StatusCode::OK); - assert_eq!(response.headers()["content-type"], "application/json"); - let body: serde_json::Value = - serde_json::from_str(&response.text().await.unwrap()).unwrap(); - assert_eq!(body["active"], true); - assert!(body["active_elapsed_ms"].is_u64()); - assert_eq!(body["generation"]["started"], 1); - assert_eq!(body["queue_capacity"], 2); - assert_eq!(body["queue_used"], 1); - assert!(body["generation"].get("active_since").is_none()); - assert_eq!( - serde_json::to_value(status(State(state.clone())).await.0).unwrap(), - initial_status - ); - receiver.recv().await.unwrap(); - assert_eq!(metrics_document(&state, false).await["queue_used"], 0); - server.abort(); - } -} +mod tests; diff --git a/control-plane/src/app/tests.rs b/control-plane/src/app/tests.rs new file mode 100644 index 00000000..6d1ceb24 --- /dev/null +++ b/control-plane/src/app/tests.rs @@ -0,0 +1,163 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[tokio::test] +async fn conditional_admission_rejects_stale_or_ambiguous_pid_before_mutation() { + let state = AppState::default(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let router = router(state.clone()); + let server = tokio::spawn(async move { axum::serve(listener, router).await }); + let client = reqwest::Client::new(); + for (path, initial) in [("drain", false), ("resume", true)] { + state.lifecycle.set_draining(initial); + for (value, status) in [ + ("0".to_string(), 400), + ("bad".into(), 400), + ((std::process::id() + 1).to_string(), 409), + ] { + let response = client + .post(format!("{url}/admin/{path}")) + .header("x-strata-expected-pid", value) + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), status); + assert_eq!(state.lifecycle.snapshot().draining, initial); + } + let duplicate = client + .post(format!("{url}/admin/{path}")) + .header("x-strata-expected-pid", std::process::id()) + .header("x-strata-expected-pid", std::process::id()) + .send() + .await + .unwrap(); + assert_eq!(duplicate.status(), StatusCode::BAD_REQUEST); + assert_eq!(state.lifecycle.snapshot().draining, initial); + let response = client + .post(format!("{url}/admin/{path}")) + .header("x-strata-expected-pid", std::process::id()) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let value: serde_json::Value = + serde_json::from_str(&response.text().await.unwrap()).unwrap(); + assert_eq!(value["server_pid"], std::process::id()); + assert_eq!(value["service"], "strata-control"); + assert_eq!(value["draining"], !initial); + } + server.abort(); + let _ = server.await; +} + +#[tokio::test] +async fn drain_rejects_new_requests_before_json_parsing_and_resume_is_idempotent() { + let state = AppState::default(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let router = router(state.clone()); + let server = tokio::spawn(async move { axum::serve(listener, router).await }); + let client = reqwest::Client::new(); + for _ in 0..2 { + let response = client + .post(format!("{url}/admin/drain")) + .send() + .await + .unwrap(); + let data: serde_json::Value = + serde_json::from_str(&response.text().await.unwrap()).unwrap(); + assert_eq!(data["draining"], true); + assert_eq!(data["drained"], true); + } + let response = client + .post(format!("{url}/v1/responses")) + .header("content-type", "application/json") + .body("invalid json") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert!(response.text().await.unwrap().contains("runtime_draining")); + assert_eq!(state.lifecycle.snapshot().requests_in_flight, 0); + let job = state.lifecycle.generation(); + assert_eq!( + lifecycle_status(State(state.clone())).await.0["drained"], + false + ); + drop(job); + state.worker.write().await.state = WorkerState::Restarting; + assert_eq!( + lifecycle_status(State(state.clone())).await.0["drained"], + false + ); + for _ in 0..2 { + let response = client + .post(format!("{url}/admin/resume")) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + } + let response = client + .post(format!("{url}/v1/responses")) + .header("content-type", "application/json") + .body("invalid json") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let _ = response.text().await.unwrap(); + server.abort(); +} + +#[tokio::test] +async fn metrics_expose_activity_without_changing_discovery() { + let (sender, mut receiver) = mpsc::channel(2); + let state = AppState { + generation: Some(sender.clone()), + ..Default::default() + }; + let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap(); + let initial_metrics = metrics_document(&state, false).await; + assert_eq!(initial_metrics["active"], false); + assert!(initial_metrics["done_decode_tokens_per_second"].is_null()); + let (result, _rx) = tokio::sync::oneshot::channel(); + sender + .send(GenerationCommand { + queue: None, + activity: None, + request: crate::wire::Generate { + token_ids: vec![10], + max_new: 1, + ..Default::default() + }, + result: crate::worker::GenerationResult::Buffered(result), + }) + .await + .unwrap(); + state.worker.write().await.metrics.start(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/metrics", listener.local_addr().unwrap()); + let router = router(state.clone()); + let server = tokio::spawn(async move { axum::serve(listener, router).await }); + let response = reqwest::get(url).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["content-type"], "application/json"); + let body: serde_json::Value = + serde_json::from_str(&response.text().await.unwrap()).unwrap(); + assert_eq!(body["active"], true); + assert!(body["active_elapsed_ms"].is_u64()); + assert_eq!(body["generation"]["started"], 1); + assert_eq!(body["queue_capacity"], 2); + assert_eq!(body["queue_used"], 1); + assert!(body["generation"].get("active_since").is_none()); + assert_eq!( + serde_json::to_value(status(State(state.clone())).await.0).unwrap(), + initial_status + ); + receiver.recv().await.unwrap(); + assert_eq!(metrics_document(&state, false).await["queue_used"], 0); + server.abort(); +} diff --git a/control-plane/src/config.rs b/control-plane/src/config.rs index e431f627..f4676995 100644 --- a/control-plane/src/config.rs +++ b/control-plane/src/config.rs @@ -785,328 +785,4 @@ fn optional_env(name: &str) -> Result, env::VarError> { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn temp(name: &str) -> PathBuf { - let dir = env::temp_dir().join(format!("strata-config-{}-{name}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - dir - } - - fn load(dir: &Path, value: serde_json::Value) -> Result { - let path = dir.join("config.json"); - fs::write(&path, value.to_string()).unwrap(); - Config::load_with_path(Some(&path)).map_err(|e| e.to_string()) - } - - fn control_vector_file( - dir: &Path, - name: &str, - architecture: &str, - kind: u32, - elements: u64, - ) -> PathBuf { - let mut bytes = b"GGUF".to_vec(); - bytes.extend_from_slice(&3u32.to_le_bytes()); - bytes.extend_from_slice(&1u64.to_le_bytes()); - bytes.extend_from_slice(&1u64.to_le_bytes()); - let key = b"general.architecture"; - bytes.extend_from_slice(&(key.len() as u64).to_le_bytes()); - bytes.extend_from_slice(key); - bytes.extend_from_slice(&8u32.to_le_bytes()); - bytes.extend_from_slice(&(architecture.len() as u64).to_le_bytes()); - bytes.extend_from_slice(architecture.as_bytes()); - let tensor = b"direction.1"; - bytes.extend_from_slice(&(tensor.len() as u64).to_le_bytes()); - bytes.extend_from_slice(tensor); - bytes.extend_from_slice(&1u32.to_le_bytes()); - bytes.extend_from_slice(&elements.to_le_bytes()); - bytes.extend_from_slice(&kind.to_le_bytes()); - bytes.extend_from_slice(&0u64.to_le_bytes()); - while !bytes.len().is_multiple_of(32) { - bytes.push(0); - } - bytes.extend(std::iter::repeat_n(0u8, elements as usize * 4)); - let path = dir.join(name); - fs::write(&path, bytes).unwrap(); - path - } - - #[test] - fn serving_settings_are_read_and_checked_at_start() { - let dir = temp("serving"); - let config = load( - &dir, - json!({ - "model": "strata-test", - "aliases": ["gpt-local", " strata-test ", "gpt-local"], - "cors_origins": ["https://chat.example.com/", "*"], - "trusted_origins": "https://strata.example.com", - "sampling": {"temperature": 0.6, "top_k": 30, "nonsense": 1}, - "reasoning_budget_tokens": 128, - "engine": {"executable": "/bin/engine", "lazy_load": true, "idle_unload_s": 90, - "min_free_vram_mib": 20000, "before_load": "echo hook", - "stall_timeout_s": 120} - }), - ) - .unwrap(); - assert_eq!(config.aliases, vec!["gpt-local"]); - assert_eq!(config.cors_origins, vec!["https://chat.example.com", "*"]); - assert_eq!(config.trusted_origins, vec!["https://strata.example.com"]); - assert!(!config.api_monitor, "the request monitor is opt-in"); - assert_eq!(config.sampling.sampling.top_k, Some(30)); - assert_eq!(config.sampling.ignored, vec!["nonsense"]); - assert_eq!(config.idle_unload, Some(Duration::from_secs(90))); - assert_eq!( - config.shared_settings_file, - Some(dir.join("config.shared-settings.json")) - ); - let worker = config.worker.unwrap(); - assert!(worker.lazy); - assert_eq!(worker.min_free_vram_mib, 20000); - assert_eq!(worker.stall_timeout, Some(Duration::from_secs(120))); - assert_eq!( - worker.before_load, - Some(crate::worker::BeforeLoad::Shell("echo hook".into())) - ); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn tool_call_recovery_is_off_unless_the_config_or_the_environment_turns_it_on() { - let dir = temp("tool-call-recovery"); - assert!( - !load(&dir, json!({"model": "m"})) - .unwrap() - .tool_call_recovery, - "experimental: opt-in" - ); - assert!( - load(&dir, json!({"model": "m", "tool_call_recovery": true})) - .unwrap() - .tool_call_recovery - ); - assert!( - !load(&dir, json!({"model": "m", "tool_call_recovery": false})) - .unwrap() - .tool_call_recovery - ); - assert!(load(&dir, json!({"model": "m", "tool_call_recovery": "yes"})).is_err()); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn the_request_monitor_is_enabled_only_by_a_true_boolean() { - let dir = temp("api-monitor"); - assert!( - load(&dir, json!({"model": "m", "api_monitor": true})) - .unwrap() - .api_monitor - ); - assert!( - !load(&dir, json!({"model": "m", "api_monitor": false})) - .unwrap() - .api_monitor - ); - assert!(load(&dir, json!({"model": "m", "api_monitor": "yes"})).is_err()); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn bad_serving_settings_stop_the_start() { - let dir = temp("serving-bad"); - for (name, value) in [ - ("sampling", json!({"sampling": {"top_k": 100}})), - ("cors", json!({"cors_origins": ["https://a.example/path"]})), - ("trusted", json!({"trusted_origins": ["*"]})), - ("aliases", json!({"aliases": [1]})), - ("alias charset", json!({"aliases": ["has space"]})), - ("budget", json!({"reasoning_budget_tokens": "many"})), - ( - "stall", - json!({"engine": {"executable": "/bin/e", "stall_timeout_s": 0}}), - ), - ( - "idle", - json!({"engine": {"executable": "/bin/e", "idle_unload_s": -1}}), - ), - ] { - assert!(load(&dir, value).is_err(), "{name}"); - } - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn a_runtime_block_excludes_every_way_of_starting_an_engine_itself() { - let dir = temp("runtime-exclusive"); - let runtime = json!({ - "address": "127.0.0.1:18766", "token_env": "LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS", - "tokenizer_dir": "/models/tokenizer", - "model": {"family": "f", "architecture": "a", "weight_format": "w", - "artifact_digest": format!("sha256:{}", "a".repeat(64))}, - "mode": {"type": "native"}, "max_context": 4096 - }); - for (name, extra) in [ - ("engine", json!({"engine": {"executable": "/bin/e"}})), - ("native_model", json!({"native_model": {}})), - ("mtp_pack", json!({"mtp_pack": "/m"})), - ("engine_probe", json!({"engine_probe": true})), - ] { - let mut value = json!({"runtime": runtime}); - for (key, item) in extra.as_object().unwrap() { - value[key] = item.clone(); - } - let error = load(&dir, value).err().unwrap_or_default(); - assert!(!error.is_empty(), "{name} must be refused"); - } - // Alone it is accepted up to the credential, which comes from the environment. - let error = load(&dir, json!({"runtime": runtime})).err().unwrap(); - assert!( - error.contains("LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS"), - "{error}" - ); - let engine_error = load( - &dir, - json!({"runtime": runtime, "engine": {"executable": "/bin/e"}}), - ) - .err() - .unwrap(); - assert!( - engine_error.contains("mutually exclusive"), - "{engine_error}" - ); - let _ = fs::remove_dir_all(dir); - } - - /// The documented example stays a valid block: it parses completely and stops only at the - /// credential, which comes from the environment. - #[test] - fn the_runtime_example_config_is_valid_up_to_the_credential() { - let dir = temp("runtime-example"); - let example: serde_json::Value = - serde_json::from_str(include_str!("../config.runtime.example.json")).unwrap(); - let mut value = example.clone(); - value.as_object_mut().unwrap().remove("api_key_file"); - let error = load(&dir, value).err().unwrap(); - assert!(error.contains("LELEKA_RUNTIME_TOKEN is not set"), "{error}"); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn a_control_vector_becomes_engine_arguments_after_a_preflight() { - let dir = temp("cvec"); - let good = control_vector_file(&dir, "good.gguf", "controlvector", 0, 8); - let config = load( - &dir, - json!({"engine": {"executable": "/bin/engine", "args": ["--max-context", "4096"], - "control_vector": {"files": [{"path": good, "scale": 0.5}], "mode": "project", - "dir": "single:3", "layer_range": [2, 40]}}}), - ) - .unwrap(); - let args = config.worker.unwrap().args; - assert_eq!(args[..2], ["--max-context", "4096"]); - assert_eq!(args[2], "--control-vector-scaled"); - assert_eq!(args[3], format!("{}:0.5", good.display())); - assert_eq!( - args[4..], - [ - "--cvec-mode", - "project", - "--cvec-dir", - "single:3", - "--control-vector-layer-range", - "2", - "40" - ] - ); - for (name, value) in [ - ( - "wrong arch", - control_vector_file(&dir, "arch.gguf", "llama", 0, 8), - ), - ( - "f16", - control_vector_file(&dir, "f16.gguf", "controlvector", 1, 8), - ), - ] { - let result = load( - &dir, - json!({"engine": {"executable": "/bin/e", "control_vector": {"files": [{"path": value, "scale": 1.0}]}}}), - ); - assert!(result.is_err(), "{name}"); - } - for bad in [ - json!({"files": []}), - json!({"files": [{"path": "relative.gguf", "scale": 1.0}]}), - json!({"files": [{"path": dir.join("missing.gguf"), "scale": 1.0}]}), - json!({"files": [{"path": good, "scale": 1.0}], "dir": "single:2"}), - json!({"files": [{"path": good, "scale": 1.0}], "mode": "mix"}), - json!({"files": [{"path": good, "scale": 1.0}], "dir": "everywhere"}), - ] { - assert!( - load( - &dir, - json!({"engine": {"executable": "/bin/e", "control_vector": bad}}) - ) - .is_err(), - "{bad}" - ); - } - assert!( - load( - &dir, - json!({"engine": {"executable": "/bin/e", "args": ["--cvec-mode", "add"], - "control_vector": {"files": [{"path": good, "scale": 1.0}]}}}) - ) - .is_err(), - "owned arguments" - ); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn vision_section_needs_an_engine_and_is_text_only_when_lazy() { - let dir = temp("vision"); - let vision = json!({"exe": "/v/strata-vision", "mmproj": "/v/mmproj.gguf", "model": "/v/model.gguf", - "gpu": true, "threads": 4, "max_tokens": 1024, "cuda_device": 1}); - let config = load( - &dir, - json!({"engine": {"executable": "/bin/true"}, "vision": vision}), - ) - .unwrap(); - let loaded = config.vision.unwrap(); - assert!(loaded.gpu); - assert_eq!(loaded.cuda_device, Some(1)); - assert_eq!(loaded.max_tokens, Some(1024)); - assert!( - config.worker.unwrap().vision.is_none(), - "serve hands the started encoder to the worker" - ); - assert!( - load(&dir, json!({"vision": vision})) - .err() - .unwrap() - .contains("requires an engine") - ); - assert!( - load( - &dir, - json!({"engine": {"executable": "/bin/true", "lazy_load": true}, "vision": vision}) - ) - .err() - .unwrap() - .contains("text-only") - ); - assert!( - load( - &dir, - json!({"engine": {"executable": "/bin/true"}, "vision": {"exe": "x"}}) - ) - .is_err() - ); - let _ = fs::remove_dir_all(dir); - } -} +mod tests; diff --git a/control-plane/src/config/tests.rs b/control-plane/src/config/tests.rs new file mode 100644 index 00000000..af072f43 --- /dev/null +++ b/control-plane/src/config/tests.rs @@ -0,0 +1,325 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use serde_json::json; + +fn temp(name: &str) -> PathBuf { + let dir = env::temp_dir().join(format!("strata-config-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +fn load(dir: &Path, value: serde_json::Value) -> Result { + let path = dir.join("config.json"); + fs::write(&path, value.to_string()).unwrap(); + Config::load_with_path(Some(&path)).map_err(|e| e.to_string()) +} + +fn control_vector_file( + dir: &Path, + name: &str, + architecture: &str, + kind: u32, + elements: u64, +) -> PathBuf { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + let key = b"general.architecture"; + bytes.extend_from_slice(&(key.len() as u64).to_le_bytes()); + bytes.extend_from_slice(key); + bytes.extend_from_slice(&8u32.to_le_bytes()); + bytes.extend_from_slice(&(architecture.len() as u64).to_le_bytes()); + bytes.extend_from_slice(architecture.as_bytes()); + let tensor = b"direction.1"; + bytes.extend_from_slice(&(tensor.len() as u64).to_le_bytes()); + bytes.extend_from_slice(tensor); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&elements.to_le_bytes()); + bytes.extend_from_slice(&kind.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + while !bytes.len().is_multiple_of(32) { + bytes.push(0); + } + bytes.extend(std::iter::repeat_n(0u8, elements as usize * 4)); + let path = dir.join(name); + fs::write(&path, bytes).unwrap(); + path +} + +#[test] +fn serving_settings_are_read_and_checked_at_start() { + let dir = temp("serving"); + let config = load( + &dir, + json!({ + "model": "strata-test", + "aliases": ["gpt-local", " strata-test ", "gpt-local"], + "cors_origins": ["https://chat.example.com/", "*"], + "trusted_origins": "https://strata.example.com", + "sampling": {"temperature": 0.6, "top_k": 30, "nonsense": 1}, + "reasoning_budget_tokens": 128, + "engine": {"executable": "/bin/engine", "lazy_load": true, "idle_unload_s": 90, + "min_free_vram_mib": 20000, "before_load": "echo hook", + "stall_timeout_s": 120} + }), + ) + .unwrap(); + assert_eq!(config.aliases, vec!["gpt-local"]); + assert_eq!(config.cors_origins, vec!["https://chat.example.com", "*"]); + assert_eq!(config.trusted_origins, vec!["https://strata.example.com"]); + assert!(!config.api_monitor, "the request monitor is opt-in"); + assert_eq!(config.sampling.sampling.top_k, Some(30)); + assert_eq!(config.sampling.ignored, vec!["nonsense"]); + assert_eq!(config.idle_unload, Some(Duration::from_secs(90))); + assert_eq!( + config.shared_settings_file, + Some(dir.join("config.shared-settings.json")) + ); + let worker = config.worker.unwrap(); + assert!(worker.lazy); + assert_eq!(worker.min_free_vram_mib, 20000); + assert_eq!(worker.stall_timeout, Some(Duration::from_secs(120))); + assert_eq!( + worker.before_load, + Some(crate::worker::BeforeLoad::Shell("echo hook".into())) + ); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn tool_call_recovery_is_off_unless_the_config_or_the_environment_turns_it_on() { + let dir = temp("tool-call-recovery"); + assert!( + !load(&dir, json!({"model": "m"})) + .unwrap() + .tool_call_recovery, + "experimental: opt-in" + ); + assert!( + load(&dir, json!({"model": "m", "tool_call_recovery": true})) + .unwrap() + .tool_call_recovery + ); + assert!( + !load(&dir, json!({"model": "m", "tool_call_recovery": false})) + .unwrap() + .tool_call_recovery + ); + assert!(load(&dir, json!({"model": "m", "tool_call_recovery": "yes"})).is_err()); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn the_request_monitor_is_enabled_only_by_a_true_boolean() { + let dir = temp("api-monitor"); + assert!( + load(&dir, json!({"model": "m", "api_monitor": true})) + .unwrap() + .api_monitor + ); + assert!( + !load(&dir, json!({"model": "m", "api_monitor": false})) + .unwrap() + .api_monitor + ); + assert!(load(&dir, json!({"model": "m", "api_monitor": "yes"})).is_err()); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn bad_serving_settings_stop_the_start() { + let dir = temp("serving-bad"); + for (name, value) in [ + ("sampling", json!({"sampling": {"top_k": 100}})), + ("cors", json!({"cors_origins": ["https://a.example/path"]})), + ("trusted", json!({"trusted_origins": ["*"]})), + ("aliases", json!({"aliases": [1]})), + ("alias charset", json!({"aliases": ["has space"]})), + ("budget", json!({"reasoning_budget_tokens": "many"})), + ( + "stall", + json!({"engine": {"executable": "/bin/e", "stall_timeout_s": 0}}), + ), + ( + "idle", + json!({"engine": {"executable": "/bin/e", "idle_unload_s": -1}}), + ), + ] { + assert!(load(&dir, value).is_err(), "{name}"); + } + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn a_runtime_block_excludes_every_way_of_starting_an_engine_itself() { + let dir = temp("runtime-exclusive"); + let runtime = json!({ + "address": "127.0.0.1:18766", "token_env": "LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS", + "tokenizer_dir": "/models/tokenizer", + "model": {"family": "f", "architecture": "a", "weight_format": "w", + "artifact_digest": format!("sha256:{}", "a".repeat(64))}, + "mode": {"type": "native"}, "max_context": 4096 + }); + for (name, extra) in [ + ("engine", json!({"engine": {"executable": "/bin/e"}})), + ("native_model", json!({"native_model": {}})), + ("mtp_pack", json!({"mtp_pack": "/m"})), + ("engine_probe", json!({"engine_probe": true})), + ] { + let mut value = json!({"runtime": runtime}); + for (key, item) in extra.as_object().unwrap() { + value[key] = item.clone(); + } + let error = load(&dir, value).err().unwrap_or_default(); + assert!(!error.is_empty(), "{name} must be refused"); + } + // Alone it is accepted up to the credential, which comes from the environment. + let error = load(&dir, json!({"runtime": runtime})).err().unwrap(); + assert!( + error.contains("LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS"), + "{error}" + ); + let engine_error = load( + &dir, + json!({"runtime": runtime, "engine": {"executable": "/bin/e"}}), + ) + .err() + .unwrap(); + assert!( + engine_error.contains("mutually exclusive"), + "{engine_error}" + ); + let _ = fs::remove_dir_all(dir); +} + +/// The documented example stays a valid block: it parses completely and stops only at the +/// credential, which comes from the environment. +#[test] +fn the_runtime_example_config_is_valid_up_to_the_credential() { + let dir = temp("runtime-example"); + let example: serde_json::Value = + serde_json::from_str(include_str!("../../config.runtime.example.json")).unwrap(); + let mut value = example.clone(); + value.as_object_mut().unwrap().remove("api_key_file"); + let error = load(&dir, value).err().unwrap(); + assert!(error.contains("LELEKA_RUNTIME_TOKEN is not set"), "{error}"); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn a_control_vector_becomes_engine_arguments_after_a_preflight() { + let dir = temp("cvec"); + let good = control_vector_file(&dir, "good.gguf", "controlvector", 0, 8); + let config = load( + &dir, + json!({"engine": {"executable": "/bin/engine", "args": ["--max-context", "4096"], + "control_vector": {"files": [{"path": good, "scale": 0.5}], "mode": "project", + "dir": "single:3", "layer_range": [2, 40]}}}), + ) + .unwrap(); + let args = config.worker.unwrap().args; + assert_eq!(args[..2], ["--max-context", "4096"]); + assert_eq!(args[2], "--control-vector-scaled"); + assert_eq!(args[3], format!("{}:0.5", good.display())); + assert_eq!( + args[4..], + [ + "--cvec-mode", + "project", + "--cvec-dir", + "single:3", + "--control-vector-layer-range", + "2", + "40" + ] + ); + for (name, value) in [ + ( + "wrong arch", + control_vector_file(&dir, "arch.gguf", "llama", 0, 8), + ), + ( + "f16", + control_vector_file(&dir, "f16.gguf", "controlvector", 1, 8), + ), + ] { + let result = load( + &dir, + json!({"engine": {"executable": "/bin/e", "control_vector": {"files": [{"path": value, "scale": 1.0}]}}}), + ); + assert!(result.is_err(), "{name}"); + } + for bad in [ + json!({"files": []}), + json!({"files": [{"path": "relative.gguf", "scale": 1.0}]}), + json!({"files": [{"path": dir.join("missing.gguf"), "scale": 1.0}]}), + json!({"files": [{"path": good, "scale": 1.0}], "dir": "single:2"}), + json!({"files": [{"path": good, "scale": 1.0}], "mode": "mix"}), + json!({"files": [{"path": good, "scale": 1.0}], "dir": "everywhere"}), + ] { + assert!( + load( + &dir, + json!({"engine": {"executable": "/bin/e", "control_vector": bad}}) + ) + .is_err(), + "{bad}" + ); + } + assert!( + load( + &dir, + json!({"engine": {"executable": "/bin/e", "args": ["--cvec-mode", "add"], + "control_vector": {"files": [{"path": good, "scale": 1.0}]}}}) + ) + .is_err(), + "owned arguments" + ); + let _ = fs::remove_dir_all(dir); +} + +#[test] +fn vision_section_needs_an_engine_and_is_text_only_when_lazy() { + let dir = temp("vision"); + let vision = json!({"exe": "/v/strata-vision", "mmproj": "/v/mmproj.gguf", "model": "/v/model.gguf", + "gpu": true, "threads": 4, "max_tokens": 1024, "cuda_device": 1}); + let config = load( + &dir, + json!({"engine": {"executable": "/bin/true"}, "vision": vision}), + ) + .unwrap(); + let loaded = config.vision.unwrap(); + assert!(loaded.gpu); + assert_eq!(loaded.cuda_device, Some(1)); + assert_eq!(loaded.max_tokens, Some(1024)); + assert!( + config.worker.unwrap().vision.is_none(), + "serve hands the started encoder to the worker" + ); + assert!( + load(&dir, json!({"vision": vision})) + .err() + .unwrap() + .contains("requires an engine") + ); + assert!( + load( + &dir, + json!({"engine": {"executable": "/bin/true", "lazy_load": true}, "vision": vision}) + ) + .err() + .unwrap() + .contains("text-only") + ); + assert!( + load( + &dir, + json!({"engine": {"executable": "/bin/true"}, "vision": {"exe": "x"}}) + ) + .is_err() + ); + let _ = fs::remove_dir_all(dir); +} diff --git a/control-plane/src/ggml_bridge.rs b/control-plane/src/ggml_bridge.rs index 08aea50f..486e3230 100644 --- a/control-plane/src/ggml_bridge.rs +++ b/control-plane/src/ggml_bridge.rs @@ -61,1294 +61,4 @@ pub fn decode_into(kind: u32, source: &[u8], destination: &mut [f32]) -> Result< } #[cfg(test)] -mod tests { - use super::*; - use crate::iq3_s; - - #[test] - fn pinned_ggml_block_sizes_match_gguf_geometry() { - for kind in [ - 2, 3, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22, 23, 29, 42, - ] { - assert_eq!( - u64::from(unsafe { strata_ggml_block_bytes(kind) }), - gguf::block_geometry(kind).unwrap().1, - "kind {kind}" - ); - } - } - - #[test] - fn pinned_ggml_iq3_matches_independent_rust_decoder() { - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - for (index, byte) in block[2..66].iter_mut().enumerate() { - *byte = (index as u8).wrapping_mul(3); - } - block[74] = 0x55; - let mut decoded = [0.0f32; 256]; - decode_into(21, &block, &mut decoded).unwrap(); - assert_eq!(decoded, iq3_s::decode_block(&block).unwrap()); - } - - // Generated packed fields only: no model weights, captures or external RNG. - // Each scale gets a reproducible field pattern independent of either decoder. - fn synthetic_iq3_block(scale_bits: u16, pattern: u32) -> [u8; iq3_s::BLOCK_BYTES] { - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&scale_bits.to_le_bytes()); - let low = pattern as u8; - let high = pattern >> 8; - for (field, byte) in block[2..].iter_mut().enumerate() { - // For any fixed high byte, odd multiplication, rotation and addition - // form a bijection of all 256 low-byte values at every field position. - let odd = (2 * field + 1) as u8; - let salt = high - .wrapping_mul(0x85eb_ca6b) - .wrapping_add((field as u32).wrapping_mul(0x9e37_79b9)); - *byte = low - .wrapping_mul(odd) - .rotate_left((field % 8) as u32) - .wrapping_add((salt ^ (salt >> 16)) as u8); - } - block - } - - fn assert_exact_iq3_bits(block: &[u8; iq3_s::BLOCK_BYTES], case: u32) { - let mut reference = [0.0f32; iq3_s::BLOCK_ELEMENTS]; - decode_into(21, block, &mut reference).unwrap(); - let actual = iq3_s::decode_block(block).unwrap(); - let scale_bits = u16::from_le_bytes([block[0], block[1]]); - for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { - assert!(actual.is_finite() && reference.is_finite()); - assert_eq!( - actual.to_bits(), - reference.to_bits(), - "case={case} scale_bits={scale_bits:#06x} element={element} block={block:?}" - ); - } - } - - #[test] - fn pinned_ggml_iq3_matches_rust_bits_for_every_finite_fp16_scale() { - // Exhaust all 63,488 finite binary16 encodings, including both signed - // zeros, every subnormal/normal and both signs of the maximum finite. - let mut low_fields = [[false; 256]; 64]; - let mut high_fields = [[false; 256]; 8]; - let mut sign_fields = [[false; 256]; 32]; - let mut scale_nibbles = [[false; 16]; 8]; - let mut grid_indexes = [false; 512]; - let mut compared = 0; - for scale_bits in 0..=u16::MAX { - if scale_bits & 0x7c00 == 0x7c00 { - continue; - } - let block = synthetic_iq3_block(scale_bits, u32::from(scale_bits)); - assert_exact_iq3_bits(&block, u32::from(scale_bits)); - for (field, value) in block[2..66].iter().enumerate() { - low_fields[field][usize::from(*value)] = true; - } - for (field, value) in block[66..74].iter().enumerate() { - high_fields[field][usize::from(*value)] = true; - } - for (field, value) in block[74..106].iter().enumerate() { - sign_fields[field][usize::from(*value)] = true; - } - for subblock in 0..8 { - let nibble = (block[106 + subblock / 2] >> (4 * (subblock % 2))) & 15; - scale_nibbles[subblock][usize::from(nibble)] = true; - for part in 0..8 { - let grid = usize::from(block[2 + 8 * subblock + part]) - | (usize::from((block[66 + subblock] >> part) & 1) << 8); - grid_indexes[grid] = true; - } - } - compared += 1; - } - assert_eq!(compared, 63_488); - assert!(low_fields.iter().flatten().all(|seen| *seen)); - assert!(high_fields.iter().flatten().all(|seen| *seen)); - assert!(sign_fields.iter().flatten().all(|seen| *seen)); - assert!(scale_nibbles.iter().flatten().all(|seen| *seen)); - assert!(grid_indexes.iter().all(|seen| *seen)); - } - - #[test] - fn pinned_ggml_iq3_batch_bits_match_rust_with_unaligned_source() { - let scales = [ - 0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00, - 0xbc00, 0x7bff, 0xfbff, - ]; - let length = scales.len() * iq3_s::BLOCK_BYTES; - let mut storage = vec![0u8; length + 16]; - let start = storage.as_ptr().align_offset(16) + 1; - let source = &mut storage[start..start + length]; - assert_eq!(source.as_ptr().align_offset(16), 15); - for (number, scale) in scales.into_iter().enumerate() { - let block = synthetic_iq3_block(scale, number as u32 + 70_000); - source[number * iq3_s::BLOCK_BYTES..(number + 1) * iq3_s::BLOCK_BYTES] - .copy_from_slice(&block); - } - let mut reference = vec![0.0f32; scales.len() * iq3_s::BLOCK_ELEMENTS]; - let mut actual = vec![0.0f32; reference.len()]; - decode_into(21, source, &mut reference).unwrap(); - iq3_s::decode_into(source, &mut actual).unwrap(); - for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { - assert_eq!( - actual.to_bits(), - reference.to_bits(), - "batch element={element}" - ); - } - } - - #[test] - fn independent_rust_iq3_refuses_every_nonfinite_fp16_scale() { - // GGML may decode these; Rust's existing refusal is deliberately retained. - let mut rejected = 0; - for scale_bits in 0..=u16::MAX { - if scale_bits & 0x7c00 != 0x7c00 { - continue; - } - let block = synthetic_iq3_block(scale_bits, u32::from(scale_bits)); - assert_eq!( - iq3_s::decode_block(&block).unwrap_err(), - "IQ3_S block has a non-finite scale" - ); - assert!(iq3_s::decode_into(&block, &mut [0.0; iq3_s::BLOCK_ELEMENTS]).is_err()); - rejected += 1; - } - assert_eq!(rejected, 2_048); - } - - // Each half covers all 16 IQ4_NL codepoints for every scale. Over patterns - // 0..256 each field additionally covers every low/high nibble combination. - fn synthetic_iq4_block(scale_bits: u16, pattern: u32) -> [u8; 18] { - let mut block = [0u8; 18]; - block[..2].copy_from_slice(&scale_bits.to_le_bytes()); - for (field, byte) in block[2..].iter_mut().enumerate() { - let low = (field as u8).wrapping_add(pattern as u8) & 15; - let high = (15 - field as u8).wrapping_add((pattern >> 4) as u8) & 15; - *byte = low | (high << 4); - } - block - } - - #[test] - fn pinned_ggml_iq4_matches_rust_bits_for_every_finite_fp16_scale() { - use leleka_quant_core::iq4_nl; - let mut packed_fields = [[false; 256]; 16]; - let mut codepoints = [[false; 16]; 32]; - let mut compared = 0; - for scale_bits in 0..=u16::MAX { - if scale_bits & 0x7c00 == 0x7c00 { - continue; - } - let block = synthetic_iq4_block(scale_bits, u32::from(scale_bits)); - let mut reference = [0.0; iq4_nl::BLOCK_ELEMENTS]; - decode_into(20, &block, &mut reference).unwrap(); - let actual = iq4_nl::decode_block(&block).unwrap(); - let mut low_seen = [false; 16]; - let mut high_seen = [false; 16]; - for (field, byte) in block[2..].iter().enumerate() { - packed_fields[field][usize::from(*byte)] = true; - codepoints[field][usize::from(byte & 15)] = true; - codepoints[field + 16][usize::from(byte >> 4)] = true; - low_seen[usize::from(byte & 15)] = true; - high_seen[usize::from(byte >> 4)] = true; - } - assert!(low_seen.into_iter().all(|seen| seen)); - assert!(high_seen.into_iter().all(|seen| seen)); - for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { - assert!(actual.is_finite() && reference.is_finite()); - assert_eq!( - actual.to_bits(), - reference.to_bits(), - "IQ4_NL scale={scale_bits:#06x} element={element} block={block:?}" - ); - } - compared += 1; - } - assert_eq!(compared, 63_488); - assert!(packed_fields.iter().flatten().all(|seen| *seen)); - assert!(codepoints.iter().flatten().all(|seen| *seen)); - } - - #[test] - fn pinned_ggml_iq4_batch_bits_match_rust_with_unaligned_source() { - use leleka_quant_core::iq4_nl; - let scales = [ - 0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00, - 0xbc00, 0x7bff, 0xfbff, - ]; - let length = scales.len() * iq4_nl::BLOCK_BYTES; - let mut storage = vec![0u8; length + 16]; - let start = storage.as_ptr().align_offset(16) + 1; - let source = &mut storage[start..start + length]; - assert_eq!(source.as_ptr().align_offset(16), 15); - for (number, scale) in scales.into_iter().enumerate() { - source[number * iq4_nl::BLOCK_BYTES..(number + 1) * iq4_nl::BLOCK_BYTES] - .copy_from_slice(&synthetic_iq4_block(scale, number as u32 + 70_000)); - } - let mut actual = vec![0.0; scales.len() * iq4_nl::BLOCK_ELEMENTS]; - let mut reference = vec![0.0; actual.len()]; - decode_into(20, source, &mut reference).unwrap(); - iq4_nl::decode_into(source, &mut actual).unwrap(); - for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { - assert_eq!( - actual.to_bits(), - reference.to_bits(), - "IQ4_NL batch element={element}" - ); - } - } - - #[test] - fn pinned_ggml_iq4_nonfinite_classification_matches_rust_without_refusal() { - use leleka_quant_core::iq4_nl; - let mut compared = 0; - for scale_bits in 0..=u16::MAX { - if scale_bits & 0x7c00 != 0x7c00 { - continue; - } - let block = synthetic_iq4_block(scale_bits, u32::from(scale_bits)); - let mut reference = [0.0; iq4_nl::BLOCK_ELEMENTS]; - let mut actual = [0.0; iq4_nl::BLOCK_ELEMENTS]; - decode_into(20, &block, &mut reference).unwrap(); - iq4_nl::decode_into(&block, &mut actual).unwrap(); - let single = iq4_nl::decode_block(&block).unwrap(); - for (element, ((actual, single), reference)) in - actual.iter().zip(&single).zip(&reference).enumerate() - { - if scale_bits & 0x03ff == 0 { - assert!(actual.is_infinite() && reference.is_infinite()); - assert_eq!(actual.to_bits(), reference.to_bits()); - assert_eq!(single.to_bits(), reference.to_bits()); - } else { - // No cross-platform NaN payload/sign contract is inferred - // from classification. Neither decoder refuses these scales. - assert!( - actual.is_nan() && single.is_nan() && reference.is_nan(), - "IQ4_NL nonfinite scale={scale_bits:#06x} element={element}" - ); - } - } - compared += 1; - } - assert_eq!(compared, 2_048); - } - - #[test] - fn q8_0_and_q2_0_match_known_block_values() { - let mut q8 = [0u8; 34]; - q8[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - for (index, byte) in q8[2..].iter_mut().enumerate() { - *byte = (index as i8 - 16) as u8; - } - let mut values = [0.0f32; 32]; - decode_into(8, &q8, &mut values).unwrap(); - assert_eq!(values[0], -16.0); - assert_eq!(values[31], 15.0); - - let mut q2 = [0u8; 18]; - q2[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - let mut values = [0.0f32; 64]; - decode_into(42, &q2, &mut values).unwrap(); - assert!(values.iter().all(|value| *value == -1.0)); - } - - fn q8_corpus(scale: u16) -> [u8; 8 * 34] { - let mut source = [0u8; 8 * 34]; - for (group, block) in source.as_chunks_mut::<34>().0.iter_mut().enumerate() { - block[..2].copy_from_slice(&scale.to_le_bytes()); - for (position, byte) in block[2..].iter_mut().enumerate() { - *byte = (group as u8 * 32 + position as u8).wrapping_add(scale as u8); - } - } - source - } - - #[test] - fn pinned_ggml_q8_matches_rust_bits_for_every_finite_scale_and_signed_codepoint() { - use leleka_quant_core::q8_0; - let mut position_codes = [[false; 256]; 32]; - let mut compared = 0; - for scale in 0..=u16::MAX { - if scale & 0x7c00 == 0x7c00 { - continue; - } - let source = q8_corpus(scale); - let mut reference = [0.0; 256]; - let mut actual = [0.0; 256]; - decode_into(8, &source, &mut reference).unwrap(); - q8_0::decode_into(&source, &mut actual).unwrap(); - let mut scale_codes = [false; 256]; - for block in source.as_chunks::<34>().0 { - for (position, code) in block[2..].iter().enumerate() { - position_codes[position][usize::from(*code)] = true; - scale_codes[usize::from(*code)] = true; - } - } - assert!(scale_codes.into_iter().all(|seen| seen)); - for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { - assert!(actual.is_finite() && reference.is_finite()); - assert_eq!( - actual.to_bits(), - reference.to_bits(), - "Q8_0 scale={scale:#06x} element={element}" - ); - } - compared += 1; - } - assert_eq!(compared, 63_488); - assert!(position_codes.iter().flatten().all(|seen| *seen)); - } - - #[test] - fn pinned_ggml_q8_nonfinite_including_zero_matches_rust_classification_and_inf_signs() { - use leleka_quant_core::q8_0; - let mut compared = 0; - for scale in 0..=u16::MAX { - if scale & 0x7c00 != 0x7c00 { - continue; - } - let source = q8_corpus(scale); - let mut reference = [0.0; 256]; - let mut actual = [0.0; 256]; - decode_into(8, &source, &mut reference).unwrap(); - q8_0::decode_into(&source, &mut actual).unwrap(); - let mut nan_count = 0; - for (actual, reference) in actual.iter().zip(&reference) { - if reference.is_nan() { - assert!(actual.is_nan()); - nan_count += 1; - } else { - assert!(actual.is_infinite() && reference.is_infinite()); - assert_eq!(actual.to_bits(), reference.to_bits()); - } - } - assert_eq!(nan_count, if scale & 0x03ff == 0 { 1 } else { 256 }); - compared += 1; - } - assert_eq!(compared, 2_048); - } - - fn iq4xs_corpus(scale: u16, group: usize) -> [u8; 136] { - let mut block = [0u8; 136]; - block[..2].copy_from_slice(&scale.to_le_bytes()); - let mut high = 0u16; - for subblock in 0..8 { - let six = (group * 8 + subblock + usize::from(scale)) & 63; - block[4 + subblock / 2] |= ((six & 15) as u8) << (4 * (subblock % 2)); - high |= ((six >> 4) as u16) << (2 * subblock); - for position in 0..16 { - let low = (position + usize::from(scale) + group) & 15; - let upper = (15 - position + (usize::from(scale) >> 4) + group) & 15; - block[8 + subblock * 16 + position] = low as u8 | ((upper as u8) << 4); - } - } - block[2..4].copy_from_slice(&high.to_le_bytes()); - block - } - - #[test] - fn pinned_ggml_iq4xs_matches_rust_bits_for_every_finite_scale_subscale_and_codepoint() { - use leleka_quant_core::iq4_xs; - let mut subscales = [[false; 64]; 8]; - let mut packed_fields = [[false; 256]; 128]; - let mut codepoints = [[false; 16]; 256]; - let mut compared = 0; - for scale in 0..=u16::MAX { - if scale & 0x7c00 == 0x7c00 { - continue; - } - let mut scale_subscales = [false; 64]; - for group in 0..8 { - let block = iq4xs_corpus(scale, group); - let high = u16::from_le_bytes([block[2], block[3]]); - for subblock in 0..8 { - let six = usize::from((block[4 + subblock / 2] >> (4 * (subblock % 2))) & 15) - | (usize::from((high >> (2 * subblock)) & 3) << 4); - subscales[subblock][six] = true; - scale_subscales[six] = true; - let mut low_seen = [false; 16]; - let mut high_seen = [false; 16]; - for position in 0..16 { - let field = subblock * 16 + position; - let packed = block[8 + field]; - packed_fields[field][usize::from(packed)] = true; - codepoints[subblock * 32 + position][usize::from(packed & 15)] = true; - codepoints[subblock * 32 + position + 16][usize::from(packed >> 4)] = true; - low_seen[usize::from(packed & 15)] = true; - high_seen[usize::from(packed >> 4)] = true; - } - assert!(low_seen.into_iter().all(|seen| seen)); - assert!(high_seen.into_iter().all(|seen| seen)); - } - let mut reference = [0.0; iq4_xs::BLOCK_ELEMENTS]; - decode_into(23, &block, &mut reference).unwrap(); - let actual = iq4_xs::decode_block(&block).unwrap(); - for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { - assert!(actual.is_finite() && reference.is_finite()); - assert_eq!( - actual.to_bits(), - reference.to_bits(), - "IQ4_XS scale={scale:#06x} group={group} element={element}" - ); - } - } - assert!(scale_subscales.into_iter().all(|seen| seen)); - compared += 1; - } - assert_eq!(compared, 63_488); - assert!(subscales.iter().flatten().all(|seen| *seen)); - assert!(packed_fields.iter().flatten().all(|seen| *seen)); - assert!(codepoints.iter().flatten().all(|seen| *seen)); - } - - #[test] - fn pinned_ggml_iq4xs_nonfinite_and_zero_subscale_match_rust_classification_and_inf_signs() { - use leleka_quant_core::iq4_xs; - let mut zero_positions = [false; 8]; - let mut compared = 0; - for scale in 0..=u16::MAX { - if scale & 0x7c00 != 0x7c00 { - continue; - } - let mut nan_count = 0; - for group in 0..8 { - let block = iq4xs_corpus(scale, group); - let mut reference = [0.0; iq4_xs::BLOCK_ELEMENTS]; - let mut actual = [0.0; iq4_xs::BLOCK_ELEMENTS]; - decode_into(23, &block, &mut reference).unwrap(); - iq4_xs::decode_into(&block, &mut actual).unwrap(); - let high = u16::from_le_bytes([block[2], block[3]]); - for subblock in 0..8 { - let six = ((block[4 + subblock / 2] >> (4 * (subblock % 2))) & 15) - | (((high >> (2 * subblock)) & 3) as u8) << 4; - zero_positions[subblock] |= six == 32; - } - for (actual, reference) in actual.iter().zip(&reference) { - if reference.is_nan() { - assert!(actual.is_nan()); - nan_count += 1; - } else { - assert!(actual.is_infinite() && reference.is_infinite()); - assert_eq!(actual.to_bits(), reference.to_bits()); - } - } - } - assert_eq!(nan_count, if scale & 0x03ff == 0 { 32 } else { 2048 }); - compared += 1; - } - assert_eq!(compared, 2_048); - assert!(zero_positions.into_iter().all(|seen| seen)); - } - - #[test] - fn pinned_ggml_q8_and_iq4xs_unaligned_batches_match_rust_bits() { - use leleka_quant_core::{iq4_xs, q8_0}; - for (kind, block_bytes, elements) in [ - (8, q8_0::BLOCK_BYTES, q8_0::BLOCK_ELEMENTS), - (23, iq4_xs::BLOCK_BYTES, iq4_xs::BLOCK_ELEMENTS), - ] { - let scales = [ - 0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, - 0x3c00, 0xbc00, 0x7bff, 0xfbff, - ]; - let mut storage = vec![0u8; scales.len() * block_bytes + 16]; - let start = storage.as_ptr().align_offset(16) + 1; - let source = &mut storage[start..start + scales.len() * block_bytes]; - assert_eq!(source.as_ptr().align_offset(16), 15); - for (number, scale) in scales.into_iter().enumerate() { - let destination = &mut source[number * block_bytes..(number + 1) * block_bytes]; - if kind == 8 { - destination.copy_from_slice(&q8_corpus(scale)[..34]); - } else { - destination.copy_from_slice(&iq4xs_corpus(scale, number % 8)); - } - } - let mut reference = vec![0.0; scales.len() * elements]; - let mut actual = vec![0.0; reference.len()]; - decode_into(kind, source, &mut reference).unwrap(); - if kind == 8 { - q8_0::decode_into(source, &mut actual).unwrap(); - } else { - iq4_xs::decode_into(source, &mut actual).unwrap(); - } - for (actual, reference) in actual.iter().zip(&reference) { - assert_eq!(actual.to_bits(), reference.to_bits()); - } - } - } - - // Independent packed fixtures: all expectations come from the pinned C oracle, - // never from the Rust decoder/helper or a generated Rust value table. - fn synthetic_k_block(kind: u32, d: u16, dmin: u16, pattern: u32) -> Vec { - let bytes = if kind == 12 { 144 } else { 176 }; - let mut block = vec![0u8; bytes]; - block[..2].copy_from_slice(&d.to_le_bytes()); - block[2..4].copy_from_slice(&dmin.to_le_bytes()); - for (position, byte) in block[4..16].iter_mut().enumerate() { - *byte = (pattern as u8) - .wrapping_mul((position * 2 + 1) as u8) - .rotate_left((position % 8) as u32) - .wrapping_add((pattern >> 8) as u8); - } - let quant_start = if kind == 12 { 16 } else { 48 }; - for pair in 0..4 { - for lane in 0..32 { - let low = (lane + pattern as usize + pair) & 15; - let high = (31 - lane + (pattern as usize >> 4) + pair) & 15; - block[quant_start + pair * 32 + lane] = low as u8 | ((high as u8) << 4); - } - } - if kind == 13 { - for (lane, byte) in block[16..48].iter_mut().enumerate() { - *byte = (pattern >> 8) as u8 ^ if lane >= 16 { 0xff } else { 0 }; - } - } - block - } - - fn assert_k_c_reference(kind: u32, block: &[u8], finite: bool) -> [f32; 256] { - use leleka_quant_core::{q4_k, q5_k}; - let mut reference = [0.0; 256]; - decode_into(kind, block, &mut reference).unwrap(); - let actual = match kind { - 12 => q4_k::decode_block(block.try_into().unwrap()).unwrap(), - 13 => q5_k::decode_block(block.try_into().unwrap()).unwrap(), - _ => unreachable!(), - }; - for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { - if finite { - assert!(actual.is_finite() && reference.is_finite()); - } - if reference.is_nan() { - assert!( - actual.is_nan(), - "kind={kind} element={element} block={block:?}" - ); - } else { - assert_eq!( - actual.to_bits(), - reference.to_bits(), - "kind={kind} element={element} block={block:?}" - ); - } - } - actual - } - - #[test] - fn pinned_ggml_q4_q5_k_exhaust_each_finite_fp16_scale_role_separately() { - for kind in [12, 13] { - for vary_min in [false, true] { - let mut compared = 0; - for bits in 0..=u16::MAX { - if bits & 0x7c00 == 0x7c00 { - continue; - } - let (d, dmin) = if vary_min { - (0xbc00, bits) - } else { - (bits, 0x3800) - }; - let block = synthetic_k_block(kind, d, dmin, u32::from(bits)); - assert_k_c_reference(kind, &block, true); - compared += 1; - } - assert_eq!(compared, 63_488, "kind={kind} min_role={vary_min}"); - } - } - } - - #[test] - fn pinned_ggml_q4_q5_k_packed_fields_and_subscale_positions_match_rust_bits() { - for kind in [12, 13] { - let mut packed_scales = [[false; 256]; 12]; - let mut scales = [[false; 64]; 8]; - let mut minima = [[false; 64]; 8]; - let mut packed_quants = [[false; 256]; 128]; - let mut high_bytes = [[false; 256]; 32]; - let mut codes = [[false; 32]; 256]; - let quant_start = if kind == 12 { 16 } else { 48 }; - for pattern in 0..=u16::MAX { - let block = synthetic_k_block(kind, 0x3555, 0xb800, u32::from(pattern)); - assert_k_c_reference(kind, &block, true); - for (position, byte) in block[4..16].iter().enumerate() { - packed_scales[position][usize::from(*byte)] = true; - } - for subblock in 0..8 { - let (scale, minimum) = if subblock < 4 { - (block[4 + subblock] & 63, block[8 + subblock] & 63) - } else { - ( - (block[8 + subblock] & 15) | ((block[subblock] >> 6) << 4), - (block[8 + subblock] >> 4) | ((block[4 + subblock] >> 6) << 4), - ) - }; - scales[subblock][usize::from(scale)] = true; - minima[subblock][usize::from(minimum)] = true; - } - for pair in 0..4 { - let mut low_seen = [false; 32]; - let mut high_seen = [false; 32]; - for lane in 0..32 { - let field = pair * 32 + lane; - let packed = block[quant_start + field]; - packed_quants[field][usize::from(packed)] = true; - let high = if kind == 13 { block[16 + lane] } else { 0 }; - if kind == 13 { - high_bytes[lane][usize::from(high)] = true; - } - let low_code = - (packed & 15) | if high & (1 << (pair * 2)) != 0 { 16 } else { 0 }; - let high_code = - (packed >> 4) | if high & (2 << (pair * 2)) != 0 { 16 } else { 0 }; - codes[pair * 64 + lane][usize::from(low_code)] = true; - codes[pair * 64 + lane + 32][usize::from(high_code)] = true; - low_seen[usize::from(low_code)] = true; - high_seen[usize::from(high_code)] = true; - } - let limit = if kind == 12 { 16 } else { 32 }; - assert!(low_seen[..limit].iter().all(|seen| *seen)); - assert!(high_seen[..limit].iter().all(|seen| *seen)); - } - } - assert!(packed_scales.iter().flatten().all(|seen| *seen)); - assert!(scales.iter().flatten().all(|seen| *seen)); - assert!(minima.iter().flatten().all(|seen| *seen)); - assert!(packed_quants.iter().flatten().all(|seen| *seen)); - let limit = if kind == 12 { 16 } else { 32 }; - assert!( - codes - .iter() - .all(|position| position[..limit].iter().all(|seen| *seen)) - ); - if kind == 13 { - assert!(high_bytes.iter().flatten().all(|seen| *seen)); - } - } - } - - #[test] - fn pinned_ggml_q4_q5_k_joint_finite_edges_and_exact_cancellation_match_rust_bits() { - let edges = [ - 0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, - 0x3800, 0xb800, 0x3bff, 0xbbff, 0x3c00, 0xbc00, 0x3c01, 0xbc01, 0x7bff, 0xfbff, - ]; - for kind in [12, 13] { - for (left, d) in edges.into_iter().enumerate() { - for (right, dmin) in edges.into_iter().enumerate() { - let block = - synthetic_k_block(kind, d, dmin, (left * 257 + right * 65_537) as u32); - assert_k_c_reference(kind, &block, true); - } - } - for d in edges { - let mut block = synthetic_k_block(kind, d, d, 0); - block[4..12].fill(1); - block[12..16].fill(0x11); - let quant_start = if kind == 12 { 16 } else { 48 }; - if kind == 13 { - block[16..48].fill(0); - } - block[quant_start..].fill(0x11); - let actual = assert_k_c_reference(kind, &block, true); - assert!(actual.iter().all(|value| value.to_bits() == 0)); - } - } - } - - #[test] - fn pinned_ggml_q4_q5_k_nonfinite_scale_roles_and_joint_edges_preserve_c_values() { - let special = [ - 0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00, - ]; - for kind in [12, 13] { - for vary_min in [false, true] { - let mut compared = 0; - for bits in 0..=u16::MAX { - if bits & 0x7c00 != 0x7c00 { - continue; - } - let (d, dmin) = if vary_min { - (0x3c00, bits) - } else { - (bits, 0xbc00) - }; - let mut block = synthetic_k_block(kind, d, dmin, u32::from(bits)); - assert_k_c_reference(kind, &block, false); - // Explicit all-zero packed scale/minimum/quant values exercise - // Inf*zero and downstream subtraction instead of assuming Inf. - block[4..].fill(0); - assert_k_c_reference(kind, &block, false); - compared += 1; - } - assert_eq!(compared, 2_048); - } - for (left, d) in special.into_iter().enumerate() { - for (right, dmin) in special.into_iter().enumerate() { - let block = - synthetic_k_block(kind, d, dmin, (left * 257 + right * 65_537) as u32); - assert_k_c_reference(kind, &block, false); - } - } - } - } - - #[test] - fn pinned_ggml_q4_q5_k_aligned_unaligned_bulk_and_shape_contracts_match_rust() { - use leleka_quant_core::{q4_k, q5_k}; - let edges = [ - 0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, - 0x3800, 0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff, - ]; - for (kind, block_bytes) in [(12, q4_k::BLOCK_BYTES), (13, q5_k::BLOCK_BYTES)] { - for unaligned in [false, true] { - let mut storage = vec![0u8; edges.len() * block_bytes + 16]; - let start = storage.as_ptr().align_offset(16) + usize::from(unaligned); - let source = &mut storage[start..start + edges.len() * block_bytes]; - assert_eq!( - source.as_ptr().align_offset(16), - if unaligned { 15 } else { 0 } - ); - for (number, d) in edges.into_iter().enumerate() { - source[number * block_bytes..(number + 1) * block_bytes].copy_from_slice( - &synthetic_k_block( - kind, - d, - edges[(number * 7 + 3) % edges.len()], - number as u32 * 65_537, - ), - ); - } - let mut reference = vec![0.0; edges.len() * 256]; - let mut actual = vec![0.0; reference.len()]; - decode_into(kind, source, &mut reference).unwrap(); - if kind == 12 { - q4_k::decode_into(source, &mut actual).unwrap(); - } else { - q5_k::decode_into(source, &mut actual).unwrap(); - } - for (actual, reference) in actual.iter().zip(&reference) { - assert_eq!(actual.to_bits(), reference.to_bits()); - } - for (input_len, output_len) in [ - (source.len() - 1, actual.len()), - (source.len(), actual.len() - 1), - (source.len(), actual.len() + 1), - ] { - let mut output = vec![123.0; output_len]; - let result = if kind == 12 { - q4_k::decode_into(&source[..input_len], &mut output) - } else { - q5_k::decode_into(&source[..input_len], &mut output) - }; - assert!(result.is_err()); - assert!(output.iter().all(|value| *value == 123.0)); - assert!(decode_into(kind, &source[..input_len], &mut output).is_err()); - assert!(output.iter().all(|value| *value == 123.0)); - } - } - } - } - - // The field generator does not call either Rust decoder or its unpack helper. - fn synthetic_q6_q2_block(kind: u32, bits: u16, pattern: u32) -> Vec { - if kind == 42 { - let mut block = vec![0u8; 18]; - block[..2].copy_from_slice(&bits.to_le_bytes()); - for (lane, byte) in block[2..].iter_mut().enumerate() { - for field in 0..4 { - *byte |= (((pattern as usize + lane + field) & 3) as u8) << (field * 2); - } - } - block - } else { - assert_eq!(kind, 14); - let mut block = vec![0u8; 210]; - block[208..].copy_from_slice(&bits.to_le_bytes()); - for scale in 0..16 { - block[192 + scale] = (pattern >> 6) as u8; - block[192 + scale] = block[192 + scale].wrapping_add((scale * 17) as u8); - } - for half in 0..2 { - for quadrant in 0..4 { - for lane in 0..32 { - let position = half * 128 + quadrant * 32 + lane; - let code = ((pattern as usize + position * 13) & 63) as u8; - let low_index = half * 64 + (quadrant % 2) * 32 + lane; - block[low_index] |= (code & 15) << ((quadrant / 2) * 4); - block[128 + half * 32 + lane] |= (code >> 4) << (quadrant * 2); - } - } - } - block - } - } - - fn rust_q6_q2_into(kind: u32, source: &[u8], output: &mut [f32]) -> Result<(), String> { - if kind == 14 { - leleka_quant_core::q6_k::decode_into(source, output) - } else { - assert_eq!(kind, 42); - leleka_quant_core::q2_0::decode_into(source, output) - } - } - - fn assert_q6_q2_c_bits(kind: u32, source: &[u8], finite: bool) { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - let mut expected = vec![0.0; source.len() / bytes as usize * elements as usize]; - let mut actual = vec![0.0; expected.len()]; - decode_into(kind, source, &mut expected).unwrap(); - rust_q6_q2_into(kind, source, &mut actual).unwrap(); - for (position, (actual, expected)) in actual.iter().zip(&expected).enumerate() { - if finite { - assert!(actual.is_finite() && expected.is_finite()); - } - if expected.is_nan() { - assert!(actual.is_nan(), "kind {kind} position {position}"); - } else { - assert_eq!( - actual.to_bits(), - expected.to_bits(), - "kind {kind} position {position}" - ); - } - } - } - - #[test] - fn pinned_ggml_q6_q2_all_finite_fp16_scales_match_exact_c_bits() { - let mut scales = 0; - for bits in 0..=u16::MAX { - if bits & 0x7c00 == 0x7c00 { - continue; - } - assert_q6_q2_c_bits(14, &synthetic_q6_q2_block(14, bits, u32::from(bits)), true); - // Four blocks exercise every Q2 code at every consecutive output position. - for pattern in 0..4 { - assert_q6_q2_c_bits(42, &synthetic_q6_q2_block(42, bits, pattern), true); - } - scales += 1; - } - assert_eq!(scales, 63_488); - } - - #[test] - fn pinned_ggml_q6_signed_subscale_quant_pairs_cover_every_output_position() { - let mut pairs = vec![vec![false; 256 * 64]; 256]; - for pattern in 0..16_384u32 { - let block = synthetic_q6_q2_block(14, 0xb555, pattern); - assert_q6_q2_c_bits(14, &block, true); - for (position, seen) in pairs.iter_mut().enumerate() { - let half = position / 128; - let quadrant = position % 128 / 32; - let lane = position % 32; - let low = block[half * 64 + (quadrant % 2) * 32 + lane]; - let high = block[128 + half * 32 + lane]; - let code = - ((low >> ((quadrant / 2) * 4)) & 15) | (((high >> (quadrant * 2)) & 3) << 4); - let scale = block[192 + half * 8 + quadrant * 2 + lane / 16]; - seen[usize::from(scale) * 64 + usize::from(code)] = true; - } - } - for (position, seen) in pairs.iter().enumerate() { - assert!( - seen.iter().all(|value| *value), - "half/quadrant/lane position {position}" - ); - } - } - - #[test] - fn pinned_ggml_q6_q2_raw_fields_cover_all_bytes_and_q2_consecutive_codes() { - for kind in [14, 42] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - let fields = if kind == 14 { 208 } else { 16 }; - let start = if kind == 14 { 0 } else { 2 }; - let mut raw_seen = vec![[false; 256]; fields]; - let mut codes_seen = vec![[false; 4]; 64]; - for pattern in 0..=u8::MAX { - let mut block = vec![0u8; bytes as usize]; - let header = if kind == 14 { 208 } else { 0 }; - block[header..header + 2].copy_from_slice(&0x3555u16.to_le_bytes()); - for field in 0..fields { - let byte = pattern - .wrapping_mul((field * 2 + 1) as u8) - .rotate_left((field % 8) as u32) - .wrapping_add((field * 19) as u8); - block[start + field] = byte; - raw_seen[field][usize::from(byte)] = true; - } - if kind == 42 { - for (position, seen) in codes_seen.iter_mut().enumerate() { - let code = (block[2 + position / 4] >> ((position % 4) * 2)) & 3; - seen[usize::from(code)] = true; - } - } - assert_q6_q2_c_bits(kind, &block, true); - } - assert!(raw_seen.iter().all(|seen| seen.iter().all(|value| *value))); - if kind == 42 { - assert_eq!(elements, 64); - assert!( - codes_seen - .iter() - .all(|seen| seen.iter().all(|value| *value)) - ); - } - } - } - - #[test] - fn pinned_ggml_q6_q2_all_nonfinite_headers_and_zero_factors_preserve_c_values() { - let mut headers = 0; - for bits in 0..=u16::MAX { - if bits & 0x7c00 != 0x7c00 { - continue; - } - let mut block = synthetic_q6_q2_block(14, bits, u32::from(bits)); - assert_q6_q2_c_bits(14, &block, false); - // Zero subscale and zero signed quant independently reach Inf*zero. - block[192..208].fill(0); - assert_q6_q2_c_bits(14, &block, false); - block[192..208].fill(1); - block[..128].fill(0); - block[128..192].fill(0xaa); // each high field 2, low 0 -> signed quant 0 - assert_q6_q2_c_bits(14, &block, false); - for pattern in 0..4 { - assert_q6_q2_c_bits(42, &synthetic_q6_q2_block(42, bits, pattern), false); - } - headers += 1; - } - assert_eq!(headers, 2048); - } - - #[test] - fn pinned_ggml_q6_q2_aligned_unaligned_bulk_and_shape_sentinels_match() { - let edges = [ - 0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, - 0x3800, 0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff, - ]; - for kind in [14, 42] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - let bytes = bytes as usize; - for unaligned in [false, true] { - let mut storage = vec![0; edges.len() * bytes + 16]; - let start = storage.as_ptr().align_offset(16) + usize::from(unaligned); - let source = &mut storage[start..start + edges.len() * bytes]; - assert_eq!( - source.as_ptr().align_offset(16), - if unaligned { 15 } else { 0 } - ); - for (number, bits) in edges.into_iter().enumerate() { - source[number * bytes..(number + 1) * bytes] - .copy_from_slice(&synthetic_q6_q2_block(kind, bits, number as u32 * 257)); - } - assert_q6_q2_c_bits(kind, source, true); - let outputs = edges.len() * elements as usize; - for (input_len, output_len) in [ - (0, outputs), - (source.len() - 1, outputs), - (source.len(), outputs - 1), - (source.len(), outputs + 1), - ] { - let mut output = vec![123.0; output_len]; - assert!(rust_q6_q2_into(kind, &source[..input_len], &mut output).is_err()); - assert!(output.iter().all(|value| *value == 123.0)); - assert!(decode_into(kind, &source[..input_len], &mut output).is_err()); - assert!(output.iter().all(|value| *value == 123.0)); - } - } - } - } - - fn pinned_c_table_bytes(name: &str, count: usize, width: usize) -> Vec { - let source = include_str!("../third_party/ggml/ggml-common.h"); - let marker = format!(", {name}, {count})"); - let body = source - .split_once(&marker) - .unwrap() - .1 - .split_once("GGML_TABLE_END()") - .unwrap() - .0; - let values: Vec = body - .split(',') - .map(str::trim) - .filter(|v| !v.is_empty()) - .map(|v| { - if let Some(hex) = v.strip_prefix("0x") { - u64::from_str_radix(hex, 16).unwrap() - } else { - v.parse().unwrap() - } - }) - .collect(); - assert_eq!(values.len(), count); - values - .iter() - .flat_map(|value| value.to_le_bytes()[..width].to_vec()) - .collect() - } - - #[test] - fn pinned_c_iq2s_iq3xxs_complete_grid_sign_and_mask_bytes_match_port_provenance() { - use sha2::{Digest, Sha256}; - for (name, count, width, digest) in [ - ( - "iq2s_grid", - 1024, - 8, - "e1aa1473412b0552c2174c30ef22ab4073f6a181b85a17056e8249bd2932fd88", - ), - ( - "iq3xxs_grid", - 256, - 4, - "46e35f5a997efdee6c99ce57854c8a0d4f0ff8ca57e5e8a60c0793ea580acf5d", - ), - ( - "ksigns_iq2xs", - 128, - 1, - "a76742a603f8beca5212ecce0f1f02f11a4887fd2f7c8b15aca0ea3eb3380c31", - ), - ( - "kmask_iq2xs", - 8, - 1, - "5ac9831b2e30eb285ef34f8501620f878432d5c04331ad1ae47f977a83ba41a5", - ), - ] { - let bytes = pinned_c_table_bytes(name, count, width); - assert_eq!(hex::encode(Sha256::digest(&bytes)), digest); - if name.ends_with("_grid") { - assert!(bytes.iter().all(|value| *value != 0)); - } - } - } - - // Independently pack wire fields; neither decoder nor its tables/helpers generate inputs. - fn synthetic_iq2s_iq3xxs_block(kind: u32, bits: u16, pattern: usize) -> Vec { - let mut block = vec![0u8; if kind == 22 { 82 } else { 98 }]; - block[..2].copy_from_slice(&bits.to_le_bytes()); - if kind == 22 { - for group in 0..32 { - let grid = (pattern + group * 17) & 1023; - block[2 + group] = grid as u8; - block[66 + group / 4] |= ((grid >> 8) as u8) << ((group % 4) * 2); - block[34 + group] = (pattern + group * 29) as u8; - } - for subblock in 0..8 { - block[74 + subblock] = - (((pattern + subblock) & 15) | ((((pattern >> 4) + subblock) & 15) << 4)) as u8; - } - } else { - assert_eq!(kind, 18); - for field in 0..64 { - block[2 + field] = (pattern + field * 17) as u8; - } - for subblock in 0..8 { - let mut word = ((((pattern >> 7) + subblock) & 15) as u32) << 28; - for group in 0..4 { - word |= (((pattern + group * 17 + subblock * 29) & 127) as u32) << (group * 7); - } - block[66 + subblock * 4..70 + subblock * 4].copy_from_slice(&word.to_le_bytes()); - } - } - block - } - - fn rust_iq2s_iq3xxs_into(kind: u32, source: &[u8], output: &mut [f32]) -> Result<(), String> { - if kind == 22 { - leleka_quant_core::iq2_s::decode_into(source, output) - } else { - assert_eq!(kind, 18); - leleka_quant_core::iq3_xxs::decode_into(source, output) - } - } - - fn assert_iq2s_iq3xxs_c_bits(kind: u32, source: &[u8], finite: bool) { - let bytes = if kind == 22 { 82 } else { 98 }; - let mut expected = vec![0.0; source.len() / bytes * 256]; - let mut actual = vec![0.0; expected.len()]; - decode_into(kind, source, &mut expected).unwrap(); - rust_iq2s_iq3xxs_into(kind, source, &mut actual).unwrap(); - for (position, (actual, expected)) in actual.iter().zip(&expected).enumerate() { - if finite { - assert!(actual.is_finite() && expected.is_finite()); - } - if expected.is_nan() { - assert!(actual.is_nan(), "kind {kind} position {position}"); - } else { - assert_eq!( - actual.to_bits(), - expected.to_bits(), - "kind {kind} position {position}" - ); - } - } - } - - #[test] - fn pinned_ggml_iq2s_iq3xxs_every_finite_fp16_matches_c_bits() { - let mut headers = 0; - for bits in 0..=u16::MAX { - if bits & 0x7c00 == 0x7c00 { - continue; - } - for kind in [22, 18] { - assert_iq2s_iq3xxs_c_bits( - kind, - &synthetic_iq2s_iq3xxs_block(kind, bits, usize::from(bits)), - true, - ); - } - headers += 1; - } - assert_eq!(headers, 63_488); - } - - #[test] - fn pinned_ggml_iq2s_iq3xxs_all_grid_sign_subscale_positions_match_c_bits() { - let c_signs = pinned_c_table_bytes("ksigns_iq2xs", 128, 1); - for kind in [22, 18] { - let grid_count = if kind == 22 { 1024 } else { 256 }; - let group_count = if kind == 22 { 32 } else { 64 }; - let sign_count = if kind == 22 { 256 } else { 128 }; - let mut grids = vec![vec![false; grid_count]; group_count]; - let mut signs = vec![vec![false; sign_count]; 32]; - let mut scale = vec![[false; 16]; if kind == 22 { 16 } else { 8 }]; - let mut output_signs = vec![[false; 2]; 256]; - for pattern in 0..if kind == 22 { 1024 } else { 2048 } { - let block = synthetic_iq2s_iq3xxs_block(kind, 0xb555, pattern); - assert_iq2s_iq3xxs_c_bits(kind, &block, true); - for group in 0..32 { - let sign = if kind == 22 { - let grid = usize::from(block[2 + group]) - | (usize::from((block[66 + group / 4] >> ((group % 4) * 2)) & 3) << 8); - grids[group][grid] = true; - let sign = usize::from(block[34 + group]); - signs[group][sign] = true; - sign as u8 - } else { - let subblock = group / 4; - let word = u32::from_le_bytes( - block[66 + subblock * 4..70 + subblock * 4] - .try_into() - .unwrap(), - ); - let code = ((word >> ((group % 4) * 7)) & 127) as usize; - signs[group][code] = true; - grids[group * 2][usize::from(block[2 + group * 2])] = true; - grids[group * 2 + 1][usize::from(block[3 + group * 2])] = true; - c_signs[code] - }; - for lane in 0..8 { - output_signs[group * 8 + lane][usize::from((sign >> lane) & 1)] = true; - } - } - for (position, seen) in scale.iter_mut().enumerate() { - let code = if kind == 22 { - (block[74 + position / 2] >> ((position % 2) * 4)) & 15 - } else { - let word = u32::from_le_bytes( - block[66 + position * 4..70 + position * 4] - .try_into() - .unwrap(), - ); - (word >> 28) as u8 - }; - seen[usize::from(code)] = true; - } - } - assert!(grids.iter().all(|seen| seen.iter().all(|v| *v))); - assert!(signs.iter().all(|seen| seen.iter().all(|v| *v))); - assert!(scale.iter().all(|seen| seen.iter().all(|v| *v))); - assert!(output_signs.iter().all(|seen| seen.iter().all(|v| *v))); - } - } - - #[test] - fn pinned_ggml_iq2s_iq3xxs_every_raw_field_byte_matches_c_bits() { - for kind in [22, 18] { - let bytes = if kind == 22 { 82 } else { 98 }; - let mut seen = vec![[false; 256]; bytes - 2]; - for pattern in 0..=u8::MAX { - let mut block = vec![0; bytes]; - block[..2].copy_from_slice(&0x3555u16.to_le_bytes()); - for (field, flags) in seen.iter_mut().enumerate() { - let value = pattern - .wrapping_mul((field * 2 + 1) as u8) - .rotate_left((field % 8) as u32) - .wrapping_add((field * 19) as u8); - block[2 + field] = value; - flags[usize::from(value)] = true; - } - assert_iq2s_iq3xxs_c_bits(kind, &block, true); - } - assert!(seen.iter().all(|seen| seen.iter().all(|v| *v))); - } - } - - #[test] - fn pinned_ggml_iq2s_iq3xxs_all_nonfinite_headers_and_zero_fields_preserve_c_values() { - let mut headers = 0; - for bits in 0..=u16::MAX { - if bits & 0x7c00 != 0x7c00 { - continue; - } - for kind in [22, 18] { - let mut block = synthetic_iq2s_iq3xxs_block(kind, bits, usize::from(bits)); - assert_iq2s_iq3xxs_c_bits(kind, &block, false); - block[2..].fill(0); - assert_iq2s_iq3xxs_c_bits(kind, &block, false); - } - headers += 1; - } - assert_eq!(headers, 2048); - } - - #[test] - fn pinned_ggml_iq2s_iq3xxs_aligned_unaligned_bulk_and_shape_sentinels_match() { - let edges = [ - 0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, - 0x3800, 0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff, - ]; - for kind in [22, 18] { - let bytes = if kind == 22 { 82 } else { 98 }; - for unaligned in [false, true] { - let mut storage = vec![0; edges.len() * bytes + 16]; - let start = storage.as_ptr().align_offset(16) + usize::from(unaligned); - let source = &mut storage[start..start + edges.len() * bytes]; - assert_eq!( - source.as_ptr().align_offset(16), - if unaligned { 15 } else { 0 } - ); - for (number, bits) in edges.into_iter().enumerate() { - source[number * bytes..(number + 1) * bytes] - .copy_from_slice(&synthetic_iq2s_iq3xxs_block(kind, bits, number * 257)); - } - assert_iq2s_iq3xxs_c_bits(kind, source, true); - let outputs = edges.len() * 256; - for (input_len, output_len) in [ - (0, outputs), - (source.len() - 1, outputs), - (source.len(), outputs - 1), - (source.len(), outputs + 1), - ] { - let mut output = vec![123.0; output_len]; - assert!( - rust_iq2s_iq3xxs_into(kind, &source[..input_len], &mut output).is_err() - ); - assert!(output.iter().all(|value| *value == 123.0)); - assert!(decode_into(kind, &source[..input_len], &mut output).is_err()); - assert!(output.iter().all(|value| *value == 123.0)); - } - } - } - } -} +mod tests; diff --git a/control-plane/src/ggml_bridge/tests.rs b/control-plane/src/ggml_bridge/tests.rs new file mode 100644 index 00000000..7c2313f1 --- /dev/null +++ b/control-plane/src/ggml_bridge/tests.rs @@ -0,0 +1,1291 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::iq3_s; + +#[test] +fn pinned_ggml_block_sizes_match_gguf_geometry() { + for kind in [ + 2, 3, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22, 23, 29, 42, + ] { + assert_eq!( + u64::from(unsafe { strata_ggml_block_bytes(kind) }), + gguf::block_geometry(kind).unwrap().1, + "kind {kind}" + ); + } +} + +#[test] +fn pinned_ggml_iq3_matches_independent_rust_decoder() { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in block[2..66].iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(3); + } + block[74] = 0x55; + let mut decoded = [0.0f32; 256]; + decode_into(21, &block, &mut decoded).unwrap(); + assert_eq!(decoded, iq3_s::decode_block(&block).unwrap()); +} + +// Generated packed fields only: no model weights, captures or external RNG. +// Each scale gets a reproducible field pattern independent of either decoder. +fn synthetic_iq3_block(scale_bits: u16, pattern: u32) -> [u8; iq3_s::BLOCK_BYTES] { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&scale_bits.to_le_bytes()); + let low = pattern as u8; + let high = pattern >> 8; + for (field, byte) in block[2..].iter_mut().enumerate() { + // For any fixed high byte, odd multiplication, rotation and addition + // form a bijection of all 256 low-byte values at every field position. + let odd = (2 * field + 1) as u8; + let salt = high + .wrapping_mul(0x85eb_ca6b) + .wrapping_add((field as u32).wrapping_mul(0x9e37_79b9)); + *byte = low + .wrapping_mul(odd) + .rotate_left((field % 8) as u32) + .wrapping_add((salt ^ (salt >> 16)) as u8); + } + block +} + +fn assert_exact_iq3_bits(block: &[u8; iq3_s::BLOCK_BYTES], case: u32) { + let mut reference = [0.0f32; iq3_s::BLOCK_ELEMENTS]; + decode_into(21, block, &mut reference).unwrap(); + let actual = iq3_s::decode_block(block).unwrap(); + let scale_bits = u16::from_le_bytes([block[0], block[1]]); + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + assert!(actual.is_finite() && reference.is_finite()); + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "case={case} scale_bits={scale_bits:#06x} element={element} block={block:?}" + ); + } +} + +#[test] +fn pinned_ggml_iq3_matches_rust_bits_for_every_finite_fp16_scale() { + // Exhaust all 63,488 finite binary16 encodings, including both signed + // zeros, every subnormal/normal and both signs of the maximum finite. + let mut low_fields = [[false; 256]; 64]; + let mut high_fields = [[false; 256]; 8]; + let mut sign_fields = [[false; 256]; 32]; + let mut scale_nibbles = [[false; 16]; 8]; + let mut grid_indexes = [false; 512]; + let mut compared = 0; + for scale_bits in 0..=u16::MAX { + if scale_bits & 0x7c00 == 0x7c00 { + continue; + } + let block = synthetic_iq3_block(scale_bits, u32::from(scale_bits)); + assert_exact_iq3_bits(&block, u32::from(scale_bits)); + for (field, value) in block[2..66].iter().enumerate() { + low_fields[field][usize::from(*value)] = true; + } + for (field, value) in block[66..74].iter().enumerate() { + high_fields[field][usize::from(*value)] = true; + } + for (field, value) in block[74..106].iter().enumerate() { + sign_fields[field][usize::from(*value)] = true; + } + for subblock in 0..8 { + let nibble = (block[106 + subblock / 2] >> (4 * (subblock % 2))) & 15; + scale_nibbles[subblock][usize::from(nibble)] = true; + for part in 0..8 { + let grid = usize::from(block[2 + 8 * subblock + part]) + | (usize::from((block[66 + subblock] >> part) & 1) << 8); + grid_indexes[grid] = true; + } + } + compared += 1; + } + assert_eq!(compared, 63_488); + assert!(low_fields.iter().flatten().all(|seen| *seen)); + assert!(high_fields.iter().flatten().all(|seen| *seen)); + assert!(sign_fields.iter().flatten().all(|seen| *seen)); + assert!(scale_nibbles.iter().flatten().all(|seen| *seen)); + assert!(grid_indexes.iter().all(|seen| *seen)); +} + +#[test] +fn pinned_ggml_iq3_batch_bits_match_rust_with_unaligned_source() { + let scales = [ + 0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00, + 0xbc00, 0x7bff, 0xfbff, + ]; + let length = scales.len() * iq3_s::BLOCK_BYTES; + let mut storage = vec![0u8; length + 16]; + let start = storage.as_ptr().align_offset(16) + 1; + let source = &mut storage[start..start + length]; + assert_eq!(source.as_ptr().align_offset(16), 15); + for (number, scale) in scales.into_iter().enumerate() { + let block = synthetic_iq3_block(scale, number as u32 + 70_000); + source[number * iq3_s::BLOCK_BYTES..(number + 1) * iq3_s::BLOCK_BYTES] + .copy_from_slice(&block); + } + let mut reference = vec![0.0f32; scales.len() * iq3_s::BLOCK_ELEMENTS]; + let mut actual = vec![0.0f32; reference.len()]; + decode_into(21, source, &mut reference).unwrap(); + iq3_s::decode_into(source, &mut actual).unwrap(); + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "batch element={element}" + ); + } +} + +#[test] +fn independent_rust_iq3_refuses_every_nonfinite_fp16_scale() { + // GGML may decode these; Rust's existing refusal is deliberately retained. + let mut rejected = 0; + for scale_bits in 0..=u16::MAX { + if scale_bits & 0x7c00 != 0x7c00 { + continue; + } + let block = synthetic_iq3_block(scale_bits, u32::from(scale_bits)); + assert_eq!( + iq3_s::decode_block(&block).unwrap_err(), + "IQ3_S block has a non-finite scale" + ); + assert!(iq3_s::decode_into(&block, &mut [0.0; iq3_s::BLOCK_ELEMENTS]).is_err()); + rejected += 1; + } + assert_eq!(rejected, 2_048); +} + +// Each half covers all 16 IQ4_NL codepoints for every scale. Over patterns +// 0..256 each field additionally covers every low/high nibble combination. +fn synthetic_iq4_block(scale_bits: u16, pattern: u32) -> [u8; 18] { + let mut block = [0u8; 18]; + block[..2].copy_from_slice(&scale_bits.to_le_bytes()); + for (field, byte) in block[2..].iter_mut().enumerate() { + let low = (field as u8).wrapping_add(pattern as u8) & 15; + let high = (15 - field as u8).wrapping_add((pattern >> 4) as u8) & 15; + *byte = low | (high << 4); + } + block +} + +#[test] +fn pinned_ggml_iq4_matches_rust_bits_for_every_finite_fp16_scale() { + use leleka_quant_core::iq4_nl; + let mut packed_fields = [[false; 256]; 16]; + let mut codepoints = [[false; 16]; 32]; + let mut compared = 0; + for scale_bits in 0..=u16::MAX { + if scale_bits & 0x7c00 == 0x7c00 { + continue; + } + let block = synthetic_iq4_block(scale_bits, u32::from(scale_bits)); + let mut reference = [0.0; iq4_nl::BLOCK_ELEMENTS]; + decode_into(20, &block, &mut reference).unwrap(); + let actual = iq4_nl::decode_block(&block).unwrap(); + let mut low_seen = [false; 16]; + let mut high_seen = [false; 16]; + for (field, byte) in block[2..].iter().enumerate() { + packed_fields[field][usize::from(*byte)] = true; + codepoints[field][usize::from(byte & 15)] = true; + codepoints[field + 16][usize::from(byte >> 4)] = true; + low_seen[usize::from(byte & 15)] = true; + high_seen[usize::from(byte >> 4)] = true; + } + assert!(low_seen.into_iter().all(|seen| seen)); + assert!(high_seen.into_iter().all(|seen| seen)); + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + assert!(actual.is_finite() && reference.is_finite()); + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "IQ4_NL scale={scale_bits:#06x} element={element} block={block:?}" + ); + } + compared += 1; + } + assert_eq!(compared, 63_488); + assert!(packed_fields.iter().flatten().all(|seen| *seen)); + assert!(codepoints.iter().flatten().all(|seen| *seen)); +} + +#[test] +fn pinned_ggml_iq4_batch_bits_match_rust_with_unaligned_source() { + use leleka_quant_core::iq4_nl; + let scales = [ + 0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00, + 0xbc00, 0x7bff, 0xfbff, + ]; + let length = scales.len() * iq4_nl::BLOCK_BYTES; + let mut storage = vec![0u8; length + 16]; + let start = storage.as_ptr().align_offset(16) + 1; + let source = &mut storage[start..start + length]; + assert_eq!(source.as_ptr().align_offset(16), 15); + for (number, scale) in scales.into_iter().enumerate() { + source[number * iq4_nl::BLOCK_BYTES..(number + 1) * iq4_nl::BLOCK_BYTES] + .copy_from_slice(&synthetic_iq4_block(scale, number as u32 + 70_000)); + } + let mut actual = vec![0.0; scales.len() * iq4_nl::BLOCK_ELEMENTS]; + let mut reference = vec![0.0; actual.len()]; + decode_into(20, source, &mut reference).unwrap(); + iq4_nl::decode_into(source, &mut actual).unwrap(); + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "IQ4_NL batch element={element}" + ); + } +} + +#[test] +fn pinned_ggml_iq4_nonfinite_classification_matches_rust_without_refusal() { + use leleka_quant_core::iq4_nl; + let mut compared = 0; + for scale_bits in 0..=u16::MAX { + if scale_bits & 0x7c00 != 0x7c00 { + continue; + } + let block = synthetic_iq4_block(scale_bits, u32::from(scale_bits)); + let mut reference = [0.0; iq4_nl::BLOCK_ELEMENTS]; + let mut actual = [0.0; iq4_nl::BLOCK_ELEMENTS]; + decode_into(20, &block, &mut reference).unwrap(); + iq4_nl::decode_into(&block, &mut actual).unwrap(); + let single = iq4_nl::decode_block(&block).unwrap(); + for (element, ((actual, single), reference)) in + actual.iter().zip(&single).zip(&reference).enumerate() + { + if scale_bits & 0x03ff == 0 { + assert!(actual.is_infinite() && reference.is_infinite()); + assert_eq!(actual.to_bits(), reference.to_bits()); + assert_eq!(single.to_bits(), reference.to_bits()); + } else { + // No cross-platform NaN payload/sign contract is inferred + // from classification. Neither decoder refuses these scales. + assert!( + actual.is_nan() && single.is_nan() && reference.is_nan(), + "IQ4_NL nonfinite scale={scale_bits:#06x} element={element}" + ); + } + } + compared += 1; + } + assert_eq!(compared, 2_048); +} + +#[test] +fn q8_0_and_q2_0_match_known_block_values() { + let mut q8 = [0u8; 34]; + q8[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in q8[2..].iter_mut().enumerate() { + *byte = (index as i8 - 16) as u8; + } + let mut values = [0.0f32; 32]; + decode_into(8, &q8, &mut values).unwrap(); + assert_eq!(values[0], -16.0); + assert_eq!(values[31], 15.0); + + let mut q2 = [0u8; 18]; + q2[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let mut values = [0.0f32; 64]; + decode_into(42, &q2, &mut values).unwrap(); + assert!(values.iter().all(|value| *value == -1.0)); +} + +fn q8_corpus(scale: u16) -> [u8; 8 * 34] { + let mut source = [0u8; 8 * 34]; + for (group, block) in source.as_chunks_mut::<34>().0.iter_mut().enumerate() { + block[..2].copy_from_slice(&scale.to_le_bytes()); + for (position, byte) in block[2..].iter_mut().enumerate() { + *byte = (group as u8 * 32 + position as u8).wrapping_add(scale as u8); + } + } + source +} + +#[test] +fn pinned_ggml_q8_matches_rust_bits_for_every_finite_scale_and_signed_codepoint() { + use leleka_quant_core::q8_0; + let mut position_codes = [[false; 256]; 32]; + let mut compared = 0; + for scale in 0..=u16::MAX { + if scale & 0x7c00 == 0x7c00 { + continue; + } + let source = q8_corpus(scale); + let mut reference = [0.0; 256]; + let mut actual = [0.0; 256]; + decode_into(8, &source, &mut reference).unwrap(); + q8_0::decode_into(&source, &mut actual).unwrap(); + let mut scale_codes = [false; 256]; + for block in source.as_chunks::<34>().0 { + for (position, code) in block[2..].iter().enumerate() { + position_codes[position][usize::from(*code)] = true; + scale_codes[usize::from(*code)] = true; + } + } + assert!(scale_codes.into_iter().all(|seen| seen)); + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + assert!(actual.is_finite() && reference.is_finite()); + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "Q8_0 scale={scale:#06x} element={element}" + ); + } + compared += 1; + } + assert_eq!(compared, 63_488); + assert!(position_codes.iter().flatten().all(|seen| *seen)); +} + +#[test] +fn pinned_ggml_q8_nonfinite_including_zero_matches_rust_classification_and_inf_signs() { + use leleka_quant_core::q8_0; + let mut compared = 0; + for scale in 0..=u16::MAX { + if scale & 0x7c00 != 0x7c00 { + continue; + } + let source = q8_corpus(scale); + let mut reference = [0.0; 256]; + let mut actual = [0.0; 256]; + decode_into(8, &source, &mut reference).unwrap(); + q8_0::decode_into(&source, &mut actual).unwrap(); + let mut nan_count = 0; + for (actual, reference) in actual.iter().zip(&reference) { + if reference.is_nan() { + assert!(actual.is_nan()); + nan_count += 1; + } else { + assert!(actual.is_infinite() && reference.is_infinite()); + assert_eq!(actual.to_bits(), reference.to_bits()); + } + } + assert_eq!(nan_count, if scale & 0x03ff == 0 { 1 } else { 256 }); + compared += 1; + } + assert_eq!(compared, 2_048); +} + +fn iq4xs_corpus(scale: u16, group: usize) -> [u8; 136] { + let mut block = [0u8; 136]; + block[..2].copy_from_slice(&scale.to_le_bytes()); + let mut high = 0u16; + for subblock in 0..8 { + let six = (group * 8 + subblock + usize::from(scale)) & 63; + block[4 + subblock / 2] |= ((six & 15) as u8) << (4 * (subblock % 2)); + high |= ((six >> 4) as u16) << (2 * subblock); + for position in 0..16 { + let low = (position + usize::from(scale) + group) & 15; + let upper = (15 - position + (usize::from(scale) >> 4) + group) & 15; + block[8 + subblock * 16 + position] = low as u8 | ((upper as u8) << 4); + } + } + block[2..4].copy_from_slice(&high.to_le_bytes()); + block +} + +#[test] +fn pinned_ggml_iq4xs_matches_rust_bits_for_every_finite_scale_subscale_and_codepoint() { + use leleka_quant_core::iq4_xs; + let mut subscales = [[false; 64]; 8]; + let mut packed_fields = [[false; 256]; 128]; + let mut codepoints = [[false; 16]; 256]; + let mut compared = 0; + for scale in 0..=u16::MAX { + if scale & 0x7c00 == 0x7c00 { + continue; + } + let mut scale_subscales = [false; 64]; + for group in 0..8 { + let block = iq4xs_corpus(scale, group); + let high = u16::from_le_bytes([block[2], block[3]]); + for subblock in 0..8 { + let six = usize::from((block[4 + subblock / 2] >> (4 * (subblock % 2))) & 15) + | (usize::from((high >> (2 * subblock)) & 3) << 4); + subscales[subblock][six] = true; + scale_subscales[six] = true; + let mut low_seen = [false; 16]; + let mut high_seen = [false; 16]; + for position in 0..16 { + let field = subblock * 16 + position; + let packed = block[8 + field]; + packed_fields[field][usize::from(packed)] = true; + codepoints[subblock * 32 + position][usize::from(packed & 15)] = true; + codepoints[subblock * 32 + position + 16][usize::from(packed >> 4)] = true; + low_seen[usize::from(packed & 15)] = true; + high_seen[usize::from(packed >> 4)] = true; + } + assert!(low_seen.into_iter().all(|seen| seen)); + assert!(high_seen.into_iter().all(|seen| seen)); + } + let mut reference = [0.0; iq4_xs::BLOCK_ELEMENTS]; + decode_into(23, &block, &mut reference).unwrap(); + let actual = iq4_xs::decode_block(&block).unwrap(); + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + assert!(actual.is_finite() && reference.is_finite()); + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "IQ4_XS scale={scale:#06x} group={group} element={element}" + ); + } + } + assert!(scale_subscales.into_iter().all(|seen| seen)); + compared += 1; + } + assert_eq!(compared, 63_488); + assert!(subscales.iter().flatten().all(|seen| *seen)); + assert!(packed_fields.iter().flatten().all(|seen| *seen)); + assert!(codepoints.iter().flatten().all(|seen| *seen)); +} + +#[test] +fn pinned_ggml_iq4xs_nonfinite_and_zero_subscale_match_rust_classification_and_inf_signs() { + use leleka_quant_core::iq4_xs; + let mut zero_positions = [false; 8]; + let mut compared = 0; + for scale in 0..=u16::MAX { + if scale & 0x7c00 != 0x7c00 { + continue; + } + let mut nan_count = 0; + for group in 0..8 { + let block = iq4xs_corpus(scale, group); + let mut reference = [0.0; iq4_xs::BLOCK_ELEMENTS]; + let mut actual = [0.0; iq4_xs::BLOCK_ELEMENTS]; + decode_into(23, &block, &mut reference).unwrap(); + iq4_xs::decode_into(&block, &mut actual).unwrap(); + let high = u16::from_le_bytes([block[2], block[3]]); + for subblock in 0..8 { + let six = ((block[4 + subblock / 2] >> (4 * (subblock % 2))) & 15) + | (((high >> (2 * subblock)) & 3) as u8) << 4; + zero_positions[subblock] |= six == 32; + } + for (actual, reference) in actual.iter().zip(&reference) { + if reference.is_nan() { + assert!(actual.is_nan()); + nan_count += 1; + } else { + assert!(actual.is_infinite() && reference.is_infinite()); + assert_eq!(actual.to_bits(), reference.to_bits()); + } + } + } + assert_eq!(nan_count, if scale & 0x03ff == 0 { 32 } else { 2048 }); + compared += 1; + } + assert_eq!(compared, 2_048); + assert!(zero_positions.into_iter().all(|seen| seen)); +} + +#[test] +fn pinned_ggml_q8_and_iq4xs_unaligned_batches_match_rust_bits() { + use leleka_quant_core::{iq4_xs, q8_0}; + for (kind, block_bytes, elements) in [ + (8, q8_0::BLOCK_BYTES, q8_0::BLOCK_ELEMENTS), + (23, iq4_xs::BLOCK_BYTES, iq4_xs::BLOCK_ELEMENTS), + ] { + let scales = [ + 0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, + 0x3c00, 0xbc00, 0x7bff, 0xfbff, + ]; + let mut storage = vec![0u8; scales.len() * block_bytes + 16]; + let start = storage.as_ptr().align_offset(16) + 1; + let source = &mut storage[start..start + scales.len() * block_bytes]; + assert_eq!(source.as_ptr().align_offset(16), 15); + for (number, scale) in scales.into_iter().enumerate() { + let destination = &mut source[number * block_bytes..(number + 1) * block_bytes]; + if kind == 8 { + destination.copy_from_slice(&q8_corpus(scale)[..34]); + } else { + destination.copy_from_slice(&iq4xs_corpus(scale, number % 8)); + } + } + let mut reference = vec![0.0; scales.len() * elements]; + let mut actual = vec![0.0; reference.len()]; + decode_into(kind, source, &mut reference).unwrap(); + if kind == 8 { + q8_0::decode_into(source, &mut actual).unwrap(); + } else { + iq4_xs::decode_into(source, &mut actual).unwrap(); + } + for (actual, reference) in actual.iter().zip(&reference) { + assert_eq!(actual.to_bits(), reference.to_bits()); + } + } +} + +// Independent packed fixtures: all expectations come from the pinned C oracle, +// never from the Rust decoder/helper or a generated Rust value table. +fn synthetic_k_block(kind: u32, d: u16, dmin: u16, pattern: u32) -> Vec { + let bytes = if kind == 12 { 144 } else { 176 }; + let mut block = vec![0u8; bytes]; + block[..2].copy_from_slice(&d.to_le_bytes()); + block[2..4].copy_from_slice(&dmin.to_le_bytes()); + for (position, byte) in block[4..16].iter_mut().enumerate() { + *byte = (pattern as u8) + .wrapping_mul((position * 2 + 1) as u8) + .rotate_left((position % 8) as u32) + .wrapping_add((pattern >> 8) as u8); + } + let quant_start = if kind == 12 { 16 } else { 48 }; + for pair in 0..4 { + for lane in 0..32 { + let low = (lane + pattern as usize + pair) & 15; + let high = (31 - lane + (pattern as usize >> 4) + pair) & 15; + block[quant_start + pair * 32 + lane] = low as u8 | ((high as u8) << 4); + } + } + if kind == 13 { + for (lane, byte) in block[16..48].iter_mut().enumerate() { + *byte = (pattern >> 8) as u8 ^ if lane >= 16 { 0xff } else { 0 }; + } + } + block +} + +fn assert_k_c_reference(kind: u32, block: &[u8], finite: bool) -> [f32; 256] { + use leleka_quant_core::{q4_k, q5_k}; + let mut reference = [0.0; 256]; + decode_into(kind, block, &mut reference).unwrap(); + let actual = match kind { + 12 => q4_k::decode_block(block.try_into().unwrap()).unwrap(), + 13 => q5_k::decode_block(block.try_into().unwrap()).unwrap(), + _ => unreachable!(), + }; + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + if finite { + assert!(actual.is_finite() && reference.is_finite()); + } + if reference.is_nan() { + assert!( + actual.is_nan(), + "kind={kind} element={element} block={block:?}" + ); + } else { + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "kind={kind} element={element} block={block:?}" + ); + } + } + actual +} + +#[test] +fn pinned_ggml_q4_q5_k_exhaust_each_finite_fp16_scale_role_separately() { + for kind in [12, 13] { + for vary_min in [false, true] { + let mut compared = 0; + for bits in 0..=u16::MAX { + if bits & 0x7c00 == 0x7c00 { + continue; + } + let (d, dmin) = if vary_min { + (0xbc00, bits) + } else { + (bits, 0x3800) + }; + let block = synthetic_k_block(kind, d, dmin, u32::from(bits)); + assert_k_c_reference(kind, &block, true); + compared += 1; + } + assert_eq!(compared, 63_488, "kind={kind} min_role={vary_min}"); + } + } +} + +#[test] +fn pinned_ggml_q4_q5_k_packed_fields_and_subscale_positions_match_rust_bits() { + for kind in [12, 13] { + let mut packed_scales = [[false; 256]; 12]; + let mut scales = [[false; 64]; 8]; + let mut minima = [[false; 64]; 8]; + let mut packed_quants = [[false; 256]; 128]; + let mut high_bytes = [[false; 256]; 32]; + let mut codes = [[false; 32]; 256]; + let quant_start = if kind == 12 { 16 } else { 48 }; + for pattern in 0..=u16::MAX { + let block = synthetic_k_block(kind, 0x3555, 0xb800, u32::from(pattern)); + assert_k_c_reference(kind, &block, true); + for (position, byte) in block[4..16].iter().enumerate() { + packed_scales[position][usize::from(*byte)] = true; + } + for subblock in 0..8 { + let (scale, minimum) = if subblock < 4 { + (block[4 + subblock] & 63, block[8 + subblock] & 63) + } else { + ( + (block[8 + subblock] & 15) | ((block[subblock] >> 6) << 4), + (block[8 + subblock] >> 4) | ((block[4 + subblock] >> 6) << 4), + ) + }; + scales[subblock][usize::from(scale)] = true; + minima[subblock][usize::from(minimum)] = true; + } + for pair in 0..4 { + let mut low_seen = [false; 32]; + let mut high_seen = [false; 32]; + for lane in 0..32 { + let field = pair * 32 + lane; + let packed = block[quant_start + field]; + packed_quants[field][usize::from(packed)] = true; + let high = if kind == 13 { block[16 + lane] } else { 0 }; + if kind == 13 { + high_bytes[lane][usize::from(high)] = true; + } + let low_code = + (packed & 15) | if high & (1 << (pair * 2)) != 0 { 16 } else { 0 }; + let high_code = + (packed >> 4) | if high & (2 << (pair * 2)) != 0 { 16 } else { 0 }; + codes[pair * 64 + lane][usize::from(low_code)] = true; + codes[pair * 64 + lane + 32][usize::from(high_code)] = true; + low_seen[usize::from(low_code)] = true; + high_seen[usize::from(high_code)] = true; + } + let limit = if kind == 12 { 16 } else { 32 }; + assert!(low_seen[..limit].iter().all(|seen| *seen)); + assert!(high_seen[..limit].iter().all(|seen| *seen)); + } + } + assert!(packed_scales.iter().flatten().all(|seen| *seen)); + assert!(scales.iter().flatten().all(|seen| *seen)); + assert!(minima.iter().flatten().all(|seen| *seen)); + assert!(packed_quants.iter().flatten().all(|seen| *seen)); + let limit = if kind == 12 { 16 } else { 32 }; + assert!( + codes + .iter() + .all(|position| position[..limit].iter().all(|seen| *seen)) + ); + if kind == 13 { + assert!(high_bytes.iter().flatten().all(|seen| *seen)); + } + } +} + +#[test] +fn pinned_ggml_q4_q5_k_joint_finite_edges_and_exact_cancellation_match_rust_bits() { + let edges = [ + 0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, + 0x3800, 0xb800, 0x3bff, 0xbbff, 0x3c00, 0xbc00, 0x3c01, 0xbc01, 0x7bff, 0xfbff, + ]; + for kind in [12, 13] { + for (left, d) in edges.into_iter().enumerate() { + for (right, dmin) in edges.into_iter().enumerate() { + let block = + synthetic_k_block(kind, d, dmin, (left * 257 + right * 65_537) as u32); + assert_k_c_reference(kind, &block, true); + } + } + for d in edges { + let mut block = synthetic_k_block(kind, d, d, 0); + block[4..12].fill(1); + block[12..16].fill(0x11); + let quant_start = if kind == 12 { 16 } else { 48 }; + if kind == 13 { + block[16..48].fill(0); + } + block[quant_start..].fill(0x11); + let actual = assert_k_c_reference(kind, &block, true); + assert!(actual.iter().all(|value| value.to_bits() == 0)); + } + } +} + +#[test] +fn pinned_ggml_q4_q5_k_nonfinite_scale_roles_and_joint_edges_preserve_c_values() { + let special = [ + 0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00, + ]; + for kind in [12, 13] { + for vary_min in [false, true] { + let mut compared = 0; + for bits in 0..=u16::MAX { + if bits & 0x7c00 != 0x7c00 { + continue; + } + let (d, dmin) = if vary_min { + (0x3c00, bits) + } else { + (bits, 0xbc00) + }; + let mut block = synthetic_k_block(kind, d, dmin, u32::from(bits)); + assert_k_c_reference(kind, &block, false); + // Explicit all-zero packed scale/minimum/quant values exercise + // Inf*zero and downstream subtraction instead of assuming Inf. + block[4..].fill(0); + assert_k_c_reference(kind, &block, false); + compared += 1; + } + assert_eq!(compared, 2_048); + } + for (left, d) in special.into_iter().enumerate() { + for (right, dmin) in special.into_iter().enumerate() { + let block = + synthetic_k_block(kind, d, dmin, (left * 257 + right * 65_537) as u32); + assert_k_c_reference(kind, &block, false); + } + } + } +} + +#[test] +fn pinned_ggml_q4_q5_k_aligned_unaligned_bulk_and_shape_contracts_match_rust() { + use leleka_quant_core::{q4_k, q5_k}; + let edges = [ + 0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, + 0x3800, 0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff, + ]; + for (kind, block_bytes) in [(12, q4_k::BLOCK_BYTES), (13, q5_k::BLOCK_BYTES)] { + for unaligned in [false, true] { + let mut storage = vec![0u8; edges.len() * block_bytes + 16]; + let start = storage.as_ptr().align_offset(16) + usize::from(unaligned); + let source = &mut storage[start..start + edges.len() * block_bytes]; + assert_eq!( + source.as_ptr().align_offset(16), + if unaligned { 15 } else { 0 } + ); + for (number, d) in edges.into_iter().enumerate() { + source[number * block_bytes..(number + 1) * block_bytes].copy_from_slice( + &synthetic_k_block( + kind, + d, + edges[(number * 7 + 3) % edges.len()], + number as u32 * 65_537, + ), + ); + } + let mut reference = vec![0.0; edges.len() * 256]; + let mut actual = vec![0.0; reference.len()]; + decode_into(kind, source, &mut reference).unwrap(); + if kind == 12 { + q4_k::decode_into(source, &mut actual).unwrap(); + } else { + q5_k::decode_into(source, &mut actual).unwrap(); + } + for (actual, reference) in actual.iter().zip(&reference) { + assert_eq!(actual.to_bits(), reference.to_bits()); + } + for (input_len, output_len) in [ + (source.len() - 1, actual.len()), + (source.len(), actual.len() - 1), + (source.len(), actual.len() + 1), + ] { + let mut output = vec![123.0; output_len]; + let result = if kind == 12 { + q4_k::decode_into(&source[..input_len], &mut output) + } else { + q5_k::decode_into(&source[..input_len], &mut output) + }; + assert!(result.is_err()); + assert!(output.iter().all(|value| *value == 123.0)); + assert!(decode_into(kind, &source[..input_len], &mut output).is_err()); + assert!(output.iter().all(|value| *value == 123.0)); + } + } + } +} + +// The field generator does not call either Rust decoder or its unpack helper. +fn synthetic_q6_q2_block(kind: u32, bits: u16, pattern: u32) -> Vec { + if kind == 42 { + let mut block = vec![0u8; 18]; + block[..2].copy_from_slice(&bits.to_le_bytes()); + for (lane, byte) in block[2..].iter_mut().enumerate() { + for field in 0..4 { + *byte |= (((pattern as usize + lane + field) & 3) as u8) << (field * 2); + } + } + block + } else { + assert_eq!(kind, 14); + let mut block = vec![0u8; 210]; + block[208..].copy_from_slice(&bits.to_le_bytes()); + for scale in 0..16 { + block[192 + scale] = (pattern >> 6) as u8; + block[192 + scale] = block[192 + scale].wrapping_add((scale * 17) as u8); + } + for half in 0..2 { + for quadrant in 0..4 { + for lane in 0..32 { + let position = half * 128 + quadrant * 32 + lane; + let code = ((pattern as usize + position * 13) & 63) as u8; + let low_index = half * 64 + (quadrant % 2) * 32 + lane; + block[low_index] |= (code & 15) << ((quadrant / 2) * 4); + block[128 + half * 32 + lane] |= (code >> 4) << (quadrant * 2); + } + } + } + block + } +} + +fn rust_q6_q2_into(kind: u32, source: &[u8], output: &mut [f32]) -> Result<(), String> { + if kind == 14 { + leleka_quant_core::q6_k::decode_into(source, output) + } else { + assert_eq!(kind, 42); + leleka_quant_core::q2_0::decode_into(source, output) + } +} + +fn assert_q6_q2_c_bits(kind: u32, source: &[u8], finite: bool) { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + let mut expected = vec![0.0; source.len() / bytes as usize * elements as usize]; + let mut actual = vec![0.0; expected.len()]; + decode_into(kind, source, &mut expected).unwrap(); + rust_q6_q2_into(kind, source, &mut actual).unwrap(); + for (position, (actual, expected)) in actual.iter().zip(&expected).enumerate() { + if finite { + assert!(actual.is_finite() && expected.is_finite()); + } + if expected.is_nan() { + assert!(actual.is_nan(), "kind {kind} position {position}"); + } else { + assert_eq!( + actual.to_bits(), + expected.to_bits(), + "kind {kind} position {position}" + ); + } + } +} + +#[test] +fn pinned_ggml_q6_q2_all_finite_fp16_scales_match_exact_c_bits() { + let mut scales = 0; + for bits in 0..=u16::MAX { + if bits & 0x7c00 == 0x7c00 { + continue; + } + assert_q6_q2_c_bits(14, &synthetic_q6_q2_block(14, bits, u32::from(bits)), true); + // Four blocks exercise every Q2 code at every consecutive output position. + for pattern in 0..4 { + assert_q6_q2_c_bits(42, &synthetic_q6_q2_block(42, bits, pattern), true); + } + scales += 1; + } + assert_eq!(scales, 63_488); +} + +#[test] +fn pinned_ggml_q6_signed_subscale_quant_pairs_cover_every_output_position() { + let mut pairs = vec![vec![false; 256 * 64]; 256]; + for pattern in 0..16_384u32 { + let block = synthetic_q6_q2_block(14, 0xb555, pattern); + assert_q6_q2_c_bits(14, &block, true); + for (position, seen) in pairs.iter_mut().enumerate() { + let half = position / 128; + let quadrant = position % 128 / 32; + let lane = position % 32; + let low = block[half * 64 + (quadrant % 2) * 32 + lane]; + let high = block[128 + half * 32 + lane]; + let code = + ((low >> ((quadrant / 2) * 4)) & 15) | (((high >> (quadrant * 2)) & 3) << 4); + let scale = block[192 + half * 8 + quadrant * 2 + lane / 16]; + seen[usize::from(scale) * 64 + usize::from(code)] = true; + } + } + for (position, seen) in pairs.iter().enumerate() { + assert!( + seen.iter().all(|value| *value), + "half/quadrant/lane position {position}" + ); + } +} + +#[test] +fn pinned_ggml_q6_q2_raw_fields_cover_all_bytes_and_q2_consecutive_codes() { + for kind in [14, 42] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + let fields = if kind == 14 { 208 } else { 16 }; + let start = if kind == 14 { 0 } else { 2 }; + let mut raw_seen = vec![[false; 256]; fields]; + let mut codes_seen = vec![[false; 4]; 64]; + for pattern in 0..=u8::MAX { + let mut block = vec![0u8; bytes as usize]; + let header = if kind == 14 { 208 } else { 0 }; + block[header..header + 2].copy_from_slice(&0x3555u16.to_le_bytes()); + for field in 0..fields { + let byte = pattern + .wrapping_mul((field * 2 + 1) as u8) + .rotate_left((field % 8) as u32) + .wrapping_add((field * 19) as u8); + block[start + field] = byte; + raw_seen[field][usize::from(byte)] = true; + } + if kind == 42 { + for (position, seen) in codes_seen.iter_mut().enumerate() { + let code = (block[2 + position / 4] >> ((position % 4) * 2)) & 3; + seen[usize::from(code)] = true; + } + } + assert_q6_q2_c_bits(kind, &block, true); + } + assert!(raw_seen.iter().all(|seen| seen.iter().all(|value| *value))); + if kind == 42 { + assert_eq!(elements, 64); + assert!( + codes_seen + .iter() + .all(|seen| seen.iter().all(|value| *value)) + ); + } + } +} + +#[test] +fn pinned_ggml_q6_q2_all_nonfinite_headers_and_zero_factors_preserve_c_values() { + let mut headers = 0; + for bits in 0..=u16::MAX { + if bits & 0x7c00 != 0x7c00 { + continue; + } + let mut block = synthetic_q6_q2_block(14, bits, u32::from(bits)); + assert_q6_q2_c_bits(14, &block, false); + // Zero subscale and zero signed quant independently reach Inf*zero. + block[192..208].fill(0); + assert_q6_q2_c_bits(14, &block, false); + block[192..208].fill(1); + block[..128].fill(0); + block[128..192].fill(0xaa); // each high field 2, low 0 -> signed quant 0 + assert_q6_q2_c_bits(14, &block, false); + for pattern in 0..4 { + assert_q6_q2_c_bits(42, &synthetic_q6_q2_block(42, bits, pattern), false); + } + headers += 1; + } + assert_eq!(headers, 2048); +} + +#[test] +fn pinned_ggml_q6_q2_aligned_unaligned_bulk_and_shape_sentinels_match() { + let edges = [ + 0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, + 0x3800, 0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff, + ]; + for kind in [14, 42] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + let bytes = bytes as usize; + for unaligned in [false, true] { + let mut storage = vec![0; edges.len() * bytes + 16]; + let start = storage.as_ptr().align_offset(16) + usize::from(unaligned); + let source = &mut storage[start..start + edges.len() * bytes]; + assert_eq!( + source.as_ptr().align_offset(16), + if unaligned { 15 } else { 0 } + ); + for (number, bits) in edges.into_iter().enumerate() { + source[number * bytes..(number + 1) * bytes] + .copy_from_slice(&synthetic_q6_q2_block(kind, bits, number as u32 * 257)); + } + assert_q6_q2_c_bits(kind, source, true); + let outputs = edges.len() * elements as usize; + for (input_len, output_len) in [ + (0, outputs), + (source.len() - 1, outputs), + (source.len(), outputs - 1), + (source.len(), outputs + 1), + ] { + let mut output = vec![123.0; output_len]; + assert!(rust_q6_q2_into(kind, &source[..input_len], &mut output).is_err()); + assert!(output.iter().all(|value| *value == 123.0)); + assert!(decode_into(kind, &source[..input_len], &mut output).is_err()); + assert!(output.iter().all(|value| *value == 123.0)); + } + } + } +} + +fn pinned_c_table_bytes(name: &str, count: usize, width: usize) -> Vec { + let source = include_str!("../../third_party/ggml/ggml-common.h"); + let marker = format!(", {name}, {count})"); + let body = source + .split_once(&marker) + .unwrap() + .1 + .split_once("GGML_TABLE_END()") + .unwrap() + .0; + let values: Vec = body + .split(',') + .map(str::trim) + .filter(|v| !v.is_empty()) + .map(|v| { + if let Some(hex) = v.strip_prefix("0x") { + u64::from_str_radix(hex, 16).unwrap() + } else { + v.parse().unwrap() + } + }) + .collect(); + assert_eq!(values.len(), count); + values + .iter() + .flat_map(|value| value.to_le_bytes()[..width].to_vec()) + .collect() +} + +#[test] +fn pinned_c_iq2s_iq3xxs_complete_grid_sign_and_mask_bytes_match_port_provenance() { + use sha2::{Digest, Sha256}; + for (name, count, width, digest) in [ + ( + "iq2s_grid", + 1024, + 8, + "e1aa1473412b0552c2174c30ef22ab4073f6a181b85a17056e8249bd2932fd88", + ), + ( + "iq3xxs_grid", + 256, + 4, + "46e35f5a997efdee6c99ce57854c8a0d4f0ff8ca57e5e8a60c0793ea580acf5d", + ), + ( + "ksigns_iq2xs", + 128, + 1, + "a76742a603f8beca5212ecce0f1f02f11a4887fd2f7c8b15aca0ea3eb3380c31", + ), + ( + "kmask_iq2xs", + 8, + 1, + "5ac9831b2e30eb285ef34f8501620f878432d5c04331ad1ae47f977a83ba41a5", + ), + ] { + let bytes = pinned_c_table_bytes(name, count, width); + assert_eq!(hex::encode(Sha256::digest(&bytes)), digest); + if name.ends_with("_grid") { + assert!(bytes.iter().all(|value| *value != 0)); + } + } +} + +// Independently pack wire fields; neither decoder nor its tables/helpers generate inputs. +fn synthetic_iq2s_iq3xxs_block(kind: u32, bits: u16, pattern: usize) -> Vec { + let mut block = vec![0u8; if kind == 22 { 82 } else { 98 }]; + block[..2].copy_from_slice(&bits.to_le_bytes()); + if kind == 22 { + for group in 0..32 { + let grid = (pattern + group * 17) & 1023; + block[2 + group] = grid as u8; + block[66 + group / 4] |= ((grid >> 8) as u8) << ((group % 4) * 2); + block[34 + group] = (pattern + group * 29) as u8; + } + for subblock in 0..8 { + block[74 + subblock] = + (((pattern + subblock) & 15) | ((((pattern >> 4) + subblock) & 15) << 4)) as u8; + } + } else { + assert_eq!(kind, 18); + for field in 0..64 { + block[2 + field] = (pattern + field * 17) as u8; + } + for subblock in 0..8 { + let mut word = ((((pattern >> 7) + subblock) & 15) as u32) << 28; + for group in 0..4 { + word |= (((pattern + group * 17 + subblock * 29) & 127) as u32) << (group * 7); + } + block[66 + subblock * 4..70 + subblock * 4].copy_from_slice(&word.to_le_bytes()); + } + } + block +} + +fn rust_iq2s_iq3xxs_into(kind: u32, source: &[u8], output: &mut [f32]) -> Result<(), String> { + if kind == 22 { + leleka_quant_core::iq2_s::decode_into(source, output) + } else { + assert_eq!(kind, 18); + leleka_quant_core::iq3_xxs::decode_into(source, output) + } +} + +fn assert_iq2s_iq3xxs_c_bits(kind: u32, source: &[u8], finite: bool) { + let bytes = if kind == 22 { 82 } else { 98 }; + let mut expected = vec![0.0; source.len() / bytes * 256]; + let mut actual = vec![0.0; expected.len()]; + decode_into(kind, source, &mut expected).unwrap(); + rust_iq2s_iq3xxs_into(kind, source, &mut actual).unwrap(); + for (position, (actual, expected)) in actual.iter().zip(&expected).enumerate() { + if finite { + assert!(actual.is_finite() && expected.is_finite()); + } + if expected.is_nan() { + assert!(actual.is_nan(), "kind {kind} position {position}"); + } else { + assert_eq!( + actual.to_bits(), + expected.to_bits(), + "kind {kind} position {position}" + ); + } + } +} + +#[test] +fn pinned_ggml_iq2s_iq3xxs_every_finite_fp16_matches_c_bits() { + let mut headers = 0; + for bits in 0..=u16::MAX { + if bits & 0x7c00 == 0x7c00 { + continue; + } + for kind in [22, 18] { + assert_iq2s_iq3xxs_c_bits( + kind, + &synthetic_iq2s_iq3xxs_block(kind, bits, usize::from(bits)), + true, + ); + } + headers += 1; + } + assert_eq!(headers, 63_488); +} + +#[test] +fn pinned_ggml_iq2s_iq3xxs_all_grid_sign_subscale_positions_match_c_bits() { + let c_signs = pinned_c_table_bytes("ksigns_iq2xs", 128, 1); + for kind in [22, 18] { + let grid_count = if kind == 22 { 1024 } else { 256 }; + let group_count = if kind == 22 { 32 } else { 64 }; + let sign_count = if kind == 22 { 256 } else { 128 }; + let mut grids = vec![vec![false; grid_count]; group_count]; + let mut signs = vec![vec![false; sign_count]; 32]; + let mut scale = vec![[false; 16]; if kind == 22 { 16 } else { 8 }]; + let mut output_signs = vec![[false; 2]; 256]; + for pattern in 0..if kind == 22 { 1024 } else { 2048 } { + let block = synthetic_iq2s_iq3xxs_block(kind, 0xb555, pattern); + assert_iq2s_iq3xxs_c_bits(kind, &block, true); + for group in 0..32 { + let sign = if kind == 22 { + let grid = usize::from(block[2 + group]) + | (usize::from((block[66 + group / 4] >> ((group % 4) * 2)) & 3) << 8); + grids[group][grid] = true; + let sign = usize::from(block[34 + group]); + signs[group][sign] = true; + sign as u8 + } else { + let subblock = group / 4; + let word = u32::from_le_bytes( + block[66 + subblock * 4..70 + subblock * 4] + .try_into() + .unwrap(), + ); + let code = ((word >> ((group % 4) * 7)) & 127) as usize; + signs[group][code] = true; + grids[group * 2][usize::from(block[2 + group * 2])] = true; + grids[group * 2 + 1][usize::from(block[3 + group * 2])] = true; + c_signs[code] + }; + for lane in 0..8 { + output_signs[group * 8 + lane][usize::from((sign >> lane) & 1)] = true; + } + } + for (position, seen) in scale.iter_mut().enumerate() { + let code = if kind == 22 { + (block[74 + position / 2] >> ((position % 2) * 4)) & 15 + } else { + let word = u32::from_le_bytes( + block[66 + position * 4..70 + position * 4] + .try_into() + .unwrap(), + ); + (word >> 28) as u8 + }; + seen[usize::from(code)] = true; + } + } + assert!(grids.iter().all(|seen| seen.iter().all(|v| *v))); + assert!(signs.iter().all(|seen| seen.iter().all(|v| *v))); + assert!(scale.iter().all(|seen| seen.iter().all(|v| *v))); + assert!(output_signs.iter().all(|seen| seen.iter().all(|v| *v))); + } +} + +#[test] +fn pinned_ggml_iq2s_iq3xxs_every_raw_field_byte_matches_c_bits() { + for kind in [22, 18] { + let bytes = if kind == 22 { 82 } else { 98 }; + let mut seen = vec![[false; 256]; bytes - 2]; + for pattern in 0..=u8::MAX { + let mut block = vec![0; bytes]; + block[..2].copy_from_slice(&0x3555u16.to_le_bytes()); + for (field, flags) in seen.iter_mut().enumerate() { + let value = pattern + .wrapping_mul((field * 2 + 1) as u8) + .rotate_left((field % 8) as u32) + .wrapping_add((field * 19) as u8); + block[2 + field] = value; + flags[usize::from(value)] = true; + } + assert_iq2s_iq3xxs_c_bits(kind, &block, true); + } + assert!(seen.iter().all(|seen| seen.iter().all(|v| *v))); + } +} + +#[test] +fn pinned_ggml_iq2s_iq3xxs_all_nonfinite_headers_and_zero_fields_preserve_c_values() { + let mut headers = 0; + for bits in 0..=u16::MAX { + if bits & 0x7c00 != 0x7c00 { + continue; + } + for kind in [22, 18] { + let mut block = synthetic_iq2s_iq3xxs_block(kind, bits, usize::from(bits)); + assert_iq2s_iq3xxs_c_bits(kind, &block, false); + block[2..].fill(0); + assert_iq2s_iq3xxs_c_bits(kind, &block, false); + } + headers += 1; + } + assert_eq!(headers, 2048); +} + +#[test] +fn pinned_ggml_iq2s_iq3xxs_aligned_unaligned_bulk_and_shape_sentinels_match() { + let edges = [ + 0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, + 0x3800, 0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff, + ]; + for kind in [22, 18] { + let bytes = if kind == 22 { 82 } else { 98 }; + for unaligned in [false, true] { + let mut storage = vec![0; edges.len() * bytes + 16]; + let start = storage.as_ptr().align_offset(16) + usize::from(unaligned); + let source = &mut storage[start..start + edges.len() * bytes]; + assert_eq!( + source.as_ptr().align_offset(16), + if unaligned { 15 } else { 0 } + ); + for (number, bits) in edges.into_iter().enumerate() { + source[number * bytes..(number + 1) * bytes] + .copy_from_slice(&synthetic_iq2s_iq3xxs_block(kind, bits, number * 257)); + } + assert_iq2s_iq3xxs_c_bits(kind, source, true); + let outputs = edges.len() * 256; + for (input_len, output_len) in [ + (0, outputs), + (source.len() - 1, outputs), + (source.len(), outputs - 1), + (source.len(), outputs + 1), + ] { + let mut output = vec![123.0; output_len]; + assert!( + rust_iq2s_iq3xxs_into(kind, &source[..input_len], &mut output).is_err() + ); + assert!(output.iter().all(|value| *value == 123.0)); + assert!(decode_into(kind, &source[..input_len], &mut output).is_err()); + assert!(output.iter().all(|value| *value == 123.0)); + } + } + } +} diff --git a/control-plane/src/gguf_f32_stream.rs b/control-plane/src/gguf_f32_stream.rs index 4c5cb411..87f77109 100644 --- a/control-plane/src/gguf_f32_stream.rs +++ b/control-plane/src/gguf_f32_stream.rs @@ -187,920 +187,4 @@ where } #[cfg(test)] -mod tests { - use super::*; - use std::io::Cursor; - - #[test] - fn iq3_stream_spans_chunks_with_bounded_buffers() { - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - let mut source = block.repeat(257); - let mut cursor = Cursor::new(&source); - let mut chunks = Vec::new(); - let output_bytes = visit(&mut cursor, 0, 21, source.len() as u64, |raw, decoded| { - assert!(raw.len() <= SOURCE_CHUNK_BYTES); - assert!(decoded.len() <= 256 * iq3_s::BLOCK_ELEMENTS * 4); - assert!( - decoded - .as_chunks::<4>() - .0 - .iter() - .all(|v| *v == 1f32.to_le_bytes()) - ); - chunks.push((raw.len(), decoded.len())); - Ok(()) - }) - .unwrap(); - assert_eq!(chunks, [(SOURCE_CHUNK_BYTES, 262_144), (110, 1024)]); - assert_eq!(output_bytes, 257 * 256 * 4); - source.pop(); - assert!( - visit( - &mut Cursor::new(source), - 0, - 21, - (257 * 110 - 1) as u64, - |_, _| Ok(()) - ) - .is_err() - ); - } - - #[test] - fn iq4_stream_spans_chunks_with_exact_c_parity_and_source_offsets() { - let blocks_per_chunk = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES; - let blocks = blocks_per_chunk + 257; - let prefix = 13; - let mut source = vec![0xa5; prefix]; - for block_index in 0..blocks { - let mut block = [0u8; iq4_nl::BLOCK_BYTES]; - let scale: u16 = [0x0001, 0x03ff, 0x0400, 0x3800, 0xbc00, 0x7bff][block_index % 6]; - block[..2].copy_from_slice(&scale.to_le_bytes()); - for (position, byte) in block[2..].iter_mut().enumerate() { - *byte = (block_index + position * 17) as u8; - } - source.extend_from_slice(&block); - } - let source_bytes = blocks * iq4_nl::BLOCK_BYTES; - source.extend_from_slice(&[0x5a; 31]); - let mut cursor = Cursor::new(&source); - let mut consumed = 0; - let mut chunks = Vec::new(); - let output_bytes = visit( - &mut cursor, - prefix as u64, - 20, - source_bytes as u64, - |raw, derived| { - assert!(raw.len() <= SOURCE_CHUNK_BYTES); - assert!(raw.len().is_multiple_of(iq4_nl::BLOCK_BYTES)); - assert!(derived.len() <= blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4); - assert_eq!( - raw, - &source[prefix + consumed..prefix + consumed + raw.len()] - ); - let mut reference = - vec![0.0; raw.len() / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS]; - ggml_bridge::decode_into(20, raw, &mut reference).unwrap(); - let reference_bytes: Vec = reference - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect(); - assert_eq!(derived, reference_bytes); - consumed += raw.len(); - chunks.push((raw.len(), derived.len())); - Ok(()) - }, - ) - .unwrap(); - assert_eq!( - chunks, - [ - ( - blocks_per_chunk * iq4_nl::BLOCK_BYTES, - blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4 - ), - (257 * iq4_nl::BLOCK_BYTES, 257 * iq4_nl::BLOCK_ELEMENTS * 4), - ] - ); - assert_eq!(consumed, source_bytes); - assert_eq!(output_bytes, (blocks * iq4_nl::BLOCK_ELEMENTS * 4) as u64); - assert_eq!(cursor.position(), (prefix + source_bytes) as u64); - } - - #[test] - fn iq4_stream_refuses_invalid_shapes_before_seek_or_callback() { - for source_bytes in [0, 1, 17, 19, 37] { - let mut cursor = Cursor::new([0u8; 64]); - cursor.set_position(7); - let mut calls = 0; - let error = visit(&mut cursor, 13, 20, source_bytes, |_, _| { - calls += 1; - Ok(()) - }) - .unwrap_err(); - assert_eq!(error, "GGUF source tensor is empty or not block-aligned"); - assert_eq!(calls, 0); - assert_eq!(cursor.position(), 7); - } - } - - #[test] - fn iq4_stream_truncation_never_delivers_an_incomplete_chunk() { - let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES; - for available in [ - iq4_nl::BLOCK_BYTES - 1, - chunk_bytes + iq4_nl::BLOCK_BYTES - 1, - ] { - let requested = if available < chunk_bytes { - iq4_nl::BLOCK_BYTES - } else { - chunk_bytes + iq4_nl::BLOCK_BYTES - }; - let mut calls = 0; - let result = visit( - &mut Cursor::new(vec![0u8; available]), - 0, - 20, - requested as u64, - |raw, derived| { - calls += 1; - assert_eq!(raw.len(), chunk_bytes); - assert_eq!( - derived.len(), - chunk_bytes / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS * 4 - ); - Ok(()) - }, - ); - assert!(result.is_err()); - assert_eq!(calls, usize::from(available >= chunk_bytes)); - } - } - - #[test] - fn iq4_stream_callback_failure_stops_without_reading_the_next_chunk() { - let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES; - for fail_on in [1, 2] { - let mut cursor = Cursor::new(vec![0u8; chunk_bytes * 3]); - let mut calls = 0; - let error = visit(&mut cursor, 0, 20, (chunk_bytes * 3) as u64, |raw, _| { - calls += 1; - assert_eq!(raw.len(), chunk_bytes); - if calls == fail_on { - Err("owned callback failure".into()) - } else { - Ok(()) - } - }) - .unwrap_err(); - assert_eq!(error, "owned callback failure"); - assert_eq!(calls, fail_on); - assert_eq!(cursor.position(), (chunk_bytes * fail_on) as u64); - } - } - - #[test] - fn iq4_stream_preserves_existing_nonfinite_classification_and_infinity_signs() { - for scale in [0x7c00u16, 0xfc00, 0x7c01, 0x7fff, 0xfc01, 0xffff] { - let mut source = AlignedSource([0u8; SOURCE_CHUNK_BYTES]); - source.0[..2].copy_from_slice(&scale.to_le_bytes()); - for (position, byte) in source.0[2..iq4_nl::BLOCK_BYTES].iter_mut().enumerate() { - *byte = ((position as u8) << 4) | (15 - position as u8); - } - let raw = &source.0[..iq4_nl::BLOCK_BYTES]; - let mut reference = [0.0; iq4_nl::BLOCK_ELEMENTS]; - ggml_bridge::decode_into(20, raw, &mut reference).unwrap(); - let mut calls = 0; - let count = visit( - &mut Cursor::new(raw), - 0, - 20, - iq4_nl::BLOCK_BYTES as u64, - |_, derived| { - calls += 1; - for (word, reference) in derived.as_chunks::<4>().0.iter().zip(reference) { - let actual = f32::from_le_bytes(*word); - if reference.is_nan() { - assert!(actual.is_nan()); - } else { - assert!(reference.is_infinite()); - assert_eq!(actual.to_bits(), reference.to_bits()); - } - } - assert_eq!(derived.len(), iq4_nl::BLOCK_ELEMENTS * 4); - Ok(()) - }, - ) - .unwrap(); - assert_eq!(calls, 1); - assert_eq!(count, (iq4_nl::BLOCK_ELEMENTS * 4) as u64); - } - } - - #[test] - fn q8_and_iq4xs_streams_preserve_bounded_c_bytes_offsets_and_receipts() { - for kind in [8, 23] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - let bytes = bytes as usize; - let per_chunk = SOURCE_CHUNK_BYTES / bytes; - let blocks = per_chunk + 17; - let prefix = 11; - let mut source = vec![0xa5; prefix]; - for number in 0..blocks { - let mut block = vec![0u8; bytes]; - let scale: u16 = [0, 0x8000, 1, 0x83ff, 0x0400, 0x3800, 0xbc00, 0x7bff][number % 8]; - block[..2].copy_from_slice(&scale.to_le_bytes()); - for (position, byte) in block[2..].iter_mut().enumerate() { - *byte = (number * 17 + position * 29) as u8; - } - source.extend_from_slice(&block); - } - let source_bytes = blocks * bytes; - source.extend_from_slice(&[0x5a; 19]); - let mut cursor = Cursor::new(&source); - let mut consumed = 0; - let mut chunks = Vec::new(); - let receipt = visit( - &mut cursor, - prefix as u64, - kind, - source_bytes as u64, - |raw, derived| { - assert!(raw.len() <= SOURCE_CHUNK_BYTES); - assert_eq!( - raw, - &source[prefix + consumed..prefix + consumed + raw.len()] - ); - let mut oracle = vec![0.0; raw.len() / bytes * elements as usize]; - ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap(); - let expected: Vec = oracle - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect(); - assert_eq!(derived, expected, "kind {kind}"); - assert!(derived.len() <= per_chunk * elements as usize * 4); - chunks.push((raw.len(), derived.len())); - consumed += raw.len(); - Ok(()) - }, - ) - .unwrap(); - assert_eq!( - chunks, - [ - (per_chunk * bytes, per_chunk * elements as usize * 4), - (17 * bytes, 17 * elements as usize * 4) - ] - ); - assert_eq!(consumed, source_bytes); - assert_eq!(receipt, blocks as u64 * elements * 4); - assert_eq!(cursor.position(), (prefix + source_bytes) as u64); - let mut calls = 0; - assert!( - visit( - &mut Cursor::new(&source), - prefix as u64, - kind, - source_bytes as u64 - 1, - |_, _| { - calls += 1; - Ok(()) - } - ) - .is_err() - ); - assert_eq!(calls, 0); - let mut truncated = Cursor::new(&source[..prefix + bytes - 1]); - assert!( - visit(&mut truncated, prefix as u64, kind, bytes as u64, |_, _| { - calls += 1; - Ok(()) - }) - .is_err() - ); - assert_eq!(calls, 0); - let mut cursor = Cursor::new(&source); - let error = visit( - &mut cursor, - prefix as u64, - kind, - source_bytes as u64, - |_, _| { - calls += 1; - Err("owned callback abort".into()) - }, - ) - .unwrap_err(); - assert_eq!(error, "owned callback abort"); - assert_eq!(calls, 1); - assert_eq!(cursor.position(), (prefix + per_chunk * bytes) as u64); - } - } - - #[test] - fn q8_and_iq4xs_streams_preserve_nonfinite_classification_and_infinity_bits() { - for kind in [8, 23] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] { - let mut block = vec![0u8; bytes as usize]; - block[..2].copy_from_slice(&scale.to_le_bytes()); - for (position, byte) in block[2..].iter_mut().enumerate() { - *byte = (position * 29) as u8; - } - let mut oracle = vec![0.0; elements as usize]; - ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap(); - let mut calls = 0; - let receipt = visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| { - assert_eq!(raw, block); - for (actual, reference) in derived.as_chunks::<4>().0.iter().zip(&oracle) { - let actual = f32::from_le_bytes(*actual); - if reference.is_nan() { - assert!(actual.is_nan()); - } else { - assert_eq!(actual.to_bits(), reference.to_bits()); - } - } - calls += 1; - Ok(()) - }) - .unwrap(); - assert_eq!(calls, 1); - assert_eq!(receipt, elements * 4); - } - } - } - - #[test] - fn actual_target_quant_types_decode_one_block_each() { - for kind in [8, 12, 13, 14, 18, 20, 21, 22, 23, 42] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - let source = vec![0u8; bytes as usize]; - let mut output = Vec::new(); - let count = visit(&mut Cursor::new(&source), 0, kind, bytes, |raw, derived| { - assert_eq!(raw.len() as u64, bytes); - output.extend_from_slice(derived); - Ok(()) - }) - .unwrap(); - assert_eq!(count, elements * 4, "kind {kind}"); - assert_eq!(output.len() as u64, elements * 4, "kind {kind}"); - assert!( - output - .as_chunks::<4>() - .0 - .iter() - .all(|word| f32::from_le_bytes(*word).is_finite()), - "kind {kind}" - ); - } - } - - #[test] - fn q4_q5_k_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() { - let edges = [ - 0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff, - ]; - for kind in [12, 13] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - let bytes = bytes as usize; - let per_chunk = SOURCE_CHUNK_BYTES / bytes; - let blocks = per_chunk + 17; - let prefix = 11; - let mut source = vec![0xa5; prefix]; - for number in 0..blocks { - let mut block = vec![0u8; bytes]; - block[..2].copy_from_slice(&edges[number % edges.len()].to_le_bytes()); - block[2..4].copy_from_slice(&edges[(number * 7 + 3) % edges.len()].to_le_bytes()); - for (position, byte) in block[4..].iter_mut().enumerate() { - *byte = (number * 17 + position * 29) as u8; - } - source.extend_from_slice(&block); - } - let requested = blocks * bytes; - source.extend_from_slice(&[0x5a; 19]); - let mut cursor = Cursor::new(&source); - let mut consumed = 0; - let mut chunks = Vec::new(); - let receipt = visit( - &mut cursor, - prefix as u64, - kind, - requested as u64, - |raw, derived| { - assert!(raw.len() <= SOURCE_CHUNK_BYTES); - assert_eq!( - raw, - &source[prefix + consumed..prefix + consumed + raw.len()] - ); - let mut oracle = vec![0.0; raw.len() / bytes * elements as usize]; - ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap(); - let expected: Vec = oracle - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect(); - assert_eq!(derived, expected, "kind {kind}"); - assert!(derived.len() <= per_chunk * elements as usize * 4); - chunks.push((raw.len(), derived.len())); - consumed += raw.len(); - Ok(()) - }, - ) - .unwrap(); - assert_eq!( - chunks, - [ - (per_chunk * bytes, per_chunk * elements as usize * 4), - (17 * bytes, 17 * elements as usize * 4) - ] - ); - assert_eq!(consumed, requested); - assert_eq!(receipt, blocks as u64 * elements * 4); - assert_eq!(cursor.position(), (prefix + requested) as u64); - for malformed in [0, 1, bytes - 1, bytes + 1] { - let mut cursor = Cursor::new(&source); - cursor.set_position(7); - let mut calls = 0; - assert!( - visit( - &mut cursor, - prefix as u64, - kind, - malformed as u64, - |_, _| { - calls += 1; - Ok(()) - } - ) - .is_err() - ); - assert_eq!(calls, 0); - assert_eq!(cursor.position(), 7); - } - for delivered in [0, 1] { - let available = delivered * per_chunk * bytes + bytes - 1; - let required = delivered * per_chunk * bytes + bytes; - let mut calls = 0; - assert!( - visit( - &mut Cursor::new(&source[..prefix + available]), - prefix as u64, - kind, - required as u64, - |raw, derived| { - calls += 1; - assert_eq!(raw.len(), per_chunk * bytes); - assert_eq!(derived.len(), per_chunk * elements as usize * 4); - Ok(()) - } - ) - .is_err() - ); - assert_eq!(calls, delivered); - } - for fail_on in [1, 2] { - let mut cursor = Cursor::new(&source); - let mut calls = 0; - let error = visit( - &mut cursor, - prefix as u64, - kind, - requested as u64, - |_, _| { - calls += 1; - if calls == fail_on { - Err("owned callback abort".into()) - } else { - Ok(()) - } - }, - ) - .unwrap_err(); - assert_eq!(error, "owned callback abort"); - assert_eq!(calls, fail_on); - assert_eq!( - cursor.position(), - (prefix - + if fail_on == 1 { - per_chunk * bytes - } else { - requested - }) as u64 - ); - } - } - } - - #[test] - fn q4_q5_k_streams_preserve_both_nonfinite_scale_roles_and_zero_packed_fields() { - let scales = [ - 0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00, - ]; - for kind in [12, 13] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - for d in scales { - for dmin in scales { - for zero_fields in [false, true] { - let mut block = vec![0u8; bytes as usize]; - block[..2].copy_from_slice(&d.to_le_bytes()); - block[2..4].copy_from_slice(&dmin.to_le_bytes()); - if !zero_fields { - for (position, byte) in block[4..].iter_mut().enumerate() { - *byte = (position * 29 + 17) as u8; - } - } - let mut oracle = vec![0.0; elements as usize]; - ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap(); - let mut calls = 0; - let receipt = - visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| { - assert_eq!(raw, block); - assert_eq!(derived.len(), elements as usize * 4); - for (actual, reference) in - derived.as_chunks::<4>().0.iter().zip(&oracle) - { - let actual = f32::from_le_bytes(*actual); - if reference.is_nan() { - assert!(actual.is_nan()); - } else { - assert_eq!(actual.to_bits(), reference.to_bits()); - } - } - calls += 1; - Ok(()) - }) - .unwrap(); - assert_eq!(calls, 1); - assert_eq!(receipt, elements * 4); - } - } - } - } - } - #[test] - fn q6_q2_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() { - let edges = [ - 0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff, - ]; - for kind in [14, 42] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - let bytes = bytes as usize; - let per_chunk = SOURCE_CHUNK_BYTES / bytes; - let blocks = per_chunk + 17; - let prefix = 11; - let mut source = vec![0xa5; prefix]; - for number in 0..blocks { - let mut block = vec![0u8; bytes]; - for (position, byte) in block.iter_mut().enumerate() { - *byte = (number * 17 + position * 29) as u8; - } - let header = if kind == 14 { 208 } else { 0 }; - block[header..header + 2] - .copy_from_slice(&edges[number % edges.len()].to_le_bytes()); - source.extend_from_slice(&block); - } - let requested = blocks * bytes; - source.extend_from_slice(&[0x5a; 19]); - let mut cursor = Cursor::new(&source); - let mut consumed = 0; - let mut chunks = Vec::new(); - let receipt = visit( - &mut cursor, - prefix as u64, - kind, - requested as u64, - |raw, derived| { - assert!(raw.len() <= SOURCE_CHUNK_BYTES); - assert_eq!( - raw, - &source[prefix + consumed..prefix + consumed + raw.len()] - ); - let mut oracle = vec![0.0; raw.len() / bytes * elements as usize]; - ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap(); - let expected: Vec = oracle - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect(); - assert_eq!(derived, expected, "kind {kind}"); - assert!(derived.len() <= per_chunk * elements as usize * 4); - chunks.push((raw.len(), derived.len())); - consumed += raw.len(); - Ok(()) - }, - ) - .unwrap(); - assert_eq!( - chunks, - [ - (per_chunk * bytes, per_chunk * elements as usize * 4), - (17 * bytes, 17 * elements as usize * 4) - ] - ); - assert_eq!(consumed, requested); - assert_eq!(receipt, blocks as u64 * elements * 4); - assert_eq!(cursor.position(), (prefix + requested) as u64); - for malformed in [0, 1, bytes - 1, bytes + 1] { - let mut cursor = Cursor::new(&source); - cursor.set_position(7); - let mut calls = 0; - assert!( - visit( - &mut cursor, - prefix as u64, - kind, - malformed as u64, - |_, _| { - calls += 1; - Ok(()) - } - ) - .is_err() - ); - assert_eq!(calls, 0); - assert_eq!(cursor.position(), 7); - } - for delivered in [0, 1] { - let available = delivered * per_chunk * bytes + bytes - 1; - let required = delivered * per_chunk * bytes + bytes; - let mut calls = 0; - assert!( - visit( - &mut Cursor::new(&source[..prefix + available]), - prefix as u64, - kind, - required as u64, - |raw, derived| { - calls += 1; - assert_eq!(raw.len(), per_chunk * bytes); - assert_eq!(derived.len(), per_chunk * elements as usize * 4); - Ok(()) - } - ) - .is_err() - ); - assert_eq!(calls, delivered); - } - for fail_on in [1, 2] { - let mut cursor = Cursor::new(&source); - let mut calls = 0; - let error = visit( - &mut cursor, - prefix as u64, - kind, - requested as u64, - |_, _| { - calls += 1; - if calls == fail_on { - Err("owned callback abort".into()) - } else { - Ok(()) - } - }, - ) - .unwrap_err(); - assert_eq!(error, "owned callback abort"); - assert_eq!(calls, fail_on); - assert_eq!( - cursor.position(), - (prefix - + if fail_on == 1 { - per_chunk * bytes - } else { - requested - }) as u64 - ); - } - } - } - - #[test] - fn q6_q2_streams_preserve_nonfinite_headers_and_zero_factors() { - for kind in [14, 42] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - for bits in [ - 0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00, - ] { - for variant in 0..3 { - let mut block = vec![0u8; bytes as usize]; - for (position, byte) in block.iter_mut().enumerate() { - *byte = (position * 29 + 17) as u8; - } - if kind == 14 { - if variant == 1 { - block[192..208].fill(0); - } - if variant == 2 { - block[..128].fill(0); - block[128..192].fill(0xaa); - } - } else if variant != 0 { - block[2..].fill(if variant == 1 { 0x55 } else { 0 }); - } - let header = if kind == 14 { 208 } else { 0 }; - block[header..header + 2].copy_from_slice(&bits.to_le_bytes()); - let mut oracle = vec![0.0; elements as usize]; - ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap(); - let mut calls = 0; - let receipt = - visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| { - assert_eq!(raw, block); - assert_eq!(derived.len(), elements as usize * 4); - for (actual, reference) in - derived.as_chunks::<4>().0.iter().zip(&oracle) - { - let actual = f32::from_le_bytes(*actual); - if reference.is_nan() { - assert!(actual.is_nan()); - } else { - assert_eq!(actual.to_bits(), reference.to_bits()); - } - } - calls += 1; - Ok(()) - }) - .unwrap(); - assert_eq!(calls, 1); - assert_eq!(receipt, elements * 4); - } - } - } - } - #[test] - fn iq2s_iq3xxs_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() { - let edges = [ - 0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff, - ]; - for kind in [22, 18] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - let bytes = bytes as usize; - let per_chunk = SOURCE_CHUNK_BYTES / bytes; - let blocks = per_chunk + 17; - let prefix = 11; - let mut source = vec![0xa5; prefix]; - for number in 0..blocks { - let mut block = vec![0u8; bytes]; - for (position, byte) in block.iter_mut().enumerate() { - *byte = (number * 17 + position * 29) as u8; - } - let header = 0; - block[header..header + 2] - .copy_from_slice(&edges[number % edges.len()].to_le_bytes()); - source.extend_from_slice(&block); - } - let requested = blocks * bytes; - source.extend_from_slice(&[0x5a; 19]); - let mut cursor = Cursor::new(&source); - let mut consumed = 0; - let mut chunks = Vec::new(); - let receipt = visit( - &mut cursor, - prefix as u64, - kind, - requested as u64, - |raw, derived| { - assert!(raw.len() <= SOURCE_CHUNK_BYTES); - assert_eq!( - raw, - &source[prefix + consumed..prefix + consumed + raw.len()] - ); - let mut oracle = vec![0.0; raw.len() / bytes * elements as usize]; - ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap(); - let expected: Vec = oracle - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect(); - assert_eq!(derived, expected, "kind {kind}"); - assert!(derived.len() <= per_chunk * elements as usize * 4); - chunks.push((raw.len(), derived.len())); - consumed += raw.len(); - Ok(()) - }, - ) - .unwrap(); - assert_eq!( - chunks, - [ - (per_chunk * bytes, per_chunk * elements as usize * 4), - (17 * bytes, 17 * elements as usize * 4) - ] - ); - assert_eq!(consumed, requested); - assert_eq!(receipt, blocks as u64 * elements * 4); - assert_eq!(cursor.position(), (prefix + requested) as u64); - for malformed in [0, 1, bytes - 1, bytes + 1] { - let mut cursor = Cursor::new(&source); - cursor.set_position(7); - let mut calls = 0; - assert!( - visit( - &mut cursor, - prefix as u64, - kind, - malformed as u64, - |_, _| { - calls += 1; - Ok(()) - } - ) - .is_err() - ); - assert_eq!(calls, 0); - assert_eq!(cursor.position(), 7); - } - for delivered in [0, 1] { - let available = delivered * per_chunk * bytes + bytes - 1; - let required = delivered * per_chunk * bytes + bytes; - let mut calls = 0; - assert!( - visit( - &mut Cursor::new(&source[..prefix + available]), - prefix as u64, - kind, - required as u64, - |raw, derived| { - calls += 1; - assert_eq!(raw.len(), per_chunk * bytes); - assert_eq!(derived.len(), per_chunk * elements as usize * 4); - Ok(()) - } - ) - .is_err() - ); - assert_eq!(calls, delivered); - } - for fail_on in [1, 2] { - let mut cursor = Cursor::new(&source); - let mut calls = 0; - let error = visit( - &mut cursor, - prefix as u64, - kind, - requested as u64, - |_, _| { - calls += 1; - if calls == fail_on { - Err("owned callback abort".into()) - } else { - Ok(()) - } - }, - ) - .unwrap_err(); - assert_eq!(error, "owned callback abort"); - assert_eq!(calls, fail_on); - assert_eq!( - cursor.position(), - (prefix - + if fail_on == 1 { - per_chunk * bytes - } else { - requested - }) as u64 - ); - } - } - } - - #[test] - fn iq2s_iq3xxs_streams_preserve_nonfinite_signed_zero_and_zero_packed_fields() { - for kind in [22, 18] { - let (elements, bytes) = gguf::block_geometry(kind).unwrap(); - for bits in [ - 0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00, - ] { - for zero_fields in [false, true] { - let mut block = vec![0; bytes as usize]; - if !zero_fields { - for (field, byte) in block[2..].iter_mut().enumerate() { - *byte = (field * 29 + 17) as u8; - } - } - block[..2].copy_from_slice(&bits.to_le_bytes()); - let mut oracle = vec![0.0; elements as usize]; - ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap(); - let mut calls = 0; - let receipt = - visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| { - assert_eq!(raw, block); - assert_eq!(derived.len(), elements as usize * 4); - for (actual, expected) in derived.as_chunks::<4>().0.iter().zip(&oracle) - { - let actual = f32::from_le_bytes(*actual); - if expected.is_nan() { - assert!(actual.is_nan()); - } else { - assert_eq!(actual.to_bits(), expected.to_bits()); - } - } - calls += 1; - Ok(()) - }) - .unwrap(); - assert_eq!(calls, 1); - assert_eq!(receipt, elements * 4); - } - } - } - } -} +mod tests; diff --git a/control-plane/src/gguf_f32_stream/tests.rs b/control-plane/src/gguf_f32_stream/tests.rs new file mode 100644 index 00000000..5fd0fec7 --- /dev/null +++ b/control-plane/src/gguf_f32_stream/tests.rs @@ -0,0 +1,917 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use std::io::Cursor; + +#[test] +fn iq3_stream_spans_chunks_with_bounded_buffers() { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let mut source = block.repeat(257); + let mut cursor = Cursor::new(&source); + let mut chunks = Vec::new(); + let output_bytes = visit(&mut cursor, 0, 21, source.len() as u64, |raw, decoded| { + assert!(raw.len() <= SOURCE_CHUNK_BYTES); + assert!(decoded.len() <= 256 * iq3_s::BLOCK_ELEMENTS * 4); + assert!( + decoded + .as_chunks::<4>() + .0 + .iter() + .all(|v| *v == 1f32.to_le_bytes()) + ); + chunks.push((raw.len(), decoded.len())); + Ok(()) + }) + .unwrap(); + assert_eq!(chunks, [(SOURCE_CHUNK_BYTES, 262_144), (110, 1024)]); + assert_eq!(output_bytes, 257 * 256 * 4); + source.pop(); + assert!( + visit( + &mut Cursor::new(source), + 0, + 21, + (257 * 110 - 1) as u64, + |_, _| Ok(()) + ) + .is_err() + ); +} + +#[test] +fn iq4_stream_spans_chunks_with_exact_c_parity_and_source_offsets() { + let blocks_per_chunk = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES; + let blocks = blocks_per_chunk + 257; + let prefix = 13; + let mut source = vec![0xa5; prefix]; + for block_index in 0..blocks { + let mut block = [0u8; iq4_nl::BLOCK_BYTES]; + let scale: u16 = [0x0001, 0x03ff, 0x0400, 0x3800, 0xbc00, 0x7bff][block_index % 6]; + block[..2].copy_from_slice(&scale.to_le_bytes()); + for (position, byte) in block[2..].iter_mut().enumerate() { + *byte = (block_index + position * 17) as u8; + } + source.extend_from_slice(&block); + } + let source_bytes = blocks * iq4_nl::BLOCK_BYTES; + source.extend_from_slice(&[0x5a; 31]); + let mut cursor = Cursor::new(&source); + let mut consumed = 0; + let mut chunks = Vec::new(); + let output_bytes = visit( + &mut cursor, + prefix as u64, + 20, + source_bytes as u64, + |raw, derived| { + assert!(raw.len() <= SOURCE_CHUNK_BYTES); + assert!(raw.len().is_multiple_of(iq4_nl::BLOCK_BYTES)); + assert!(derived.len() <= blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4); + assert_eq!( + raw, + &source[prefix + consumed..prefix + consumed + raw.len()] + ); + let mut reference = + vec![0.0; raw.len() / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS]; + ggml_bridge::decode_into(20, raw, &mut reference).unwrap(); + let reference_bytes: Vec = reference + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect(); + assert_eq!(derived, reference_bytes); + consumed += raw.len(); + chunks.push((raw.len(), derived.len())); + Ok(()) + }, + ) + .unwrap(); + assert_eq!( + chunks, + [ + ( + blocks_per_chunk * iq4_nl::BLOCK_BYTES, + blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4 + ), + (257 * iq4_nl::BLOCK_BYTES, 257 * iq4_nl::BLOCK_ELEMENTS * 4), + ] + ); + assert_eq!(consumed, source_bytes); + assert_eq!(output_bytes, (blocks * iq4_nl::BLOCK_ELEMENTS * 4) as u64); + assert_eq!(cursor.position(), (prefix + source_bytes) as u64); +} + +#[test] +fn iq4_stream_refuses_invalid_shapes_before_seek_or_callback() { + for source_bytes in [0, 1, 17, 19, 37] { + let mut cursor = Cursor::new([0u8; 64]); + cursor.set_position(7); + let mut calls = 0; + let error = visit(&mut cursor, 13, 20, source_bytes, |_, _| { + calls += 1; + Ok(()) + }) + .unwrap_err(); + assert_eq!(error, "GGUF source tensor is empty or not block-aligned"); + assert_eq!(calls, 0); + assert_eq!(cursor.position(), 7); + } +} + +#[test] +fn iq4_stream_truncation_never_delivers_an_incomplete_chunk() { + let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES; + for available in [ + iq4_nl::BLOCK_BYTES - 1, + chunk_bytes + iq4_nl::BLOCK_BYTES - 1, + ] { + let requested = if available < chunk_bytes { + iq4_nl::BLOCK_BYTES + } else { + chunk_bytes + iq4_nl::BLOCK_BYTES + }; + let mut calls = 0; + let result = visit( + &mut Cursor::new(vec![0u8; available]), + 0, + 20, + requested as u64, + |raw, derived| { + calls += 1; + assert_eq!(raw.len(), chunk_bytes); + assert_eq!( + derived.len(), + chunk_bytes / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS * 4 + ); + Ok(()) + }, + ); + assert!(result.is_err()); + assert_eq!(calls, usize::from(available >= chunk_bytes)); + } +} + +#[test] +fn iq4_stream_callback_failure_stops_without_reading_the_next_chunk() { + let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES; + for fail_on in [1, 2] { + let mut cursor = Cursor::new(vec![0u8; chunk_bytes * 3]); + let mut calls = 0; + let error = visit(&mut cursor, 0, 20, (chunk_bytes * 3) as u64, |raw, _| { + calls += 1; + assert_eq!(raw.len(), chunk_bytes); + if calls == fail_on { + Err("owned callback failure".into()) + } else { + Ok(()) + } + }) + .unwrap_err(); + assert_eq!(error, "owned callback failure"); + assert_eq!(calls, fail_on); + assert_eq!(cursor.position(), (chunk_bytes * fail_on) as u64); + } +} + +#[test] +fn iq4_stream_preserves_existing_nonfinite_classification_and_infinity_signs() { + for scale in [0x7c00u16, 0xfc00, 0x7c01, 0x7fff, 0xfc01, 0xffff] { + let mut source = AlignedSource([0u8; SOURCE_CHUNK_BYTES]); + source.0[..2].copy_from_slice(&scale.to_le_bytes()); + for (position, byte) in source.0[2..iq4_nl::BLOCK_BYTES].iter_mut().enumerate() { + *byte = ((position as u8) << 4) | (15 - position as u8); + } + let raw = &source.0[..iq4_nl::BLOCK_BYTES]; + let mut reference = [0.0; iq4_nl::BLOCK_ELEMENTS]; + ggml_bridge::decode_into(20, raw, &mut reference).unwrap(); + let mut calls = 0; + let count = visit( + &mut Cursor::new(raw), + 0, + 20, + iq4_nl::BLOCK_BYTES as u64, + |_, derived| { + calls += 1; + for (word, reference) in derived.as_chunks::<4>().0.iter().zip(reference) { + let actual = f32::from_le_bytes(*word); + if reference.is_nan() { + assert!(actual.is_nan()); + } else { + assert!(reference.is_infinite()); + assert_eq!(actual.to_bits(), reference.to_bits()); + } + } + assert_eq!(derived.len(), iq4_nl::BLOCK_ELEMENTS * 4); + Ok(()) + }, + ) + .unwrap(); + assert_eq!(calls, 1); + assert_eq!(count, (iq4_nl::BLOCK_ELEMENTS * 4) as u64); + } +} + +#[test] +fn q8_and_iq4xs_streams_preserve_bounded_c_bytes_offsets_and_receipts() { + for kind in [8, 23] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + let bytes = bytes as usize; + let per_chunk = SOURCE_CHUNK_BYTES / bytes; + let blocks = per_chunk + 17; + let prefix = 11; + let mut source = vec![0xa5; prefix]; + for number in 0..blocks { + let mut block = vec![0u8; bytes]; + let scale: u16 = [0, 0x8000, 1, 0x83ff, 0x0400, 0x3800, 0xbc00, 0x7bff][number % 8]; + block[..2].copy_from_slice(&scale.to_le_bytes()); + for (position, byte) in block[2..].iter_mut().enumerate() { + *byte = (number * 17 + position * 29) as u8; + } + source.extend_from_slice(&block); + } + let source_bytes = blocks * bytes; + source.extend_from_slice(&[0x5a; 19]); + let mut cursor = Cursor::new(&source); + let mut consumed = 0; + let mut chunks = Vec::new(); + let receipt = visit( + &mut cursor, + prefix as u64, + kind, + source_bytes as u64, + |raw, derived| { + assert!(raw.len() <= SOURCE_CHUNK_BYTES); + assert_eq!( + raw, + &source[prefix + consumed..prefix + consumed + raw.len()] + ); + let mut oracle = vec![0.0; raw.len() / bytes * elements as usize]; + ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap(); + let expected: Vec = oracle + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect(); + assert_eq!(derived, expected, "kind {kind}"); + assert!(derived.len() <= per_chunk * elements as usize * 4); + chunks.push((raw.len(), derived.len())); + consumed += raw.len(); + Ok(()) + }, + ) + .unwrap(); + assert_eq!( + chunks, + [ + (per_chunk * bytes, per_chunk * elements as usize * 4), + (17 * bytes, 17 * elements as usize * 4) + ] + ); + assert_eq!(consumed, source_bytes); + assert_eq!(receipt, blocks as u64 * elements * 4); + assert_eq!(cursor.position(), (prefix + source_bytes) as u64); + let mut calls = 0; + assert!( + visit( + &mut Cursor::new(&source), + prefix as u64, + kind, + source_bytes as u64 - 1, + |_, _| { + calls += 1; + Ok(()) + } + ) + .is_err() + ); + assert_eq!(calls, 0); + let mut truncated = Cursor::new(&source[..prefix + bytes - 1]); + assert!( + visit(&mut truncated, prefix as u64, kind, bytes as u64, |_, _| { + calls += 1; + Ok(()) + }) + .is_err() + ); + assert_eq!(calls, 0); + let mut cursor = Cursor::new(&source); + let error = visit( + &mut cursor, + prefix as u64, + kind, + source_bytes as u64, + |_, _| { + calls += 1; + Err("owned callback abort".into()) + }, + ) + .unwrap_err(); + assert_eq!(error, "owned callback abort"); + assert_eq!(calls, 1); + assert_eq!(cursor.position(), (prefix + per_chunk * bytes) as u64); + } +} + +#[test] +fn q8_and_iq4xs_streams_preserve_nonfinite_classification_and_infinity_bits() { + for kind in [8, 23] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] { + let mut block = vec![0u8; bytes as usize]; + block[..2].copy_from_slice(&scale.to_le_bytes()); + for (position, byte) in block[2..].iter_mut().enumerate() { + *byte = (position * 29) as u8; + } + let mut oracle = vec![0.0; elements as usize]; + ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap(); + let mut calls = 0; + let receipt = visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| { + assert_eq!(raw, block); + for (actual, reference) in derived.as_chunks::<4>().0.iter().zip(&oracle) { + let actual = f32::from_le_bytes(*actual); + if reference.is_nan() { + assert!(actual.is_nan()); + } else { + assert_eq!(actual.to_bits(), reference.to_bits()); + } + } + calls += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(calls, 1); + assert_eq!(receipt, elements * 4); + } + } +} + +#[test] +fn actual_target_quant_types_decode_one_block_each() { + for kind in [8, 12, 13, 14, 18, 20, 21, 22, 23, 42] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + let source = vec![0u8; bytes as usize]; + let mut output = Vec::new(); + let count = visit(&mut Cursor::new(&source), 0, kind, bytes, |raw, derived| { + assert_eq!(raw.len() as u64, bytes); + output.extend_from_slice(derived); + Ok(()) + }) + .unwrap(); + assert_eq!(count, elements * 4, "kind {kind}"); + assert_eq!(output.len() as u64, elements * 4, "kind {kind}"); + assert!( + output + .as_chunks::<4>() + .0 + .iter() + .all(|word| f32::from_le_bytes(*word).is_finite()), + "kind {kind}" + ); + } +} + +#[test] +fn q4_q5_k_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() { + let edges = [ + 0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff, + ]; + for kind in [12, 13] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + let bytes = bytes as usize; + let per_chunk = SOURCE_CHUNK_BYTES / bytes; + let blocks = per_chunk + 17; + let prefix = 11; + let mut source = vec![0xa5; prefix]; + for number in 0..blocks { + let mut block = vec![0u8; bytes]; + block[..2].copy_from_slice(&edges[number % edges.len()].to_le_bytes()); + block[2..4].copy_from_slice(&edges[(number * 7 + 3) % edges.len()].to_le_bytes()); + for (position, byte) in block[4..].iter_mut().enumerate() { + *byte = (number * 17 + position * 29) as u8; + } + source.extend_from_slice(&block); + } + let requested = blocks * bytes; + source.extend_from_slice(&[0x5a; 19]); + let mut cursor = Cursor::new(&source); + let mut consumed = 0; + let mut chunks = Vec::new(); + let receipt = visit( + &mut cursor, + prefix as u64, + kind, + requested as u64, + |raw, derived| { + assert!(raw.len() <= SOURCE_CHUNK_BYTES); + assert_eq!( + raw, + &source[prefix + consumed..prefix + consumed + raw.len()] + ); + let mut oracle = vec![0.0; raw.len() / bytes * elements as usize]; + ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap(); + let expected: Vec = oracle + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect(); + assert_eq!(derived, expected, "kind {kind}"); + assert!(derived.len() <= per_chunk * elements as usize * 4); + chunks.push((raw.len(), derived.len())); + consumed += raw.len(); + Ok(()) + }, + ) + .unwrap(); + assert_eq!( + chunks, + [ + (per_chunk * bytes, per_chunk * elements as usize * 4), + (17 * bytes, 17 * elements as usize * 4) + ] + ); + assert_eq!(consumed, requested); + assert_eq!(receipt, blocks as u64 * elements * 4); + assert_eq!(cursor.position(), (prefix + requested) as u64); + for malformed in [0, 1, bytes - 1, bytes + 1] { + let mut cursor = Cursor::new(&source); + cursor.set_position(7); + let mut calls = 0; + assert!( + visit( + &mut cursor, + prefix as u64, + kind, + malformed as u64, + |_, _| { + calls += 1; + Ok(()) + } + ) + .is_err() + ); + assert_eq!(calls, 0); + assert_eq!(cursor.position(), 7); + } + for delivered in [0, 1] { + let available = delivered * per_chunk * bytes + bytes - 1; + let required = delivered * per_chunk * bytes + bytes; + let mut calls = 0; + assert!( + visit( + &mut Cursor::new(&source[..prefix + available]), + prefix as u64, + kind, + required as u64, + |raw, derived| { + calls += 1; + assert_eq!(raw.len(), per_chunk * bytes); + assert_eq!(derived.len(), per_chunk * elements as usize * 4); + Ok(()) + } + ) + .is_err() + ); + assert_eq!(calls, delivered); + } + for fail_on in [1, 2] { + let mut cursor = Cursor::new(&source); + let mut calls = 0; + let error = visit( + &mut cursor, + prefix as u64, + kind, + requested as u64, + |_, _| { + calls += 1; + if calls == fail_on { + Err("owned callback abort".into()) + } else { + Ok(()) + } + }, + ) + .unwrap_err(); + assert_eq!(error, "owned callback abort"); + assert_eq!(calls, fail_on); + assert_eq!( + cursor.position(), + (prefix + + if fail_on == 1 { + per_chunk * bytes + } else { + requested + }) as u64 + ); + } + } +} + +#[test] +fn q4_q5_k_streams_preserve_both_nonfinite_scale_roles_and_zero_packed_fields() { + let scales = [ + 0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00, + ]; + for kind in [12, 13] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + for d in scales { + for dmin in scales { + for zero_fields in [false, true] { + let mut block = vec![0u8; bytes as usize]; + block[..2].copy_from_slice(&d.to_le_bytes()); + block[2..4].copy_from_slice(&dmin.to_le_bytes()); + if !zero_fields { + for (position, byte) in block[4..].iter_mut().enumerate() { + *byte = (position * 29 + 17) as u8; + } + } + let mut oracle = vec![0.0; elements as usize]; + ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap(); + let mut calls = 0; + let receipt = + visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| { + assert_eq!(raw, block); + assert_eq!(derived.len(), elements as usize * 4); + for (actual, reference) in + derived.as_chunks::<4>().0.iter().zip(&oracle) + { + let actual = f32::from_le_bytes(*actual); + if reference.is_nan() { + assert!(actual.is_nan()); + } else { + assert_eq!(actual.to_bits(), reference.to_bits()); + } + } + calls += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(calls, 1); + assert_eq!(receipt, elements * 4); + } + } + } + } +} +#[test] +fn q6_q2_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() { + let edges = [ + 0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff, + ]; + for kind in [14, 42] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + let bytes = bytes as usize; + let per_chunk = SOURCE_CHUNK_BYTES / bytes; + let blocks = per_chunk + 17; + let prefix = 11; + let mut source = vec![0xa5; prefix]; + for number in 0..blocks { + let mut block = vec![0u8; bytes]; + for (position, byte) in block.iter_mut().enumerate() { + *byte = (number * 17 + position * 29) as u8; + } + let header = if kind == 14 { 208 } else { 0 }; + block[header..header + 2] + .copy_from_slice(&edges[number % edges.len()].to_le_bytes()); + source.extend_from_slice(&block); + } + let requested = blocks * bytes; + source.extend_from_slice(&[0x5a; 19]); + let mut cursor = Cursor::new(&source); + let mut consumed = 0; + let mut chunks = Vec::new(); + let receipt = visit( + &mut cursor, + prefix as u64, + kind, + requested as u64, + |raw, derived| { + assert!(raw.len() <= SOURCE_CHUNK_BYTES); + assert_eq!( + raw, + &source[prefix + consumed..prefix + consumed + raw.len()] + ); + let mut oracle = vec![0.0; raw.len() / bytes * elements as usize]; + ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap(); + let expected: Vec = oracle + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect(); + assert_eq!(derived, expected, "kind {kind}"); + assert!(derived.len() <= per_chunk * elements as usize * 4); + chunks.push((raw.len(), derived.len())); + consumed += raw.len(); + Ok(()) + }, + ) + .unwrap(); + assert_eq!( + chunks, + [ + (per_chunk * bytes, per_chunk * elements as usize * 4), + (17 * bytes, 17 * elements as usize * 4) + ] + ); + assert_eq!(consumed, requested); + assert_eq!(receipt, blocks as u64 * elements * 4); + assert_eq!(cursor.position(), (prefix + requested) as u64); + for malformed in [0, 1, bytes - 1, bytes + 1] { + let mut cursor = Cursor::new(&source); + cursor.set_position(7); + let mut calls = 0; + assert!( + visit( + &mut cursor, + prefix as u64, + kind, + malformed as u64, + |_, _| { + calls += 1; + Ok(()) + } + ) + .is_err() + ); + assert_eq!(calls, 0); + assert_eq!(cursor.position(), 7); + } + for delivered in [0, 1] { + let available = delivered * per_chunk * bytes + bytes - 1; + let required = delivered * per_chunk * bytes + bytes; + let mut calls = 0; + assert!( + visit( + &mut Cursor::new(&source[..prefix + available]), + prefix as u64, + kind, + required as u64, + |raw, derived| { + calls += 1; + assert_eq!(raw.len(), per_chunk * bytes); + assert_eq!(derived.len(), per_chunk * elements as usize * 4); + Ok(()) + } + ) + .is_err() + ); + assert_eq!(calls, delivered); + } + for fail_on in [1, 2] { + let mut cursor = Cursor::new(&source); + let mut calls = 0; + let error = visit( + &mut cursor, + prefix as u64, + kind, + requested as u64, + |_, _| { + calls += 1; + if calls == fail_on { + Err("owned callback abort".into()) + } else { + Ok(()) + } + }, + ) + .unwrap_err(); + assert_eq!(error, "owned callback abort"); + assert_eq!(calls, fail_on); + assert_eq!( + cursor.position(), + (prefix + + if fail_on == 1 { + per_chunk * bytes + } else { + requested + }) as u64 + ); + } + } +} + +#[test] +fn q6_q2_streams_preserve_nonfinite_headers_and_zero_factors() { + for kind in [14, 42] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + for bits in [ + 0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00, + ] { + for variant in 0..3 { + let mut block = vec![0u8; bytes as usize]; + for (position, byte) in block.iter_mut().enumerate() { + *byte = (position * 29 + 17) as u8; + } + if kind == 14 { + if variant == 1 { + block[192..208].fill(0); + } + if variant == 2 { + block[..128].fill(0); + block[128..192].fill(0xaa); + } + } else if variant != 0 { + block[2..].fill(if variant == 1 { 0x55 } else { 0 }); + } + let header = if kind == 14 { 208 } else { 0 }; + block[header..header + 2].copy_from_slice(&bits.to_le_bytes()); + let mut oracle = vec![0.0; elements as usize]; + ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap(); + let mut calls = 0; + let receipt = + visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| { + assert_eq!(raw, block); + assert_eq!(derived.len(), elements as usize * 4); + for (actual, reference) in + derived.as_chunks::<4>().0.iter().zip(&oracle) + { + let actual = f32::from_le_bytes(*actual); + if reference.is_nan() { + assert!(actual.is_nan()); + } else { + assert_eq!(actual.to_bits(), reference.to_bits()); + } + } + calls += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(calls, 1); + assert_eq!(receipt, elements * 4); + } + } + } +} +#[test] +fn iq2s_iq3xxs_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() { + let edges = [ + 0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff, + ]; + for kind in [22, 18] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + let bytes = bytes as usize; + let per_chunk = SOURCE_CHUNK_BYTES / bytes; + let blocks = per_chunk + 17; + let prefix = 11; + let mut source = vec![0xa5; prefix]; + for number in 0..blocks { + let mut block = vec![0u8; bytes]; + for (position, byte) in block.iter_mut().enumerate() { + *byte = (number * 17 + position * 29) as u8; + } + let header = 0; + block[header..header + 2] + .copy_from_slice(&edges[number % edges.len()].to_le_bytes()); + source.extend_from_slice(&block); + } + let requested = blocks * bytes; + source.extend_from_slice(&[0x5a; 19]); + let mut cursor = Cursor::new(&source); + let mut consumed = 0; + let mut chunks = Vec::new(); + let receipt = visit( + &mut cursor, + prefix as u64, + kind, + requested as u64, + |raw, derived| { + assert!(raw.len() <= SOURCE_CHUNK_BYTES); + assert_eq!( + raw, + &source[prefix + consumed..prefix + consumed + raw.len()] + ); + let mut oracle = vec![0.0; raw.len() / bytes * elements as usize]; + ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap(); + let expected: Vec = oracle + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect(); + assert_eq!(derived, expected, "kind {kind}"); + assert!(derived.len() <= per_chunk * elements as usize * 4); + chunks.push((raw.len(), derived.len())); + consumed += raw.len(); + Ok(()) + }, + ) + .unwrap(); + assert_eq!( + chunks, + [ + (per_chunk * bytes, per_chunk * elements as usize * 4), + (17 * bytes, 17 * elements as usize * 4) + ] + ); + assert_eq!(consumed, requested); + assert_eq!(receipt, blocks as u64 * elements * 4); + assert_eq!(cursor.position(), (prefix + requested) as u64); + for malformed in [0, 1, bytes - 1, bytes + 1] { + let mut cursor = Cursor::new(&source); + cursor.set_position(7); + let mut calls = 0; + assert!( + visit( + &mut cursor, + prefix as u64, + kind, + malformed as u64, + |_, _| { + calls += 1; + Ok(()) + } + ) + .is_err() + ); + assert_eq!(calls, 0); + assert_eq!(cursor.position(), 7); + } + for delivered in [0, 1] { + let available = delivered * per_chunk * bytes + bytes - 1; + let required = delivered * per_chunk * bytes + bytes; + let mut calls = 0; + assert!( + visit( + &mut Cursor::new(&source[..prefix + available]), + prefix as u64, + kind, + required as u64, + |raw, derived| { + calls += 1; + assert_eq!(raw.len(), per_chunk * bytes); + assert_eq!(derived.len(), per_chunk * elements as usize * 4); + Ok(()) + } + ) + .is_err() + ); + assert_eq!(calls, delivered); + } + for fail_on in [1, 2] { + let mut cursor = Cursor::new(&source); + let mut calls = 0; + let error = visit( + &mut cursor, + prefix as u64, + kind, + requested as u64, + |_, _| { + calls += 1; + if calls == fail_on { + Err("owned callback abort".into()) + } else { + Ok(()) + } + }, + ) + .unwrap_err(); + assert_eq!(error, "owned callback abort"); + assert_eq!(calls, fail_on); + assert_eq!( + cursor.position(), + (prefix + + if fail_on == 1 { + per_chunk * bytes + } else { + requested + }) as u64 + ); + } + } +} + +#[test] +fn iq2s_iq3xxs_streams_preserve_nonfinite_signed_zero_and_zero_packed_fields() { + for kind in [22, 18] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + for bits in [ + 0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00, + ] { + for zero_fields in [false, true] { + let mut block = vec![0; bytes as usize]; + if !zero_fields { + for (field, byte) in block[2..].iter_mut().enumerate() { + *byte = (field * 29 + 17) as u8; + } + } + block[..2].copy_from_slice(&bits.to_le_bytes()); + let mut oracle = vec![0.0; elements as usize]; + ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap(); + let mut calls = 0; + let receipt = + visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| { + assert_eq!(raw, block); + assert_eq!(derived.len(), elements as usize * 4); + for (actual, expected) in derived.as_chunks::<4>().0.iter().zip(&oracle) + { + let actual = f32::from_le_bytes(*actual); + if expected.is_nan() { + assert!(actual.is_nan()); + } else { + assert_eq!(actual.to_bits(), expected.to_bits()); + } + } + calls += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(calls, 1); + assert_eq!(receipt, elements * 4); + } + } + } +} diff --git a/control-plane/src/harmony_family.rs b/control-plane/src/harmony_family.rs index ce4d392a..995409e8 100644 --- a/control-plane/src/harmony_family.rs +++ b/control-plane/src/harmony_family.rs @@ -281,235 +281,4 @@ impl TokenDecoder for HarmonyDecoder { } #[cfg(test)] -mod tests { - use super::*; - - /// A tiny vocabulary: the byte tokens, a few merges, and the Harmony markers as control tokens. - fn codec() -> GptOssCodec { - let chars = leleka_tokenizer::gguf_bpe::byte_alphabet(); - let mut tokens: Vec = chars.iter().map(|c| c.to_string()).collect(); - let mut types = vec![1i64; 256]; - for marker in [ - "<|start|>", - "<|end|>", - "<|message|>", - "<|channel|>", - "<|call|>", - "<|return|>", - "<|constrain|>", - "<|endoftext|>", - ] { - tokens.push(marker.to_owned()); - types.push(3); - } - let t: Vec<&str> = tokens.iter().map(String::as_str).collect(); - GptOssCodec::new(GgufBpe::from_parts(&t, &types, &[], None, None, None).unwrap()).unwrap() - } - - /// Token ids for a script of text and markers. - fn script(c: &GptOssCodec, parts: &[&str]) -> Vec { - let mut ids = Vec::new(); - for part in parts { - match c.bpe.token_id(part) { - Some(id) if part.starts_with("<|") => ids.push(id), - _ => ids.extend(c.bpe.encode(part, false)), - } - } - ids - } - - fn decode(c: &GptOssCodec, ids: &[u32]) -> String { - String::from_utf8(crate::codec::decode_all(c, ids).unwrap()).unwrap() - } - - #[test] - fn reasoning_then_an_answer_becomes_think_markup() { - let c = codec(); - let ids = script( - &c, - &[ - "<|channel|>", - "analysis", - "<|message|>", - "Let me think.", - "<|end|>", - "<|start|>", - "assistant", - "<|channel|>", - "final", - "<|message|>", - "Paris.", - ], - ); - assert_eq!(decode(&c, &ids), "Let me think.\n\nParis."); - } - - #[test] - fn an_answer_without_reasoning_still_closes_the_think_block() { - let c = codec(); - let ids = script(&c, &["<|channel|>", "final", "<|message|>", "Hi"]); - assert_eq!(decode(&c, &ids), "\n\nHi"); - } - - #[test] - fn a_tool_call_becomes_a_tool_call_block_and_is_closed_by_finish() { - let c = codec(); - // the generation's last token <|call|> is terminal and never decoded - let ids = script( - &c, - &[ - "<|channel|>", - "analysis", - "<|message|>", - "Need weather.", - "<|end|>", - "<|start|>", - "assistant", - "<|channel|>", - "commentary to=functions.get_weather ", - "<|constrain|>", - "json", - "<|message|>", - "{\"city\":\"Paris\",\"days\":3,\"deep\":true}", - ], - ); - assert_eq!( - decode(&c, &ids), - "Need weather.\n\n\n\n\nParis\n\n\n3\n\n\ntrue\n\n\n" - ); - } - - #[test] - fn a_preamble_and_two_calls_keep_their_order() { - let c = codec(); - let ids = script( - &c, - &[ - "<|channel|>", - "commentary", - "<|message|>", - "Checking.", - "<|end|>", - "<|start|>", - "assistant", - "<|channel|>", - "commentary to=functions.a ", - "<|constrain|>", - "json", - "<|message|>", - "{}", - "<|end|>", - "<|start|>", - "assistant", - "<|channel|>", - "commentary to=functions.b ", - "<|constrain|>", - "json", - "<|message|>", - "{\"x\":\"1\"}", - ], - ); - assert_eq!( - decode(&c, &ids), - "\n\nChecking.\n\n\n\n\n\n\n\n\n\n1\n\n\n" - ); - } - - #[test] - fn reasoning_only_closes_the_block_when_its_message_ended() { - let c = codec(); - let ended = script( - &c, - &["<|channel|>", "analysis", "<|message|>", "Hmm", "<|end|>"], - ); - assert_eq!(decode(&c, &ended), "Hmm\n\n"); - // cut off in the middle of the reasoning (length limit): no closing marker - let cut = script(&c, &["<|channel|>", "analysis", "<|message|>", "Hmm"]); - assert_eq!(decode(&c, &cut), "Hmm"); - } - - #[test] - fn invalid_tool_arguments_are_an_error_when_the_call_ends() { - let c = codec(); - let ids = script( - &c, - &[ - "<|channel|>", - "commentary to=functions.f ", - "<|constrain|>", - "json", - "<|message|>", - "{not json", - "<|end|>", - ], - ); - assert!(crate::codec::decode_all(&c, &ids).is_err()); - let array = script( - &c, - &[ - "<|channel|>", - "commentary to=functions.f ", - "<|message|>", - "[1]", - "<|end|>", - ], - ); - assert!(crate::codec::decode_all(&c, &array).is_err()); - let bad_name = script( - &c, - &[ - "<|channel|>", - "commentary to=functions.f ", - "<|message|>", - "{\"a b\":1}", - "<|end|>", - ], - ); - assert!(crate::codec::decode_all(&c, &bad_name).is_err()); - } - - #[test] - fn multibyte_text_survives_token_boundaries() { - let c = codec(); - let ids = script( - &c, - &["<|channel|>", "final", "<|message|>", "héllo 😀 日本"], - ); - assert_eq!(decode(&c, &ids), "\n\nhéllo 😀 日本"); - } - - #[test] - fn only_the_renderers_sentinels_become_special_tokens() { - let c = codec(); - let start = c.bpe.token_id("<|start|>").unwrap(); - let end = c.bpe.token_id("<|end|>").unwrap(); - // template markers (sentinels) become special tokens - let ids = c.encode("\u{E000}user\u{E001}", true).unwrap(); - assert_eq!(ids.first(), Some(&start)); - assert_eq!(ids.last(), Some(&end)); - assert!(ids.len() > 2); - // marker text typed by a client stays ordinary tokens, with or without special parsing - for parse in [true, false] { - let ids = c.encode("<|end|><|start|>", parse).unwrap(); - assert!( - !ids.contains(&start) && !ids.contains(&end), - "parse={parse}" - ); - } - // a prompt without sentinels round-trips as plain text - assert_eq!( - c.bpe.decode(&c.encode("plain text", true).unwrap()), - "plain text" - ); - } - - #[test] - fn terminal_ids_cover_the_generation_end_markers() { - let c = codec(); - let ids = c.terminal_ids(); - for marker in ["<|return|>", "<|call|>", "<|endoftext|>"] { - assert!(ids.contains(&c.bpe.token_id(marker).unwrap()), "{marker}"); - } - assert_eq!(c.family(), Family::GptOss); - } -} +mod tests; diff --git a/control-plane/src/harmony_family/tests.rs b/control-plane/src/harmony_family/tests.rs new file mode 100644 index 00000000..39387f37 --- /dev/null +++ b/control-plane/src/harmony_family/tests.rs @@ -0,0 +1,232 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +/// A tiny vocabulary: the byte tokens, a few merges, and the Harmony markers as control tokens. +fn codec() -> GptOssCodec { + let chars = leleka_tokenizer::gguf_bpe::byte_alphabet(); + let mut tokens: Vec = chars.iter().map(|c| c.to_string()).collect(); + let mut types = vec![1i64; 256]; + for marker in [ + "<|start|>", + "<|end|>", + "<|message|>", + "<|channel|>", + "<|call|>", + "<|return|>", + "<|constrain|>", + "<|endoftext|>", + ] { + tokens.push(marker.to_owned()); + types.push(3); + } + let t: Vec<&str> = tokens.iter().map(String::as_str).collect(); + GptOssCodec::new(GgufBpe::from_parts(&t, &types, &[], None, None, None).unwrap()).unwrap() +} + +/// Token ids for a script of text and markers. +fn script(c: &GptOssCodec, parts: &[&str]) -> Vec { + let mut ids = Vec::new(); + for part in parts { + match c.bpe.token_id(part) { + Some(id) if part.starts_with("<|") => ids.push(id), + _ => ids.extend(c.bpe.encode(part, false)), + } + } + ids +} + +fn decode(c: &GptOssCodec, ids: &[u32]) -> String { + String::from_utf8(crate::codec::decode_all(c, ids).unwrap()).unwrap() +} + +#[test] +fn reasoning_then_an_answer_becomes_think_markup() { + let c = codec(); + let ids = script( + &c, + &[ + "<|channel|>", + "analysis", + "<|message|>", + "Let me think.", + "<|end|>", + "<|start|>", + "assistant", + "<|channel|>", + "final", + "<|message|>", + "Paris.", + ], + ); + assert_eq!(decode(&c, &ids), "Let me think.\n\nParis."); +} + +#[test] +fn an_answer_without_reasoning_still_closes_the_think_block() { + let c = codec(); + let ids = script(&c, &["<|channel|>", "final", "<|message|>", "Hi"]); + assert_eq!(decode(&c, &ids), "\n\nHi"); +} + +#[test] +fn a_tool_call_becomes_a_tool_call_block_and_is_closed_by_finish() { + let c = codec(); + // the generation's last token <|call|> is terminal and never decoded + let ids = script( + &c, + &[ + "<|channel|>", + "analysis", + "<|message|>", + "Need weather.", + "<|end|>", + "<|start|>", + "assistant", + "<|channel|>", + "commentary to=functions.get_weather ", + "<|constrain|>", + "json", + "<|message|>", + "{\"city\":\"Paris\",\"days\":3,\"deep\":true}", + ], + ); + assert_eq!( + decode(&c, &ids), + "Need weather.\n\n\n\n\nParis\n\n\n3\n\n\ntrue\n\n\n" + ); +} + +#[test] +fn a_preamble_and_two_calls_keep_their_order() { + let c = codec(); + let ids = script( + &c, + &[ + "<|channel|>", + "commentary", + "<|message|>", + "Checking.", + "<|end|>", + "<|start|>", + "assistant", + "<|channel|>", + "commentary to=functions.a ", + "<|constrain|>", + "json", + "<|message|>", + "{}", + "<|end|>", + "<|start|>", + "assistant", + "<|channel|>", + "commentary to=functions.b ", + "<|constrain|>", + "json", + "<|message|>", + "{\"x\":\"1\"}", + ], + ); + assert_eq!( + decode(&c, &ids), + "\n\nChecking.\n\n\n\n\n\n\n\n\n\n1\n\n\n" + ); +} + +#[test] +fn reasoning_only_closes_the_block_when_its_message_ended() { + let c = codec(); + let ended = script( + &c, + &["<|channel|>", "analysis", "<|message|>", "Hmm", "<|end|>"], + ); + assert_eq!(decode(&c, &ended), "Hmm\n\n"); + // cut off in the middle of the reasoning (length limit): no closing marker + let cut = script(&c, &["<|channel|>", "analysis", "<|message|>", "Hmm"]); + assert_eq!(decode(&c, &cut), "Hmm"); +} + +#[test] +fn invalid_tool_arguments_are_an_error_when_the_call_ends() { + let c = codec(); + let ids = script( + &c, + &[ + "<|channel|>", + "commentary to=functions.f ", + "<|constrain|>", + "json", + "<|message|>", + "{not json", + "<|end|>", + ], + ); + assert!(crate::codec::decode_all(&c, &ids).is_err()); + let array = script( + &c, + &[ + "<|channel|>", + "commentary to=functions.f ", + "<|message|>", + "[1]", + "<|end|>", + ], + ); + assert!(crate::codec::decode_all(&c, &array).is_err()); + let bad_name = script( + &c, + &[ + "<|channel|>", + "commentary to=functions.f ", + "<|message|>", + "{\"a b\":1}", + "<|end|>", + ], + ); + assert!(crate::codec::decode_all(&c, &bad_name).is_err()); +} + +#[test] +fn multibyte_text_survives_token_boundaries() { + let c = codec(); + let ids = script( + &c, + &["<|channel|>", "final", "<|message|>", "héllo 😀 日本"], + ); + assert_eq!(decode(&c, &ids), "\n\nhéllo 😀 日本"); +} + +#[test] +fn only_the_renderers_sentinels_become_special_tokens() { + let c = codec(); + let start = c.bpe.token_id("<|start|>").unwrap(); + let end = c.bpe.token_id("<|end|>").unwrap(); + // template markers (sentinels) become special tokens + let ids = c.encode("\u{E000}user\u{E001}", true).unwrap(); + assert_eq!(ids.first(), Some(&start)); + assert_eq!(ids.last(), Some(&end)); + assert!(ids.len() > 2); + // marker text typed by a client stays ordinary tokens, with or without special parsing + for parse in [true, false] { + let ids = c.encode("<|end|><|start|>", parse).unwrap(); + assert!( + !ids.contains(&start) && !ids.contains(&end), + "parse={parse}" + ); + } + // a prompt without sentinels round-trips as plain text + assert_eq!( + c.bpe.decode(&c.encode("plain text", true).unwrap()), + "plain text" + ); +} + +#[test] +fn terminal_ids_cover_the_generation_end_markers() { + let c = codec(); + let ids = c.terminal_ids(); + for marker in ["<|return|>", "<|call|>", "<|endoftext|>"] { + assert!(ids.contains(&c.bpe.token_id(marker).unwrap()), "{marker}"); + } + assert_eq!(c.family(), Family::GptOss); +} diff --git a/control-plane/src/kar.rs b/control-plane/src/kar.rs index 5009b550..e502a971 100644 --- a/control-plane/src/kar.rs +++ b/control-plane/src/kar.rs @@ -295,219 +295,4 @@ pub fn verify_source_files( } #[cfg(test)] -mod tests { - use super::*; - use crate::model::ModelFile; - use crate::{kar_codec, kar_writer}; - use std::fs; - - fn put_u32(bytes: &mut [u8], offset: usize, value: u32) { - bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); - } - - fn put_u64(bytes: &mut [u8], offset: usize, value: u64) { - bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); - } - - #[test] - fn crc32_matches_iso_hdlc_reference() { - assert_eq!(crc32(b"123456789"), 0xcbf4_3926); - let first = crc32_step(!0, b"1234"); - assert_eq!(!crc32_step(first, b"56789"), 0xcbf4_3926); - } - - #[test] - fn source_identity_uses_verified_shards_in_filename_order() { - let root = std::env::temp_dir().join(format!("strata-kar-source-{}", std::process::id())); - fs::create_dir(&root).unwrap(); - fs::write(root.join("b.gguf"), b"def").unwrap(); - fs::write(root.join("a.gguf"), b"abc").unwrap(); - let sha = |bytes: &[u8]| hex::encode(Sha256::digest(bytes)); - let manifest = Manifest { - schema_version: 1, - files: vec![ - ModelFile { - name: "b.gguf".into(), - url: "https://example.invalid/b".into(), - size: 3, - sha256: sha(b"def"), - }, - ModelFile { - name: "a.gguf".into(), - url: "https://example.invalid/a".into(), - size: 3, - sha256: sha(b"abc"), - }, - ], - }; - let mut digest = [0; 32]; - digest.copy_from_slice(&Sha256::digest(b"abcdef")); - let summary = Summary { - archive_bytes: 1, - tensor_count: 1, - total_elements: 1, - source_total_elements: 1, - accounted_bpw: 8.0, - source_digest: digest, - source_bytes: 6, - max_planes: 0, - }; - verify_source_files(&summary, &manifest, &root).unwrap(); - fs::write(root.join("b.gguf"), b"xyz").unwrap(); - assert!( - verify_source_files(&summary, &manifest, &root) - .unwrap_err() - .contains("SHA-256") - ); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn inspects_a_raw_archive_and_rejects_corruption() { - let mut archive = vec![0u8; 768]; - let payload_crc = crc32(&archive[512..]); - let (header, rest) = archive.split_at_mut(256); - let (directory, string_and_payload) = rest.split_at_mut(192); - let names = &mut string_and_payload[..7]; - names.copy_from_slice(b"weight\0"); - put_u32(directory, 0, 0); - directory[4..6].copy_from_slice(&6u16.to_le_bytes()); - directory[6] = 1; - directory[7] = 1; - for index in 0..4 { - put_u64(directory, 8 + index * 8, if index == 0 { 64 } else { 1 }); - } - put_u64(directory, 48, 64); - put_u64(directory, 56, 64); - put_u64(directory, 112, 512); - put_u64(directory, 120, 256); - put_u32(directory, 108, payload_crc); - - header[..8].copy_from_slice(b"KARCHIV2"); - put_u32(header, 8, 2); - put_u32(header, 12, 0x04030201); - put_u32(header, 16, 256); - put_u32(header, 20, 192); - put_u64(header, 24, 256); - put_u32(header, 32, 1); - put_u64(header, 40, 448); - put_u64(header, 48, 7); - put_u64(header, 56, 512); - put_u64(header, 64, 768); - put_u64(header, 72, 64); - put_u64(header, 88, 64); - put_u64(header, 120, 256); - header[96..104].copy_from_slice(&96f64.to_le_bytes()); - header[106] = 1; - let mut digest = Sha256::new(); - digest.update(names); - digest.update(directory); - header[160..192].copy_from_slice(&digest.finalize()); - let header_crc = crc32(&header[..192]); - put_u32(header, 192, header_crc); - - let path = std::env::temp_dir().join(format!("strata-kar-test-{}", std::process::id())); - fs::write(&path, &archive).unwrap(); - let summary = inspect(&path).unwrap(); - assert_eq!(summary.tensor_count, 1); - assert_eq!(summary.accounted_bpw, 96.0); - assert_eq!(verify(&path).unwrap(), summary); - let mut decoder = VerifiedRangeDecoder::open(&path).unwrap(); - assert_eq!(decoder.element_count("weight").unwrap(), 64); - assert_eq!( - decoder.decode_range("weight", 0, 8, 4).unwrap(), - vec![0.0; 4] - ); - let mut nested = archive.clone(); - let (header, rest) = nested.split_at_mut(256); - let (directory, string_and_payload) = rest.split_at_mut(192); - directory[7] = 0; - put_u64(directory, 8, 32); - put_u64(directory, 48, 32); - put_u64(directory, 56, 32); - directory[42..45].fill(1); - directory[46..48].copy_from_slice(&32u16.to_le_bytes()); - put_u64(directory, 64, 512); - put_u64(directory, 72, 2); - put_u64(directory, 80, 528); - put_u64(directory, 88, 4); - put_u64(directory, 96, 544); - put_u32(directory, 104, 16); - put_u64(header, 72, 32); - put_u64(header, 80, 48); - put_u64(header, 88, 32); - header[96..104].copy_from_slice(&192f64.to_le_bytes()); - header[104..106].fill(1); - let mut digest = Sha256::new(); - digest.update(&string_and_payload[..7]); - digest.update(directory); - header[160..192].copy_from_slice(&digest.finalize()); - let header_crc = crc32(&header[..192]); - put_u32(header, 192, header_crc); - fs::write(&path, &nested).unwrap(); - let summary = inspect(&path).unwrap(); - assert_eq!(summary.accounted_bpw, 192.0); - assert_eq!(verify(&path).unwrap(), summary); - nested[512] ^= 1; - fs::write(&path, &nested).unwrap(); - assert_eq!(inspect(&path).unwrap(), summary); - assert!(verify(&path).unwrap_err().contains("payload CRC")); - - archive[300] ^= 1; - fs::write(&path, &archive).unwrap(); - assert!(inspect(&path).unwrap_err().contains("digest")); - archive.truncate(767); - fs::write(&path, &archive).unwrap(); - assert!(inspect(&path).unwrap_err().contains("length")); - fs::remove_file(path).unwrap(); - } - - #[test] - fn bounded_archive_range_decode_crosses_scale_and_plane_groups() { - let weights = [-1.0f32, -0.25, 0.25, 1.0].repeat(24); - let encoded = - kar_codec::encode_with_boundaries(&weights, 32, &[-0.5, 0.0, 0.5], 2).unwrap(); - let book1 = [0xb800u16, 0x3800]; - let book2 = [0xba00u16, 0xb400, 0x3400, 0x3a00]; - let books: [&[u16]; 2] = [&book1, &book2]; - let planes = encoded.planes.iter().map(Vec::as_slice).collect::>(); - let source = kar_writer::SourceIdentity { - name: "range-fixture", - architecture: "synthetic", - builder: "strata-next/kar-range-test", - digest: Sha256::digest(b"source").into(), - total_elements: 96, - bytes: 384, - }; - let tensor = [kar_writer::Tensor { - name: "expert", - dims: &[96], - source_dtype: 0, - source_digest: Sha256::digest(b"weights").into(), - source_offset: 0, - data: kar_writer::TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - scales: &encoded.scales, - books: &books, - planes: &planes, - }, - }]; - let path = - std::env::temp_dir().join(format!("strata-kar-range-{}.kar", std::process::id())); - let _ = fs::remove_file(&path); - kar_writer::write_archive(&path, &source, &tensor).unwrap(); - let full = decode_preview_tensor(&path, "expert", 2).unwrap(); - for (start, count) in [(0, 1), (27, 10), (31, 34), (64, 32), (95, 1)] { - assert_eq!( - decode_tensor_range(&path, "expert", 2, start, count).unwrap(), - full[start..start + count] - ); - } - assert!(decode_tensor_range(&path, "expert", 2, 96, 1).is_err()); - assert!(decode_tensor_range(&path, "expert", 2, 0, 0).is_err()); - fs::remove_file(path).unwrap(); - } -} +mod tests; diff --git a/control-plane/src/kar/tests.rs b/control-plane/src/kar/tests.rs new file mode 100644 index 00000000..a4635e80 --- /dev/null +++ b/control-plane/src/kar/tests.rs @@ -0,0 +1,216 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::model::ModelFile; +use crate::{kar_codec, kar_writer}; +use std::fs; + +fn put_u32(bytes: &mut [u8], offset: usize, value: u32) { + bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} + +fn put_u64(bytes: &mut [u8], offset: usize, value: u64) { + bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} + +#[test] +fn crc32_matches_iso_hdlc_reference() { + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); + let first = crc32_step(!0, b"1234"); + assert_eq!(!crc32_step(first, b"56789"), 0xcbf4_3926); +} + +#[test] +fn source_identity_uses_verified_shards_in_filename_order() { + let root = std::env::temp_dir().join(format!("strata-kar-source-{}", std::process::id())); + fs::create_dir(&root).unwrap(); + fs::write(root.join("b.gguf"), b"def").unwrap(); + fs::write(root.join("a.gguf"), b"abc").unwrap(); + let sha = |bytes: &[u8]| hex::encode(Sha256::digest(bytes)); + let manifest = Manifest { + schema_version: 1, + files: vec![ + ModelFile { + name: "b.gguf".into(), + url: "https://example.invalid/b".into(), + size: 3, + sha256: sha(b"def"), + }, + ModelFile { + name: "a.gguf".into(), + url: "https://example.invalid/a".into(), + size: 3, + sha256: sha(b"abc"), + }, + ], + }; + let mut digest = [0; 32]; + digest.copy_from_slice(&Sha256::digest(b"abcdef")); + let summary = Summary { + archive_bytes: 1, + tensor_count: 1, + total_elements: 1, + source_total_elements: 1, + accounted_bpw: 8.0, + source_digest: digest, + source_bytes: 6, + max_planes: 0, + }; + verify_source_files(&summary, &manifest, &root).unwrap(); + fs::write(root.join("b.gguf"), b"xyz").unwrap(); + assert!( + verify_source_files(&summary, &manifest, &root) + .unwrap_err() + .contains("SHA-256") + ); + fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn inspects_a_raw_archive_and_rejects_corruption() { + let mut archive = vec![0u8; 768]; + let payload_crc = crc32(&archive[512..]); + let (header, rest) = archive.split_at_mut(256); + let (directory, string_and_payload) = rest.split_at_mut(192); + let names = &mut string_and_payload[..7]; + names.copy_from_slice(b"weight\0"); + put_u32(directory, 0, 0); + directory[4..6].copy_from_slice(&6u16.to_le_bytes()); + directory[6] = 1; + directory[7] = 1; + for index in 0..4 { + put_u64(directory, 8 + index * 8, if index == 0 { 64 } else { 1 }); + } + put_u64(directory, 48, 64); + put_u64(directory, 56, 64); + put_u64(directory, 112, 512); + put_u64(directory, 120, 256); + put_u32(directory, 108, payload_crc); + + header[..8].copy_from_slice(b"KARCHIV2"); + put_u32(header, 8, 2); + put_u32(header, 12, 0x04030201); + put_u32(header, 16, 256); + put_u32(header, 20, 192); + put_u64(header, 24, 256); + put_u32(header, 32, 1); + put_u64(header, 40, 448); + put_u64(header, 48, 7); + put_u64(header, 56, 512); + put_u64(header, 64, 768); + put_u64(header, 72, 64); + put_u64(header, 88, 64); + put_u64(header, 120, 256); + header[96..104].copy_from_slice(&96f64.to_le_bytes()); + header[106] = 1; + let mut digest = Sha256::new(); + digest.update(names); + digest.update(directory); + header[160..192].copy_from_slice(&digest.finalize()); + let header_crc = crc32(&header[..192]); + put_u32(header, 192, header_crc); + + let path = std::env::temp_dir().join(format!("strata-kar-test-{}", std::process::id())); + fs::write(&path, &archive).unwrap(); + let summary = inspect(&path).unwrap(); + assert_eq!(summary.tensor_count, 1); + assert_eq!(summary.accounted_bpw, 96.0); + assert_eq!(verify(&path).unwrap(), summary); + let mut decoder = VerifiedRangeDecoder::open(&path).unwrap(); + assert_eq!(decoder.element_count("weight").unwrap(), 64); + assert_eq!( + decoder.decode_range("weight", 0, 8, 4).unwrap(), + vec![0.0; 4] + ); + let mut nested = archive.clone(); + let (header, rest) = nested.split_at_mut(256); + let (directory, string_and_payload) = rest.split_at_mut(192); + directory[7] = 0; + put_u64(directory, 8, 32); + put_u64(directory, 48, 32); + put_u64(directory, 56, 32); + directory[42..45].fill(1); + directory[46..48].copy_from_slice(&32u16.to_le_bytes()); + put_u64(directory, 64, 512); + put_u64(directory, 72, 2); + put_u64(directory, 80, 528); + put_u64(directory, 88, 4); + put_u64(directory, 96, 544); + put_u32(directory, 104, 16); + put_u64(header, 72, 32); + put_u64(header, 80, 48); + put_u64(header, 88, 32); + header[96..104].copy_from_slice(&192f64.to_le_bytes()); + header[104..106].fill(1); + let mut digest = Sha256::new(); + digest.update(&string_and_payload[..7]); + digest.update(directory); + header[160..192].copy_from_slice(&digest.finalize()); + let header_crc = crc32(&header[..192]); + put_u32(header, 192, header_crc); + fs::write(&path, &nested).unwrap(); + let summary = inspect(&path).unwrap(); + assert_eq!(summary.accounted_bpw, 192.0); + assert_eq!(verify(&path).unwrap(), summary); + nested[512] ^= 1; + fs::write(&path, &nested).unwrap(); + assert_eq!(inspect(&path).unwrap(), summary); + assert!(verify(&path).unwrap_err().contains("payload CRC")); + + archive[300] ^= 1; + fs::write(&path, &archive).unwrap(); + assert!(inspect(&path).unwrap_err().contains("digest")); + archive.truncate(767); + fs::write(&path, &archive).unwrap(); + assert!(inspect(&path).unwrap_err().contains("length")); + fs::remove_file(path).unwrap(); +} + +#[test] +fn bounded_archive_range_decode_crosses_scale_and_plane_groups() { + let weights = [-1.0f32, -0.25, 0.25, 1.0].repeat(24); + let encoded = + kar_codec::encode_with_boundaries(&weights, 32, &[-0.5, 0.0, 0.5], 2).unwrap(); + let book1 = [0xb800u16, 0x3800]; + let book2 = [0xba00u16, 0xb400, 0x3400, 0x3a00]; + let books: [&[u16]; 2] = [&book1, &book2]; + let planes = encoded.planes.iter().map(Vec::as_slice).collect::>(); + let source = kar_writer::SourceIdentity { + name: "range-fixture", + architecture: "synthetic", + builder: "strata-next/kar-range-test", + digest: Sha256::digest(b"source").into(), + total_elements: 96, + bytes: 384, + }; + let tensor = [kar_writer::Tensor { + name: "expert", + dims: &[96], + source_dtype: 0, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &encoded.scales, + books: &books, + planes: &planes, + }, + }]; + let path = + std::env::temp_dir().join(format!("strata-kar-range-{}.kar", std::process::id())); + let _ = fs::remove_file(&path); + kar_writer::write_archive(&path, &source, &tensor).unwrap(); + let full = decode_preview_tensor(&path, "expert", 2).unwrap(); + for (start, count) in [(0, 1), (27, 10), (31, 34), (64, 32), (95, 1)] { + assert_eq!( + decode_tensor_range(&path, "expert", 2, start, count).unwrap(), + full[start..start + count] + ); + } + assert!(decode_tensor_range(&path, "expert", 2, 96, 1).is_err()); + assert!(decode_tensor_range(&path, "expert", 2, 0, 0).is_err()); + fs::remove_file(path).unwrap(); +} diff --git a/control-plane/src/kar_quality.rs b/control-plane/src/kar_quality.rs index 4b58873c..b6870c9b 100644 --- a/control-plane/src/kar_quality.rs +++ b/control-plane/src/kar_quality.rs @@ -499,20 +499,4 @@ pub fn write_report(path: &Path, report: &Report) -> Result<(), String> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn sampled_windows_are_bounded_and_distinct() { - assert_eq!(sample_windows(256, 256).unwrap().len(), 1); - assert_eq!(sample_windows(5000, 1).unwrap().len(), 1); - assert_eq!(sample_windows(8192, 256).unwrap().len(), 2); - let windows = sample_windows(32_000, 256).unwrap(); - assert_eq!(windows.len(), 3); - assert!(windows.iter().all(|window| { - window.start.is_multiple_of(256) - && window.elements == 4096 - && window.start + window.elements <= 32_000 - })); - } -} +mod tests; diff --git a/control-plane/src/kar_quality/tests.rs b/control-plane/src/kar_quality/tests.rs new file mode 100644 index 00000000..79526bec --- /dev/null +++ b/control-plane/src/kar_quality/tests.rs @@ -0,0 +1,17 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn sampled_windows_are_bounded_and_distinct() { + assert_eq!(sample_windows(256, 256).unwrap().len(), 1); + assert_eq!(sample_windows(5000, 1).unwrap().len(), 1); + assert_eq!(sample_windows(8192, 256).unwrap().len(), 2); + let windows = sample_windows(32_000, 256).unwrap(); + assert_eq!(windows.len(), 3); + assert!(windows.iter().all(|window| { + window.start.is_multiple_of(256) + && window.elements == 4096 + && window.start + window.elements <= 32_000 + })); +} diff --git a/control-plane/src/kar_stream_encode.rs b/control-plane/src/kar_stream_encode.rs index 037078d3..7ad8af86 100644 --- a/control-plane/src/kar_stream_encode.rs +++ b/control-plane/src/kar_stream_encode.rs @@ -251,155 +251,4 @@ fn hash_file(path: &Path) -> Result<[u8; 32], String> { } #[cfg(test)] -mod tests { - use super::*; - use crate::{iq3_s, kar, kar_writer}; - use std::io::Cursor; - use std::time::{SystemTime, UNIX_EPOCH}; - - #[test] - fn streamed_section_matches_existing_writer_and_forms_verified_archive() { - let root = std::env::temp_dir().join(format!( - "strata-stream-section-{}-{}", - std::process::id(), - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::create_dir(&root).unwrap(); - let weights = (0..33) - .map(|number| [-1.0f32, -0.25, 0.25, 1.0][number % 4]) - .collect::>(); - let source = weights - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect::>(); - let calibration = kar_codec::Calibration { - boundaries: vec![-0.5, 0.0, 0.5], - books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], - }; - let expected = - kar_codec::encode_with_boundaries(&weights, 32, &calibration.boundaries, 2).unwrap(); - let books = calibration - .books - .iter() - .map(Vec::as_slice) - .collect::>(); - let planes = expected - .planes - .iter() - .map(Vec::as_slice) - .collect::>(); - let source_digest: [u8; 32] = Sha256::digest(&source).into(); - let reference = root.join("reference.section"); - kar_writer::write_nested_section( - &reference, - &kar_writer::Tensor { - name: "expert", - dims: &[33], - source_dtype: 0, - source_digest, - source_offset: 0, - data: kar_writer::TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - scales: &expected.scales, - books: &books, - planes: &planes, - }, - }, - ) - .unwrap(); - let output = root.join("streamed.section"); - let streamed = encode_section( - &mut Cursor::new(&source), - 0, - 0, - source.len() as u64, - weights.len() as u64, - &calibration, - &output, - ) - .unwrap(); - assert_eq!(fs::read(&output).unwrap(), fs::read(&reference).unwrap()); - assert_eq!(streamed.source_digest, source_digest); - assert_eq!(streamed.derived_digest, source_digest); - assert!(streamed.relative_l2.is_finite()); - let archive = root.join("model.kar"); - kar_writer::write_archive( - &archive, - &kar_writer::SourceIdentity { - name: "streamed-test", - architecture: "synthetic", - builder: "test-streamed-g32-l2", - digest: source_digest, - total_elements: 33, - bytes: source.len() as u64, - }, - &[kar_writer::Tensor { - name: "expert", - dims: &[33], - source_dtype: 0, - source_digest, - source_offset: 0, - data: kar_writer::TensorData::NestedFile { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - levels: 2, - path: &output, - offset: 0, - bytes: streamed.bytes, - digest: streamed.digest, - }, - }], - ) - .unwrap(); - assert_eq!(kar::verify(&archive).unwrap().tensor_count, 1); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn iq3_section_preserves_source_and_virtual_f32_identity_across_chunks() { - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - let source = block.repeat(257); - let calibration = kar_codec::Calibration { - boundaries: vec![-0.5, 0.0, 0.5], - books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], - }; - let path = std::env::temp_dir().join(format!( - "strata-iq3-stream-{}-{}.section", - std::process::id(), - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let result = encode_section( - &mut Cursor::new(&source), - 0, - 21, - source.len() as u64, - (257 * iq3_s::BLOCK_ELEMENTS) as u64, - &calibration, - &path, - ) - .unwrap(); - assert_eq!( - result.source_digest.as_slice(), - Sha256::digest(&source).as_slice() - ); - let virtual_f32 = 1.0f32.to_le_bytes().repeat(257 * iq3_s::BLOCK_ELEMENTS); - assert_eq!( - result.derived_digest.as_slice(), - Sha256::digest(&virtual_f32).as_slice() - ); - assert_eq!(result.relative_l2, 0.25); - fs::remove_file(path).unwrap(); - } -} +mod tests; diff --git a/control-plane/src/kar_stream_encode/tests.rs b/control-plane/src/kar_stream_encode/tests.rs new file mode 100644 index 00000000..4f1a2fca --- /dev/null +++ b/control-plane/src/kar_stream_encode/tests.rs @@ -0,0 +1,152 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::{iq3_s, kar, kar_writer}; +use std::io::Cursor; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[test] +fn streamed_section_matches_existing_writer_and_forms_verified_archive() { + let root = std::env::temp_dir().join(format!( + "strata-stream-section-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir(&root).unwrap(); + let weights = (0..33) + .map(|number| [-1.0f32, -0.25, 0.25, 1.0][number % 4]) + .collect::>(); + let source = weights + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect::>(); + let calibration = kar_codec::Calibration { + boundaries: vec![-0.5, 0.0, 0.5], + books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], + }; + let expected = + kar_codec::encode_with_boundaries(&weights, 32, &calibration.boundaries, 2).unwrap(); + let books = calibration + .books + .iter() + .map(Vec::as_slice) + .collect::>(); + let planes = expected + .planes + .iter() + .map(Vec::as_slice) + .collect::>(); + let source_digest: [u8; 32] = Sha256::digest(&source).into(); + let reference = root.join("reference.section"); + kar_writer::write_nested_section( + &reference, + &kar_writer::Tensor { + name: "expert", + dims: &[33], + source_dtype: 0, + source_digest, + source_offset: 0, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &expected.scales, + books: &books, + planes: &planes, + }, + }, + ) + .unwrap(); + let output = root.join("streamed.section"); + let streamed = encode_section( + &mut Cursor::new(&source), + 0, + 0, + source.len() as u64, + weights.len() as u64, + &calibration, + &output, + ) + .unwrap(); + assert_eq!(fs::read(&output).unwrap(), fs::read(&reference).unwrap()); + assert_eq!(streamed.source_digest, source_digest); + assert_eq!(streamed.derived_digest, source_digest); + assert!(streamed.relative_l2.is_finite()); + let archive = root.join("model.kar"); + kar_writer::write_archive( + &archive, + &kar_writer::SourceIdentity { + name: "streamed-test", + architecture: "synthetic", + builder: "test-streamed-g32-l2", + digest: source_digest, + total_elements: 33, + bytes: source.len() as u64, + }, + &[kar_writer::Tensor { + name: "expert", + dims: &[33], + source_dtype: 0, + source_digest, + source_offset: 0, + data: kar_writer::TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + levels: 2, + path: &output, + offset: 0, + bytes: streamed.bytes, + digest: streamed.digest, + }, + }], + ) + .unwrap(); + assert_eq!(kar::verify(&archive).unwrap().tensor_count, 1); + fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn iq3_section_preserves_source_and_virtual_f32_identity_across_chunks() { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let source = block.repeat(257); + let calibration = kar_codec::Calibration { + boundaries: vec![-0.5, 0.0, 0.5], + books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], + }; + let path = std::env::temp_dir().join(format!( + "strata-iq3-stream-{}-{}.section", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let result = encode_section( + &mut Cursor::new(&source), + 0, + 21, + source.len() as u64, + (257 * iq3_s::BLOCK_ELEMENTS) as u64, + &calibration, + &path, + ) + .unwrap(); + assert_eq!( + result.source_digest.as_slice(), + Sha256::digest(&source).as_slice() + ); + let virtual_f32 = 1.0f32.to_le_bytes().repeat(257 * iq3_s::BLOCK_ELEMENTS); + assert_eq!( + result.derived_digest.as_slice(), + Sha256::digest(&virtual_f32).as_slice() + ); + assert_eq!(result.relative_l2, 0.25); + fs::remove_file(path).unwrap(); +} diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs index e55065f3..3ba3f39e 100644 --- a/control-plane/src/kar_writer.rs +++ b/control-plane/src/kar_writer.rs @@ -949,345 +949,4 @@ fn put_u64(bytes: &mut [u8], offset: usize, value: u64) { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn streams_canonical_nested_section_and_rejects_corruption() { - let source = SourceIdentity { - name: "nested-fixture", - architecture: "qwen35", - builder: "strata-next-test", - digest: Sha256::digest(b"source").into(), - total_elements: 32, - bytes: 6, - }; - let book1 = [0xbc00, 0x3c00]; - let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00]; - let books: [&[u16]; 2] = [&book1, &book2]; - let plane1 = [0xaaaa_aaaa]; - let plane2 = [0x5555_5555]; - let planes: [&[u32]; 2] = [&plane1, &plane2]; - let source_digest: [u8; 32] = Sha256::digest(b"weights").into(); - let original = - std::env::temp_dir().join(format!("strata-nested-{}.kar", std::process::id())); - let streamed = - std::env::temp_dir().join(format!("strata-nested-stream-{}.kar", std::process::id())); - let spool = - std::env::temp_dir().join(format!("strata-nested-spool-{}.bin", std::process::id())); - let _ = fs::remove_file(&original); - let _ = fs::remove_file(&streamed); - let nested = [Tensor { - name: "expert", - dims: &[32], - source_dtype: 1, - source_digest, - source_offset: 0, - data: TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - scales: &[0x3c00], - books: &books, - planes: &planes, - }, - }]; - write_archive(&original, &source, &nested).unwrap(); - let reference = fs::read(&original).unwrap(); - let section_offset = - u64::from_le_bytes(reference[256 + 112..256 + 120].try_into().unwrap()) as usize; - let section_bytes = - u64::from_le_bytes(reference[256 + 120..256 + 128].try_into().unwrap()) as usize; - let section = &reference[section_offset..section_offset + section_bytes]; - let native_spool = std::env::temp_dir().join(format!( - "strata-nested-native-spool-{}.bin", - std::process::id() - )); - let _ = fs::remove_file(&native_spool); - let native_section = write_nested_section(&native_spool, &nested[0]).unwrap(); - assert_eq!(native_section.bytes, section_bytes as u64); - assert_eq!(fs::read(&native_spool).unwrap(), section); - let expected_digest: [u8; 32] = Sha256::digest(section).into(); - assert_eq!(native_section.digest, expected_digest); - let mut spool_bytes = vec![0xabu8; 11]; - spool_bytes.extend_from_slice(section); - fs::write(&spool, &spool_bytes).unwrap(); - let digest: [u8; 32] = Sha256::digest(section).into(); - let file_tensor = |digest| { - [Tensor { - name: "expert", - dims: &[32], - source_dtype: 1, - source_digest, - source_offset: 0, - data: TensorData::NestedFile { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - levels: 2, - path: &spool, - offset: 11, - bytes: section_bytes as u64, - digest, - }, - }] - }; - write_archive(&streamed, &source, &file_tensor(digest)).unwrap(); - assert_eq!(fs::read(&streamed).unwrap(), reference); - fs::remove_file(&streamed).unwrap(); - - spool_bytes[11] = 0; - spool_bytes[12] = 0x7c; - fs::write(&spool, &spool_bytes).unwrap(); - assert!( - write_archive(&streamed, &source, &file_tensor(digest)) - .unwrap_err() - .contains("non-finite f16 scale") - ); - assert!(!streamed.exists()); - spool_bytes[11..11 + section_bytes].copy_from_slice(section); - spool_bytes[13] = 1; - fs::write(&spool, &spool_bytes).unwrap(); - assert!( - write_archive(&streamed, &source, &file_tensor(digest)) - .unwrap_err() - .contains("nonzero padding") - ); - assert!(!streamed.exists()); - spool_bytes[11..11 + section_bytes].copy_from_slice(section); - fs::write(&spool, &spool_bytes).unwrap(); - assert!( - write_archive(&streamed, &source, &file_tensor([0; 32])) - .unwrap_err() - .contains("nested section digest mismatch") - ); - assert!(!streamed.exists()); - fs::remove_file(original).unwrap(); - fs::remove_file(spool).unwrap(); - fs::remove_file(native_spool).unwrap(); - } - - #[test] - fn streams_raw_tensor_across_buffer_boundary() { - let raw = vec![0x5au8; 1_048_580]; - let source = SourceIdentity { - name: "large-synthetic", - architecture: "qwen35", - builder: "strata-next-test", - digest: Sha256::digest(&raw).into(), - total_elements: 262_145, - bytes: raw.len() as u64, - }; - let input = - std::env::temp_dir().join(format!("strata-kar-large-{}.bin", std::process::id())); - let output = - std::env::temp_dir().join(format!("strata-kar-large-{}.kar", std::process::id())); - let _ = fs::remove_file(&output); - fs::write(&input, &raw).unwrap(); - let tensors = [Tensor { - name: "large", - dims: &[262_145], - source_dtype: 0, - source_digest: Sha256::digest(&raw).into(), - source_offset: 0, - data: TensorData::RawFile { - path: &input, - offset: 0, - bytes: raw.len() as u64, - }, - }]; - let summary = write_archive(&output, &source, &tensors).unwrap(); - assert_eq!(summary.tensor_count, 1); - assert_eq!(summary.total_elements, 262_145); - assert_eq!(kar::verify(&output).unwrap(), summary); - fs::remove_file(output).unwrap(); - fs::remove_file(input).unwrap(); - } - - #[test] - fn consuming_writer_removes_staged_input_after_verified_copy() { - let raw = (0..32u32) - .flat_map(|value| (value as f32).to_le_bytes()) - .collect::>(); - let root = std::env::temp_dir().join(format!("strata-kar-consume-{}", std::process::id())); - let _ = fs::remove_dir_all(&root); - fs::create_dir(&root).unwrap(); - let input = root.join("section.bin"); - let output = root.join("archive.kar"); - fs::write(&input, &raw).unwrap(); - let digest: [u8; 32] = Sha256::digest(&raw).into(); - let source = SourceIdentity { - name: "synthetic", - architecture: "qwen35", - builder: "consume-test", - digest, - total_elements: 32, - bytes: raw.len() as u64, - }; - let tensors = [Tensor { - name: "raw", - dims: &[32], - source_dtype: 0, - source_digest: digest, - source_offset: 0, - data: TensorData::RawFile { - path: &input, - offset: 0, - bytes: raw.len() as u64, - }, - }]; - let summary = write_archive_consuming_files(&output, &source, &tensors).unwrap(); - assert!(!input.exists()); - assert_eq!(kar::verify(&output).unwrap(), summary); - fs::remove_dir_all(root).unwrap(); - } - - #[test] - fn archive_bytes_match_pinned_koference_reference_writer() { - // Oracle: koference 806d2398, r08/code/kar_container.py, RAW + NESTED fixture. - let raw = (0..32) - .flat_map(|value| (value as f32).to_le_bytes()) - .collect::>(); - let mut source_bytes = raw.clone(); - source_bytes.extend_from_slice(b"weights"); - let source = SourceIdentity { - name: "synthetic", - architecture: "qwen35", - builder: "kar_container.py/2", - digest: Sha256::digest(&source_bytes).into(), - total_elements: 64, - bytes: source_bytes.len() as u64, - }; - let book1 = [0xbc00, 0x3c00]; - let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00]; - let books: [&[u16]; 2] = [&book1, &book2]; - let plane1 = [0xaaaa_aaaa]; - let plane2 = [0x5555_5555]; - let planes: [&[u32]; 2] = [&plane1, &plane2]; - let tensors = [ - Tensor { - name: "norm", - dims: &[32], - source_dtype: 0, - source_digest: Sha256::digest(&raw).into(), - source_offset: 0, - data: TensorData::Raw(&raw), - }, - Tensor { - name: "expert", - dims: &[32], - source_dtype: 1, - source_digest: Sha256::digest(b"weights").into(), - source_offset: 0, - data: TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - scales: &[0x3c00], - books: &books, - planes: &planes, - }, - }, - ]; - let path = - std::env::temp_dir().join(format!("strata-kar-writer-{}.kar", std::process::id())); - let _ = fs::remove_file(&path); - let summary = write_archive(&path, &source, &tensors).unwrap(); - assert_eq!(summary.archive_bytes, 1280); - assert_eq!(summary.tensor_count, 2); - assert_eq!(summary.accounted_bpw, 160.0); - let archive = fs::read(&path).unwrap(); - assert_eq!( - hex::encode(Sha256::digest(&archive)), - "013d3daa3f8ee70feb7045eee29390cb51e16d2a8558444cc8d6cbb91918f4f2" - ); - assert!(write_archive(&path, &source, &tensors).is_err()); - let other = path.with_file_name(format!("strata-kar-stale-{}.kar", std::process::id())); - let stale = other.with_file_name(format!( - "{}.part", - other.file_name().unwrap().to_string_lossy() - )); - fs::write(&stale, b"previous work").unwrap(); - assert!(write_archive(&other, &source, &tensors).is_err()); - assert_eq!(fs::read(&stale).unwrap(), b"previous work"); - fs::remove_file(stale).unwrap(); - let invalid = [Tensor { - name: "bad-scale", - dims: &[32], - source_dtype: 1, - source_digest: Sha256::digest(b"weights").into(), - source_offset: 0, - data: TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - scales: &[0x7c00], - books: &books, - planes: &planes, - }, - }]; - assert!( - write_archive(&other, &source, &invalid) - .unwrap_err() - .contains("non-finite f16 scale") - ); - assert!(!other.exists()); - let raw_file = - path.with_file_name(format!("strata-kar-raw-input-{}.bin", std::process::id())); - let mut padded_raw = vec![0u8; 17]; - padded_raw.extend_from_slice(&raw); - fs::write(&raw_file, &padded_raw).unwrap(); - let streamed_tensors = [ - Tensor { - name: "norm", - dims: &[32], - source_dtype: 0, - source_digest: Sha256::digest(&raw).into(), - source_offset: 0, - data: TensorData::RawFile { - path: &raw_file, - offset: 17, - bytes: raw.len() as u64, - }, - }, - Tensor { - name: "expert", - dims: &[32], - source_dtype: 1, - source_digest: Sha256::digest(b"weights").into(), - source_offset: 0, - data: TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 2, - scales: &[0x3c00], - books: &books, - planes: &planes, - }, - }, - ]; - let streamed = - path.with_file_name(format!("strata-kar-streamed-{}.kar", std::process::id())); - let _ = fs::remove_file(&streamed); - write_archive(&streamed, &source, &streamed_tensors).unwrap(); - assert_eq!(fs::read(&streamed).unwrap(), archive); - padded_raw[17] ^= 1; - fs::write(&raw_file, padded_raw).unwrap(); - let corrupt = path.with_file_name(format!("strata-kar-corrupt-{}.kar", std::process::id())); - let _ = fs::remove_file(&corrupt); - assert!( - write_archive(&corrupt, &source, &streamed_tensors) - .unwrap_err() - .contains("RAW source digest mismatch") - ); - assert!(!corrupt.exists()); - fs::remove_file(streamed).unwrap(); - fs::remove_file(raw_file).unwrap(); - fs::remove_file(path).unwrap(); - } -} +mod tests; diff --git a/control-plane/src/kar_writer/tests.rs b/control-plane/src/kar_writer/tests.rs new file mode 100644 index 00000000..ec5bf25c --- /dev/null +++ b/control-plane/src/kar_writer/tests.rs @@ -0,0 +1,342 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn streams_canonical_nested_section_and_rejects_corruption() { + let source = SourceIdentity { + name: "nested-fixture", + architecture: "qwen35", + builder: "strata-next-test", + digest: Sha256::digest(b"source").into(), + total_elements: 32, + bytes: 6, + }; + let book1 = [0xbc00, 0x3c00]; + let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00]; + let books: [&[u16]; 2] = [&book1, &book2]; + let plane1 = [0xaaaa_aaaa]; + let plane2 = [0x5555_5555]; + let planes: [&[u32]; 2] = [&plane1, &plane2]; + let source_digest: [u8; 32] = Sha256::digest(b"weights").into(); + let original = + std::env::temp_dir().join(format!("strata-nested-{}.kar", std::process::id())); + let streamed = + std::env::temp_dir().join(format!("strata-nested-stream-{}.kar", std::process::id())); + let spool = + std::env::temp_dir().join(format!("strata-nested-spool-{}.bin", std::process::id())); + let _ = fs::remove_file(&original); + let _ = fs::remove_file(&streamed); + let nested = [Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest, + source_offset: 0, + data: TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &[0x3c00], + books: &books, + planes: &planes, + }, + }]; + write_archive(&original, &source, &nested).unwrap(); + let reference = fs::read(&original).unwrap(); + let section_offset = + u64::from_le_bytes(reference[256 + 112..256 + 120].try_into().unwrap()) as usize; + let section_bytes = + u64::from_le_bytes(reference[256 + 120..256 + 128].try_into().unwrap()) as usize; + let section = &reference[section_offset..section_offset + section_bytes]; + let native_spool = std::env::temp_dir().join(format!( + "strata-nested-native-spool-{}.bin", + std::process::id() + )); + let _ = fs::remove_file(&native_spool); + let native_section = write_nested_section(&native_spool, &nested[0]).unwrap(); + assert_eq!(native_section.bytes, section_bytes as u64); + assert_eq!(fs::read(&native_spool).unwrap(), section); + let expected_digest: [u8; 32] = Sha256::digest(section).into(); + assert_eq!(native_section.digest, expected_digest); + let mut spool_bytes = vec![0xabu8; 11]; + spool_bytes.extend_from_slice(section); + fs::write(&spool, &spool_bytes).unwrap(); + let digest: [u8; 32] = Sha256::digest(section).into(); + let file_tensor = |digest| { + [Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest, + source_offset: 0, + data: TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + levels: 2, + path: &spool, + offset: 11, + bytes: section_bytes as u64, + digest, + }, + }] + }; + write_archive(&streamed, &source, &file_tensor(digest)).unwrap(); + assert_eq!(fs::read(&streamed).unwrap(), reference); + fs::remove_file(&streamed).unwrap(); + + spool_bytes[11] = 0; + spool_bytes[12] = 0x7c; + fs::write(&spool, &spool_bytes).unwrap(); + assert!( + write_archive(&streamed, &source, &file_tensor(digest)) + .unwrap_err() + .contains("non-finite f16 scale") + ); + assert!(!streamed.exists()); + spool_bytes[11..11 + section_bytes].copy_from_slice(section); + spool_bytes[13] = 1; + fs::write(&spool, &spool_bytes).unwrap(); + assert!( + write_archive(&streamed, &source, &file_tensor(digest)) + .unwrap_err() + .contains("nonzero padding") + ); + assert!(!streamed.exists()); + spool_bytes[11..11 + section_bytes].copy_from_slice(section); + fs::write(&spool, &spool_bytes).unwrap(); + assert!( + write_archive(&streamed, &source, &file_tensor([0; 32])) + .unwrap_err() + .contains("nested section digest mismatch") + ); + assert!(!streamed.exists()); + fs::remove_file(original).unwrap(); + fs::remove_file(spool).unwrap(); + fs::remove_file(native_spool).unwrap(); +} + +#[test] +fn streams_raw_tensor_across_buffer_boundary() { + let raw = vec![0x5au8; 1_048_580]; + let source = SourceIdentity { + name: "large-synthetic", + architecture: "qwen35", + builder: "strata-next-test", + digest: Sha256::digest(&raw).into(), + total_elements: 262_145, + bytes: raw.len() as u64, + }; + let input = + std::env::temp_dir().join(format!("strata-kar-large-{}.bin", std::process::id())); + let output = + std::env::temp_dir().join(format!("strata-kar-large-{}.kar", std::process::id())); + let _ = fs::remove_file(&output); + fs::write(&input, &raw).unwrap(); + let tensors = [Tensor { + name: "large", + dims: &[262_145], + source_dtype: 0, + source_digest: Sha256::digest(&raw).into(), + source_offset: 0, + data: TensorData::RawFile { + path: &input, + offset: 0, + bytes: raw.len() as u64, + }, + }]; + let summary = write_archive(&output, &source, &tensors).unwrap(); + assert_eq!(summary.tensor_count, 1); + assert_eq!(summary.total_elements, 262_145); + assert_eq!(kar::verify(&output).unwrap(), summary); + fs::remove_file(output).unwrap(); + fs::remove_file(input).unwrap(); +} + +#[test] +fn consuming_writer_removes_staged_input_after_verified_copy() { + let raw = (0..32u32) + .flat_map(|value| (value as f32).to_le_bytes()) + .collect::>(); + let root = std::env::temp_dir().join(format!("strata-kar-consume-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let input = root.join("section.bin"); + let output = root.join("archive.kar"); + fs::write(&input, &raw).unwrap(); + let digest: [u8; 32] = Sha256::digest(&raw).into(); + let source = SourceIdentity { + name: "synthetic", + architecture: "qwen35", + builder: "consume-test", + digest, + total_elements: 32, + bytes: raw.len() as u64, + }; + let tensors = [Tensor { + name: "raw", + dims: &[32], + source_dtype: 0, + source_digest: digest, + source_offset: 0, + data: TensorData::RawFile { + path: &input, + offset: 0, + bytes: raw.len() as u64, + }, + }]; + let summary = write_archive_consuming_files(&output, &source, &tensors).unwrap(); + assert!(!input.exists()); + assert_eq!(kar::verify(&output).unwrap(), summary); + fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn archive_bytes_match_pinned_koference_reference_writer() { + // Oracle: koference 806d2398, r08/code/kar_container.py, RAW + NESTED fixture. + let raw = (0..32) + .flat_map(|value| (value as f32).to_le_bytes()) + .collect::>(); + let mut source_bytes = raw.clone(); + source_bytes.extend_from_slice(b"weights"); + let source = SourceIdentity { + name: "synthetic", + architecture: "qwen35", + builder: "kar_container.py/2", + digest: Sha256::digest(&source_bytes).into(), + total_elements: 64, + bytes: source_bytes.len() as u64, + }; + let book1 = [0xbc00, 0x3c00]; + let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00]; + let books: [&[u16]; 2] = [&book1, &book2]; + let plane1 = [0xaaaa_aaaa]; + let plane2 = [0x5555_5555]; + let planes: [&[u32]; 2] = [&plane1, &plane2]; + let tensors = [ + Tensor { + name: "norm", + dims: &[32], + source_dtype: 0, + source_digest: Sha256::digest(&raw).into(), + source_offset: 0, + data: TensorData::Raw(&raw), + }, + Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &[0x3c00], + books: &books, + planes: &planes, + }, + }, + ]; + let path = + std::env::temp_dir().join(format!("strata-kar-writer-{}.kar", std::process::id())); + let _ = fs::remove_file(&path); + let summary = write_archive(&path, &source, &tensors).unwrap(); + assert_eq!(summary.archive_bytes, 1280); + assert_eq!(summary.tensor_count, 2); + assert_eq!(summary.accounted_bpw, 160.0); + let archive = fs::read(&path).unwrap(); + assert_eq!( + hex::encode(Sha256::digest(&archive)), + "013d3daa3f8ee70feb7045eee29390cb51e16d2a8558444cc8d6cbb91918f4f2" + ); + assert!(write_archive(&path, &source, &tensors).is_err()); + let other = path.with_file_name(format!("strata-kar-stale-{}.kar", std::process::id())); + let stale = other.with_file_name(format!( + "{}.part", + other.file_name().unwrap().to_string_lossy() + )); + fs::write(&stale, b"previous work").unwrap(); + assert!(write_archive(&other, &source, &tensors).is_err()); + assert_eq!(fs::read(&stale).unwrap(), b"previous work"); + fs::remove_file(stale).unwrap(); + let invalid = [Tensor { + name: "bad-scale", + dims: &[32], + source_dtype: 1, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &[0x7c00], + books: &books, + planes: &planes, + }, + }]; + assert!( + write_archive(&other, &source, &invalid) + .unwrap_err() + .contains("non-finite f16 scale") + ); + assert!(!other.exists()); + let raw_file = + path.with_file_name(format!("strata-kar-raw-input-{}.bin", std::process::id())); + let mut padded_raw = vec![0u8; 17]; + padded_raw.extend_from_slice(&raw); + fs::write(&raw_file, &padded_raw).unwrap(); + let streamed_tensors = [ + Tensor { + name: "norm", + dims: &[32], + source_dtype: 0, + source_digest: Sha256::digest(&raw).into(), + source_offset: 0, + data: TensorData::RawFile { + path: &raw_file, + offset: 17, + bytes: raw.len() as u64, + }, + }, + Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &[0x3c00], + books: &books, + planes: &planes, + }, + }, + ]; + let streamed = + path.with_file_name(format!("strata-kar-streamed-{}.kar", std::process::id())); + let _ = fs::remove_file(&streamed); + write_archive(&streamed, &source, &streamed_tensors).unwrap(); + assert_eq!(fs::read(&streamed).unwrap(), archive); + padded_raw[17] ^= 1; + fs::write(&raw_file, padded_raw).unwrap(); + let corrupt = path.with_file_name(format!("strata-kar-corrupt-{}.kar", std::process::id())); + let _ = fs::remove_file(&corrupt); + assert!( + write_archive(&corrupt, &source, &streamed_tensors) + .unwrap_err() + .contains("RAW source digest mismatch") + ); + assert!(!corrupt.exists()); + fs::remove_file(streamed).unwrap(); + fs::remove_file(raw_file).unwrap(); + fs::remove_file(path).unwrap(); +} diff --git a/control-plane/src/mcp.rs b/control-plane/src/mcp.rs index b331d8a4..c6c64f09 100644 --- a/control-plane/src/mcp.rs +++ b/control-plane/src/mcp.rs @@ -1420,101 +1420,4 @@ pub fn settings_from(block: &Value) -> Result { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn results_read_as_text_with_other_blocks_named() { - // An unknown block prints as written (Python's `json.dumps(block)` in the Original keeps the server's key order; the - // separators differ, see json_order.rs). That needs serde_json's `preserve_order`, declared in control-plane/Cargo.toml. - let result = json!({"content": [ - {"type": "text", "text": "hello"}, - {"type": "resource", "resource": {"uri": "file:///a", "mimeType": "image/png"}}, - {"type": "resource", "resource": {"text": "inline"}}, - {"type": "resource_link", "name": "doc", "uri": "http://x"}, - {"type": "image", "mimeType": "image/png", "data": "AAAAAAAA"}, - {"type": "weird", "k": 1}, - "not a block" - ]}); - assert_eq!( - result_text(&result), - "hello\n[resource file:///a (image/png), not shown]\ninline\n[resource link: doc http://x]\n[image (image/png, 6 bytes): not shown to the model]\n{\"type\":\"weird\",\"k\":1}" - ); - assert_eq!( - result_text(&json!({"structuredContent": {"a": 1}})), - "{\"a\":1}" - ); - assert_eq!(result_text(&json!({})), ""); - assert_eq!(group_thousands(1234567), "1,234,567"); - assert_eq!(group_thousands(12), "12"); - } - - #[test] - fn json_rpc_errors_read_like_the_originals() { - assert_eq!( - response_result(&json!({"error": {"code": -32602, "message": "unknown tool x"}})) - .unwrap_err(), - failed("unknown tool x (code -32602)") - ); - assert_eq!( - response_result(&json!({"error": "plain"})).unwrap_err(), - failed("\"plain\" (code None)") - ); - assert_eq!(response_result(&json!({"id": 1})).unwrap(), json!({})); - } - - #[test] - fn server_entries_are_checked_at_start() { - let ok = servers_from( - &json!({"a": {"command": "npx", "args": ["x"]}, "b": {"url": "http://h/mcp", "headers": {"k": "v"}}, - "off": {"command": "x", "disabled": true}}), - "config mcp_servers", - ) - .unwrap(); - assert_eq!(ok.keys().collect::>(), vec!["a", "b"]); - for bad in [ - json!({"a": "nope"}), - json!({"a": {}}), - json!({"a": {"command": " "}}), - json!({"a": {"command": "x", "args": "y"}}), - json!({"a": {"command": "x", "env": ["x"]}}), - json!({"a": {"url": "http://h", "type": "sse"}}), - json!({"a": {"url": "http://h", "headers": ["x"]}}), - json!([1]), - ] { - assert!(servers_from(&bad, "w").is_err(), "{bad}"); - } - assert!(servers_from(&Value::Null, "w").unwrap().is_empty()); - } - - #[test] - fn settings_block_is_checked() { - let s = settings_from(&json!({"timeout_s": 5, "max_result_chars": 100, "max_rounds": 3, "start_timeout_s": 7.5, "x": 1})).unwrap(); - assert_eq!( - s, - Settings { - timeout_s: 5.0, - max_result_chars: 100, - max_rounds: 3, - start_timeout_s: 7.5 - } - ); - for bad in [ - json!({"timeout_s": 0}), - json!({"timeout_s": "5"}), - json!({"max_rounds": 0}), - json!({"max_result_chars": 1.5}), - ] { - assert!(settings_from(&bad).is_err(), "{bad}"); - } - assert_eq!(settings_from(&Value::Null).unwrap(), Settings::default()); - } - - #[test] - fn tool_names_are_cleaned_and_made_unique() { - assert_eq!(clean("my server!"), "my_server_"); - assert_eq!(clean(""), "x"); - assert_eq!(fmt_g(60.0), "60"); - assert_eq!(fmt_g(0.5), "0.5"); - } -} +mod tests; diff --git a/control-plane/src/mcp/tests.rs b/control-plane/src/mcp/tests.rs new file mode 100644 index 00000000..2f61c829 --- /dev/null +++ b/control-plane/src/mcp/tests.rs @@ -0,0 +1,98 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn results_read_as_text_with_other_blocks_named() { + // An unknown block prints as written (Python's `json.dumps(block)` in the Original keeps the server's key order; the + // separators differ, see json_order.rs). That needs serde_json's `preserve_order`, declared in control-plane/Cargo.toml. + let result = json!({"content": [ + {"type": "text", "text": "hello"}, + {"type": "resource", "resource": {"uri": "file:///a", "mimeType": "image/png"}}, + {"type": "resource", "resource": {"text": "inline"}}, + {"type": "resource_link", "name": "doc", "uri": "http://x"}, + {"type": "image", "mimeType": "image/png", "data": "AAAAAAAA"}, + {"type": "weird", "k": 1}, + "not a block" + ]}); + assert_eq!( + result_text(&result), + "hello\n[resource file:///a (image/png), not shown]\ninline\n[resource link: doc http://x]\n[image (image/png, 6 bytes): not shown to the model]\n{\"type\":\"weird\",\"k\":1}" + ); + assert_eq!( + result_text(&json!({"structuredContent": {"a": 1}})), + "{\"a\":1}" + ); + assert_eq!(result_text(&json!({})), ""); + assert_eq!(group_thousands(1234567), "1,234,567"); + assert_eq!(group_thousands(12), "12"); +} + +#[test] +fn json_rpc_errors_read_like_the_originals() { + assert_eq!( + response_result(&json!({"error": {"code": -32602, "message": "unknown tool x"}})) + .unwrap_err(), + failed("unknown tool x (code -32602)") + ); + assert_eq!( + response_result(&json!({"error": "plain"})).unwrap_err(), + failed("\"plain\" (code None)") + ); + assert_eq!(response_result(&json!({"id": 1})).unwrap(), json!({})); +} + +#[test] +fn server_entries_are_checked_at_start() { + let ok = servers_from( + &json!({"a": {"command": "npx", "args": ["x"]}, "b": {"url": "http://h/mcp", "headers": {"k": "v"}}, + "off": {"command": "x", "disabled": true}}), + "config mcp_servers", + ) + .unwrap(); + assert_eq!(ok.keys().collect::>(), vec!["a", "b"]); + for bad in [ + json!({"a": "nope"}), + json!({"a": {}}), + json!({"a": {"command": " "}}), + json!({"a": {"command": "x", "args": "y"}}), + json!({"a": {"command": "x", "env": ["x"]}}), + json!({"a": {"url": "http://h", "type": "sse"}}), + json!({"a": {"url": "http://h", "headers": ["x"]}}), + json!([1]), + ] { + assert!(servers_from(&bad, "w").is_err(), "{bad}"); + } + assert!(servers_from(&Value::Null, "w").unwrap().is_empty()); +} + +#[test] +fn settings_block_is_checked() { + let s = settings_from(&json!({"timeout_s": 5, "max_result_chars": 100, "max_rounds": 3, "start_timeout_s": 7.5, "x": 1})).unwrap(); + assert_eq!( + s, + Settings { + timeout_s: 5.0, + max_result_chars: 100, + max_rounds: 3, + start_timeout_s: 7.5 + } + ); + for bad in [ + json!({"timeout_s": 0}), + json!({"timeout_s": "5"}), + json!({"max_rounds": 0}), + json!({"max_result_chars": 1.5}), + ] { + assert!(settings_from(&bad).is_err(), "{bad}"); + } + assert_eq!(settings_from(&Value::Null).unwrap(), Settings::default()); +} + +#[test] +fn tool_names_are_cleaned_and_made_unique() { + assert_eq!(clean("my server!"), "my_server_"); + assert_eq!(clean(""), "x"); + assert_eq!(fmt_g(60.0), "60"); + assert_eq!(fmt_g(0.5), "0.5"); +} diff --git a/control-plane/src/messages.rs b/control-plane/src/messages.rs index 2553639a..5320191d 100644 --- a/control-plane/src/messages.rs +++ b/control-plane/src/messages.rs @@ -599,92 +599,4 @@ fn stream_response(mut body: Body) -> Response { } #[cfg(test)] -mod tests { - use super::*; - - /// The arguments string of a replayed `tool_use` keeps the order the client wrote (the Original is Python: `json.loads`, - /// then the template walks the dict in that order). It does not depend on a sort: `{"z":1,"a":2}` stays `z`, `a`. - #[test] - fn tool_use_arguments_keep_the_order_the_client_wrote() { - let (native, _) = serde_json::from_value::(json!({"model":"fixture","max_tokens":8,"messages":[ - {"role":"user","content":"Do it"}, - {"role":"assistant","content":[{"type":"tool_use","id":"call","name":"work","input":{"z":1,"a":{"y":true,"b":[{"d":1,"c":2}]}}}]}, - {"role":"user","content":[{"type":"tool_result","tool_use_id":"call","content":"ok"}]} - ]})).unwrap().into_responses().unwrap(); - assert_eq!( - native["input"][1]["arguments"], - r#"{"z":1,"a":{"y":true,"b":[{"d":1,"c":2}]}}"# - ); - } - - #[test] - fn tool_results_preserve_errors_empty_content_and_success_bytes() { - let text = "failure 🌍\n\"quote\" \\ path\u{0000}"; - let make = |result: Value| { - serde_json::from_value::(json!({"model":"fixture","max_tokens":8,"messages":[ - {"role":"user","content":"Do it"}, - {"role":"assistant","content":[{"type":"tool_use","id":"call","name":"work","input":{}}]}, - {"role":"user","content":[result]} - ]})).unwrap().into_responses() - }; - for error in [None, Some(false), Some(true)] { - for content in [ - None, - Some(json!(text)), - Some(json!([])), - Some(json!([ - {"type":"text","text":text}, {"type":"text","text":"last"} - ])), - ] { - let normalized = match &content { - None => String::new(), - Some(Value::String(s)) => s.clone(), - Some(Value::Array(parts)) if parts.is_empty() => String::new(), - _ => format!("{text}\nlast"), - }; - let mut result = json!({"type":"tool_result","tool_use_id":"call"}); - if let Some(content) = content { - result["content"] = content; - } - if let Some(error) = error { - result["is_error"] = json!(error); - } - let (native, _) = make(result).unwrap(); - let output = native["input"][2]["output"].as_str().unwrap(); - assert_eq!(native["input"][2]["call_id"], "call"); - assert_eq!(native["input"][2]["type"], "function_call_output"); - assert_eq!(native["input"].as_array().unwrap().len(), 3); - if error == Some(true) { - // the exact bytes the model reads: sorted keys, compact, no ASCII escaping - // (`json.dumps(..., ensure_ascii=False, separators=(",", ":"), sort_keys=True)`) - assert_eq!( - output, - format!( - r#"{{"content":{},"is_error":true}}"#, - serde_json::to_string(&normalized).unwrap() - ) - ); - assert!(output.starts_with(r#"{"content":""#)); - } else { - assert_eq!(output, normalized); - } - } - } - for content in [ - Value::Null, - json!(3), - json!({}), - json!([{"type":"image","source":{}}]), - ] { - assert!(make(json!({"type":"tool_result","tool_use_id":"call","content":content,"is_error":true})).is_err()); - } - for flag in [json!("true"), json!(1), json!({})] { - assert!( - serde_json::from_value::( - json!({"type":"tool_result","tool_use_id":"call","is_error":flag}) - ) - .is_err() - ); - } - } -} +mod tests; diff --git a/control-plane/src/messages/tests.rs b/control-plane/src/messages/tests.rs new file mode 100644 index 00000000..0b5b57d4 --- /dev/null +++ b/control-plane/src/messages/tests.rs @@ -0,0 +1,89 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +/// The arguments string of a replayed `tool_use` keeps the order the client wrote (the Original is Python: `json.loads`, +/// then the template walks the dict in that order). It does not depend on a sort: `{"z":1,"a":2}` stays `z`, `a`. +#[test] +fn tool_use_arguments_keep_the_order_the_client_wrote() { + let (native, _) = serde_json::from_value::(json!({"model":"fixture","max_tokens":8,"messages":[ + {"role":"user","content":"Do it"}, + {"role":"assistant","content":[{"type":"tool_use","id":"call","name":"work","input":{"z":1,"a":{"y":true,"b":[{"d":1,"c":2}]}}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"call","content":"ok"}]} + ]})).unwrap().into_responses().unwrap(); + assert_eq!( + native["input"][1]["arguments"], + r#"{"z":1,"a":{"y":true,"b":[{"d":1,"c":2}]}}"# + ); +} + +#[test] +fn tool_results_preserve_errors_empty_content_and_success_bytes() { + let text = "failure 🌍\n\"quote\" \\ path\u{0000}"; + let make = |result: Value| { + serde_json::from_value::(json!({"model":"fixture","max_tokens":8,"messages":[ + {"role":"user","content":"Do it"}, + {"role":"assistant","content":[{"type":"tool_use","id":"call","name":"work","input":{}}]}, + {"role":"user","content":[result]} + ]})).unwrap().into_responses() + }; + for error in [None, Some(false), Some(true)] { + for content in [ + None, + Some(json!(text)), + Some(json!([])), + Some(json!([ + {"type":"text","text":text}, {"type":"text","text":"last"} + ])), + ] { + let normalized = match &content { + None => String::new(), + Some(Value::String(s)) => s.clone(), + Some(Value::Array(parts)) if parts.is_empty() => String::new(), + _ => format!("{text}\nlast"), + }; + let mut result = json!({"type":"tool_result","tool_use_id":"call"}); + if let Some(content) = content { + result["content"] = content; + } + if let Some(error) = error { + result["is_error"] = json!(error); + } + let (native, _) = make(result).unwrap(); + let output = native["input"][2]["output"].as_str().unwrap(); + assert_eq!(native["input"][2]["call_id"], "call"); + assert_eq!(native["input"][2]["type"], "function_call_output"); + assert_eq!(native["input"].as_array().unwrap().len(), 3); + if error == Some(true) { + // the exact bytes the model reads: sorted keys, compact, no ASCII escaping + // (`json.dumps(..., ensure_ascii=False, separators=(",", ":"), sort_keys=True)`) + assert_eq!( + output, + format!( + r#"{{"content":{},"is_error":true}}"#, + serde_json::to_string(&normalized).unwrap() + ) + ); + assert!(output.starts_with(r#"{"content":""#)); + } else { + assert_eq!(output, normalized); + } + } + } + for content in [ + Value::Null, + json!(3), + json!({}), + json!([{"type":"image","source":{}}]), + ] { + assert!(make(json!({"type":"tool_result","tool_use_id":"call","content":content,"is_error":true})).is_err()); + } + for flag in [json!("true"), json!(1), json!({})] { + assert!( + serde_json::from_value::( + json!({"type":"tool_result","tool_use_id":"call","is_error":flag}) + ) + .is_err() + ); + } +} diff --git a/control-plane/src/model.rs b/control-plane/src/model.rs index 2a8103b6..21332082 100644 --- a/control-plane/src/model.rs +++ b/control-plane/src/model.rs @@ -452,376 +452,4 @@ fn part_path(destination: &Path) -> PathBuf { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - use std::time::{SystemTime, UNIX_EPOCH}; - use tokio::{net::TcpListener, time::timeout}; - - #[cfg(unix)] // model fetch is an offline tool that needs statvfs - #[tokio::test] - async fn insufficient_space_stops_before_network_or_partial_file() { - let root = std::env::temp_dir().join(format!( - "strata-space-test-{}-{}", - std::process::id(), - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let manifest = Manifest { - schema_version: 1, - files: vec![ModelFile { - name: "huge.gguf".into(), - url: "https://example.invalid/huge.gguf".into(), - size: u64::MAX, - sha256: "0".repeat(64), - }], - }; - let error = fetch(&manifest, &root).await.unwrap_err().to_string(); - assert!(error.contains("insufficient disk space")); - assert!(!root.join("huge.gguf.part").exists()); - fs::remove_dir_all(root).await.unwrap(); - } - - #[cfg(unix)] // model fetch is an offline tool that needs statvfs - #[tokio::test] - async fn interrupted_download_resumes_and_verifies() { - let base = std::env::temp_dir().join(format!( - "strata-model-test-{}-{}", - std::process::id(), - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::create_dir_all(&base).await.unwrap(); - let output = base.join("model"); - fs::create_dir_all(&output).await.unwrap(); - fs::write(output.join("sample.bin.part"), b"abc") - .await - .unwrap(); - - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = listener.accept().await.unwrap(); - let mut request = Vec::new(); - let mut buffer = [0u8; 1024]; - while !request.ends_with(b"\r\n\r\n") { - let count = socket.read(&mut buffer).await.unwrap(); - assert!(count > 0); - request.extend_from_slice(&buffer[..count]); - } - let request = String::from_utf8(request).unwrap(); - assert!(request.to_ascii_lowercase().contains("range: bytes=3-")); - socket - .write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef") - .await - .unwrap(); - }); - let manifest_path = base.join("manifest.json"); - fs::write( - &manifest_path, - serde_json::to_vec(&json!({ - "schema_version": 1, - "files": [{ - "name": "sample.bin", - "url": format!("http://{address}/sample.bin"), - "size": 6, - "sha256": hex::encode(Sha256::digest(b"abcdef")) - }] - })) - .unwrap(), - ) - .await - .unwrap(); - let manifest = Manifest::load(&manifest_path).await.unwrap(); - timeout(Duration::from_secs(5), fetch(&manifest, &output)) - .await - .unwrap() - .unwrap(); - server.await.unwrap(); - verify(&manifest, &output).await.unwrap(); - assert_eq!( - fs::read(output.join("sample.bin")).await.unwrap(), - b"abcdef" - ); - assert!(!output.join("sample.bin.part").exists()); - fs::write(output.join("sample.bin"), b"xxxxxx") - .await - .unwrap(); - assert!(verify(&manifest, &output).await.is_err()); - fs::remove_dir_all(&base).await.unwrap(); - } - - #[cfg(unix)] // model fetch is an offline tool that needs statvfs - #[tokio::test] - async fn checksum_mismatch_never_publishes_download() { - let base = std::env::temp_dir().join(format!( - "strata-bad-download-{}-{}", - std::process::id(), - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = listener.accept().await.unwrap(); - let mut request = Vec::new(); - let mut buffer = [0u8; 1024]; - while !request.ends_with(b"\r\n\r\n") { - let count = socket.read(&mut buffer).await.unwrap(); - assert!(count > 0); - request.extend_from_slice(&buffer[..count]); - } - socket - .write_all( - b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nxxxxxx", - ) - .await - .unwrap(); - }); - let manifest = Manifest { - schema_version: 1, - files: vec![ModelFile { - name: "sample.bin".into(), - url: format!("http://{address}/sample.bin"), - size: 6, - sha256: hex::encode(Sha256::digest(b"abcdef")), - }], - }; - let error = timeout(Duration::from_secs(5), fetch(&manifest, &base)) - .await - .unwrap() - .unwrap_err(); - assert!(error.to_string().contains("SHA-256 mismatch")); - server.await.unwrap(); - assert!(!base.join("sample.bin").exists()); - assert!(!base.join("sample.bin.part").exists()); - // Also cover a full-length partial left by a prior interrupted process. - fs::write(base.join("sample.bin.part"), b"xxxxxx") - .await - .unwrap(); - let error = timeout(Duration::from_secs(5), fetch(&manifest, &base)) - .await - .unwrap() - .unwrap_err(); - assert!(error.to_string().contains("size/SHA-256 verification")); - assert!(!base.join("sample.bin").exists()); - fs::remove_dir_all(base).await.unwrap(); - } - - #[cfg(unix)] // model fetch is an offline tool that needs statvfs - #[tokio::test] - async fn transient_server_failure_retries_the_same_partial_download() { - let base = std::env::temp_dir().join(format!( - "strata-retry-test-{}-{}", - std::process::id(), - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::create_dir_all(&base).await.unwrap(); - fs::write(base.join("sample.bin.part"), b"abc") - .await - .unwrap(); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let server = tokio::spawn(async move { - for attempt in 0..2 { - let (mut socket, _) = listener.accept().await.unwrap(); - let mut request = Vec::new(); - let mut buffer = [0u8; 1024]; - while !request.ends_with(b"\r\n\r\n") { - let count = socket.read(&mut buffer).await.unwrap(); - assert!(count > 0); - request.extend_from_slice(&buffer[..count]); - } - assert!( - String::from_utf8(request) - .unwrap() - .to_ascii_lowercase() - .contains("range: bytes=3-") - ); - if attempt == 0 { - socket - .write_all( - b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", - ) - .await - .unwrap(); - } else { - socket - .write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef") - .await - .unwrap(); - } - } - }); - let manifest = Manifest::parse( - &serde_json::to_vec(&json!({ - "schema_version": 1, - "files": [{ - "name": "sample.bin", - "url": format!("http://{address}/sample.bin"), - "size": 6, - "sha256": hex::encode(Sha256::digest(b"abcdef")) - }] - })) - .unwrap(), - ) - .unwrap(); - timeout(Duration::from_secs(5), fetch(&manifest, &base)) - .await - .unwrap() - .unwrap(); - server.await.unwrap(); - assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef"); - assert!(!base.join("sample.bin.part").exists()); - fs::remove_dir_all(base).await.unwrap(); - } - - #[cfg(unix)] // model fetch is an offline tool that needs statvfs - #[tokio::test] - async fn short_response_resumes_from_new_partial_offset() { - let base = std::env::temp_dir().join(format!( - "strata-short-response-test-{}-{}", - std::process::id(), - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::create_dir_all(&base).await.unwrap(); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let server = tokio::spawn(async move { - for attempt in 0..2 { - let (mut socket, _) = listener.accept().await.unwrap(); - let mut request = Vec::new(); - let mut buffer = [0u8; 1024]; - while !request.ends_with(b"\r\n\r\n") { - let count = socket.read(&mut buffer).await.unwrap(); - assert!(count > 0); - request.extend_from_slice(&buffer[..count]); - } - let request = String::from_utf8(request).unwrap().to_ascii_lowercase(); - if attempt == 0 { - assert!(!request.contains("range:")); - socket - .write_all( - b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: close\r\n\r\nabc", - ) - .await - .unwrap(); - } else { - assert!(request.contains("range: bytes=3-")); - socket - .write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef") - .await - .unwrap(); - } - } - }); - let manifest = Manifest::parse( - &serde_json::to_vec(&json!({ - "schema_version": 1, - "files": [{ - "name": "sample.bin", - "url": format!("http://{address}/sample.bin"), - "size": 6, - "sha256": hex::encode(Sha256::digest(b"abcdef")) - }] - })) - .unwrap(), - ) - .unwrap(); - timeout(Duration::from_secs(5), fetch(&manifest, &base)) - .await - .unwrap() - .unwrap(); - server.await.unwrap(); - assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef"); - assert!(!base.join("sample.bin.part").exists()); - fs::remove_dir_all(base).await.unwrap(); - } - - #[tokio::test] - async fn manifest_rejects_path_traversal() { - let path = - std::env::temp_dir().join(format!("strata-bad-manifest-{}.json", std::process::id())); - fs::write(&path, serde_json::to_vec(&json!({ - "schema_version": 1, - "files": [{"name": "../escape", "url": "https://example.com/file", "size": 1, "sha256": "a".repeat(64)}] - })).unwrap()).await.unwrap(); - assert!(Manifest::load(&path).await.is_err()); - fs::remove_file(path).await.unwrap(); - } - - #[test] - fn hub_token_is_only_attached_to_exact_https_host() { - let client = Client::new(); - for (url, expected_auth) in [ - ( - "https://huggingface.co/org/repo/resolve/commit/model.gguf", - true, - ), - ("https://huggingface.co.evil.example/model.gguf", false), - ("https://example.com/model.gguf", false), - ("http://localhost/model.gguf", false), - ] { - let file = ModelFile { - name: "model.gguf".into(), - url: url.into(), - size: 1, - sha256: "0".repeat(64), - }; - let request = model_request(&client, &file, 3, Some("test-secret")) - .unwrap() - .build() - .unwrap(); - assert_eq!( - request - .headers() - .get(reqwest::header::AUTHORIZATION) - .is_some(), - expected_auth, - "{url}" - ); - assert_eq!(request.headers().get(RANGE).unwrap(), "bytes=3-"); - } - } - - #[test] - fn manifest_rejects_url_credentials() { - let bytes = serde_json::to_vec(&json!({ - "schema_version": 1, - "files": [{ - "name": "model.gguf", - "url": "https://alice:secret@huggingface.co/model.gguf", - "size": 1, - "sha256": "0".repeat(64) - }] - })) - .unwrap(); - assert!(Manifest::parse(&bytes).is_err()); - } - - #[tokio::test] - async fn builtin_profile_is_embedded_and_pinned() { - let manifest = Manifest::from_spec("qwen-iq3-s").await.unwrap(); - assert_eq!(manifest.files.len(), 2); - assert_eq!( - manifest.files[0].size + manifest.files[1].size, - 83_617_662_656 - ); - assert!(manifest.files.iter().all(|file| { - file.url - .contains("/resolve/ed59f92082b1e93c0e96d60a8b11aab089b52f09/") - })); - } -} +mod tests; diff --git a/control-plane/src/model/tests.rs b/control-plane/src/model/tests.rs new file mode 100644 index 00000000..1246b231 --- /dev/null +++ b/control-plane/src/model/tests.rs @@ -0,0 +1,373 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use serde_json::json; +use std::time::{SystemTime, UNIX_EPOCH}; +use tokio::{net::TcpListener, time::timeout}; + +#[cfg(unix)] // model fetch is an offline tool that needs statvfs +#[tokio::test] +async fn insufficient_space_stops_before_network_or_partial_file() { + let root = std::env::temp_dir().join(format!( + "strata-space-test-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let manifest = Manifest { + schema_version: 1, + files: vec![ModelFile { + name: "huge.gguf".into(), + url: "https://example.invalid/huge.gguf".into(), + size: u64::MAX, + sha256: "0".repeat(64), + }], + }; + let error = fetch(&manifest, &root).await.unwrap_err().to_string(); + assert!(error.contains("insufficient disk space")); + assert!(!root.join("huge.gguf.part").exists()); + fs::remove_dir_all(root).await.unwrap(); +} + +#[cfg(unix)] // model fetch is an offline tool that needs statvfs +#[tokio::test] +async fn interrupted_download_resumes_and_verifies() { + let base = std::env::temp_dir().join(format!( + "strata-model-test-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&base).await.unwrap(); + let output = base.join("model"); + fs::create_dir_all(&output).await.unwrap(); + fs::write(output.join("sample.bin.part"), b"abc") + .await + .unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0u8; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0); + request.extend_from_slice(&buffer[..count]); + } + let request = String::from_utf8(request).unwrap(); + assert!(request.to_ascii_lowercase().contains("range: bytes=3-")); + socket + .write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef") + .await + .unwrap(); + }); + let manifest_path = base.join("manifest.json"); + fs::write( + &manifest_path, + serde_json::to_vec(&json!({ + "schema_version": 1, + "files": [{ + "name": "sample.bin", + "url": format!("http://{address}/sample.bin"), + "size": 6, + "sha256": hex::encode(Sha256::digest(b"abcdef")) + }] + })) + .unwrap(), + ) + .await + .unwrap(); + let manifest = Manifest::load(&manifest_path).await.unwrap(); + timeout(Duration::from_secs(5), fetch(&manifest, &output)) + .await + .unwrap() + .unwrap(); + server.await.unwrap(); + verify(&manifest, &output).await.unwrap(); + assert_eq!( + fs::read(output.join("sample.bin")).await.unwrap(), + b"abcdef" + ); + assert!(!output.join("sample.bin.part").exists()); + fs::write(output.join("sample.bin"), b"xxxxxx") + .await + .unwrap(); + assert!(verify(&manifest, &output).await.is_err()); + fs::remove_dir_all(&base).await.unwrap(); +} + +#[cfg(unix)] // model fetch is an offline tool that needs statvfs +#[tokio::test] +async fn checksum_mismatch_never_publishes_download() { + let base = std::env::temp_dir().join(format!( + "strata-bad-download-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0u8; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0); + request.extend_from_slice(&buffer[..count]); + } + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nxxxxxx", + ) + .await + .unwrap(); + }); + let manifest = Manifest { + schema_version: 1, + files: vec![ModelFile { + name: "sample.bin".into(), + url: format!("http://{address}/sample.bin"), + size: 6, + sha256: hex::encode(Sha256::digest(b"abcdef")), + }], + }; + let error = timeout(Duration::from_secs(5), fetch(&manifest, &base)) + .await + .unwrap() + .unwrap_err(); + assert!(error.to_string().contains("SHA-256 mismatch")); + server.await.unwrap(); + assert!(!base.join("sample.bin").exists()); + assert!(!base.join("sample.bin.part").exists()); + // Also cover a full-length partial left by a prior interrupted process. + fs::write(base.join("sample.bin.part"), b"xxxxxx") + .await + .unwrap(); + let error = timeout(Duration::from_secs(5), fetch(&manifest, &base)) + .await + .unwrap() + .unwrap_err(); + assert!(error.to_string().contains("size/SHA-256 verification")); + assert!(!base.join("sample.bin").exists()); + fs::remove_dir_all(base).await.unwrap(); +} + +#[cfg(unix)] // model fetch is an offline tool that needs statvfs +#[tokio::test] +async fn transient_server_failure_retries_the_same_partial_download() { + let base = std::env::temp_dir().join(format!( + "strata-retry-test-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&base).await.unwrap(); + fs::write(base.join("sample.bin.part"), b"abc") + .await + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + for attempt in 0..2 { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0u8; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0); + request.extend_from_slice(&buffer[..count]); + } + assert!( + String::from_utf8(request) + .unwrap() + .to_ascii_lowercase() + .contains("range: bytes=3-") + ); + if attempt == 0 { + socket + .write_all( + b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + } else { + socket + .write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef") + .await + .unwrap(); + } + } + }); + let manifest = Manifest::parse( + &serde_json::to_vec(&json!({ + "schema_version": 1, + "files": [{ + "name": "sample.bin", + "url": format!("http://{address}/sample.bin"), + "size": 6, + "sha256": hex::encode(Sha256::digest(b"abcdef")) + }] + })) + .unwrap(), + ) + .unwrap(); + timeout(Duration::from_secs(5), fetch(&manifest, &base)) + .await + .unwrap() + .unwrap(); + server.await.unwrap(); + assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef"); + assert!(!base.join("sample.bin.part").exists()); + fs::remove_dir_all(base).await.unwrap(); +} + +#[cfg(unix)] // model fetch is an offline tool that needs statvfs +#[tokio::test] +async fn short_response_resumes_from_new_partial_offset() { + let base = std::env::temp_dir().join(format!( + "strata-short-response-test-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&base).await.unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + for attempt in 0..2 { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0u8; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0); + request.extend_from_slice(&buffer[..count]); + } + let request = String::from_utf8(request).unwrap().to_ascii_lowercase(); + if attempt == 0 { + assert!(!request.contains("range:")); + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: close\r\n\r\nabc", + ) + .await + .unwrap(); + } else { + assert!(request.contains("range: bytes=3-")); + socket + .write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef") + .await + .unwrap(); + } + } + }); + let manifest = Manifest::parse( + &serde_json::to_vec(&json!({ + "schema_version": 1, + "files": [{ + "name": "sample.bin", + "url": format!("http://{address}/sample.bin"), + "size": 6, + "sha256": hex::encode(Sha256::digest(b"abcdef")) + }] + })) + .unwrap(), + ) + .unwrap(); + timeout(Duration::from_secs(5), fetch(&manifest, &base)) + .await + .unwrap() + .unwrap(); + server.await.unwrap(); + assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef"); + assert!(!base.join("sample.bin.part").exists()); + fs::remove_dir_all(base).await.unwrap(); +} + +#[tokio::test] +async fn manifest_rejects_path_traversal() { + let path = + std::env::temp_dir().join(format!("strata-bad-manifest-{}.json", std::process::id())); + fs::write(&path, serde_json::to_vec(&json!({ + "schema_version": 1, + "files": [{"name": "../escape", "url": "https://example.com/file", "size": 1, "sha256": "a".repeat(64)}] + })).unwrap()).await.unwrap(); + assert!(Manifest::load(&path).await.is_err()); + fs::remove_file(path).await.unwrap(); +} + +#[test] +fn hub_token_is_only_attached_to_exact_https_host() { + let client = Client::new(); + for (url, expected_auth) in [ + ( + "https://huggingface.co/org/repo/resolve/commit/model.gguf", + true, + ), + ("https://huggingface.co.evil.example/model.gguf", false), + ("https://example.com/model.gguf", false), + ("http://localhost/model.gguf", false), + ] { + let file = ModelFile { + name: "model.gguf".into(), + url: url.into(), + size: 1, + sha256: "0".repeat(64), + }; + let request = model_request(&client, &file, 3, Some("test-secret")) + .unwrap() + .build() + .unwrap(); + assert_eq!( + request + .headers() + .get(reqwest::header::AUTHORIZATION) + .is_some(), + expected_auth, + "{url}" + ); + assert_eq!(request.headers().get(RANGE).unwrap(), "bytes=3-"); + } +} + +#[test] +fn manifest_rejects_url_credentials() { + let bytes = serde_json::to_vec(&json!({ + "schema_version": 1, + "files": [{ + "name": "model.gguf", + "url": "https://alice:secret@huggingface.co/model.gguf", + "size": 1, + "sha256": "0".repeat(64) + }] + })) + .unwrap(); + assert!(Manifest::parse(&bytes).is_err()); +} + +#[tokio::test] +async fn builtin_profile_is_embedded_and_pinned() { + let manifest = Manifest::from_spec("qwen-iq3-s").await.unwrap(); + assert_eq!(manifest.files.len(), 2); + assert_eq!( + manifest.files[0].size + manifest.files[1].size, + 83_617_662_656 + ); + assert!(manifest.files.iter().all(|file| { + file.url + .contains("/resolve/ed59f92082b1e93c0e96d60a8b11aab089b52f09/") + })); +} diff --git a/control-plane/src/native_pack.rs b/control-plane/src/native_pack.rs index bbe24f3c..4f4238cb 100644 --- a/control-plane/src/native_pack.rs +++ b/control-plane/src/native_pack.rs @@ -1141,250 +1141,4 @@ fn same_bytes( } #[cfg(test)] -mod tests { - use super::*; - - /// One layer of expert tensors of `kind`, the way a GGUF index lists them (no file behind it). - fn one_layer(kind: u32) -> Vec { - let tensor = |name: &str, dimensions: Vec, bytes: u64, kind: u32| gguf::TensorInfo { - name: name.to_owned(), - dimensions, - kind, - offset: 0, - bytes, - }; - vec![Shard { - path: PathBuf::from("m.gguf"), - index: gguf::TensorIndex { - summary: gguf::Summary { - tensors: 4, - metadata: 0, - architecture: None, - split_no: None, - split_count: None, - split_tensors_count: None, - data_start: 0, - file_size: 0, - types: Default::default(), - }, - tensors: vec![ - tensor("blk.0.ffn_gate_inp.weight", vec![64, 4], 1024, 0), - tensor("blk.0.ffn_gate_exps.weight", vec![64, 64, 4], 4096, kind), - tensor("blk.0.ffn_up_exps.weight", vec![64, 64, 4], 4096, kind), - tensor("blk.0.ffn_down_exps.weight", vec![64, 64, 4], 4096, kind), - ], - }, - }] - } - - /// Strata 0.1.50 packs NVFP4 experts with a scale tail this packer does not write: it refuses them instead of writing a pack - /// whose experts the engine would read without their scales. - #[test] - fn nvfp4_experts_are_refused_and_other_experts_are_laid_out() { - let error = expert_layout(&one_layer(40)) - .err() - .expect("NVFP4 is refused"); - assert!(error.to_string().contains("NVFP4 experts"), "{error}"); - let shards = one_layer(21); - let layout = expert_layout(&shards).expect("IQ3_S experts"); - assert_eq!(layout.n_expert, 4); - assert!(layout.text.starts_with("# strata native experts v3:")); - } - - /// `iq_pack.py` `NATIVE_PLE_KEY` = {Q2_0, Q8_0, IQ3_XXS, IQ4_XS} (Strata 0.1.50, #381); any other quantized key is converted. - #[test] - fn the_native_ple_key_encodings_are_the_originals() { - for (kind, native) in [ - (42, true), - (8, true), - (18, true), - (23, true), - (21, false), - (14, false), - (12, false), - (16, false), - ] { - assert_eq!(native_ple_key(kind), native, "kind {kind}"); - } - } - - /// 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. - #[test] - fn f16_and_bf16_rounding_match_numpy_and_gguf_py() { - let vectors = include_bytes!("../tests/fixtures/offline/f16_bf16_vectors.golden"); - assert_eq!(vectors.len() % 8, 0); - let mut checked = 0; - for record in vectors.as_chunks::<8>().0 { - let bits = u32::from_le_bytes(record[0..4].try_into().unwrap()); - let f16 = u16::from_le_bytes(record[4..6].try_into().unwrap()); - let bf16 = u16::from_le_bytes(record[6..8].try_into().unwrap()); - let value = f32::from_bits(bits); - if value.is_finite() { - // the packer refuses non-finite inputs before rounding; NaN payloads are not compared - assert_eq!( - kar_codec::f32_to_f16_bits(value), - f16, - "f16 of {bits:#010x}" - ); - } - assert_eq!(bf16_round_nearest_even(value), bf16, "bf16 of {bits:#010x}"); - checked += 1; - } - assert!(checked >= 4000); - } - - struct Golden { - header: String, - name: String, - experts: u64, - total: u64, - rows: Vec>, - } - - fn parse_golden(text: &str) -> Golden { - let header = text.lines().next().unwrap().to_owned(); - let after = |marker: &str| { - header - .split(marker) - .nth(1) - .unwrap() - .split(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '.' && c != '-') - .next() - .unwrap() - .to_owned() - }; - Golden { - name: after("offsets in "), - experts: after("n_expert ").parse().unwrap(), - total: after("total ").parse().unwrap(), - rows: text - .lines() - .skip(1) - .map(|l| l.split(' ').map(str::to_owned).collect()) - .collect(), - header, - } - } - - /// Rebuild the tensor directories that produce a real layer table, then run the packer's own layout code. - /// Gate/up/down element counts follow from the blob size and the two quantization geometries; the hidden size - /// is the model's 2560. - fn shards_for(golden: &Golden) -> Vec { - const HIDDEN: u64 = 2560; - let mut names = vec![golden.name.clone()]; - let mut tensors: Vec> = vec![Vec::new()]; - let at = |name: &str, names: &mut Vec, tensors: &mut Vec>| { - if let Some(i) = names.iter().position(|n| n == name) { - return i; - } - names.push(name.to_owned()); - tensors.push(Vec::new()); - names.len() - 1 - }; - for row in &golden.rows { - let layer: u64 = row[0].parse().unwrap(); - let (gu, d): (u32, u32) = (row[1].parse().unwrap(), row[2].parse().unwrap()); - let blob: u64 = row[4].parse().unwrap(); - let offsets: Vec = row[5..8].iter().map(|v| v.parse().unwrap()).collect(); - let column = row.get(8).cloned().unwrap_or_default(); - let files: Vec = if column.contains(',') { - column.split(',').map(str::to_owned).collect() - } else { - vec![column; 3] - }; - let (ge, gb) = gguf::block_geometry(gu).unwrap(); - let (de, db) = gguf::block_geometry(d).unwrap(); - // blob = 2 * X * gb/ge + X * db/de for X = HIDDEN * FF elements per expert - let numerator = blob * ge * de; - let denominator = 2 * gb * de + db * ge; - assert_eq!(numerator % denominator, 0, "layer {layer}"); - let x = numerator / denominator; - assert_eq!(x % HIDDEN, 0); - let ff = x / HIDDEN; - let shard = |i: usize, names: &mut Vec, t: &mut Vec>| { - if files[i].is_empty() { - 0 - } else { - at(&files[i], names, t) - } - }; - let experts = golden.experts; - let roles = [ - ("gate", gu, vec![HIDDEN, ff, experts], x / ge * gb * experts), - ("up", gu, vec![HIDDEN, ff, experts], x / ge * gb * experts), - ("down", d, vec![ff, HIDDEN, experts], x / de * db * experts), - ]; - let router = gguf::TensorInfo { - name: format!("blk.{layer}.ffn_gate_inp.weight"), - dimensions: vec![HIDDEN, experts], - kind: 0, - offset: 0, - bytes: HIDDEN * experts * 4, - }; - tensors[0].push(router); - for (i, (role, kind, dimensions, bytes)) in roles.into_iter().enumerate() { - let s = shard(i, &mut names, &mut tensors); - tensors[s].push(gguf::TensorInfo { - name: format!("blk.{layer}.ffn_{role}_exps.weight"), - dimensions, - kind, - offset: offsets[i], - bytes, - }); - } - } - names - .into_iter() - .zip(tensors) - .map(|(name, tensors)| Shard { - path: PathBuf::from(name), - index: gguf::TensorIndex { - summary: gguf::Summary { - tensors: tensors.len() as u64, - metadata: 0, - architecture: Some("qwen4exp".into()), - split_no: None, - split_count: None, - split_tensors_count: None, - data_start: 0, - file_size: 0, - types: BTreeMap::new(), - }, - tensors, - }, - }) - .collect() - } - - /// The six real per-layer expert tables shipped with Strata (IQ3_S, IQ3_XXS, IQ2_XS, Q2_0 packs, the coder - /// IQ1_M pack, and Swift's IQ2_XS whose layers 13-47 live in the second shard): the Rust layout reproduces - /// every row byte for byte. The v2 files predate the shard column; their header wording differs, their rows - /// and totals do not. - #[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"), - ]; - for text in goldens { - let golden = parse_golden(text); - let shards = shards_for(&golden); - let layout = expert_layout(&shards).unwrap(); - assert_eq!(layout.n_expert, golden.experts); - assert_eq!(layout.total, golden.total, "{}", golden.name); - let produced = layout.text.lines().skip(1).collect::>(); - let wanted = text.lines().skip(1).collect::>(); - assert_eq!(produced, wanted, "{}", golden.name); - if golden.header.contains("native experts v3") - || golden.header.contains("native experts v4") - { - assert_eq!(layout.text, text, "{}", golden.name); - } - } - } -} +mod tests; diff --git a/control-plane/src/native_pack/tests.rs b/control-plane/src/native_pack/tests.rs new file mode 100644 index 00000000..c5d240f2 --- /dev/null +++ b/control-plane/src/native_pack/tests.rs @@ -0,0 +1,247 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +/// One layer of expert tensors of `kind`, the way a GGUF index lists them (no file behind it). +fn one_layer(kind: u32) -> Vec { + let tensor = |name: &str, dimensions: Vec, bytes: u64, kind: u32| gguf::TensorInfo { + name: name.to_owned(), + dimensions, + kind, + offset: 0, + bytes, + }; + vec![Shard { + path: PathBuf::from("m.gguf"), + index: gguf::TensorIndex { + summary: gguf::Summary { + tensors: 4, + metadata: 0, + architecture: None, + split_no: None, + split_count: None, + split_tensors_count: None, + data_start: 0, + file_size: 0, + types: Default::default(), + }, + tensors: vec![ + tensor("blk.0.ffn_gate_inp.weight", vec![64, 4], 1024, 0), + tensor("blk.0.ffn_gate_exps.weight", vec![64, 64, 4], 4096, kind), + tensor("blk.0.ffn_up_exps.weight", vec![64, 64, 4], 4096, kind), + tensor("blk.0.ffn_down_exps.weight", vec![64, 64, 4], 4096, kind), + ], + }, + }] +} + +/// Strata 0.1.50 packs NVFP4 experts with a scale tail this packer does not write: it refuses them instead of writing a pack +/// whose experts the engine would read without their scales. +#[test] +fn nvfp4_experts_are_refused_and_other_experts_are_laid_out() { + let error = expert_layout(&one_layer(40)) + .err() + .expect("NVFP4 is refused"); + assert!(error.to_string().contains("NVFP4 experts"), "{error}"); + let shards = one_layer(21); + let layout = expert_layout(&shards).expect("IQ3_S experts"); + assert_eq!(layout.n_expert, 4); + assert!(layout.text.starts_with("# strata native experts v3:")); +} + +/// `iq_pack.py` `NATIVE_PLE_KEY` = {Q2_0, Q8_0, IQ3_XXS, IQ4_XS} (Strata 0.1.50, #381); any other quantized key is converted. +#[test] +fn the_native_ple_key_encodings_are_the_originals() { + for (kind, native) in [ + (42, true), + (8, true), + (18, true), + (23, true), + (21, false), + (14, false), + (12, false), + (16, false), + ] { + assert_eq!(native_ple_key(kind), native, "kind {kind}"); + } +} + +/// 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. +#[test] +fn f16_and_bf16_rounding_match_numpy_and_gguf_py() { + let vectors = include_bytes!("../../tests/fixtures/offline/f16_bf16_vectors.golden"); + assert_eq!(vectors.len() % 8, 0); + let mut checked = 0; + for record in vectors.as_chunks::<8>().0 { + let bits = u32::from_le_bytes(record[0..4].try_into().unwrap()); + let f16 = u16::from_le_bytes(record[4..6].try_into().unwrap()); + let bf16 = u16::from_le_bytes(record[6..8].try_into().unwrap()); + let value = f32::from_bits(bits); + if value.is_finite() { + // the packer refuses non-finite inputs before rounding; NaN payloads are not compared + assert_eq!( + kar_codec::f32_to_f16_bits(value), + f16, + "f16 of {bits:#010x}" + ); + } + assert_eq!(bf16_round_nearest_even(value), bf16, "bf16 of {bits:#010x}"); + checked += 1; + } + assert!(checked >= 4000); +} + +struct Golden { + header: String, + name: String, + experts: u64, + total: u64, + rows: Vec>, +} + +fn parse_golden(text: &str) -> Golden { + let header = text.lines().next().unwrap().to_owned(); + let after = |marker: &str| { + header + .split(marker) + .nth(1) + .unwrap() + .split(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '.' && c != '-') + .next() + .unwrap() + .to_owned() + }; + Golden { + name: after("offsets in "), + experts: after("n_expert ").parse().unwrap(), + total: after("total ").parse().unwrap(), + rows: text + .lines() + .skip(1) + .map(|l| l.split(' ').map(str::to_owned).collect()) + .collect(), + header, + } +} + +/// Rebuild the tensor directories that produce a real layer table, then run the packer's own layout code. +/// Gate/up/down element counts follow from the blob size and the two quantization geometries; the hidden size +/// is the model's 2560. +fn shards_for(golden: &Golden) -> Vec { + const HIDDEN: u64 = 2560; + let mut names = vec![golden.name.clone()]; + let mut tensors: Vec> = vec![Vec::new()]; + let at = |name: &str, names: &mut Vec, tensors: &mut Vec>| { + if let Some(i) = names.iter().position(|n| n == name) { + return i; + } + names.push(name.to_owned()); + tensors.push(Vec::new()); + names.len() - 1 + }; + for row in &golden.rows { + let layer: u64 = row[0].parse().unwrap(); + let (gu, d): (u32, u32) = (row[1].parse().unwrap(), row[2].parse().unwrap()); + let blob: u64 = row[4].parse().unwrap(); + let offsets: Vec = row[5..8].iter().map(|v| v.parse().unwrap()).collect(); + let column = row.get(8).cloned().unwrap_or_default(); + let files: Vec = if column.contains(',') { + column.split(',').map(str::to_owned).collect() + } else { + vec![column; 3] + }; + let (ge, gb) = gguf::block_geometry(gu).unwrap(); + let (de, db) = gguf::block_geometry(d).unwrap(); + // blob = 2 * X * gb/ge + X * db/de for X = HIDDEN * FF elements per expert + let numerator = blob * ge * de; + let denominator = 2 * gb * de + db * ge; + assert_eq!(numerator % denominator, 0, "layer {layer}"); + let x = numerator / denominator; + assert_eq!(x % HIDDEN, 0); + let ff = x / HIDDEN; + let shard = |i: usize, names: &mut Vec, t: &mut Vec>| { + if files[i].is_empty() { + 0 + } else { + at(&files[i], names, t) + } + }; + let experts = golden.experts; + let roles = [ + ("gate", gu, vec![HIDDEN, ff, experts], x / ge * gb * experts), + ("up", gu, vec![HIDDEN, ff, experts], x / ge * gb * experts), + ("down", d, vec![ff, HIDDEN, experts], x / de * db * experts), + ]; + let router = gguf::TensorInfo { + name: format!("blk.{layer}.ffn_gate_inp.weight"), + dimensions: vec![HIDDEN, experts], + kind: 0, + offset: 0, + bytes: HIDDEN * experts * 4, + }; + tensors[0].push(router); + for (i, (role, kind, dimensions, bytes)) in roles.into_iter().enumerate() { + let s = shard(i, &mut names, &mut tensors); + tensors[s].push(gguf::TensorInfo { + name: format!("blk.{layer}.ffn_{role}_exps.weight"), + dimensions, + kind, + offset: offsets[i], + bytes, + }); + } + } + names + .into_iter() + .zip(tensors) + .map(|(name, tensors)| Shard { + path: PathBuf::from(name), + index: gguf::TensorIndex { + summary: gguf::Summary { + tensors: tensors.len() as u64, + metadata: 0, + architecture: Some("qwen4exp".into()), + split_no: None, + split_count: None, + split_tensors_count: None, + data_start: 0, + file_size: 0, + types: BTreeMap::new(), + }, + tensors, + }, + }) + .collect() +} + +/// The six real per-layer expert tables shipped with Strata (IQ3_S, IQ3_XXS, IQ2_XS, Q2_0 packs, the coder +/// IQ1_M pack, and Swift's IQ2_XS whose layers 13-47 live in the second shard): the Rust layout reproduces +/// every row byte for byte. The v2 files predate the shard column; their header wording differs, their rows +/// and totals do not. +#[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"), + ]; + for text in goldens { + let golden = parse_golden(text); + let shards = shards_for(&golden); + let layout = expert_layout(&shards).unwrap(); + assert_eq!(layout.n_expert, golden.experts); + assert_eq!(layout.total, golden.total, "{}", golden.name); + let produced = layout.text.lines().skip(1).collect::>(); + let wanted = text.lines().skip(1).collect::>(); + assert_eq!(produced, wanted, "{}", golden.name); + if golden.header.contains("native experts v3") + || golden.header.contains("native experts v4") + { + assert_eq!(layout.text, text, "{}", golden.name); + } + } +} diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 9eedb907..b6cd965b 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -1390,825 +1390,4 @@ fn hash_file(path: &Path) -> Result<[u8; 32], String> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn kar_payload_preflight_rejects_too_small_volumes_conservatively() { - assert_eq!( - minimum_part_payload_bytes(707_775_598_080, 2).unwrap(), - 44_235_974_880 - ); - assert!(minimum_part_payload_bytes(707_775_598_080, 2).unwrap() > 23 * (1 << 30)); - assert_eq!(minimum_part_payload_bytes(4, 8).unwrap(), 4); - assert!(minimum_part_payload_bytes(u64::MAX, 8).is_err()); - } - use crate::model::ModelFile; - - fn string(out: &mut Vec, value: &str) { - out.extend_from_slice(&(value.len() as u64).to_le_bytes()); - out.extend_from_slice(value.as_bytes()); - } - - fn one_shard(name: &str, kind: u32, elements: u64, payload: &[u8]) -> Vec { - one_shard_with_arch(name, kind, elements, payload, true) - } - - fn one_shard_with_arch( - name: &str, - kind: u32, - elements: u64, - payload: &[u8], - include_architecture: bool, - ) -> Vec { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - gguf.extend_from_slice(&u64::from(include_architecture).to_le_bytes()); - if include_architecture { - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); - } - string(&mut gguf, name); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&elements.to_le_bytes()); - gguf.extend_from_slice(&kind.to_le_bytes()); - gguf.extend_from_slice(&0u64.to_le_bytes()); - gguf.resize(gguf.len().div_ceil(32) * 32, 0); - gguf.extend_from_slice(payload); - gguf - } - - fn ple_shard(payload: &[u8]) -> Vec { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); - string(&mut gguf, stream_parts::PLE_TENSOR_NAME); - gguf.extend_from_slice(&2u32.to_le_bytes()); - gguf.extend_from_slice(&32u64.to_le_bytes()); - gguf.extend_from_slice(&16u64.to_le_bytes()); - gguf.extend_from_slice(&0u32.to_le_bytes()); - gguf.extend_from_slice(&0u64.to_le_bytes()); - gguf.resize(gguf.len().div_ceil(32) * 32, 0); - gguf.extend_from_slice(payload); - gguf - } - - #[test] - fn converts_two_small_f32_gguf_tensors_and_rejects_duplicate_output() { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&2u64.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); - for (name, offset) in [("first", 0u64), ("second", 128)] { - string(&mut gguf, name); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&32u64.to_le_bytes()); - gguf.extend_from_slice(&0u32.to_le_bytes()); - gguf.extend_from_slice(&offset.to_le_bytes()); - } - let data_start = gguf.len().div_ceil(32) * 32; - gguf.resize(data_start, 0); - for index in 0..64 { - let value = [-1.0f32, -0.25, 0.25, 1.0][index % 4]; - gguf.extend_from_slice(&value.to_le_bytes()); - } - let source_path = - std::env::temp_dir().join(format!("strata-preview-{}.gguf", std::process::id())); - let output = - std::env::temp_dir().join(format!("strata-preview-{}.kar", std::process::id())); - let _ = fs::remove_file(&output); - fs::write(&source_path, &gguf).unwrap(); - let summary = prepare_f32(&source_path, &output, 2).unwrap(); - assert_eq!(summary.archive.tensor_count, 2); - assert_eq!(summary.archive.total_elements, 64); - assert!(summary.maximum_relative_l2.is_finite()); - assert_eq!( - summary.archive.source_digest, - hash_file(&source_path).unwrap() - ); - assert_eq!(summary.archive_digest, hash_file(&output).unwrap()); - let staging = output.with_file_name(format!( - "{}.parts-{}", - output.file_name().unwrap().to_string_lossy(), - std::process::id() - )); - assert!(!staging.exists()); - assert!(prepare_f32(&source_path, &output, 2).is_err()); - assert!(!staging.exists()); - let failed_source = - std::env::temp_dir().join(format!("strata-preview-bad-{}.gguf", std::process::id())); - let failed_output = - std::env::temp_dir().join(format!("strata-preview-bad-{}.kar", std::process::id())); - let _ = fs::remove_file(&failed_output); - let mut broken = gguf.clone(); - let last = broken.len() - 4; - broken[last..].copy_from_slice(&f32::NAN.to_le_bytes()); - fs::write(&failed_source, broken).unwrap(); - assert!( - prepare_f32(&failed_source, &failed_output, 2) - .unwrap_err() - .contains("invalid KAR normalization input") - ); - assert!(!failed_output.exists()); - let failed_staging = failed_output.with_file_name(format!( - "{}.parts-{}", - failed_output.file_name().unwrap().to_string_lossy(), - std::process::id() - )); - assert!(!failed_staging.exists()); - fs::remove_file(failed_source).unwrap(); - fs::remove_file(&output).unwrap(); - fs::remove_file(&source_path).unwrap(); - } - - #[test] - fn refuses_quantized_gguf_until_source_decoder_is_available() { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); - string(&mut gguf, "expert"); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&256u64.to_le_bytes()); - gguf.extend_from_slice(&21u32.to_le_bytes()); - gguf.extend_from_slice(&0u64.to_le_bytes()); - gguf.resize(gguf.len().div_ceil(32) * 32, 0); - gguf.extend_from_slice(&[0u8; 110]); - let source_path = - std::env::temp_dir().join(format!("strata-preview-iq3-{}.gguf", std::process::id())); - let output = - std::env::temp_dir().join(format!("strata-preview-iq3-{}.kar", std::process::id())); - let _ = fs::remove_file(&output); - fs::write(&source_path, gguf).unwrap(); - assert!( - prepare_f32(&source_path, &output, 2) - .unwrap_err() - .contains("supports only F32") - ); - assert!(!output.exists()); - fs::remove_file(source_path).unwrap(); - } - - #[test] - fn prepares_iq3_preview_with_virtual_f32_source_and_provenance() { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); - string(&mut gguf, "expert"); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&256u64.to_le_bytes()); - gguf.extend_from_slice(&21u32.to_le_bytes()); - gguf.extend_from_slice(&0u64.to_le_bytes()); - gguf.resize(gguf.len().div_ceil(32) * 32, 0); - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - for (index, byte) in block[2..66].iter_mut().enumerate() { - *byte = (index as u8).wrapping_mul(3); - } - block[74] = 0x55; - gguf.extend_from_slice(&block); - let base = - std::env::temp_dir().join(format!("strata-preview-iq3-good-{}", std::process::id())); - let source_path = base.with_extension("gguf"); - let output = base.with_extension("kar"); - let provenance = output.with_file_name(format!( - "{}.provenance.json", - output.file_name().unwrap().to_string_lossy() - )); - let _ = fs::remove_file(&output); - let _ = fs::remove_file(&provenance); - fs::write(&source_path, gguf).unwrap(); - let identity = derived_iq3::fingerprint(&source_path).unwrap(); - let result = prepare_iq3(&source_path, &output, 2).unwrap(); - assert_eq!(result.archive.source_digest, identity.derived_sha256); - assert_eq!(result.archive.source_bytes, identity.derived_bytes); - assert_eq!( - result.provenance_path.as_deref(), - Some(provenance.as_path()) - ); - assert_eq!(kar::verify(&output).unwrap(), result.archive); - let record: serde_json::Value = - serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap(); - assert_eq!( - record["original_gguf_sha256"], - hex::encode(identity.gguf_sha256) - ); - assert_eq!( - record["derived_f32_sha256"], - hex::encode(identity.derived_sha256) - ); - assert_eq!(record["archive_sha256"], hex::encode(result.archive_digest)); - assert!(result.maximum_relative_l2.is_finite()); - assert_eq!(verify_iq3(&source_path, &output).unwrap(), result.archive); - let saved_provenance = fs::read(&provenance).unwrap(); - let mut changed = record.clone(); - changed["archive_sha256"] = serde_json::Value::String("00".repeat(32)); - fs::write(&provenance, serde_json::to_vec(&changed).unwrap()).unwrap(); - assert!( - verify_iq3(&source_path, &output) - .unwrap_err() - .contains("provenance differs") - ); - fs::write(&provenance, saved_provenance).unwrap(); - assert!(verify_iq3(&source_path, &output).is_ok()); - let blocked_output = base.with_file_name(format!( - "strata-preview-iq3-blocked-{}.kar", - std::process::id() - )); - let blocked_provenance = blocked_output.with_file_name(format!( - "{}.provenance.json", - blocked_output.file_name().unwrap().to_string_lossy() - )); - let _ = fs::remove_file(&blocked_output); - fs::write(&blocked_provenance, b"reserved").unwrap(); - assert!( - prepare_iq3(&source_path, &blocked_output, 2) - .unwrap_err() - .contains("provenance destination already exists") - ); - assert!(!blocked_output.exists()); - fs::remove_file(blocked_provenance).unwrap(); - fs::remove_file(provenance).unwrap(); - fs::remove_file(output).unwrap(); - fs::remove_file(source_path).unwrap(); - } - - #[test] - fn prepares_and_verifies_mixed_preview_with_each_source_kind() { - let tensors = [ - ("bf16", 30u32, 320u64, 32u64), - ("iq3", 21, 0, 256), - ("f16", 1, 256, 32), - ("f32", 0, 128, 32), - ]; - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&(tensors.len() as u64).to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); - for (name, kind, offset, elements) in tensors { - string(&mut gguf, name); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&elements.to_le_bytes()); - gguf.extend_from_slice(&kind.to_le_bytes()); - gguf.extend_from_slice(&offset.to_le_bytes()); - } - gguf.resize(gguf.len().div_ceil(32) * 32, 0); - let mut payload = vec![0u8; 384]; - payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - for (index, byte) in payload[2..66].iter_mut().enumerate() { - *byte = (index as u8).wrapping_mul(3); - } - payload[74] = 0x55; - let values = [-1.0f32, -0.25, 0.25, 1.0]; - for index in 0..32 { - let value = values[index % values.len()]; - payload[128 + 4 * index..132 + 4 * index].copy_from_slice(&value.to_le_bytes()); - let f16 = kar_codec::f32_to_f16_bits(value).to_le_bytes(); - payload[256 + 2 * index..258 + 2 * index].copy_from_slice(&f16); - let bf16 = (value.to_bits() >> 16) as u16; - payload[320 + 2 * index..322 + 2 * index].copy_from_slice(&bf16.to_le_bytes()); - } - gguf.extend_from_slice(&payload); - let base = - std::env::temp_dir().join(format!("strata-preview-mixed-{}", std::process::id())); - let source_path = base.with_extension("gguf"); - let output = base.with_extension("kar"); - let provenance = provenance_path(&output).unwrap(); - let _ = fs::remove_file(&output); - let _ = fs::remove_file(&provenance); - fs::write(&source_path, gguf).unwrap(); - let identity = derived_mixed::fingerprint(&source_path).unwrap(); - let result = prepare_mixed(&source_path, &output, 2).unwrap(); - assert_eq!(result.archive.source_digest, identity.derived_sha256); - assert_eq!(result.archive.source_bytes, identity.derived_bytes); - assert_eq!(result.archive.tensor_count, 4); - assert_eq!(verify_mixed(&source_path, &output).unwrap(), result.archive); - assert!(verify_iq3(&source_path, &output).is_err()); - let record: serde_json::Value = - serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap(); - assert_eq!(record["schema"], "strata-next/mixed-preview-provenance-v1"); - assert_eq!(record["tensors"][0]["source_kind"], 30); - assert!(result.maximum_relative_l2.is_finite()); - fs::remove_file(provenance).unwrap(); - fs::remove_file(output).unwrap(); - fs::remove_file(source_path).unwrap(); - } - - #[cfg(unix)] // archive preparation is an offline Unix tool - #[tokio::test] - async fn prepares_and_verifies_manifest_pinned_sharded_preview() { - let directory = - std::env::temp_dir().join(format!("strata-preview-shards-{}", std::process::id())); - let _ = fs::remove_dir_all(&directory); - fs::create_dir(&directory).unwrap(); - let mut dense = Vec::new(); - for index in 0..32 { - dense.extend_from_slice(&[-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()); - } - let f32 = one_shard("dense", 0, 32, &dense); - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - for (index, byte) in block[2..66].iter_mut().enumerate() { - *byte = (index as u8).wrapping_mul(3); - } - block[74] = 0x55; - let iq3 = one_shard_with_arch("expert", 21, 256, &block, false); - fs::write(directory.join("a-f32.gguf"), &f32).unwrap(); - fs::write(directory.join("z-iq3.gguf"), &iq3).unwrap(); - let mut manifest = Manifest { - schema_version: 1, - files: vec![ - ModelFile { - name: "z-iq3.gguf".into(), - url: "https://example.invalid/z".into(), - size: iq3.len() as u64, - sha256: hex::encode(Sha256::digest(&iq3)), - }, - ModelFile { - name: "a-f32.gguf".into(), - url: "https://example.invalid/a".into(), - size: f32.len() as u64, - sha256: hex::encode(Sha256::digest(&f32)), - }, - ], - }; - let output = directory.join("sharded.kar"); - let identity = derived_mixed::fingerprint_shards(&manifest, &directory).unwrap(); - let result = prepare_sharded(&manifest, &directory, &output, 2).unwrap(); - assert_eq!(result.archive.tensor_count, 2); - assert_eq!(result.archive.source_digest, identity.derived_sha256); - assert_eq!(result.archive.source_bytes, identity.derived_bytes); - assert_eq!( - verify_sharded(&manifest, &directory, &output).unwrap(), - result.archive - ); - assert!(matches!( - crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2) - .await - .unwrap(), - crate::model_pipeline::PreviewOutcome::Reused(_) - )); - assert!( - crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 3) - .await - .is_err() - ); - let record: serde_json::Value = - serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap(); - assert_eq!( - record["schema"], - "strata-next/sharded-preview-provenance-v1" - ); - assert_eq!(record["shards"][0]["name"], "a-f32.gguf"); - assert_eq!(record["tensors"][1]["derived_offset"], 128); - let streamed_output = directory.join("streamed.kar"); - let streamed = - prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(); - assert_eq!(streamed.archive.source_digest, identity.derived_sha256); - assert_eq!(streamed.archive.tensor_count, 2); - let decoded = kar::decode_preview_tensor(&streamed_output, "dense", 2).unwrap(); - let reference = dense - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)) - .collect::>(); - assert_eq!(decoded.len(), reference.len()); - assert!( - decoded - .iter() - .zip(&reference) - .all(|(actual, expected)| (actual - expected).abs() < 0.1) - ); - assert_eq!( - verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(), - streamed.archive - ); - let sampled = - crate::kar_quality::analyze(&manifest, &directory, &streamed_output, 2).unwrap(); - assert_eq!( - sampled.records.len(), - streamed.archive.tensor_count as usize - ); - assert!( - sampled - .records - .iter() - .all(|record| { record.sampled_elements > 0 && record.relative_l2.is_finite() }) - ); - let reused = crate::kar_quality::analyze_previously_verified( - &manifest, - &directory, - &streamed_output, - 2, - ) - .unwrap(); - assert!( - reused - .records - .iter() - .zip(&sampled.records) - .all(|(a, b)| { a.name == b.name && a.relative_l2 == b.relative_l2 }) - ); - assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 3).is_err()); - assert!(verify_sharded(&manifest, &directory, &streamed_output).is_err()); - let streamed_record: serde_json::Value = - serde_json::from_slice(&fs::read(streamed.provenance_path.unwrap()).unwrap()).unwrap(); - assert_eq!( - streamed_record["schema"], - "strata-next/sharded-stream-provenance-v4" - ); - assert_eq!( - streamed_record["partitioned_tensors"], - serde_json::json!([]) - ); - assert_eq!(streamed_record["levels"], 2); - assert!(prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err()); - manifest.files[0].sha256 = "00".repeat(32); - assert!(verify_sharded(&manifest, &directory, &output).is_err()); - assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err()); - manifest.files[0].sha256 = hex::encode(Sha256::digest(&iq3)); - let mut corrupted = fs::read(&output).unwrap(); - let last = corrupted.len() - 1; - corrupted[last] ^= 1; - fs::write(&output, corrupted).unwrap(); - assert!( - crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2) - .await - .is_err() - ); - fs::remove_dir_all(directory).unwrap(); - } - - #[cfg(unix)] // archive preparation is an offline Unix tool - #[test] - fn streamed_preparation_keeps_unsplittable_tensors_exact() { - let directory = - std::env::temp_dir().join(format!("strata-stream-raw-{}", std::process::id())); - let _ = fs::remove_dir_all(&directory); - fs::create_dir(&directory).unwrap(); - let mut files = Vec::new(); - for (name, kind, elements, payload) in [ - ("a", 21, 256, vec![0u8; iq3_s::BLOCK_BYTES]), - ("b", 20, 32, vec![0u8; 18]), - ] { - let bytes = one_shard_with_arch(name, kind, elements, &payload, name == "a"); - let filename = format!("{name}.gguf"); - fs::write(directory.join(&filename), &bytes).unwrap(); - files.push(ModelFile { - name: filename, - url: "https://example.invalid/source".into(), - size: bytes.len() as u64, - sha256: hex::encode(Sha256::digest(&bytes)), - }); - } - let manifest = Manifest { - schema_version: 1, - files, - }; - let archive = directory.join("raw.kar"); - let result = prepare_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(); - assert_eq!(result.archive.max_planes, 0); - assert_eq!(result.maximum_relative_l2, 0.0); - let sampled = crate::kar_quality::analyze(&manifest, &directory, &archive, 2).unwrap(); - assert_eq!(sampled.records.len(), 2); - assert!( - sampled - .records - .iter() - .all(|record| record.relative_l2 == 0.0) - ); - let reused = - crate::kar_quality::analyze_previously_verified(&manifest, &directory, &archive, 2) - .unwrap(); - assert!( - reused - .records - .iter() - .all(|record| record.relative_l2 == 0.0) - ); - assert_eq!( - verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(), - result.archive - ); - fs::remove_dir_all(directory).unwrap(); - } - - #[cfg(unix)] // archive preparation is an offline Unix tool - #[test] - fn selected_overlay_reconstructs_source_and_cleans_staging() { - let directory = std::env::temp_dir().join(format!("strata-overlay-{}", std::process::id())); - let _ = fs::remove_dir_all(&directory); - fs::create_dir(&directory).unwrap(); - let values = (0..256) - .map(|index| (index as f32 - 127.5) / 128.0) - .collect::>(); - let dense = values - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect::>(); - let files = [ - ("a.gguf", one_shard("dense", 0, 256, &dense)), - ( - "b.gguf", - one_shard_with_arch("extra", 21, 256, &[0u8; iq3_s::BLOCK_BYTES], false), - ), - ] - .into_iter() - .map(|(name, bytes)| { - fs::write(directory.join(name), &bytes).unwrap(); - ModelFile { - name: name.into(), - url: "https://example.invalid/source".into(), - size: bytes.len() as u64, - sha256: hex::encode(Sha256::digest(&bytes)), - } - }) - .collect(); - let manifest = Manifest { - schema_version: 1, - files, - }; - let base = directory.join("base.kar"); - let prepared = prepare_sharded_streamed(&manifest, &directory, &base, 2).unwrap(); - let policy = directory.join("candidates.json"); - fs::write( - &policy, - serde_json::to_vec(&serde_json::json!({ - "schema": "strata-next/proposed-kar-precision-candidates-v1", - "source_archive_sha256": hex::encode(prepared.archive_digest), - "proposed_levels": 3, - "records": [{"name": "dense", "elements": 256}], - })) - .unwrap(), - ) - .unwrap(); - let overlay = directory.join("overlay.kar"); - let result = - crate::kar_overlay::prepare(&manifest, &directory, &base, &policy, &overlay).unwrap(); - assert_eq!(result.record_count, 1); - assert_eq!(kar::verify(&overlay).unwrap().max_planes, 3); - assert!(result.maximum_relative_l2.is_finite()); - let decoded = kar::decode_preview_tensor(&overlay, "dense", 3).unwrap(); - let error_sum = decoded - .iter() - .zip(&values) - .map(|(actual, expected)| f64::from(actual - expected).powi(2)) - .sum::(); - let reference_sum = values - .iter() - .map(|value| f64::from(*value).powi(2)) - .sum::(); - assert!(((error_sum / reference_sum).sqrt() - result.maximum_relative_l2).abs() < 1e-7); - assert!(result.provenance_path.exists()); - let comparison = - crate::kar_overlay::compare(&manifest, &directory, &base, &overlay).unwrap(); - assert_eq!(comparison.records.len(), 1); - assert_eq!(comparison.records[0].name, "dense"); - let selection = crate::kar_overlay::resolve_verified(&base, &overlay).unwrap(); - assert_eq!(selection.replacement_count, 1); - assert_eq!(selection.records.len(), 2); - assert_eq!(selection.records[0].name, "dense"); - assert_eq!(selection.records[0].archive, "overlay"); - assert_eq!(selection.records[1].archive, "base"); - let mut provenance: serde_json::Value = - serde_json::from_slice(&fs::read(&result.provenance_path).unwrap()).unwrap(); - provenance["records"][0]["f32_sha256"] = serde_json::json!("00".repeat(32)); - fs::write( - &result.provenance_path, - serde_json::to_vec(&provenance).unwrap(), - ) - .unwrap(); - assert!(crate::kar_overlay::resolve_verified(&base, &overlay).is_err()); - assert!( - (comparison.records[0].overlay_relative_l2 - result.maximum_relative_l2).abs() < 1e-7 - ); - assert!( - !directory - .join(format!( - "overlay.kar.overlay-sections-{}", - std::process::id() - )) - .exists() - ); - fs::remove_dir_all(directory).unwrap(); - } - - #[cfg(unix)] // archive preparation is an offline Unix tool - #[test] - fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { - let directory = - std::env::temp_dir().join(format!("strata-stream-split-{}", std::process::id())); - let _ = fs::remove_dir_all(&directory); - fs::create_dir(&directory).unwrap(); - let dense = (0..512) - .flat_map(|index| [-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()) - .collect::>(); - let dense_shard = one_shard("dense", 0, 512, &dense); - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - let iq3_shard = one_shard_with_arch("expert", 21, 256, &block, false); - let files = [("a-dense.gguf", dense_shard), ("z-iq3.gguf", iq3_shard)] - .into_iter() - .map(|(name, bytes)| { - fs::write(directory.join(name), &bytes).unwrap(); - ModelFile { - name: name.into(), - url: "https://example.invalid/source".into(), - size: bytes.len() as u64, - sha256: hex::encode(Sha256::digest(&bytes)), - } - }) - .collect(); - let manifest = Manifest { - schema_version: 1, - files, - }; - let archive = directory.join("split.kar"); - let result = - prepare_sharded_streamed_with_limit(&manifest, &directory, &archive, 2, 256).unwrap(); - assert_eq!(result.archive.tensor_count, 3); - assert_eq!(result.tensor_distortions.len(), 3); - assert_eq!( - result.maximum_relative_l2, - result - .tensor_distortions - .iter() - .map(|entry| entry.relative_l2) - .fold(0.0f64, f64::max) - ); - assert!( - result - .tensor_distortions - .iter() - .all(|entry| entry.section_bytes > 0 && entry.relative_l2.is_finite()) - ); - assert_eq!( - verify_sharded_inner(&manifest, &directory, &archive, Some(2), 256, None).unwrap(), - result.archive - ); - assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); - let provenance: serde_json::Value = - serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap(); - let parts = provenance["partitioned_tensors"][0]["parts"] - .as_array() - .unwrap(); - assert_eq!(parts.len(), 2); - assert_eq!(parts[0]["dimensions"], serde_json::json!([256])); - assert_eq!(parts[1]["derived_offset"], 1024); - for (number, part) in parts.iter().enumerate() { - let name = part["name"].as_str().unwrap(); - let decoded = kar::decode_preview_tensor(&archive, name, 2).unwrap(); - assert_eq!(decoded.len(), 256); - for (actual, original) in decoded.iter().zip( - dense[number * 1024..(number + 1) * 1024] - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ) { - assert!((actual - original).abs() < 0.1); - } - } - fs::remove_dir_all(directory).unwrap(); - } - - #[cfg(unix)] // archive preparation is an offline Unix tool - #[test] - fn ple_partition_policy_is_versioned_and_verified() { - let directory = std::env::temp_dir().join(format!( - "strata-ple-parts-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::create_dir(&directory).unwrap(); - let ple_values = (0..512) - .flat_map(|index| ((index as f32 - 255.5) / 256.0).to_le_bytes()) - .collect::>(); - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - let dense_values = (0..256) - .map(|index| (index as f32 - 127.5) / 128.0) - .flat_map(f32::to_le_bytes) - .collect::>(); - let files = [ - ("a-ple.gguf", ple_shard(&ple_values)), - ( - "m-dense.gguf", - one_shard_with_arch("dense", 0, 256, &dense_values, false), - ), - ( - "z-expert.gguf", - one_shard_with_arch("expert", 21, 256, &block, false), - ), - ] - .into_iter() - .map(|(name, bytes)| { - fs::write(directory.join(name), &bytes).unwrap(); - ModelFile { - name: name.into(), - url: "https://example.invalid/source".into(), - size: bytes.len() as u64, - sha256: hex::encode(Sha256::digest(&bytes)), - } - }) - .collect(); - let manifest = Manifest { - schema_version: 1, - files, - }; - let archive = directory.join("ple.kar"); - let prepared = - prepare_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(); - assert_eq!(prepared.archive.tensor_count, 6); - assert_eq!( - verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(), - prepared.archive - ); - assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); - assert!(verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 256).is_err()); - let provenance: serde_json::Value = - serde_json::from_slice(&fs::read(prepared.provenance_path.unwrap()).unwrap()).unwrap(); - assert_eq!( - provenance["schema"], - "strata-next/sharded-stream-provenance-v5" - ); - assert_eq!(provenance["ple_part_elements"], 128); - assert_eq!( - provenance["partitioned_tensors"][0]["parts"] - .as_array() - .unwrap() - .len(), - 4 - ); - let policy = directory.join("candidates.json"); - fs::write( - &policy, - serde_json::to_vec(&serde_json::json!({ - "schema": "strata-next/proposed-kar-precision-candidates-v1", - "source_archive_sha256": hex::encode(prepared.archive_digest), - "proposed_levels": 3, - "records": [ - {"name": "dense", "elements": 256}, - {"name": "per_layer_token_embd.weight#strata-part-001-of-004", "elements": 128} - ], - })) - .unwrap(), - ) - .unwrap(); - let overlay = directory.join("overlay.kar"); - crate::kar_overlay::prepare(&manifest, &directory, &archive, &policy, &overlay).unwrap(); - let selection = crate::kar_overlay::resolve_verified(&archive, &overlay).unwrap(); - assert_eq!(selection.replacement_count, 2); - assert_eq!(selection.records.len(), 6); - let memory = crate::kar_memory::plan_selected(&archive, &overlay, 2, 3, 1 << 20).unwrap(); - assert_eq!(memory.record_count, 6); - assert_eq!(memory.replacement_count, 2); - assert!(memory.selected_overlay_compressed_bytes > 0); - assert_eq!( - memory - .largest_records - .iter() - .filter(|record| record.archive == "overlay") - .count(), - 2 - ); - assert_eq!( - memory.selected_compressed_bytes, - memory.selected_base_compressed_bytes + memory.selected_overlay_compressed_bytes - ); - let comparison = - crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).unwrap(); - assert_eq!(comparison.records.len(), 2); - assert_eq!(comparison.records[1].elements, 128); - let sidecar = archive.with_file_name("ple.kar.provenance.json"); - let mut corrupted: serde_json::Value = - serde_json::from_slice(&fs::read(&sidecar).unwrap()).unwrap(); - corrupted["partitioned_tensors"][0]["parts"][0]["source_byte_offset"] = 4.into(); - fs::write(&sidecar, serde_json::to_vec(&corrupted).unwrap()).unwrap(); - assert!(crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).is_err()); - fs::remove_dir_all(directory).unwrap(); - } -} +mod tests; diff --git a/control-plane/src/prepare_preview/tests.rs b/control-plane/src/prepare_preview/tests.rs new file mode 100644 index 00000000..be6f338e --- /dev/null +++ b/control-plane/src/prepare_preview/tests.rs @@ -0,0 +1,822 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn kar_payload_preflight_rejects_too_small_volumes_conservatively() { + assert_eq!( + minimum_part_payload_bytes(707_775_598_080, 2).unwrap(), + 44_235_974_880 + ); + assert!(minimum_part_payload_bytes(707_775_598_080, 2).unwrap() > 23 * (1 << 30)); + assert_eq!(minimum_part_payload_bytes(4, 8).unwrap(), 4); + assert!(minimum_part_payload_bytes(u64::MAX, 8).is_err()); +} +use crate::model::ModelFile; + +fn string(out: &mut Vec, value: &str) { + out.extend_from_slice(&(value.len() as u64).to_le_bytes()); + out.extend_from_slice(value.as_bytes()); +} + +fn one_shard(name: &str, kind: u32, elements: u64, payload: &[u8]) -> Vec { + one_shard_with_arch(name, kind, elements, payload, true) +} + +fn one_shard_with_arch( + name: &str, + kind: u32, + elements: u64, + payload: &[u8], + include_architecture: bool, +) -> Vec { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&u64::from(include_architecture).to_le_bytes()); + if include_architecture { + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + } + string(&mut gguf, name); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&elements.to_le_bytes()); + gguf.extend_from_slice(&kind.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + gguf.extend_from_slice(payload); + gguf +} + +fn ple_shard(payload: &[u8]) -> Vec { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + string(&mut gguf, stream_parts::PLE_TENSOR_NAME); + gguf.extend_from_slice(&2u32.to_le_bytes()); + gguf.extend_from_slice(&32u64.to_le_bytes()); + gguf.extend_from_slice(&16u64.to_le_bytes()); + gguf.extend_from_slice(&0u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + gguf.extend_from_slice(payload); + gguf +} + +#[test] +fn converts_two_small_f32_gguf_tensors_and_rejects_duplicate_output() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&2u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + for (name, offset) in [("first", 0u64), ("second", 128)] { + string(&mut gguf, name); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&32u64.to_le_bytes()); + gguf.extend_from_slice(&0u32.to_le_bytes()); + gguf.extend_from_slice(&offset.to_le_bytes()); + } + let data_start = gguf.len().div_ceil(32) * 32; + gguf.resize(data_start, 0); + for index in 0..64 { + let value = [-1.0f32, -0.25, 0.25, 1.0][index % 4]; + gguf.extend_from_slice(&value.to_le_bytes()); + } + let source_path = + std::env::temp_dir().join(format!("strata-preview-{}.gguf", std::process::id())); + let output = + std::env::temp_dir().join(format!("strata-preview-{}.kar", std::process::id())); + let _ = fs::remove_file(&output); + fs::write(&source_path, &gguf).unwrap(); + let summary = prepare_f32(&source_path, &output, 2).unwrap(); + assert_eq!(summary.archive.tensor_count, 2); + assert_eq!(summary.archive.total_elements, 64); + assert!(summary.maximum_relative_l2.is_finite()); + assert_eq!( + summary.archive.source_digest, + hash_file(&source_path).unwrap() + ); + assert_eq!(summary.archive_digest, hash_file(&output).unwrap()); + let staging = output.with_file_name(format!( + "{}.parts-{}", + output.file_name().unwrap().to_string_lossy(), + std::process::id() + )); + assert!(!staging.exists()); + assert!(prepare_f32(&source_path, &output, 2).is_err()); + assert!(!staging.exists()); + let failed_source = + std::env::temp_dir().join(format!("strata-preview-bad-{}.gguf", std::process::id())); + let failed_output = + std::env::temp_dir().join(format!("strata-preview-bad-{}.kar", std::process::id())); + let _ = fs::remove_file(&failed_output); + let mut broken = gguf.clone(); + let last = broken.len() - 4; + broken[last..].copy_from_slice(&f32::NAN.to_le_bytes()); + fs::write(&failed_source, broken).unwrap(); + assert!( + prepare_f32(&failed_source, &failed_output, 2) + .unwrap_err() + .contains("invalid KAR normalization input") + ); + assert!(!failed_output.exists()); + let failed_staging = failed_output.with_file_name(format!( + "{}.parts-{}", + failed_output.file_name().unwrap().to_string_lossy(), + std::process::id() + )); + assert!(!failed_staging.exists()); + fs::remove_file(failed_source).unwrap(); + fs::remove_file(&output).unwrap(); + fs::remove_file(&source_path).unwrap(); +} + +#[test] +fn refuses_quantized_gguf_until_source_decoder_is_available() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + string(&mut gguf, "expert"); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&256u64.to_le_bytes()); + gguf.extend_from_slice(&21u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + gguf.extend_from_slice(&[0u8; 110]); + let source_path = + std::env::temp_dir().join(format!("strata-preview-iq3-{}.gguf", std::process::id())); + let output = + std::env::temp_dir().join(format!("strata-preview-iq3-{}.kar", std::process::id())); + let _ = fs::remove_file(&output); + fs::write(&source_path, gguf).unwrap(); + assert!( + prepare_f32(&source_path, &output, 2) + .unwrap_err() + .contains("supports only F32") + ); + assert!(!output.exists()); + fs::remove_file(source_path).unwrap(); +} + +#[test] +fn prepares_iq3_preview_with_virtual_f32_source_and_provenance() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + string(&mut gguf, "expert"); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&256u64.to_le_bytes()); + gguf.extend_from_slice(&21u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in block[2..66].iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(3); + } + block[74] = 0x55; + gguf.extend_from_slice(&block); + let base = + std::env::temp_dir().join(format!("strata-preview-iq3-good-{}", std::process::id())); + let source_path = base.with_extension("gguf"); + let output = base.with_extension("kar"); + let provenance = output.with_file_name(format!( + "{}.provenance.json", + output.file_name().unwrap().to_string_lossy() + )); + let _ = fs::remove_file(&output); + let _ = fs::remove_file(&provenance); + fs::write(&source_path, gguf).unwrap(); + let identity = derived_iq3::fingerprint(&source_path).unwrap(); + let result = prepare_iq3(&source_path, &output, 2).unwrap(); + assert_eq!(result.archive.source_digest, identity.derived_sha256); + assert_eq!(result.archive.source_bytes, identity.derived_bytes); + assert_eq!( + result.provenance_path.as_deref(), + Some(provenance.as_path()) + ); + assert_eq!(kar::verify(&output).unwrap(), result.archive); + let record: serde_json::Value = + serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap(); + assert_eq!( + record["original_gguf_sha256"], + hex::encode(identity.gguf_sha256) + ); + assert_eq!( + record["derived_f32_sha256"], + hex::encode(identity.derived_sha256) + ); + assert_eq!(record["archive_sha256"], hex::encode(result.archive_digest)); + assert!(result.maximum_relative_l2.is_finite()); + assert_eq!(verify_iq3(&source_path, &output).unwrap(), result.archive); + let saved_provenance = fs::read(&provenance).unwrap(); + let mut changed = record.clone(); + changed["archive_sha256"] = serde_json::Value::String("00".repeat(32)); + fs::write(&provenance, serde_json::to_vec(&changed).unwrap()).unwrap(); + assert!( + verify_iq3(&source_path, &output) + .unwrap_err() + .contains("provenance differs") + ); + fs::write(&provenance, saved_provenance).unwrap(); + assert!(verify_iq3(&source_path, &output).is_ok()); + let blocked_output = base.with_file_name(format!( + "strata-preview-iq3-blocked-{}.kar", + std::process::id() + )); + let blocked_provenance = blocked_output.with_file_name(format!( + "{}.provenance.json", + blocked_output.file_name().unwrap().to_string_lossy() + )); + let _ = fs::remove_file(&blocked_output); + fs::write(&blocked_provenance, b"reserved").unwrap(); + assert!( + prepare_iq3(&source_path, &blocked_output, 2) + .unwrap_err() + .contains("provenance destination already exists") + ); + assert!(!blocked_output.exists()); + fs::remove_file(blocked_provenance).unwrap(); + fs::remove_file(provenance).unwrap(); + fs::remove_file(output).unwrap(); + fs::remove_file(source_path).unwrap(); +} + +#[test] +fn prepares_and_verifies_mixed_preview_with_each_source_kind() { + let tensors = [ + ("bf16", 30u32, 320u64, 32u64), + ("iq3", 21, 0, 256), + ("f16", 1, 256, 32), + ("f32", 0, 128, 32), + ]; + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&(tensors.len() as u64).to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + for (name, kind, offset, elements) in tensors { + string(&mut gguf, name); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&elements.to_le_bytes()); + gguf.extend_from_slice(&kind.to_le_bytes()); + gguf.extend_from_slice(&offset.to_le_bytes()); + } + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + let mut payload = vec![0u8; 384]; + payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in payload[2..66].iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(3); + } + payload[74] = 0x55; + let values = [-1.0f32, -0.25, 0.25, 1.0]; + for index in 0..32 { + let value = values[index % values.len()]; + payload[128 + 4 * index..132 + 4 * index].copy_from_slice(&value.to_le_bytes()); + let f16 = kar_codec::f32_to_f16_bits(value).to_le_bytes(); + payload[256 + 2 * index..258 + 2 * index].copy_from_slice(&f16); + let bf16 = (value.to_bits() >> 16) as u16; + payload[320 + 2 * index..322 + 2 * index].copy_from_slice(&bf16.to_le_bytes()); + } + gguf.extend_from_slice(&payload); + let base = + std::env::temp_dir().join(format!("strata-preview-mixed-{}", std::process::id())); + let source_path = base.with_extension("gguf"); + let output = base.with_extension("kar"); + let provenance = provenance_path(&output).unwrap(); + let _ = fs::remove_file(&output); + let _ = fs::remove_file(&provenance); + fs::write(&source_path, gguf).unwrap(); + let identity = derived_mixed::fingerprint(&source_path).unwrap(); + let result = prepare_mixed(&source_path, &output, 2).unwrap(); + assert_eq!(result.archive.source_digest, identity.derived_sha256); + assert_eq!(result.archive.source_bytes, identity.derived_bytes); + assert_eq!(result.archive.tensor_count, 4); + assert_eq!(verify_mixed(&source_path, &output).unwrap(), result.archive); + assert!(verify_iq3(&source_path, &output).is_err()); + let record: serde_json::Value = + serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap(); + assert_eq!(record["schema"], "strata-next/mixed-preview-provenance-v1"); + assert_eq!(record["tensors"][0]["source_kind"], 30); + assert!(result.maximum_relative_l2.is_finite()); + fs::remove_file(provenance).unwrap(); + fs::remove_file(output).unwrap(); + fs::remove_file(source_path).unwrap(); +} + +#[cfg(unix)] // archive preparation is an offline Unix tool +#[tokio::test] +async fn prepares_and_verifies_manifest_pinned_sharded_preview() { + let directory = + std::env::temp_dir().join(format!("strata-preview-shards-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let mut dense = Vec::new(); + for index in 0..32 { + dense.extend_from_slice(&[-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()); + } + let f32 = one_shard("dense", 0, 32, &dense); + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in block[2..66].iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(3); + } + block[74] = 0x55; + let iq3 = one_shard_with_arch("expert", 21, 256, &block, false); + fs::write(directory.join("a-f32.gguf"), &f32).unwrap(); + fs::write(directory.join("z-iq3.gguf"), &iq3).unwrap(); + let mut manifest = Manifest { + schema_version: 1, + files: vec![ + ModelFile { + name: "z-iq3.gguf".into(), + url: "https://example.invalid/z".into(), + size: iq3.len() as u64, + sha256: hex::encode(Sha256::digest(&iq3)), + }, + ModelFile { + name: "a-f32.gguf".into(), + url: "https://example.invalid/a".into(), + size: f32.len() as u64, + sha256: hex::encode(Sha256::digest(&f32)), + }, + ], + }; + let output = directory.join("sharded.kar"); + let identity = derived_mixed::fingerprint_shards(&manifest, &directory).unwrap(); + let result = prepare_sharded(&manifest, &directory, &output, 2).unwrap(); + assert_eq!(result.archive.tensor_count, 2); + assert_eq!(result.archive.source_digest, identity.derived_sha256); + assert_eq!(result.archive.source_bytes, identity.derived_bytes); + assert_eq!( + verify_sharded(&manifest, &directory, &output).unwrap(), + result.archive + ); + assert!(matches!( + crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2) + .await + .unwrap(), + crate::model_pipeline::PreviewOutcome::Reused(_) + )); + assert!( + crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 3) + .await + .is_err() + ); + let record: serde_json::Value = + serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap(); + assert_eq!( + record["schema"], + "strata-next/sharded-preview-provenance-v1" + ); + assert_eq!(record["shards"][0]["name"], "a-f32.gguf"); + assert_eq!(record["tensors"][1]["derived_offset"], 128); + let streamed_output = directory.join("streamed.kar"); + let streamed = + prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(); + assert_eq!(streamed.archive.source_digest, identity.derived_sha256); + assert_eq!(streamed.archive.tensor_count, 2); + let decoded = kar::decode_preview_tensor(&streamed_output, "dense", 2).unwrap(); + let reference = dense + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)) + .collect::>(); + assert_eq!(decoded.len(), reference.len()); + assert!( + decoded + .iter() + .zip(&reference) + .all(|(actual, expected)| (actual - expected).abs() < 0.1) + ); + assert_eq!( + verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(), + streamed.archive + ); + let sampled = + crate::kar_quality::analyze(&manifest, &directory, &streamed_output, 2).unwrap(); + assert_eq!( + sampled.records.len(), + streamed.archive.tensor_count as usize + ); + assert!( + sampled + .records + .iter() + .all(|record| { record.sampled_elements > 0 && record.relative_l2.is_finite() }) + ); + let reused = crate::kar_quality::analyze_previously_verified( + &manifest, + &directory, + &streamed_output, + 2, + ) + .unwrap(); + assert!( + reused + .records + .iter() + .zip(&sampled.records) + .all(|(a, b)| { a.name == b.name && a.relative_l2 == b.relative_l2 }) + ); + assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 3).is_err()); + assert!(verify_sharded(&manifest, &directory, &streamed_output).is_err()); + let streamed_record: serde_json::Value = + serde_json::from_slice(&fs::read(streamed.provenance_path.unwrap()).unwrap()).unwrap(); + assert_eq!( + streamed_record["schema"], + "strata-next/sharded-stream-provenance-v4" + ); + assert_eq!( + streamed_record["partitioned_tensors"], + serde_json::json!([]) + ); + assert_eq!(streamed_record["levels"], 2); + assert!(prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err()); + manifest.files[0].sha256 = "00".repeat(32); + assert!(verify_sharded(&manifest, &directory, &output).is_err()); + assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err()); + manifest.files[0].sha256 = hex::encode(Sha256::digest(&iq3)); + let mut corrupted = fs::read(&output).unwrap(); + let last = corrupted.len() - 1; + corrupted[last] ^= 1; + fs::write(&output, corrupted).unwrap(); + assert!( + crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2) + .await + .is_err() + ); + fs::remove_dir_all(directory).unwrap(); +} + +#[cfg(unix)] // archive preparation is an offline Unix tool +#[test] +fn streamed_preparation_keeps_unsplittable_tensors_exact() { + let directory = + std::env::temp_dir().join(format!("strata-stream-raw-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let mut files = Vec::new(); + for (name, kind, elements, payload) in [ + ("a", 21, 256, vec![0u8; iq3_s::BLOCK_BYTES]), + ("b", 20, 32, vec![0u8; 18]), + ] { + let bytes = one_shard_with_arch(name, kind, elements, &payload, name == "a"); + let filename = format!("{name}.gguf"); + fs::write(directory.join(&filename), &bytes).unwrap(); + files.push(ModelFile { + name: filename, + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + }); + } + let manifest = Manifest { + schema_version: 1, + files, + }; + let archive = directory.join("raw.kar"); + let result = prepare_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(); + assert_eq!(result.archive.max_planes, 0); + assert_eq!(result.maximum_relative_l2, 0.0); + let sampled = crate::kar_quality::analyze(&manifest, &directory, &archive, 2).unwrap(); + assert_eq!(sampled.records.len(), 2); + assert!( + sampled + .records + .iter() + .all(|record| record.relative_l2 == 0.0) + ); + let reused = + crate::kar_quality::analyze_previously_verified(&manifest, &directory, &archive, 2) + .unwrap(); + assert!( + reused + .records + .iter() + .all(|record| record.relative_l2 == 0.0) + ); + assert_eq!( + verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(), + result.archive + ); + fs::remove_dir_all(directory).unwrap(); +} + +#[cfg(unix)] // archive preparation is an offline Unix tool +#[test] +fn selected_overlay_reconstructs_source_and_cleans_staging() { + let directory = std::env::temp_dir().join(format!("strata-overlay-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let values = (0..256) + .map(|index| (index as f32 - 127.5) / 128.0) + .collect::>(); + let dense = values + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect::>(); + let files = [ + ("a.gguf", one_shard("dense", 0, 256, &dense)), + ( + "b.gguf", + one_shard_with_arch("extra", 21, 256, &[0u8; iq3_s::BLOCK_BYTES], false), + ), + ] + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect(); + let manifest = Manifest { + schema_version: 1, + files, + }; + let base = directory.join("base.kar"); + let prepared = prepare_sharded_streamed(&manifest, &directory, &base, 2).unwrap(); + let policy = directory.join("candidates.json"); + fs::write( + &policy, + serde_json::to_vec(&serde_json::json!({ + "schema": "strata-next/proposed-kar-precision-candidates-v1", + "source_archive_sha256": hex::encode(prepared.archive_digest), + "proposed_levels": 3, + "records": [{"name": "dense", "elements": 256}], + })) + .unwrap(), + ) + .unwrap(); + let overlay = directory.join("overlay.kar"); + let result = + crate::kar_overlay::prepare(&manifest, &directory, &base, &policy, &overlay).unwrap(); + assert_eq!(result.record_count, 1); + assert_eq!(kar::verify(&overlay).unwrap().max_planes, 3); + assert!(result.maximum_relative_l2.is_finite()); + let decoded = kar::decode_preview_tensor(&overlay, "dense", 3).unwrap(); + let error_sum = decoded + .iter() + .zip(&values) + .map(|(actual, expected)| f64::from(actual - expected).powi(2)) + .sum::(); + let reference_sum = values + .iter() + .map(|value| f64::from(*value).powi(2)) + .sum::(); + assert!(((error_sum / reference_sum).sqrt() - result.maximum_relative_l2).abs() < 1e-7); + assert!(result.provenance_path.exists()); + let comparison = + crate::kar_overlay::compare(&manifest, &directory, &base, &overlay).unwrap(); + assert_eq!(comparison.records.len(), 1); + assert_eq!(comparison.records[0].name, "dense"); + let selection = crate::kar_overlay::resolve_verified(&base, &overlay).unwrap(); + assert_eq!(selection.replacement_count, 1); + assert_eq!(selection.records.len(), 2); + assert_eq!(selection.records[0].name, "dense"); + assert_eq!(selection.records[0].archive, "overlay"); + assert_eq!(selection.records[1].archive, "base"); + let mut provenance: serde_json::Value = + serde_json::from_slice(&fs::read(&result.provenance_path).unwrap()).unwrap(); + provenance["records"][0]["f32_sha256"] = serde_json::json!("00".repeat(32)); + fs::write( + &result.provenance_path, + serde_json::to_vec(&provenance).unwrap(), + ) + .unwrap(); + assert!(crate::kar_overlay::resolve_verified(&base, &overlay).is_err()); + assert!( + (comparison.records[0].overlay_relative_l2 - result.maximum_relative_l2).abs() < 1e-7 + ); + assert!( + !directory + .join(format!( + "overlay.kar.overlay-sections-{}", + std::process::id() + )) + .exists() + ); + fs::remove_dir_all(directory).unwrap(); +} + +#[cfg(unix)] // archive preparation is an offline Unix tool +#[test] +fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { + let directory = + std::env::temp_dir().join(format!("strata-stream-split-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let dense = (0..512) + .flat_map(|index| [-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()) + .collect::>(); + let dense_shard = one_shard("dense", 0, 512, &dense); + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let iq3_shard = one_shard_with_arch("expert", 21, 256, &block, false); + let files = [("a-dense.gguf", dense_shard), ("z-iq3.gguf", iq3_shard)] + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect(); + let manifest = Manifest { + schema_version: 1, + files, + }; + let archive = directory.join("split.kar"); + let result = + prepare_sharded_streamed_with_limit(&manifest, &directory, &archive, 2, 256).unwrap(); + assert_eq!(result.archive.tensor_count, 3); + assert_eq!(result.tensor_distortions.len(), 3); + assert_eq!( + result.maximum_relative_l2, + result + .tensor_distortions + .iter() + .map(|entry| entry.relative_l2) + .fold(0.0f64, f64::max) + ); + assert!( + result + .tensor_distortions + .iter() + .all(|entry| entry.section_bytes > 0 && entry.relative_l2.is_finite()) + ); + assert_eq!( + verify_sharded_inner(&manifest, &directory, &archive, Some(2), 256, None).unwrap(), + result.archive + ); + assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); + let provenance: serde_json::Value = + serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap(); + let parts = provenance["partitioned_tensors"][0]["parts"] + .as_array() + .unwrap(); + assert_eq!(parts.len(), 2); + assert_eq!(parts[0]["dimensions"], serde_json::json!([256])); + assert_eq!(parts[1]["derived_offset"], 1024); + for (number, part) in parts.iter().enumerate() { + let name = part["name"].as_str().unwrap(); + let decoded = kar::decode_preview_tensor(&archive, name, 2).unwrap(); + assert_eq!(decoded.len(), 256); + for (actual, original) in decoded.iter().zip( + dense[number * 1024..(number + 1) * 1024] + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)), + ) { + assert!((actual - original).abs() < 0.1); + } + } + fs::remove_dir_all(directory).unwrap(); +} + +#[cfg(unix)] // archive preparation is an offline Unix tool +#[test] +fn ple_partition_policy_is_versioned_and_verified() { + let directory = std::env::temp_dir().join(format!( + "strata-ple-parts-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir(&directory).unwrap(); + let ple_values = (0..512) + .flat_map(|index| ((index as f32 - 255.5) / 256.0).to_le_bytes()) + .collect::>(); + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let dense_values = (0..256) + .map(|index| (index as f32 - 127.5) / 128.0) + .flat_map(f32::to_le_bytes) + .collect::>(); + let files = [ + ("a-ple.gguf", ple_shard(&ple_values)), + ( + "m-dense.gguf", + one_shard_with_arch("dense", 0, 256, &dense_values, false), + ), + ( + "z-expert.gguf", + one_shard_with_arch("expert", 21, 256, &block, false), + ), + ] + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect(); + let manifest = Manifest { + schema_version: 1, + files, + }; + let archive = directory.join("ple.kar"); + let prepared = + prepare_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(); + assert_eq!(prepared.archive.tensor_count, 6); + assert_eq!( + verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(), + prepared.archive + ); + assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); + assert!(verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 256).is_err()); + let provenance: serde_json::Value = + serde_json::from_slice(&fs::read(prepared.provenance_path.unwrap()).unwrap()).unwrap(); + assert_eq!( + provenance["schema"], + "strata-next/sharded-stream-provenance-v5" + ); + assert_eq!(provenance["ple_part_elements"], 128); + assert_eq!( + provenance["partitioned_tensors"][0]["parts"] + .as_array() + .unwrap() + .len(), + 4 + ); + let policy = directory.join("candidates.json"); + fs::write( + &policy, + serde_json::to_vec(&serde_json::json!({ + "schema": "strata-next/proposed-kar-precision-candidates-v1", + "source_archive_sha256": hex::encode(prepared.archive_digest), + "proposed_levels": 3, + "records": [ + {"name": "dense", "elements": 256}, + {"name": "per_layer_token_embd.weight#strata-part-001-of-004", "elements": 128} + ], + })) + .unwrap(), + ) + .unwrap(); + let overlay = directory.join("overlay.kar"); + crate::kar_overlay::prepare(&manifest, &directory, &archive, &policy, &overlay).unwrap(); + let selection = crate::kar_overlay::resolve_verified(&archive, &overlay).unwrap(); + assert_eq!(selection.replacement_count, 2); + assert_eq!(selection.records.len(), 6); + let memory = crate::kar_memory::plan_selected(&archive, &overlay, 2, 3, 1 << 20).unwrap(); + assert_eq!(memory.record_count, 6); + assert_eq!(memory.replacement_count, 2); + assert!(memory.selected_overlay_compressed_bytes > 0); + assert_eq!( + memory + .largest_records + .iter() + .filter(|record| record.archive == "overlay") + .count(), + 2 + ); + assert_eq!( + memory.selected_compressed_bytes, + memory.selected_base_compressed_bytes + memory.selected_overlay_compressed_bytes + ); + let comparison = + crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).unwrap(); + assert_eq!(comparison.records.len(), 2); + assert_eq!(comparison.records[1].elements, 128); + let sidecar = archive.with_file_name("ple.kar.provenance.json"); + let mut corrupted: serde_json::Value = + serde_json::from_slice(&fs::read(&sidecar).unwrap()).unwrap(); + corrupted["partitioned_tensors"][0]["parts"][0]["source_byte_offset"] = 4.into(); + fs::write(&sidecar, serde_json::to_vec(&corrupted).unwrap()).unwrap(); + assert!(crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).is_err()); + fs::remove_dir_all(directory).unwrap(); +} diff --git a/control-plane/src/prometheus.rs b/control-plane/src/prometheus.rs index 95a695c4..a5cac408 100644 --- a/control-plane/src/prometheus.rs +++ b/control-plane/src/prometheus.rs @@ -601,146 +601,4 @@ pub fn wanted(query: Option<&str>, accept: Option<&str>) -> bool { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn document() -> Value { - json!({ - "model": "qwen \"3.8\"", "up": true, "queue_used": 1, "queue_capacity": 64, - "generation": {"started": 5, "completed": 3, "cancelled": 1, "failed_or_interrupted": 1}, - "totals": {"prompt_tokens": 1000, "reused": 400, "output_tokens": 250, "prompt_ms": 2500.0, "decode_ms": 1250.0, "drafts_offered": 90, "drafts_accepted": 60}, - "memory": {"gate_rejections": 2}, - "live": {"active": true, "elapsed_s": 3.5, "queued": 0}, - "engine": {"max_context": 262144}, - "hardware": {"gpu_util": 91, "gpu_mem_used": 31457280000u64, "gpu_temp": 61, "gpu_power": 480.5, "cpu": 31.0, "tok_s": 128.4, "tok_s_mean": 120.0, "prefill_tok_s_mean": 5050.0, "ram_used": 5.0e10}, - "telemetry": {"phase": "decode", "context": {"live_tokens": 101200, "used_pct": 38.6}, - "throughput": {"decode_tok_s_last": 100.0, "decode_tok_s_lifetime": null}, - "cache": {"requests": 2, "hit_ratio": 0.5}}, - }) - } - - #[test] - fn counters_gauges_and_labels_render_in_the_text_format() { - let text = render(&document()); - 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")); - assert!(text.contains("leleka_up 1\n") && text.contains("leleka_generation_active 1\n")); - assert!(text.contains( - "# TYPE leleka_gpu_memory_used_bytes gauge\nleleka_gpu_memory_used_bytes 31457280000\n" - )); - assert!(text.contains("leleka_gpu_power_watts 480.5\n")); - assert!(text.contains("leleka_context_live_tokens 101200\n")); - // one HELP/TYPE per metric, a series per label value - assert_eq!( - text.matches("# TYPE leleka_decode_tokens_per_second") - .count(), - 1 - ); - assert!(text.contains("leleka_decode_tokens_per_second{window=\"live\"} 128.4\n")); - assert!(text.contains("leleka_decode_tokens_per_second{window=\"last\"} 100\n")); - assert!(text.contains("leleka_decode_tokens_per_second{window=\"average\"} 120\n")); - assert!( - text.contains("leleka_engine_phase{phase=\"decode\"} 1\n") - && text.contains("leleka_engine_phase{phase=\"idle\"} 0\n") - ); - assert!(text.contains("leleka_info{model=\"qwen \\\"3.8\\\"\"} 1\n")); - } - - #[test] - fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() { - let mut doc = document(); - doc["api_uptime_s"] = json!(120); - doc["supervisor"] = json!({"uptime_s": 86400, "restarts_total": 3}); - doc["telemetry"]["uptime_s"] = json!(3600); - doc["telemetry"]["gpu"] = json!({"mem_clock_mhz": 14001, "pcie_rx_kb_s": 2048, "pcie_tx_kb_s": 1024, "throttle_reasons": 0x44}); - doc["telemetry"]["spec"] = json!({"rounds": 100, "tokens": 320, "tokens_per_round": 3.2}); - doc["telemetry"]["expert_tier"] = json!({"vram_entries": 900, "pcie_entries": 60, "cpu_entries": 40, "swaps": 7, "vram_ratio": 0.9}); - let text = render(&doc); - for expected in [ - "leleka_gpu_pcie_receive_bytes_per_second 2097152\n", - "leleka_gpu_pcie_transmit_bytes_per_second 1048576\n", - "leleka_gpu_memory_clock_megahertz 14001\n", - "# TYPE leleka_engine_restarts_total counter\nleleka_engine_restarts_total 3\n", - "leleka_service_uptime_seconds 86400\n", - "leleka_api_uptime_seconds 120\n", - "leleka_engine_uptime_seconds 3600\n", - "leleka_spec_tokens_per_round 3.2\n", - "leleka_expert_tier_entries_total{tier=\"vram\"} 900\n", - "leleka_expert_tier_entries_total{tier=\"pcie\"} 60\n", - "leleka_expert_tier_vram_ratio 0.9\n", - "leleka_gpu_throttled{reason=\"hw_thermal\"} 1\n", - "leleka_gpu_throttled{reason=\"sw_power_cap\"} 1\n", - "leleka_gpu_throttled{reason=\"hw_slowdown\"} 0\n", - "leleka_request_ttft_seconds_bucket{le=\"+Inf\"}", - "leleka_engine_lost_total ", - ] { - assert!(text.contains(expected), "{expected} missing:\n{text}"); - } - // not eprintln!: tests/log_failure_sse.rs forbids it in this crate (it panics when stderr is unwritable) - let _ = std::io::Write::write_fmt( - &mut std::io::stderr(), - format_args!( - "PROM-SAMPLE -{text} -" - ), - ); - // one TYPE line per metric even with three tier series - assert_eq!( - text.matches("# TYPE leleka_expert_tier_entries_total") - .count(), - 1 - ); - // every label value comes from a fixed list, never from a request - for line in text - .lines() - .filter(|l| l.contains('{') && !l.starts_with('#')) - { - assert!(!line.contains("req-") && !line.contains("s-"), "{line}"); - } - } - - #[test] - fn unmeasured_figures_are_not_exposed() { - let text = render(&document()); - // 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})); - 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 - for line in text.lines() { - assert!( - line.starts_with("# HELP ") - || line.starts_with("# TYPE ") - || line.starts_with("leleka_"), - "{line}" - ); - } - } - - #[test] - fn the_format_is_chosen_by_query_or_accept() { - assert!(wanted(Some("format=prometheus"), None)); - assert!(wanted(Some("requests=all&format=openmetrics"), None)); - assert!(!wanted(Some("format=json"), Some("text/plain"))); - assert!(!wanted(None, None)); - assert!(!wanted(None, Some("*/*"))); - assert!(!wanted(None, Some("application/json"))); - // what a Prometheus server sends - assert!(wanted( - None, - Some( - "application/openmetrics-text;version=1.0.0,text/plain;version=0.0.4;q=0.5,*/*;q=0.1" - ) - )); - assert!(wanted(None, Some("text/plain"))); - // a browser or SDK that prefers JSON keeps the JSON document - assert!(!wanted(None, Some("application/json, text/plain, */*"))); - } -} +mod tests; diff --git a/control-plane/src/prometheus/tests.rs b/control-plane/src/prometheus/tests.rs new file mode 100644 index 00000000..f7f16dd1 --- /dev/null +++ b/control-plane/src/prometheus/tests.rs @@ -0,0 +1,143 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use serde_json::json; + +fn document() -> Value { + json!({ + "model": "qwen \"3.8\"", "up": true, "queue_used": 1, "queue_capacity": 64, + "generation": {"started": 5, "completed": 3, "cancelled": 1, "failed_or_interrupted": 1}, + "totals": {"prompt_tokens": 1000, "reused": 400, "output_tokens": 250, "prompt_ms": 2500.0, "decode_ms": 1250.0, "drafts_offered": 90, "drafts_accepted": 60}, + "memory": {"gate_rejections": 2}, + "live": {"active": true, "elapsed_s": 3.5, "queued": 0}, + "engine": {"max_context": 262144}, + "hardware": {"gpu_util": 91, "gpu_mem_used": 31457280000u64, "gpu_temp": 61, "gpu_power": 480.5, "cpu": 31.0, "tok_s": 128.4, "tok_s_mean": 120.0, "prefill_tok_s_mean": 5050.0, "ram_used": 5.0e10}, + "telemetry": {"phase": "decode", "context": {"live_tokens": 101200, "used_pct": 38.6}, + "throughput": {"decode_tok_s_last": 100.0, "decode_tok_s_lifetime": null}, + "cache": {"requests": 2, "hit_ratio": 0.5}}, + }) +} + +#[test] +fn counters_gauges_and_labels_render_in_the_text_format() { + let text = render(&document()); + 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")); + assert!(text.contains("leleka_up 1\n") && text.contains("leleka_generation_active 1\n")); + assert!(text.contains( + "# TYPE leleka_gpu_memory_used_bytes gauge\nleleka_gpu_memory_used_bytes 31457280000\n" + )); + assert!(text.contains("leleka_gpu_power_watts 480.5\n")); + assert!(text.contains("leleka_context_live_tokens 101200\n")); + // one HELP/TYPE per metric, a series per label value + assert_eq!( + text.matches("# TYPE leleka_decode_tokens_per_second") + .count(), + 1 + ); + assert!(text.contains("leleka_decode_tokens_per_second{window=\"live\"} 128.4\n")); + assert!(text.contains("leleka_decode_tokens_per_second{window=\"last\"} 100\n")); + assert!(text.contains("leleka_decode_tokens_per_second{window=\"average\"} 120\n")); + assert!( + text.contains("leleka_engine_phase{phase=\"decode\"} 1\n") + && text.contains("leleka_engine_phase{phase=\"idle\"} 0\n") + ); + assert!(text.contains("leleka_info{model=\"qwen \\\"3.8\\\"\"} 1\n")); +} + +#[test] +fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() { + let mut doc = document(); + doc["api_uptime_s"] = json!(120); + doc["supervisor"] = json!({"uptime_s": 86400, "restarts_total": 3}); + doc["telemetry"]["uptime_s"] = json!(3600); + doc["telemetry"]["gpu"] = json!({"mem_clock_mhz": 14001, "pcie_rx_kb_s": 2048, "pcie_tx_kb_s": 1024, "throttle_reasons": 0x44}); + doc["telemetry"]["spec"] = json!({"rounds": 100, "tokens": 320, "tokens_per_round": 3.2}); + doc["telemetry"]["expert_tier"] = json!({"vram_entries": 900, "pcie_entries": 60, "cpu_entries": 40, "swaps": 7, "vram_ratio": 0.9}); + let text = render(&doc); + for expected in [ + "leleka_gpu_pcie_receive_bytes_per_second 2097152\n", + "leleka_gpu_pcie_transmit_bytes_per_second 1048576\n", + "leleka_gpu_memory_clock_megahertz 14001\n", + "# TYPE leleka_engine_restarts_total counter\nleleka_engine_restarts_total 3\n", + "leleka_service_uptime_seconds 86400\n", + "leleka_api_uptime_seconds 120\n", + "leleka_engine_uptime_seconds 3600\n", + "leleka_spec_tokens_per_round 3.2\n", + "leleka_expert_tier_entries_total{tier=\"vram\"} 900\n", + "leleka_expert_tier_entries_total{tier=\"pcie\"} 60\n", + "leleka_expert_tier_vram_ratio 0.9\n", + "leleka_gpu_throttled{reason=\"hw_thermal\"} 1\n", + "leleka_gpu_throttled{reason=\"sw_power_cap\"} 1\n", + "leleka_gpu_throttled{reason=\"hw_slowdown\"} 0\n", + "leleka_request_ttft_seconds_bucket{le=\"+Inf\"}", + "leleka_engine_lost_total ", + ] { + assert!(text.contains(expected), "{expected} missing:\n{text}"); + } + // not eprintln!: tests/log_failure_sse.rs forbids it in this crate (it panics when stderr is unwritable) + let _ = std::io::Write::write_fmt( + &mut std::io::stderr(), + format_args!( + "PROM-SAMPLE +{text} +" + ), + ); + // one TYPE line per metric even with three tier series + assert_eq!( + text.matches("# TYPE leleka_expert_tier_entries_total") + .count(), + 1 + ); + // every label value comes from a fixed list, never from a request + for line in text + .lines() + .filter(|l| l.contains('{') && !l.starts_with('#')) + { + assert!(!line.contains("req-") && !line.contains("s-"), "{line}"); + } +} + +#[test] +fn unmeasured_figures_are_not_exposed() { + let text = render(&document()); + // 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})); + 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 + for line in text.lines() { + assert!( + line.starts_with("# HELP ") + || line.starts_with("# TYPE ") + || line.starts_with("leleka_"), + "{line}" + ); + } +} + +#[test] +fn the_format_is_chosen_by_query_or_accept() { + assert!(wanted(Some("format=prometheus"), None)); + assert!(wanted(Some("requests=all&format=openmetrics"), None)); + assert!(!wanted(Some("format=json"), Some("text/plain"))); + assert!(!wanted(None, None)); + assert!(!wanted(None, Some("*/*"))); + assert!(!wanted(None, Some("application/json"))); + // what a Prometheus server sends + assert!(wanted( + None, + Some( + "application/openmetrics-text;version=1.0.0,text/plain;version=0.0.4;q=0.5,*/*;q=0.1" + ) + )); + assert!(wanted(None, Some("text/plain"))); + // a browser or SDK that prefers JSON keeps the JSON document + assert!(!wanted(None, Some("application/json, text/plain, */*"))); +} diff --git a/control-plane/src/reasoning_budget.rs b/control-plane/src/reasoning_budget.rs index c81abf54..65c767d7 100644 --- a/control-plane/src/reasoning_budget.rs +++ b/control-plane/src/reasoning_budget.rs @@ -399,219 +399,4 @@ pub fn run( } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn budget(request: Value, default: Value) -> Result, String> { - reasoning_budget(Some(&request), &default) - } - - #[test] - fn budget_rules() { - assert_eq!(budget(json!({}), json!(0)), Ok(None)); - assert_eq!(budget(json!({}), json!(7)), Ok(Some(7))); - assert_eq!( - budget(json!({"reasoning_budget_tokens": 5}), json!(7)), - Ok(Some(5)) - ); - assert_eq!( - budget(json!({"reasoning_budget_tokens": 0}), json!(7)), - Ok(None) - ); - assert_eq!( - budget(json!({"reasoning_budget_tokens": -3}), json!(7)), - Ok(None) - ); - assert_eq!( - budget(json!({"reasoning_budget_tokens": 4.0}), json!(0)), - Ok(Some(4)) - ); - assert_eq!( - budget(json!({"reasoning_budget_tokens": null}), json!(9)), - Ok(Some(9)) - ); - assert_eq!(reasoning_budget(None, &json!(2)), Ok(Some(2))); - assert_eq!( - budget(json!({"reasoning_budget_tokens": 1.5}), json!(0)).unwrap_err(), - "reasoning_budget_tokens=1.5: expected a whole number of tokens (0: no budget)" - ); - assert_eq!( - budget(json!({"reasoning_budget_tokens": true}), json!(0)).unwrap_err(), - "reasoning_budget_tokens=True: expected a whole number of tokens (0: no budget)" - ); - assert_eq!( - budget(json!({"reasoning_budget_tokens": "it's"}), json!(0)).unwrap_err(), - "reasoning_budget_tokens=\"it's\": expected a whole number of tokens (0: no budget)" - ); - } - - #[test] - fn python_float_repr() { - assert_eq!(float_repr(1e-5), "1e-05"); - assert_eq!(float_repr(2.5e-7), "2.5e-07"); - assert_eq!(float_repr(1e16), "1e+16"); - assert_eq!(float_repr(0.0001), "0.0001"); - assert_eq!(float_repr(123456789.125), "123456789.125"); - assert_eq!(float_repr(2.0), "2.0"); - } - - #[test] - fn utf8_stream_holds_split_characters() { - let mut stream = Utf8Stream::default(); - assert_eq!(stream.push(&[0xE4]), ""); - assert!(stream.pending()); - assert_eq!(stream.push(&[0xBD]), ""); - assert_eq!(stream.push(&[0xA0, b'!']), "\u{4f60}!"); - assert!(!stream.pending()); - assert_eq!(stream.push(&[0xFF, b'a']), "\u{FFFD}a"); - assert_eq!(stream.push(&[0xE4, b'a']), "\u{FFFD}a"); - } - - struct Bytes; - - impl TokenCodec for Bytes { - fn token_bytes(&self, id: u32) -> Vec { - vec![id as u8] - } - - fn wrap_up_ids(&self) -> Vec { - REASONING_WRAP_UP.bytes().map(u32::from).collect() - } - } - - struct Scripted { - streams: Vec>, - calls: Vec<(Vec, usize)>, - } - - impl TokenEngine for Scripted { - fn generate<'a>( - &'a mut self, - prompt: &[u32], - max_new: usize, - ) -> Box> + 'a> { - self.calls.push((prompt.to_vec(), max_new)); - let call = self.calls.len() - 1; - let stream = self.streams.get(call).cloned().unwrap_or_default(); - Box::new(stream.into_iter().take(max_new).map(Ok)) - } - } - - fn ids(text: &str) -> Vec { - text.bytes().map(u32::from).collect() - } - - #[test] - fn wraps_at_the_budget_and_continues_from_the_longer_prompt() { - let mut engine = Scripted { - streams: vec![ids("aaaaaaaaaaaaaaaaaaaa"), ids("answer")], - calls: Vec::new(), - }; - let stops = HashSet::from([0u32]); - let request = RunRequest { - prompt: &[1, 2, 3], - thinking: true, - budget: Some(4), - max_new: 500, - stop_ids: &stops, - }; - let run = run(&mut engine, &Bytes, &request, &|| false).unwrap(); - assert_eq!(run.wrapped_after, Some(4)); - assert_eq!(run.finish, Finish::Length); - assert_eq!(run.text, format!("aaaa{REASONING_WRAP_UP}answer")); - let extra = Bytes.wrap_up_ids(); - assert_eq!(engine.calls.len(), 2); - assert_eq!(engine.calls[0], (vec![1, 2, 3], 500)); - let mut second = vec![1, 2, 3]; - second.extend(ids("aaaa")); - second.extend(&extra); - assert_eq!(engine.calls[1], (second, 500 - 4 - extra.len())); - assert_eq!(run.completion_tokens, 4 + extra.len() + 6); - } - - #[test] - fn no_wrap_when_thinking_ends_first_or_the_room_is_short() { - let stops = HashSet::from([0u32]); - let mut engine = Scripted { - streams: vec![ids("abcd")], - calls: Vec::new(), - }; - let request = RunRequest { - prompt: &[], - thinking: true, - budget: Some(3), - max_new: 100, - stop_ids: &stops, - }; - let finished = run(&mut engine, &Bytes, &request, &|| false).unwrap(); - assert_eq!(finished.wrapped_after, None); - assert_eq!(engine.calls.len(), 1); - - let mut engine = Scripted { - streams: vec![ids("aaaaaaaa")], - calls: Vec::new(), - }; - let tight = RunRequest { - max_new: 3 + Bytes.wrap_up_ids().len(), - budget: Some(3), - ..request - }; - let finished = run(&mut engine, &Bytes, &tight, &|| false).unwrap(); - assert_eq!(finished.wrapped_after, None); - assert_eq!(finished.completion_tokens, 3); - assert_eq!(engine.calls.len(), 1); - } - - #[test] - fn waits_for_a_clean_point() { - // the budget (2) is reached while "<" is held back as a possible "" and again inside a 3-byte character - let mut stream = ids("a<"); - stream.extend([0xE4u32, 0xBD, 0xA0, u32::from(b'x')]); - let mut engine = Scripted { - streams: vec![stream, ids("ok")], - calls: Vec::new(), - }; - let stops = HashSet::new(); - let request = RunRequest { - prompt: &[], - thinking: true, - budget: Some(2), - max_new: 200, - stop_ids: &stops, - }; - let finished = run(&mut engine, &Bytes, &request, &|| false).unwrap(); - // "a", "<" (held back), 0xE4 and 0xBD (a character split across tokens), 0xA0 (whole, and the "<" before it - // can no longer start the tag): the first clean point is the fifth token - assert_eq!(finished.wrapped_after, Some(5)); - } - - #[test] - fn stop_token_and_cancel() { - let stops = HashSet::from([7u32]); - let mut engine = Scripted { - streams: vec![vec![b'a'.into(), 7, b'b'.into()]], - calls: Vec::new(), - }; - let request = RunRequest { - prompt: &[], - thinking: false, - budget: Some(1), - max_new: 10, - stop_ids: &stops, - }; - let stopped = run(&mut engine, &Bytes, &request, &|| false).unwrap(); - assert_eq!( - (stopped.finish, stopped.completion_tokens), - (Finish::Stop, 2) - ); - assert_eq!(stopped.generated, vec![u32::from(b'a'), 7]); - assert_eq!(stopped.wrapped_after, None); - let mut engine = Scripted { - streams: vec![ids("zz")], - calls: Vec::new(), - }; - let cancelled = run(&mut engine, &Bytes, &request, &|| true).unwrap(); - assert_eq!(cancelled.finish, Finish::Cancel); - } -} +mod tests; diff --git a/control-plane/src/reasoning_budget/tests.rs b/control-plane/src/reasoning_budget/tests.rs new file mode 100644 index 00000000..cd8c208f --- /dev/null +++ b/control-plane/src/reasoning_budget/tests.rs @@ -0,0 +1,216 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use serde_json::json; + +fn budget(request: Value, default: Value) -> Result, String> { + reasoning_budget(Some(&request), &default) +} + +#[test] +fn budget_rules() { + assert_eq!(budget(json!({}), json!(0)), Ok(None)); + assert_eq!(budget(json!({}), json!(7)), Ok(Some(7))); + assert_eq!( + budget(json!({"reasoning_budget_tokens": 5}), json!(7)), + Ok(Some(5)) + ); + assert_eq!( + budget(json!({"reasoning_budget_tokens": 0}), json!(7)), + Ok(None) + ); + assert_eq!( + budget(json!({"reasoning_budget_tokens": -3}), json!(7)), + Ok(None) + ); + assert_eq!( + budget(json!({"reasoning_budget_tokens": 4.0}), json!(0)), + Ok(Some(4)) + ); + assert_eq!( + budget(json!({"reasoning_budget_tokens": null}), json!(9)), + Ok(Some(9)) + ); + assert_eq!(reasoning_budget(None, &json!(2)), Ok(Some(2))); + assert_eq!( + budget(json!({"reasoning_budget_tokens": 1.5}), json!(0)).unwrap_err(), + "reasoning_budget_tokens=1.5: expected a whole number of tokens (0: no budget)" + ); + assert_eq!( + budget(json!({"reasoning_budget_tokens": true}), json!(0)).unwrap_err(), + "reasoning_budget_tokens=True: expected a whole number of tokens (0: no budget)" + ); + assert_eq!( + budget(json!({"reasoning_budget_tokens": "it's"}), json!(0)).unwrap_err(), + "reasoning_budget_tokens=\"it's\": expected a whole number of tokens (0: no budget)" + ); +} + +#[test] +fn python_float_repr() { + assert_eq!(float_repr(1e-5), "1e-05"); + assert_eq!(float_repr(2.5e-7), "2.5e-07"); + assert_eq!(float_repr(1e16), "1e+16"); + assert_eq!(float_repr(0.0001), "0.0001"); + assert_eq!(float_repr(123456789.125), "123456789.125"); + assert_eq!(float_repr(2.0), "2.0"); +} + +#[test] +fn utf8_stream_holds_split_characters() { + let mut stream = Utf8Stream::default(); + assert_eq!(stream.push(&[0xE4]), ""); + assert!(stream.pending()); + assert_eq!(stream.push(&[0xBD]), ""); + assert_eq!(stream.push(&[0xA0, b'!']), "\u{4f60}!"); + assert!(!stream.pending()); + assert_eq!(stream.push(&[0xFF, b'a']), "\u{FFFD}a"); + assert_eq!(stream.push(&[0xE4, b'a']), "\u{FFFD}a"); +} + +struct Bytes; + +impl TokenCodec for Bytes { + fn token_bytes(&self, id: u32) -> Vec { + vec![id as u8] + } + + fn wrap_up_ids(&self) -> Vec { + REASONING_WRAP_UP.bytes().map(u32::from).collect() + } +} + +struct Scripted { + streams: Vec>, + calls: Vec<(Vec, usize)>, +} + +impl TokenEngine for Scripted { + fn generate<'a>( + &'a mut self, + prompt: &[u32], + max_new: usize, + ) -> Box> + 'a> { + self.calls.push((prompt.to_vec(), max_new)); + let call = self.calls.len() - 1; + let stream = self.streams.get(call).cloned().unwrap_or_default(); + Box::new(stream.into_iter().take(max_new).map(Ok)) + } +} + +fn ids(text: &str) -> Vec { + text.bytes().map(u32::from).collect() +} + +#[test] +fn wraps_at_the_budget_and_continues_from_the_longer_prompt() { + let mut engine = Scripted { + streams: vec![ids("aaaaaaaaaaaaaaaaaaaa"), ids("answer")], + calls: Vec::new(), + }; + let stops = HashSet::from([0u32]); + let request = RunRequest { + prompt: &[1, 2, 3], + thinking: true, + budget: Some(4), + max_new: 500, + stop_ids: &stops, + }; + let run = run(&mut engine, &Bytes, &request, &|| false).unwrap(); + assert_eq!(run.wrapped_after, Some(4)); + assert_eq!(run.finish, Finish::Length); + assert_eq!(run.text, format!("aaaa{REASONING_WRAP_UP}answer")); + let extra = Bytes.wrap_up_ids(); + assert_eq!(engine.calls.len(), 2); + assert_eq!(engine.calls[0], (vec![1, 2, 3], 500)); + let mut second = vec![1, 2, 3]; + second.extend(ids("aaaa")); + second.extend(&extra); + assert_eq!(engine.calls[1], (second, 500 - 4 - extra.len())); + assert_eq!(run.completion_tokens, 4 + extra.len() + 6); +} + +#[test] +fn no_wrap_when_thinking_ends_first_or_the_room_is_short() { + let stops = HashSet::from([0u32]); + let mut engine = Scripted { + streams: vec![ids("abcd")], + calls: Vec::new(), + }; + let request = RunRequest { + prompt: &[], + thinking: true, + budget: Some(3), + max_new: 100, + stop_ids: &stops, + }; + let finished = run(&mut engine, &Bytes, &request, &|| false).unwrap(); + assert_eq!(finished.wrapped_after, None); + assert_eq!(engine.calls.len(), 1); + + let mut engine = Scripted { + streams: vec![ids("aaaaaaaa")], + calls: Vec::new(), + }; + let tight = RunRequest { + max_new: 3 + Bytes.wrap_up_ids().len(), + budget: Some(3), + ..request + }; + let finished = run(&mut engine, &Bytes, &tight, &|| false).unwrap(); + assert_eq!(finished.wrapped_after, None); + assert_eq!(finished.completion_tokens, 3); + assert_eq!(engine.calls.len(), 1); +} + +#[test] +fn waits_for_a_clean_point() { + // the budget (2) is reached while "<" is held back as a possible "" and again inside a 3-byte character + let mut stream = ids("a<"); + stream.extend([0xE4u32, 0xBD, 0xA0, u32::from(b'x')]); + let mut engine = Scripted { + streams: vec![stream, ids("ok")], + calls: Vec::new(), + }; + let stops = HashSet::new(); + let request = RunRequest { + prompt: &[], + thinking: true, + budget: Some(2), + max_new: 200, + stop_ids: &stops, + }; + let finished = run(&mut engine, &Bytes, &request, &|| false).unwrap(); + // "a", "<" (held back), 0xE4 and 0xBD (a character split across tokens), 0xA0 (whole, and the "<" before it + // can no longer start the tag): the first clean point is the fifth token + assert_eq!(finished.wrapped_after, Some(5)); +} + +#[test] +fn stop_token_and_cancel() { + let stops = HashSet::from([7u32]); + let mut engine = Scripted { + streams: vec![vec![b'a'.into(), 7, b'b'.into()]], + calls: Vec::new(), + }; + let request = RunRequest { + prompt: &[], + thinking: false, + budget: Some(1), + max_new: 10, + stop_ids: &stops, + }; + let stopped = run(&mut engine, &Bytes, &request, &|| false).unwrap(); + assert_eq!( + (stopped.finish, stopped.completion_tokens), + (Finish::Stop, 2) + ); + assert_eq!(stopped.generated, vec![u32::from(b'a'), 7]); + assert_eq!(stopped.wrapped_after, None); + let mut engine = Scripted { + streams: vec![ids("zz")], + calls: Vec::new(), + }; + let cancelled = run(&mut engine, &Bytes, &request, &|| true).unwrap(); + assert_eq!(cancelled.finish, Finish::Cancel); +} diff --git a/control-plane/src/request_log.rs b/control-plane/src/request_log.rs index 6f17a070..5e331adc 100644 --- a/control-plane/src/request_log.rs +++ b/control-plane/src/request_log.rs @@ -729,303 +729,4 @@ pub fn render_prometheus(out: &mut String) { } #[cfg(test)] -mod tests { - use super::*; - use leleka_obs::{Format, Level, Settings}; - - const JSON: Settings = Settings { - min_level: Level::Info, - format: Format::Json, - debug: false, - legacy: false, - }; - - fn done(line: &str) -> Done { - let crate::wire::Event::Done(done) = crate::wire::parse_line(line).unwrap().unwrap() else { - panic!() - }; - done - } - - fn record_of(ctx: &ReqCtx) -> Record { - let record = ctx.with(|s| Record::from_state(s)).unwrap(); - ctx.with(|s| s.emitted = true); // do not publish from the test - record - } - - fn line(record: &Record) -> String { - leleka_obs::format_line( - &JSON, - 1_793_613_072_345, - Level::Info, - "api", - "request", - &record.fields(), - 0, - ) - } - - fn ctx() -> ReqCtx { - ReqCtx::new( - "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d".into(), - 0, - Some("s-0123456789".into()), - Some("qwen-iq3".into()), - None, - ) - } - - #[test] - fn a_completed_request_has_the_figures_an_analysis_needs() { - let c = ctx(); - c.set_stream(true); - c.engine_start(); - std::thread::sleep(std::time::Duration::from_millis(15)); - c.first_token(); - c.done(&done("DONE 400 182341 900.0 5600.0 stop 0 0 181900"), false); - let r = record_of(&c); - assert_eq!(r.outcome, "stop"); - assert_eq!( - (r.prompt_tokens, r.output_tokens), - (Some(182341), Some(400)) - ); - assert!(r.ttft_ms.unwrap() >= 15 && r.queue_ms.unwrap() < r.ttft_ms.unwrap()); - assert!(r.prefill_tps.is_some() && r.decode_tps.is_some()); - let text = line(&r); - for key in [ - "\"rid\":\"0b1c", - "\"sid\":\"s-01", - "\"ep\":\"responses\"", - "\"stream\":true", - "\"fin\":\"stop\"", - "\"ptok\":182341", - "\"otok\":400", - "\"restart\":false", - "\"err\":\"none\"", - ] { - assert!(text.contains(key), "{key} missing: {text}"); - } - } - - #[test] - fn the_line_is_one_json_object_under_a_kilobyte_even_when_every_field_is_present() { - let mut r = Record { - id: "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d".into(), - sid: Some("s-0123456789".into()), - endpoint: 2, - stream: Some(true), - model: Some("qwen3.8-flash-next-gsq-iq3".into()), - profile: Some("laptop-workstation".into()), - status: Some(200), - outcome: "disconnect", - prompt_tokens: Some(262_144), - cached_tokens: Some(262_000), - output_tokens: Some(65_536), - queue_ms: Some(123_456), - ttft_ms: Some(1_234_567), - prefill_tps: Some(16_000.5), - decode_tps: Some(149.9), - total_ms: 3_600_000, - restart: true, - error_class: "engine_refused", - error: Some("engine refused the generation: ".to_owned() + &"x".repeat(200)), - hardware: Some(crate::memory_view::Brief { - sm_clock_mhz: Some(2_850), - temp_c: Some(84), - throttle: Some(0x44), - gate: Some("normal".into()), - ram_available_mib: Some(120_000), - }), - }; - let text = line(&r); - assert!(text.len() < 1024, "{} bytes: {text}", text.len()); - assert!(!text.contains('\n') && text.starts_with('{') && text.ends_with('}')); - // a typical request is smaller still - r.error = None; - r.error_class = "none"; - r.restart = false; - let typical = line(&r); - assert!(typical.len() < 700, "{}", typical.len()); - // the volume estimate quoted in the report: bytes per request, worst case and typical (cargo test -- --nocapture) - let _ = std::io::Write::write_fmt( - &mut std::io::stderr(), - format_args!( - "RECORD-BYTES worst={} typical={}\nRECORD-SAMPLE {typical}\n", - text.len(), - typical.len() - ), - ); - } - - #[test] - fn neither_prompt_text_nor_credentials_can_reach_the_line() { - leleka_obs::register_secret("sk-test-super-secret-key-0123456789"); - let c = ctx(); - c.engine_start(); - // an engine error that echoes input is reduced to a length: it is not one of our own messages - c.error("tokenizer failed on: my password is sk-test-super-secret-key-0123456789 and the prompt text"); - let r = record_of(&c); - let text = line(&r); - assert_eq!(r.error_class, "other"); - assert!( - !text.contains("sk-test") - && !text.contains("password") - && !text.contains("prompt text"), - "{text}" - ); - assert!(text.contains("\"err_msg\":\"91 bytes\""), "{text}"); - // our own wording is kept - let c = ctx(); - c.engine_start(); - c.error("engine made no progress for 30 s during a request (stall watchdog)"); - let r = record_of(&c); - assert_eq!(r.error_class, "stall"); - assert!(line(&r).contains("engine made no progress")); - } - - #[test] - fn rejections_abandonment_and_failures_are_told_apart() { - let c = ctx(); - c.set_http_status(503); - assert_eq!(record_of(&c).outcome, "rejected"); - assert_eq!(record_of(&c).error_class, "unavailable"); - let c = ctx(); - assert_eq!(record_of(&c).outcome, "abandoned"); - let c = ctx(); - c.engine_start(); - c.error("engine stream ended without a terminal event"); - c.engine_restarted(); - let r = record_of(&c); - assert_eq!( - (r.outcome, r.error_class, r.restart), - ("error", "stream_ended", true) - ); - let c = ctx(); - c.engine_start(); - c.done(&done("DONE 3 10 1.0 4.0 stop"), true); - assert_eq!(record_of(&c).outcome, "disconnect"); - } - - #[test] - fn the_record_is_published_once() { - let c = ctx(); - c.finalize(); - c.finalize(); - assert_eq!(c.with(|s| s.emitted), Some(true)); - } - - #[test] - fn the_session_header_is_hashed_not_copied() { - let mut headers = HeaderMap::new(); - assert_eq!(session_tag(&headers), None); - headers.insert( - "session_id", - HeaderValue::from_static("user-4417-conversation"), - ); - let tag = session_tag(&headers).unwrap(); - assert!( - tag.starts_with("s-") && tag.len() == 12 && !tag.contains("4417"), - "{tag}" - ); - assert_eq!(session_tag(&headers).unwrap(), tag); - } - - fn counted(endpoint: &str, outcome: &str) -> u64 { - let mut text = String::new(); - 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) - } - - #[tokio::test] - async fn the_middleware_names_the_request_hands_it_to_the_handler_and_records_a_rejection() { - let observe = Observe { - model: Some("m".into()), - memory: Arc::new(Default::default()), - }; - let app = axum::Router::new() - .route( - "/v1/chat/completions", - axum::routing::post(|| async { - let handle = ObsHandle::current(); - assert!( - handle.0.is_some(), - "the handler must see the request's record" - ); - handle.set_stream(false); - (axum::http::StatusCode::SERVICE_UNAVAILABLE, "busy") - }), - ) - .layer(axum::middleware::from_fn_with_state( - observe, - super::observe, - )); - 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 }); - let before = counted("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")); - // the record is written when the last reference to it is gone, just after the response - let mut after = before; - for _ in 0..50 { - after = counted("chat", "rejected"); - if after > before { - break; - } - tokio::time::sleep(std::time::Duration::from_millis(20)).await; - } - assert!( - after > before, - "the rejection must be counted: {before} -> {after}" - ); - server.abort(); - } - - #[test] - fn the_prometheus_text_has_fixed_labels_and_valid_lines() { - let c = ctx(); - c.engine_start(); - c.first_token(); - c.done(&done("DONE 10 100 5.0 100.0 length"), false); - record_of(&c).publish(); - let mut text = String::new(); - 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() { - assert!( - line.starts_with("# HELP ") - || line.starts_with("# TYPE ") - || line.starts_with("leleka_"), - "{line}" - ); - assert!( - !line.contains("0b1c2d3e"), - "no request id in a metric: {line}" - ); - } - } -} +mod tests; diff --git a/control-plane/src/request_log/tests.rs b/control-plane/src/request_log/tests.rs new file mode 100644 index 00000000..5a504166 --- /dev/null +++ b/control-plane/src/request_log/tests.rs @@ -0,0 +1,300 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use leleka_obs::{Format, Level, Settings}; + +const JSON: Settings = Settings { + min_level: Level::Info, + format: Format::Json, + debug: false, + legacy: false, +}; + +fn done(line: &str) -> Done { + let crate::wire::Event::Done(done) = crate::wire::parse_line(line).unwrap().unwrap() else { + panic!() + }; + done +} + +fn record_of(ctx: &ReqCtx) -> Record { + let record = ctx.with(|s| Record::from_state(s)).unwrap(); + ctx.with(|s| s.emitted = true); // do not publish from the test + record +} + +fn line(record: &Record) -> String { + leleka_obs::format_line( + &JSON, + 1_793_613_072_345, + Level::Info, + "api", + "request", + &record.fields(), + 0, + ) +} + +fn ctx() -> ReqCtx { + ReqCtx::new( + "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d".into(), + 0, + Some("s-0123456789".into()), + Some("qwen-iq3".into()), + None, + ) +} + +#[test] +fn a_completed_request_has_the_figures_an_analysis_needs() { + let c = ctx(); + c.set_stream(true); + c.engine_start(); + std::thread::sleep(std::time::Duration::from_millis(15)); + c.first_token(); + c.done(&done("DONE 400 182341 900.0 5600.0 stop 0 0 181900"), false); + let r = record_of(&c); + assert_eq!(r.outcome, "stop"); + assert_eq!( + (r.prompt_tokens, r.output_tokens), + (Some(182341), Some(400)) + ); + assert!(r.ttft_ms.unwrap() >= 15 && r.queue_ms.unwrap() < r.ttft_ms.unwrap()); + assert!(r.prefill_tps.is_some() && r.decode_tps.is_some()); + let text = line(&r); + for key in [ + "\"rid\":\"0b1c", + "\"sid\":\"s-01", + "\"ep\":\"responses\"", + "\"stream\":true", + "\"fin\":\"stop\"", + "\"ptok\":182341", + "\"otok\":400", + "\"restart\":false", + "\"err\":\"none\"", + ] { + assert!(text.contains(key), "{key} missing: {text}"); + } +} + +#[test] +fn the_line_is_one_json_object_under_a_kilobyte_even_when_every_field_is_present() { + let mut r = Record { + id: "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d".into(), + sid: Some("s-0123456789".into()), + endpoint: 2, + stream: Some(true), + model: Some("qwen3.8-flash-next-gsq-iq3".into()), + profile: Some("laptop-workstation".into()), + status: Some(200), + outcome: "disconnect", + prompt_tokens: Some(262_144), + cached_tokens: Some(262_000), + output_tokens: Some(65_536), + queue_ms: Some(123_456), + ttft_ms: Some(1_234_567), + prefill_tps: Some(16_000.5), + decode_tps: Some(149.9), + total_ms: 3_600_000, + restart: true, + error_class: "engine_refused", + error: Some("engine refused the generation: ".to_owned() + &"x".repeat(200)), + hardware: Some(crate::memory_view::Brief { + sm_clock_mhz: Some(2_850), + temp_c: Some(84), + throttle: Some(0x44), + gate: Some("normal".into()), + ram_available_mib: Some(120_000), + }), + }; + let text = line(&r); + assert!(text.len() < 1024, "{} bytes: {text}", text.len()); + assert!(!text.contains('\n') && text.starts_with('{') && text.ends_with('}')); + // a typical request is smaller still + r.error = None; + r.error_class = "none"; + r.restart = false; + let typical = line(&r); + assert!(typical.len() < 700, "{}", typical.len()); + // the volume estimate quoted in the report: bytes per request, worst case and typical (cargo test -- --nocapture) + let _ = std::io::Write::write_fmt( + &mut std::io::stderr(), + format_args!( + "RECORD-BYTES worst={} typical={}\nRECORD-SAMPLE {typical}\n", + text.len(), + typical.len() + ), + ); +} + +#[test] +fn neither_prompt_text_nor_credentials_can_reach_the_line() { + leleka_obs::register_secret("sk-test-super-secret-key-0123456789"); + let c = ctx(); + c.engine_start(); + // an engine error that echoes input is reduced to a length: it is not one of our own messages + c.error("tokenizer failed on: my password is sk-test-super-secret-key-0123456789 and the prompt text"); + let r = record_of(&c); + let text = line(&r); + assert_eq!(r.error_class, "other"); + assert!( + !text.contains("sk-test") + && !text.contains("password") + && !text.contains("prompt text"), + "{text}" + ); + assert!(text.contains("\"err_msg\":\"91 bytes\""), "{text}"); + // our own wording is kept + let c = ctx(); + c.engine_start(); + c.error("engine made no progress for 30 s during a request (stall watchdog)"); + let r = record_of(&c); + assert_eq!(r.error_class, "stall"); + assert!(line(&r).contains("engine made no progress")); +} + +#[test] +fn rejections_abandonment_and_failures_are_told_apart() { + let c = ctx(); + c.set_http_status(503); + assert_eq!(record_of(&c).outcome, "rejected"); + assert_eq!(record_of(&c).error_class, "unavailable"); + let c = ctx(); + assert_eq!(record_of(&c).outcome, "abandoned"); + let c = ctx(); + c.engine_start(); + c.error("engine stream ended without a terminal event"); + c.engine_restarted(); + let r = record_of(&c); + assert_eq!( + (r.outcome, r.error_class, r.restart), + ("error", "stream_ended", true) + ); + let c = ctx(); + c.engine_start(); + c.done(&done("DONE 3 10 1.0 4.0 stop"), true); + assert_eq!(record_of(&c).outcome, "disconnect"); +} + +#[test] +fn the_record_is_published_once() { + let c = ctx(); + c.finalize(); + c.finalize(); + assert_eq!(c.with(|s| s.emitted), Some(true)); +} + +#[test] +fn the_session_header_is_hashed_not_copied() { + let mut headers = HeaderMap::new(); + assert_eq!(session_tag(&headers), None); + headers.insert( + "session_id", + HeaderValue::from_static("user-4417-conversation"), + ); + let tag = session_tag(&headers).unwrap(); + assert!( + tag.starts_with("s-") && tag.len() == 12 && !tag.contains("4417"), + "{tag}" + ); + assert_eq!(session_tag(&headers).unwrap(), tag); +} + +fn counted(endpoint: &str, outcome: &str) -> u64 { + let mut text = String::new(); + 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) +} + +#[tokio::test] +async fn the_middleware_names_the_request_hands_it_to_the_handler_and_records_a_rejection() { + let observe = Observe { + model: Some("m".into()), + memory: Arc::new(Default::default()), + }; + let app = axum::Router::new() + .route( + "/v1/chat/completions", + axum::routing::post(|| async { + let handle = ObsHandle::current(); + assert!( + handle.0.is_some(), + "the handler must see the request's record" + ); + handle.set_stream(false); + (axum::http::StatusCode::SERVICE_UNAVAILABLE, "busy") + }), + ) + .layer(axum::middleware::from_fn_with_state( + observe, + super::observe, + )); + 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 }); + let before = counted("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")); + // the record is written when the last reference to it is gone, just after the response + let mut after = before; + for _ in 0..50 { + after = counted("chat", "rejected"); + if after > before { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + assert!( + after > before, + "the rejection must be counted: {before} -> {after}" + ); + server.abort(); +} + +#[test] +fn the_prometheus_text_has_fixed_labels_and_valid_lines() { + let c = ctx(); + c.engine_start(); + c.first_token(); + c.done(&done("DONE 10 100 5.0 100.0 length"), false); + record_of(&c).publish(); + let mut text = String::new(); + 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() { + assert!( + line.starts_with("# HELP ") + || line.starts_with("# TYPE ") + || line.starts_with("leleka_"), + "{line}" + ); + assert!( + !line.contains("0b1c2d3e"), + "no request id in a metric: {line}" + ); + } +} diff --git a/control-plane/src/request_monitor.rs b/control-plane/src/request_monitor.rs index 821dfcd4..02cd259f 100644 --- a/control-plane/src/request_monitor.rs +++ b/control-plane/src/request_monitor.rs @@ -571,153 +571,4 @@ pub async fn capture( } #[cfg(test)] -mod tests { - use super::*; - - fn record() -> Shared { - RequestMonitor::new(true).begin( - "/v1/chat/completions", - br#"{"model":"m","stream":true,"messages":[{"role":"user","content":"hi"}]}"#, - ) - } - - #[test] - fn the_request_is_captured_as_pretty_json_with_its_model_and_stream_flag() { - let monitor = RequestMonitor::new(true); - let shared = monitor.begin("/v1/responses", br#"{"model":"qwen","stream":false,"text":{"format":{"type":"json_object"}},"input":"hi"}"#); - let r = shared.lock().unwrap(); - assert_eq!( - (r.model.clone(), r.stream, r.state), - (json!("qwen"), false, "queued") - ); - assert_eq!(r.response_format, json!("json_object")); - assert!(r.input.contains("\"input\": \"hi\""), "{}", r.input); - assert_eq!(r.id.len(), 12); - // a body that is not JSON is kept as text - let other = monitor.begin("/v1/responses", b"not json"); - assert_eq!(other.lock().unwrap().input, "not json"); - } - - #[test] - fn chat_anthropic_and_responses_streams_are_read() { - let shared = record(); - let mut r = shared.lock().unwrap(); - r.absorb_event(&json!({"choices": [{"delta": {"content": "Hel"}}]})); - assert_eq!(r.state, "generating"); - assert!(r.first_token_s.is_some()); - r.absorb_event(&json!({"choices": [{"delta": {"content": "lo", "reasoning_content": "think"}}], "usage": {"completion_tokens": 2}})); - r.absorb_event( - &json!({"type": "content_block_delta", "delta": {"type": "text_delta", "text": "!"}}), - ); - r.absorb_event(&json!({"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": "+"}})); - r.absorb_event(&json!({"type": "response.output_text.delta", "delta": "?"})); - r.absorb_event(&json!({"type": "response.reasoning_text.delta", "delta": "-"})); - assert_eq!( - (r.output.as_str(), r.reasoning.as_str()), - ("Hello!?", "think+-") - ); - assert_eq!(r.usage, Some(json!({"completion_tokens": 2}))); - r.absorb_event(&json!({"type": "message_start", "message": {"usage": {"input_tokens": 9, "output_tokens": 1}}})); - r.absorb_event(&json!({"type": "message_delta", "usage": {"output_tokens": 7}})); - assert_eq!( - r.usage, - Some(json!({"input_tokens": 9, "output_tokens": 7})) - ); - r.absorb_event(&json!({"type": "response.completed", "response": {"usage": {"input_tokens": 3, "output_tokens": 4, "total_tokens": 7}}})); - assert_eq!(r.usage.as_ref().unwrap()["total_tokens"], 7); - r.absorb_event( - &json!({"type": "response.failed", "response": {"error": {"message": "boom"}}}), - ); - assert_eq!(r.error, Some(json!({"message": "boom"}))); - r.settle(None); - assert_eq!(r.state, "error"); - } - - #[test] - fn whole_responses_of_the_three_dialects_are_read() { - let chat = json!({"choices": [{"message": {"content": "A", "reasoning_content": "r"}}], "usage": {"completion_tokens": 1}}); - let messages = json!({"type": "message", "content": [{"type": "thinking", "thinking": "t"}, {"type": "text", "text": "B"}], "usage": {"output_tokens": 1}}); - let responses = json!({"object": "response", "output": [ - {"type": "reasoning", "content": [{"type": "reasoning_text", "text": "x"}], "summary": [{"text": "y"}]}, - {"type": "message", "content": [{"type": "output_text", "text": "C"}]}], "usage": {"output_tokens": 3}}); - for (body, output, reasoning) in [ - (chat, "A", "r"), - (messages, "B", "t"), - (responses, "C", "xy"), - ] { - let shared = record(); - let mut r = shared.lock().unwrap(); - r.absorb_response(&body); - r.settle(None); - assert_eq!( - (r.output.as_str(), r.reasoning.as_str(), r.state), - (output, reasoning, "completed") - ); - assert_eq!( - serde_json::from_str::(r.response.as_ref().unwrap()).unwrap(), - body - ); - assert!(r.usage.is_some()); - } - } - - #[test] - fn an_http_error_or_a_dropped_stream_is_not_a_success() { - let shared = record(); - let mut r = shared.lock().unwrap(); - r.http_status = Some(429); - r.settle(None); - assert_eq!(r.state, "error"); - let shared = record(); - let mut r = shared.lock().unwrap(); - r.http_status = Some(200); - r.settle(Some("disconnected")); - assert_eq!((r.state, r.outcome), ("disconnected", Some("disconnected"))); - // settling twice keeps the first verdict - r.settle(None); - assert_eq!(r.state, "disconnected"); - } - - #[test] - fn captured_text_is_bounded_and_flagged_at_a_character_boundary() { - let shared = record(); - let mut r = shared.lock().unwrap(); - let big = "é".repeat(CAP); - r.add_output(Some(&big)); - r.add_output(Some("more")); - assert!(r.output.len() <= CAP && r.output_truncated); - assert!(r.output.chars().all(|c| c == 'é')); - let monitor = RequestMonitor::new(true); - let body = format!("{{\"input\":\"{}\"}}", "x".repeat(CAP + 100)); - let huge = monitor.begin("/v1/responses", body.as_bytes()); - let huge = huge.lock().unwrap(); - assert_eq!(huge.input.len(), CAP); - assert!(huge.input_truncated); - } - - #[test] - fn retention_evicts_the_oldest_and_summaries_leave_the_payload_out() { - let monitor = RequestMonitor::new(true); - let first = monitor.begin("/v1/messages", br#"{"messages":[]}"#); - let first_id = first.lock().unwrap().id.clone(); - for _ in 0..RETENTION { - monitor.begin("/v1/messages", br#"{"messages":[]}"#); - } - assert_eq!(monitor.summaries().len(), RETENTION); - assert!(monitor.detail(&first_id).is_none()); - let newest = monitor.summaries().remove(0); - for payload in ["input", "output", "reasoning", "response"] { - assert!(newest.get(payload).is_none(), "{payload}"); - } - let detail = monitor.detail(newest["id"].as_str().unwrap()).unwrap(); - assert!(detail.get("input").is_some() && detail.get("output").is_some()); - assert!(newest["queue_s"].is_null() && newest["load_s"].is_null()); - } - - #[test] - fn a_disabled_monitor_keeps_nothing() { - let monitor = RequestMonitor::default(); - assert!(!monitor.enabled()); - assert!(monitor.summaries().is_empty()); - } -} +mod tests; diff --git a/control-plane/src/request_monitor/tests.rs b/control-plane/src/request_monitor/tests.rs new file mode 100644 index 00000000..42f3f130 --- /dev/null +++ b/control-plane/src/request_monitor/tests.rs @@ -0,0 +1,150 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn record() -> Shared { + RequestMonitor::new(true).begin( + "/v1/chat/completions", + br#"{"model":"m","stream":true,"messages":[{"role":"user","content":"hi"}]}"#, + ) +} + +#[test] +fn the_request_is_captured_as_pretty_json_with_its_model_and_stream_flag() { + let monitor = RequestMonitor::new(true); + let shared = monitor.begin("/v1/responses", br#"{"model":"qwen","stream":false,"text":{"format":{"type":"json_object"}},"input":"hi"}"#); + let r = shared.lock().unwrap(); + assert_eq!( + (r.model.clone(), r.stream, r.state), + (json!("qwen"), false, "queued") + ); + assert_eq!(r.response_format, json!("json_object")); + assert!(r.input.contains("\"input\": \"hi\""), "{}", r.input); + assert_eq!(r.id.len(), 12); + // a body that is not JSON is kept as text + let other = monitor.begin("/v1/responses", b"not json"); + assert_eq!(other.lock().unwrap().input, "not json"); +} + +#[test] +fn chat_anthropic_and_responses_streams_are_read() { + let shared = record(); + let mut r = shared.lock().unwrap(); + r.absorb_event(&json!({"choices": [{"delta": {"content": "Hel"}}]})); + assert_eq!(r.state, "generating"); + assert!(r.first_token_s.is_some()); + r.absorb_event(&json!({"choices": [{"delta": {"content": "lo", "reasoning_content": "think"}}], "usage": {"completion_tokens": 2}})); + r.absorb_event( + &json!({"type": "content_block_delta", "delta": {"type": "text_delta", "text": "!"}}), + ); + r.absorb_event(&json!({"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": "+"}})); + r.absorb_event(&json!({"type": "response.output_text.delta", "delta": "?"})); + r.absorb_event(&json!({"type": "response.reasoning_text.delta", "delta": "-"})); + assert_eq!( + (r.output.as_str(), r.reasoning.as_str()), + ("Hello!?", "think+-") + ); + assert_eq!(r.usage, Some(json!({"completion_tokens": 2}))); + r.absorb_event(&json!({"type": "message_start", "message": {"usage": {"input_tokens": 9, "output_tokens": 1}}})); + r.absorb_event(&json!({"type": "message_delta", "usage": {"output_tokens": 7}})); + assert_eq!( + r.usage, + Some(json!({"input_tokens": 9, "output_tokens": 7})) + ); + r.absorb_event(&json!({"type": "response.completed", "response": {"usage": {"input_tokens": 3, "output_tokens": 4, "total_tokens": 7}}})); + assert_eq!(r.usage.as_ref().unwrap()["total_tokens"], 7); + r.absorb_event( + &json!({"type": "response.failed", "response": {"error": {"message": "boom"}}}), + ); + assert_eq!(r.error, Some(json!({"message": "boom"}))); + r.settle(None); + assert_eq!(r.state, "error"); +} + +#[test] +fn whole_responses_of_the_three_dialects_are_read() { + let chat = json!({"choices": [{"message": {"content": "A", "reasoning_content": "r"}}], "usage": {"completion_tokens": 1}}); + let messages = json!({"type": "message", "content": [{"type": "thinking", "thinking": "t"}, {"type": "text", "text": "B"}], "usage": {"output_tokens": 1}}); + let responses = json!({"object": "response", "output": [ + {"type": "reasoning", "content": [{"type": "reasoning_text", "text": "x"}], "summary": [{"text": "y"}]}, + {"type": "message", "content": [{"type": "output_text", "text": "C"}]}], "usage": {"output_tokens": 3}}); + for (body, output, reasoning) in [ + (chat, "A", "r"), + (messages, "B", "t"), + (responses, "C", "xy"), + ] { + let shared = record(); + let mut r = shared.lock().unwrap(); + r.absorb_response(&body); + r.settle(None); + assert_eq!( + (r.output.as_str(), r.reasoning.as_str(), r.state), + (output, reasoning, "completed") + ); + assert_eq!( + serde_json::from_str::(r.response.as_ref().unwrap()).unwrap(), + body + ); + assert!(r.usage.is_some()); + } +} + +#[test] +fn an_http_error_or_a_dropped_stream_is_not_a_success() { + let shared = record(); + let mut r = shared.lock().unwrap(); + r.http_status = Some(429); + r.settle(None); + assert_eq!(r.state, "error"); + let shared = record(); + let mut r = shared.lock().unwrap(); + r.http_status = Some(200); + r.settle(Some("disconnected")); + assert_eq!((r.state, r.outcome), ("disconnected", Some("disconnected"))); + // settling twice keeps the first verdict + r.settle(None); + assert_eq!(r.state, "disconnected"); +} + +#[test] +fn captured_text_is_bounded_and_flagged_at_a_character_boundary() { + let shared = record(); + let mut r = shared.lock().unwrap(); + let big = "é".repeat(CAP); + r.add_output(Some(&big)); + r.add_output(Some("more")); + assert!(r.output.len() <= CAP && r.output_truncated); + assert!(r.output.chars().all(|c| c == 'é')); + let monitor = RequestMonitor::new(true); + let body = format!("{{\"input\":\"{}\"}}", "x".repeat(CAP + 100)); + let huge = monitor.begin("/v1/responses", body.as_bytes()); + let huge = huge.lock().unwrap(); + assert_eq!(huge.input.len(), CAP); + assert!(huge.input_truncated); +} + +#[test] +fn retention_evicts_the_oldest_and_summaries_leave_the_payload_out() { + let monitor = RequestMonitor::new(true); + let first = monitor.begin("/v1/messages", br#"{"messages":[]}"#); + let first_id = first.lock().unwrap().id.clone(); + for _ in 0..RETENTION { + monitor.begin("/v1/messages", br#"{"messages":[]}"#); + } + assert_eq!(monitor.summaries().len(), RETENTION); + assert!(monitor.detail(&first_id).is_none()); + let newest = monitor.summaries().remove(0); + for payload in ["input", "output", "reasoning", "response"] { + assert!(newest.get(payload).is_none(), "{payload}"); + } + let detail = monitor.detail(newest["id"].as_str().unwrap()).unwrap(); + assert!(detail.get("input").is_some() && detail.get("output").is_some()); + assert!(newest["queue_s"].is_null() && newest["load_s"].is_null()); +} + +#[test] +fn a_disabled_monitor_keeps_nothing() { + let monitor = RequestMonitor::default(); + assert!(!monitor.enabled()); + assert!(monitor.summaries().is_empty()); +} diff --git a/control-plane/src/service_install.rs b/control-plane/src/service_install.rs index 07891f4a..134690c0 100644 --- a/control-plane/src/service_install.rs +++ b/control-plane/src/service_install.rs @@ -790,146 +790,4 @@ mod unix { } #[cfg(test)] -mod tests { - use super::*; - #[test] - fn ready_install_is_explicit_and_control_compatible() { - let base = ["--config", "/config", "--working-dir", "/work"] - .map(str::to_owned) - .to_vec(); - let ready = [ - "--start-ready", - "--ready-url", - "http://127.0.0.1:8080", - "--ready-model", - "test", - ] - .map(str::to_owned); - let mut args = base.clone(); - args.extend(ready.clone()); - let (options, readiness) = install_options(&args).unwrap(); - assert!(options.start && !options.enable); - let control = ready_control_args(&options, &readiness.unwrap()); - assert_eq!(control_options(&control).unwrap().0, "start-ready"); - for suffix in [ - vec!["--start"], - vec!["--start-ready"], - vec!["--ready-timeout-s", "0"], - vec!["--ready-model", "duplicate"], - ] { - let mut bad = args.clone(); - bad.extend(suffix.into_iter().map(str::to_owned)); - assert!(install_options(&bad).is_err()); - } - let mut without = base.clone(); - without.extend(ready[1..].iter().cloned()); - assert!(install_options(&without).is_err()); - let mut missing = base.clone(); - missing.push("--start-ready".into()); - assert!(install_options(&missing).is_err()); - assert!(install_options(&base).unwrap().1.is_none()); - let mut old = base; - old.push("--start".into()); - assert!(install_options(&old).unwrap().0.start); - } - #[test] - fn control_only_explicit_scoped_actions() { - let args = ["--config", "/a", "--working-dir", "/b"]; - for action in ["status", "start", "stop", "restart", "enable", "disable"] { - let values = std::iter::once(action) - .chain(args) - .map(str::to_owned) - .collect::>(); - assert_eq!(control_options(&values).unwrap().0, action); - let mut values = values; - values.push("--start".into()); - assert!(control_options(&values).is_err()); - } - for action in ["kill", "daemon-reload", "--all", ""] { - let values = std::iter::once(action) - .chain(args) - .map(str::to_owned) - .collect::>(); - assert!(control_options(&values).is_err()); - } - } - - #[test] - fn arguments_and_scoped_names() { - for name in ["strata-next.service", "strata-next-prod_2.service"] { - assert!(validate_name(name).is_ok()); - } - for name in [ - "other.service", - "strata-next-.service", - "strata-next@a.service", - "strata-next-../a.service", - "strata-next-a\n.service", - ] { - assert!(validate_name(name).is_err()); - } - for args in [ - vec![], - vec!["--start", "--start"], - vec!["--enable", "--enable"], - vec!["--config", "/a", "--config", "/b"], - vec!["--enable"], - ] { - assert!(parse(&args.iter().map(|s| s.to_string()).collect::>()).is_err()); - } - let options = - parse(&["--config", "/a", "--working-dir", "/b", "--start"].map(str::to_owned)) - .unwrap(); - assert!(options.start); - assert!(!options.enable); - let enabled = - parse(&["--config", "/a", "--working-dir", "/b", "--enable"].map(str::to_owned)) - .unwrap(); - assert!(enabled.enable && !enabled.start); - let invalid_control = - ["start", "--config", "/a", "--working-dir", "/b", "--enable"].map(str::to_owned); - assert!(control_options(&invalid_control).is_err()); - assert_eq!(options.unit, "strata-next.service"); - } - #[test] - fn managed_readiness_options_and_active_process_are_strict() { - let base = ["start-ready", "--config", "/a", "--working-dir", "/b"]; - let mut args = base.map(str::to_owned).to_vec(); - assert!(control_options(&args).is_err()); - args.extend( - [ - "--ready-url", - "http://127.0.0.1:8080", - "--ready-model", - "fixture", - ] - .map(str::to_owned), - ); - assert!(control_options(&args).unwrap().2.is_some()); - for action in ["restart-ready", "drain-stop", "resume"] { - args[0] = action.into(); - assert!(control_options(&args).is_ok()); - } - for action in ["status", "start", "restart", "enable"] { - args[0] = action.into(); - assert!(control_options(&args).is_err()); - } - args[0] = "start-ready".into(); - args.extend(["--ready-timeout-s", "0"].map(str::to_owned)); - assert!(control_options(&args).is_err()); - let good = - serde_json::json!({"active_state":"active", "sub_state":"running", "main_pid":123}); - assert_eq!(active_pid(&good).unwrap(), 123); - for (key, value) in [ - ("main_pid", serde_json::json!(0)), - ("main_pid", serde_json::json!(4294967296u64)), - ("main_pid", serde_json::json!("123")), - ("active_state", serde_json::json!("inactive")), - ("sub_state", serde_json::json!("dead")), - ] { - let mut bad = good.clone(); - bad[key] = value; - assert!(active_pid(&bad).is_err()); - } - } -} +mod tests; diff --git a/control-plane/src/service_install/tests.rs b/control-plane/src/service_install/tests.rs new file mode 100644 index 00000000..e5ebcd22 --- /dev/null +++ b/control-plane/src/service_install/tests.rs @@ -0,0 +1,143 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +#[test] +fn ready_install_is_explicit_and_control_compatible() { + let base = ["--config", "/config", "--working-dir", "/work"] + .map(str::to_owned) + .to_vec(); + let ready = [ + "--start-ready", + "--ready-url", + "http://127.0.0.1:8080", + "--ready-model", + "test", + ] + .map(str::to_owned); + let mut args = base.clone(); + args.extend(ready.clone()); + let (options, readiness) = install_options(&args).unwrap(); + assert!(options.start && !options.enable); + let control = ready_control_args(&options, &readiness.unwrap()); + assert_eq!(control_options(&control).unwrap().0, "start-ready"); + for suffix in [ + vec!["--start"], + vec!["--start-ready"], + vec!["--ready-timeout-s", "0"], + vec!["--ready-model", "duplicate"], + ] { + let mut bad = args.clone(); + bad.extend(suffix.into_iter().map(str::to_owned)); + assert!(install_options(&bad).is_err()); + } + let mut without = base.clone(); + without.extend(ready[1..].iter().cloned()); + assert!(install_options(&without).is_err()); + let mut missing = base.clone(); + missing.push("--start-ready".into()); + assert!(install_options(&missing).is_err()); + assert!(install_options(&base).unwrap().1.is_none()); + let mut old = base; + old.push("--start".into()); + assert!(install_options(&old).unwrap().0.start); +} +#[test] +fn control_only_explicit_scoped_actions() { + let args = ["--config", "/a", "--working-dir", "/b"]; + for action in ["status", "start", "stop", "restart", "enable", "disable"] { + let values = std::iter::once(action) + .chain(args) + .map(str::to_owned) + .collect::>(); + assert_eq!(control_options(&values).unwrap().0, action); + let mut values = values; + values.push("--start".into()); + assert!(control_options(&values).is_err()); + } + for action in ["kill", "daemon-reload", "--all", ""] { + let values = std::iter::once(action) + .chain(args) + .map(str::to_owned) + .collect::>(); + assert!(control_options(&values).is_err()); + } +} + +#[test] +fn arguments_and_scoped_names() { + for name in ["strata-next.service", "strata-next-prod_2.service"] { + assert!(validate_name(name).is_ok()); + } + for name in [ + "other.service", + "strata-next-.service", + "strata-next@a.service", + "strata-next-../a.service", + "strata-next-a\n.service", + ] { + assert!(validate_name(name).is_err()); + } + for args in [ + vec![], + vec!["--start", "--start"], + vec!["--enable", "--enable"], + vec!["--config", "/a", "--config", "/b"], + vec!["--enable"], + ] { + assert!(parse(&args.iter().map(|s| s.to_string()).collect::>()).is_err()); + } + let options = + parse(&["--config", "/a", "--working-dir", "/b", "--start"].map(str::to_owned)) + .unwrap(); + assert!(options.start); + assert!(!options.enable); + let enabled = + parse(&["--config", "/a", "--working-dir", "/b", "--enable"].map(str::to_owned)) + .unwrap(); + assert!(enabled.enable && !enabled.start); + let invalid_control = + ["start", "--config", "/a", "--working-dir", "/b", "--enable"].map(str::to_owned); + assert!(control_options(&invalid_control).is_err()); + assert_eq!(options.unit, "strata-next.service"); +} +#[test] +fn managed_readiness_options_and_active_process_are_strict() { + let base = ["start-ready", "--config", "/a", "--working-dir", "/b"]; + let mut args = base.map(str::to_owned).to_vec(); + assert!(control_options(&args).is_err()); + args.extend( + [ + "--ready-url", + "http://127.0.0.1:8080", + "--ready-model", + "fixture", + ] + .map(str::to_owned), + ); + assert!(control_options(&args).unwrap().2.is_some()); + for action in ["restart-ready", "drain-stop", "resume"] { + args[0] = action.into(); + assert!(control_options(&args).is_ok()); + } + for action in ["status", "start", "restart", "enable"] { + args[0] = action.into(); + assert!(control_options(&args).is_err()); + } + args[0] = "start-ready".into(); + args.extend(["--ready-timeout-s", "0"].map(str::to_owned)); + assert!(control_options(&args).is_err()); + let good = + serde_json::json!({"active_state":"active", "sub_state":"running", "main_pid":123}); + assert_eq!(active_pid(&good).unwrap(), 123); + for (key, value) in [ + ("main_pid", serde_json::json!(0)), + ("main_pid", serde_json::json!(4294967296u64)), + ("main_pid", serde_json::json!("123")), + ("active_state", serde_json::json!("inactive")), + ("sub_state", serde_json::json!("dead")), + ] { + let mut bad = good.clone(); + bad[key] = value; + assert!(active_pid(&bad).is_err()); + } +} diff --git a/control-plane/src/service_switch.rs b/control-plane/src/service_switch.rs index f38087f9..fb0c2afc 100644 --- a/control-plane/src/service_switch.rs +++ b/control-plane/src/service_switch.rs @@ -674,119 +674,4 @@ async fn reconcile(args: &[String]) -> Result { } #[cfg(test)] -mod tests { - use super::*; - #[test] - fn reconciliation_requires_explicit_exact_digest_arguments() { - let args = vec![ - "--catalog".into(), - "/catalog".into(), - "--state-dir".into(), - "/state".into(), - "--expected-journal-sha".into(), - "a".repeat(64), - ]; - assert!(reconcile_arguments(&args).is_ok()); - for digest in ["a".repeat(63), "A".repeat(64), "z".repeat(64)] { - let mut bad = args.clone(); - bad[5] = digest; - assert!(reconcile_arguments(&bad).is_err()); - } - assert!(reconcile_arguments(&args[..5]).is_err()); - let mut duplicate = args.clone(); - duplicate.extend(args[..2].iter().cloned()); - assert!(reconcile_arguments(&duplicate).is_err()); - } - #[test] - fn explicit_distinct_profiles_and_strict_catalog() { - assert!(arguments(&[]).is_err()); - let mut args = [ - "--catalog", - "/catalog", - "--from", - "a", - "--to", - "b", - "--state-dir", - "/state", - ] - .map(str::to_owned); - assert!(arguments(&args).is_ok()); - assert!( - arguments(&[ - args[0].clone(), - args[1].clone(), - args[4].clone(), - args[5].clone(), - args[6].clone(), - args[7].clone() - ]) - .is_ok() - ); - args[5] = "a".into(); - assert!(arguments(&args).is_err()); - assert!(serde_json::from_value::(json!({"unit":"a","config":"/a","working_dir":"/a","url":"http://127.0.0.1","model":"a","env_file":"/unsupported"})).is_err()); - } - #[test] - fn selection_refuses_ambiguous_or_unsettled_manager_state() { - let running = - json!({"manager":{"main_pid":42,"active_state":"active","sub_state":"running"}}); - let stopped = - json!({"manager":{"main_pid":0,"active_state":"inactive","sub_state":"dead"}}); - assert_eq!( - select_active(&[("a".into(), stopped.clone())]).unwrap(), - None - ); - assert_eq!( - select_active(&[("a".into(), stopped), ("b".into(), running.clone())]).unwrap(), - Some(("b".into(), 42)) - ); - assert!(select_active(&[("a".into(), running.clone()), ("b".into(), running)]).is_err()); - for state in ["failed", "activating", "deactivating", "unknown"] { - assert!( - select_active(&[( - "a".into(), - json!({"manager":{"main_pid":0,"active_state":state}}) - )]) - .is_err() - ); - } - } - #[cfg(unix)] - #[test] - fn durable_phases_lock_and_private_inputs_fail_closed() { - use std::{ - fs, - os::unix::fs::{PermissionsExt, symlink}, - }; - let root = std::env::temp_dir().join(format!( - "strata-switch-test-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let mut journal = storage::Journal::open(&root, json!({"schema_version":1})).unwrap(); - assert!(storage::Journal::open(&root, json!({"schema_version":1})).is_err()); - journal.phase("preparing").unwrap(); - let path = root.join("transaction.json"); - let state: Value = - serde_json::from_slice(&storage::read(&path, true, 65536).unwrap()).unwrap(); - assert_eq!(state["phase"], "preparing"); - journal.phase("rolled_back").unwrap(); - drop(journal); - let mut journal = storage::Journal::open(&root, json!({"schema_version":1})).unwrap(); - journal.phase("starting_target").unwrap(); - drop(journal); - assert!(storage::Journal::open(&root, json!({"schema_version":1})).is_err()); - let alias = root.join("alias"); - symlink(&path, &alias).unwrap(); - assert!(storage::read(&alias, true, 65536).is_err()); - assert!(storage::read(&path, true, 1).is_err()); - fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); - assert!(storage::read(&path, true, 65536).is_err()); - assert!(storage::read(&path, false, 65536).is_ok()); - fs::remove_dir_all(root).unwrap(); - } -} +mod tests; diff --git a/control-plane/src/service_switch/tests.rs b/control-plane/src/service_switch/tests.rs new file mode 100644 index 00000000..d1073565 --- /dev/null +++ b/control-plane/src/service_switch/tests.rs @@ -0,0 +1,116 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +#[test] +fn reconciliation_requires_explicit_exact_digest_arguments() { + let args = vec![ + "--catalog".into(), + "/catalog".into(), + "--state-dir".into(), + "/state".into(), + "--expected-journal-sha".into(), + "a".repeat(64), + ]; + assert!(reconcile_arguments(&args).is_ok()); + for digest in ["a".repeat(63), "A".repeat(64), "z".repeat(64)] { + let mut bad = args.clone(); + bad[5] = digest; + assert!(reconcile_arguments(&bad).is_err()); + } + assert!(reconcile_arguments(&args[..5]).is_err()); + let mut duplicate = args.clone(); + duplicate.extend(args[..2].iter().cloned()); + assert!(reconcile_arguments(&duplicate).is_err()); +} +#[test] +fn explicit_distinct_profiles_and_strict_catalog() { + assert!(arguments(&[]).is_err()); + let mut args = [ + "--catalog", + "/catalog", + "--from", + "a", + "--to", + "b", + "--state-dir", + "/state", + ] + .map(str::to_owned); + assert!(arguments(&args).is_ok()); + assert!( + arguments(&[ + args[0].clone(), + args[1].clone(), + args[4].clone(), + args[5].clone(), + args[6].clone(), + args[7].clone() + ]) + .is_ok() + ); + args[5] = "a".into(); + assert!(arguments(&args).is_err()); + assert!(serde_json::from_value::(json!({"unit":"a","config":"/a","working_dir":"/a","url":"http://127.0.0.1","model":"a","env_file":"/unsupported"})).is_err()); +} +#[test] +fn selection_refuses_ambiguous_or_unsettled_manager_state() { + let running = + json!({"manager":{"main_pid":42,"active_state":"active","sub_state":"running"}}); + let stopped = + json!({"manager":{"main_pid":0,"active_state":"inactive","sub_state":"dead"}}); + assert_eq!( + select_active(&[("a".into(), stopped.clone())]).unwrap(), + None + ); + assert_eq!( + select_active(&[("a".into(), stopped), ("b".into(), running.clone())]).unwrap(), + Some(("b".into(), 42)) + ); + assert!(select_active(&[("a".into(), running.clone()), ("b".into(), running)]).is_err()); + for state in ["failed", "activating", "deactivating", "unknown"] { + assert!( + select_active(&[( + "a".into(), + json!({"manager":{"main_pid":0,"active_state":state}}) + )]) + .is_err() + ); + } +} +#[cfg(unix)] +#[test] +fn durable_phases_lock_and_private_inputs_fail_closed() { + use std::{ + fs, + os::unix::fs::{PermissionsExt, symlink}, + }; + let root = std::env::temp_dir().join(format!( + "strata-switch-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let mut journal = storage::Journal::open(&root, json!({"schema_version":1})).unwrap(); + assert!(storage::Journal::open(&root, json!({"schema_version":1})).is_err()); + journal.phase("preparing").unwrap(); + let path = root.join("transaction.json"); + let state: Value = + serde_json::from_slice(&storage::read(&path, true, 65536).unwrap()).unwrap(); + assert_eq!(state["phase"], "preparing"); + journal.phase("rolled_back").unwrap(); + drop(journal); + let mut journal = storage::Journal::open(&root, json!({"schema_version":1})).unwrap(); + journal.phase("starting_target").unwrap(); + drop(journal); + assert!(storage::Journal::open(&root, json!({"schema_version":1})).is_err()); + let alias = root.join("alias"); + symlink(&path, &alias).unwrap(); + assert!(storage::read(&alias, true, 65536).is_err()); + assert!(storage::read(&path, true, 1).is_err()); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + assert!(storage::read(&path, true, 65536).is_err()); + assert!(storage::read(&path, false, 65536).is_ok()); + fs::remove_dir_all(root).unwrap(); +} diff --git a/control-plane/src/wait_ready.rs b/control-plane/src/wait_ready.rs index 656baddf..367b8302 100644 --- a/control-plane/src/wait_ready.rs +++ b/control-plane/src/wait_ready.rs @@ -325,120 +325,4 @@ pub async fn run(args: &[String]) -> Result { } #[cfg(test)] -mod tests { - use super::*; - - fn args(url: &str) -> Vec { - ["--url", url, "--model", "fixture"] - .map(str::to_owned) - .to_vec() - } - - #[tokio::test] - async fn managed_readiness_requires_exact_numeric_pid_but_plain_wait_is_compatible() { - for reported in [ - None, - Some(json!(123)), - Some(json!(124)), - Some(json!("123")), - Some(json!(0)), - ] { - let mut body = json!({"service":"strata-control", "model":"fixture", "ready":true, "worker":"ready"}); - if let Some(value) = reported.clone() { - body["server_pid"] = value; - } - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let router = axum::Router::new().route( - "/status", - axum::routing::get(move || async move { axum::Json(body) }), - ); - let server = tokio::spawn(async move { - axum::serve(listener, router).await.unwrap(); - }); - let managed = Waiter::new(&args(&url)).unwrap().wait(Some(123)).await; - assert_eq!(managed.is_ok(), reported == Some(json!(123))); - if let Ok(value) = managed { - assert_eq!(value["server_pid"], 123); - } - let plain = run(&args(&url)).await.unwrap(); - assert_eq!(plain["ready"], true); - assert!(plain.get("server_pid").is_none()); - server.abort(); - let _ = server.await; - } - } - - #[tokio::test] - async fn admission_refuses_wrong_endpoint_and_never_replays_failed_post() { - use std::sync::{ - Arc, - atomic::{AtomicUsize, Ordering}, - }; - for reported_pid in [124, 123] { - let calls = Arc::new(AtomicUsize::new(0)); - let observed = calls.clone(); - let value = json!({"service":"strata-control","model":"fixture","server_pid":reported_pid, - "shutting_down":false,"draining":false,"drained":false,"requests_in_flight":0,"generation_jobs":0,"worker":"ready"}); - let app = axum::Router::new() - .route( - "/admin/lifecycle", - axum::routing::get(move || async move { axum::Json(value) }), - ) - .route( - "/admin/drain", - axum::routing::post(move |headers: axum::http::HeaderMap| async move { - assert_eq!(headers["x-strata-expected-pid"], "123"); - observed.fetch_add(1, Ordering::SeqCst); - axum::http::StatusCode::INTERNAL_SERVER_ERROR - }), - ); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let server = tokio::spawn(async move { - axum::serve(listener, app).await.unwrap(); - }); - assert!( - Waiter::new(&args(&url)) - .unwrap() - .admission(123, true) - .await - .is_err() - ); - assert_eq!( - calls.load(Ordering::SeqCst), - usize::from(reported_pid == 123) - ); - server.abort(); - let _ = server.await; - } - } - - #[test] - fn validates_origin_and_budgets_before_network_or_credentials() { - for url in ["http://127.0.0.1:18082", "http://[::1]:18082/"] { - let options = parse(&args(url)).unwrap(); - assert_eq!(options.url.path(), "/status"); - } - for url in [ - "https://127.0.0.1", - "http://localhost", - "http://192.0.2.1", - "http://key@127.0.0.1", - "http://127.0.0.1/status", - "http://127.0.0.1?key=x", - "http://127.0.0.1#x", - "http://127.0.0.1:0", - ] { - assert!(parse(&args(url)).is_err()); - } - for budget in ["0", "3601", "-1", "nan"] { - let mut args = args("http://127.0.0.1"); - args.extend(["--timeout-s".into(), budget.into()]); - assert!(parse(&args).is_err()); - } - let mut repeated = args("http://127.0.0.1"); - repeated.extend(["--model".into(), "other".into()]); - assert!(parse(&repeated).is_err()); - } -} +mod tests; diff --git a/control-plane/src/wait_ready/tests.rs b/control-plane/src/wait_ready/tests.rs new file mode 100644 index 00000000..f0cbdb0c --- /dev/null +++ b/control-plane/src/wait_ready/tests.rs @@ -0,0 +1,117 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn args(url: &str) -> Vec { + ["--url", url, "--model", "fixture"] + .map(str::to_owned) + .to_vec() +} + +#[tokio::test] +async fn managed_readiness_requires_exact_numeric_pid_but_plain_wait_is_compatible() { + for reported in [ + None, + Some(json!(123)), + Some(json!(124)), + Some(json!("123")), + Some(json!(0)), + ] { + let mut body = json!({"service":"strata-control", "model":"fixture", "ready":true, "worker":"ready"}); + if let Some(value) = reported.clone() { + body["server_pid"] = value; + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let router = axum::Router::new().route( + "/status", + axum::routing::get(move || async move { axum::Json(body) }), + ); + let server = tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + let managed = Waiter::new(&args(&url)).unwrap().wait(Some(123)).await; + assert_eq!(managed.is_ok(), reported == Some(json!(123))); + if let Ok(value) = managed { + assert_eq!(value["server_pid"], 123); + } + let plain = run(&args(&url)).await.unwrap(); + assert_eq!(plain["ready"], true); + assert!(plain.get("server_pid").is_none()); + server.abort(); + let _ = server.await; + } +} + +#[tokio::test] +async fn admission_refuses_wrong_endpoint_and_never_replays_failed_post() { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + for reported_pid in [124, 123] { + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let value = json!({"service":"strata-control","model":"fixture","server_pid":reported_pid, + "shutting_down":false,"draining":false,"drained":false,"requests_in_flight":0,"generation_jobs":0,"worker":"ready"}); + let app = axum::Router::new() + .route( + "/admin/lifecycle", + axum::routing::get(move || async move { axum::Json(value) }), + ) + .route( + "/admin/drain", + axum::routing::post(move |headers: axum::http::HeaderMap| async move { + assert_eq!(headers["x-strata-expected-pid"], "123"); + observed.fetch_add(1, Ordering::SeqCst); + axum::http::StatusCode::INTERNAL_SERVER_ERROR + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + assert!( + Waiter::new(&args(&url)) + .unwrap() + .admission(123, true) + .await + .is_err() + ); + assert_eq!( + calls.load(Ordering::SeqCst), + usize::from(reported_pid == 123) + ); + server.abort(); + let _ = server.await; + } +} + +#[test] +fn validates_origin_and_budgets_before_network_or_credentials() { + for url in ["http://127.0.0.1:18082", "http://[::1]:18082/"] { + let options = parse(&args(url)).unwrap(); + assert_eq!(options.url.path(), "/status"); + } + for url in [ + "https://127.0.0.1", + "http://localhost", + "http://192.0.2.1", + "http://key@127.0.0.1", + "http://127.0.0.1/status", + "http://127.0.0.1?key=x", + "http://127.0.0.1#x", + "http://127.0.0.1:0", + ] { + assert!(parse(&args(url)).is_err()); + } + for budget in ["0", "3601", "-1", "nan"] { + let mut args = args("http://127.0.0.1"); + args.extend(["--timeout-s".into(), budget.into()]); + assert!(parse(&args).is_err()); + } + let mut repeated = args("http://127.0.0.1"); + repeated.extend(["--model".into(), "other".into()]); + assert!(parse(&repeated).is_err()); +} diff --git a/crates/backend-api/src/scripted.rs b/crates/backend-api/src/scripted.rs index ef1741b5..2b03ec45 100644 --- a/crates/backend-api/src/scripted.rs +++ b/crates/backend-api/src/scripted.rs @@ -550,164 +550,4 @@ fn play(shared: &Shared, cancel: &AtomicBool, sink: GenerationSink, script: Scri } #[cfg(test)] -mod tests { - use super::*; - use crate::InferenceMode; - - fn config() -> RuntimeConfig { - RuntimeConfig { - load_config_version: crate::LOAD_CONFIG_VERSION, - inference_mode: InferenceMode::Native, - gpu_memory_limit_bytes: None, - allow_experimental: false, - } - } - - fn request(id: &str) -> GenerationRequest { - GenerationRequest { - request_id: id.into(), - prompt: "p".into(), - max_output_tokens: 8, - temperature_milli: 0, - sampling: Default::default(), - } - } - - fn loaded() -> (ScriptedEngine, ScriptedHandle, LoadedModel) { - let (mut engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor()); - let model = engine - .load(ScriptedEngine::fixture_descriptor(), config()) - .unwrap(); - (engine, handle, model) - } - - fn drain(stream: &mut GenerationStream) -> (Vec, bool) { - let mut events = Vec::new(); - loop { - match stream.recv() { - Ok(Some(event)) => events.push(event), - Ok(None) => return (events, true), - Err(_) => return (events, false), - } - } - } - - #[test] - fn plays_text_then_exactly_one_terminal_and_records_the_request() { - let (mut engine, handle, model) = loaded(); - let usage = Usage { - input_tokens: 3, - output_tokens: 2, - reused_input_tokens: 1, - }; - handle.push(Script::stop_with(&["a", "b"], usage.clone())); - let mut stream = engine.start_generation(&model, request("r1")).unwrap(); - let (events, terminated) = drain(&mut stream); - assert!(terminated); - assert_eq!( - events, - vec![ - GenerationEvent::TextDelta { text: "a".into() }, - GenerationEvent::TextDelta { text: "b".into() }, - GenerationEvent::Terminal(GenerationTerminal::Completed { - reason: FinishReason::Stop, - usage - }), - ] - ); - assert_eq!(handle.requests().len(), 1); - assert_eq!(handle.requests()[0].request_id, "r1"); - // The slot is free as soon as the terminal event was published. - handle.push(Script::stop_with(&[], Usage::default())); - assert!(engine.start_generation(&model, request("r2")).is_ok()); - } - - #[test] - fn refuses_a_second_concurrent_generation_unloaded_and_stale_handles() { - let (mut engine, handle, model) = loaded(); - handle.push(Script::hanging_after(&["x"])); - let _stream = engine.start_generation(&model, request("r1")).unwrap(); - assert_eq!( - engine - .start_generation(&model, request("r2")) - .err() - .unwrap() - .code, - ErrorCode::ResourceExhausted - ); - engine.cancel("r1").unwrap(); - handle.restart_engine(); - let refused = engine - .start_generation(&model, request("r3")) - .err() - .unwrap(); - assert_eq!(refused.code, ErrorCode::BackendUnavailable); - handle.reload_engine(); - // The old handle is stale after a restart even though the model is ready again. - let stale = engine - .start_generation(&model, request("r4")) - .err() - .unwrap(); - assert_eq!(stale.message, "stale model handle"); - } - - #[test] - fn cancel_ends_a_hanging_generation_with_a_cancelled_terminal() { - let (mut engine, handle, model) = loaded(); - handle.push(Script::hanging_after(&["x"])); - let mut stream = engine.start_generation(&model, request("r1")).unwrap(); - assert!(matches!( - stream.recv().unwrap(), - Some(GenerationEvent::TextDelta { .. }) - )); - engine.cancel("r1").unwrap(); - assert!(matches!( - stream.recv().unwrap(), - Some(GenerationEvent::Terminal(GenerationTerminal::Cancelled)) - )); - assert_eq!(handle.cancels(), vec!["r1".to_owned()]); - assert!(engine.cancel("r1").is_err()); - } - - #[test] - fn a_dead_engine_ends_the_stream_without_a_terminal_event() { - let (mut engine, handle, model) = loaded(); - handle.push(Script::dying_after(&["x"])); - let mut stream = engine.start_generation(&model, request("r1")).unwrap(); - let (events, terminated) = drain(&mut stream); - assert!(!terminated); - assert_eq!(events.len(), 1); - - handle.push(Script::hanging_after(&["y"])); - let mut stream = engine.start_generation(&model, request("r2")); - // r1's slot was released when the engine died, so r2 started. - let stream = stream.as_mut().unwrap(); - let _ = stream.recv(); - handle.restart_engine(); - let (_, terminated) = drain(stream); - assert!(!terminated); - } - - #[test] - fn a_responder_sees_the_request_and_dropping_the_stream_stops_the_script() { - let (mut engine, handle, model) = loaded(); - handle.respond_with(|request| { - Script::stop_with(&[request.prompt.as_str()], Usage::default()) - }); - let mut stream = engine.start_generation(&model, request("r1")).unwrap(); - let (events, _) = drain(&mut stream); - assert_eq!(events[0], GenerationEvent::TextDelta { text: "p".into() }); - drop(stream); - - handle.respond_with(|_| Script::hanging_after(&["z"])); - let stream = engine.start_generation(&model, request("r2")).unwrap(); - drop(stream); - for _ in 0..200 { - if !handle.is_generating() { - return; - } - thread::sleep(Duration::from_millis(5)); - } - panic!("a dropped stream must release the generation"); - } -} +mod tests; diff --git a/crates/backend-api/src/scripted/tests.rs b/crates/backend-api/src/scripted/tests.rs new file mode 100644 index 00000000..66a71433 --- /dev/null +++ b/crates/backend-api/src/scripted/tests.rs @@ -0,0 +1,161 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::InferenceMode; + +fn config() -> RuntimeConfig { + RuntimeConfig { + load_config_version: crate::LOAD_CONFIG_VERSION, + inference_mode: InferenceMode::Native, + gpu_memory_limit_bytes: None, + allow_experimental: false, + } +} + +fn request(id: &str) -> GenerationRequest { + GenerationRequest { + request_id: id.into(), + prompt: "p".into(), + max_output_tokens: 8, + temperature_milli: 0, + sampling: Default::default(), + } +} + +fn loaded() -> (ScriptedEngine, ScriptedHandle, LoadedModel) { + let (mut engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor()); + let model = engine + .load(ScriptedEngine::fixture_descriptor(), config()) + .unwrap(); + (engine, handle, model) +} + +fn drain(stream: &mut GenerationStream) -> (Vec, bool) { + let mut events = Vec::new(); + loop { + match stream.recv() { + Ok(Some(event)) => events.push(event), + Ok(None) => return (events, true), + Err(_) => return (events, false), + } + } +} + +#[test] +fn plays_text_then_exactly_one_terminal_and_records_the_request() { + let (mut engine, handle, model) = loaded(); + let usage = Usage { + input_tokens: 3, + output_tokens: 2, + reused_input_tokens: 1, + }; + handle.push(Script::stop_with(&["a", "b"], usage.clone())); + let mut stream = engine.start_generation(&model, request("r1")).unwrap(); + let (events, terminated) = drain(&mut stream); + assert!(terminated); + assert_eq!( + events, + vec![ + GenerationEvent::TextDelta { text: "a".into() }, + GenerationEvent::TextDelta { text: "b".into() }, + GenerationEvent::Terminal(GenerationTerminal::Completed { + reason: FinishReason::Stop, + usage + }), + ] + ); + assert_eq!(handle.requests().len(), 1); + assert_eq!(handle.requests()[0].request_id, "r1"); + // The slot is free as soon as the terminal event was published. + handle.push(Script::stop_with(&[], Usage::default())); + assert!(engine.start_generation(&model, request("r2")).is_ok()); +} + +#[test] +fn refuses_a_second_concurrent_generation_unloaded_and_stale_handles() { + let (mut engine, handle, model) = loaded(); + handle.push(Script::hanging_after(&["x"])); + let _stream = engine.start_generation(&model, request("r1")).unwrap(); + assert_eq!( + engine + .start_generation(&model, request("r2")) + .err() + .unwrap() + .code, + ErrorCode::ResourceExhausted + ); + engine.cancel("r1").unwrap(); + handle.restart_engine(); + let refused = engine + .start_generation(&model, request("r3")) + .err() + .unwrap(); + assert_eq!(refused.code, ErrorCode::BackendUnavailable); + handle.reload_engine(); + // The old handle is stale after a restart even though the model is ready again. + let stale = engine + .start_generation(&model, request("r4")) + .err() + .unwrap(); + assert_eq!(stale.message, "stale model handle"); +} + +#[test] +fn cancel_ends_a_hanging_generation_with_a_cancelled_terminal() { + let (mut engine, handle, model) = loaded(); + handle.push(Script::hanging_after(&["x"])); + let mut stream = engine.start_generation(&model, request("r1")).unwrap(); + assert!(matches!( + stream.recv().unwrap(), + Some(GenerationEvent::TextDelta { .. }) + )); + engine.cancel("r1").unwrap(); + assert!(matches!( + stream.recv().unwrap(), + Some(GenerationEvent::Terminal(GenerationTerminal::Cancelled)) + )); + assert_eq!(handle.cancels(), vec!["r1".to_owned()]); + assert!(engine.cancel("r1").is_err()); +} + +#[test] +fn a_dead_engine_ends_the_stream_without_a_terminal_event() { + let (mut engine, handle, model) = loaded(); + handle.push(Script::dying_after(&["x"])); + let mut stream = engine.start_generation(&model, request("r1")).unwrap(); + let (events, terminated) = drain(&mut stream); + assert!(!terminated); + assert_eq!(events.len(), 1); + + handle.push(Script::hanging_after(&["y"])); + let mut stream = engine.start_generation(&model, request("r2")); + // r1's slot was released when the engine died, so r2 started. + let stream = stream.as_mut().unwrap(); + let _ = stream.recv(); + handle.restart_engine(); + let (_, terminated) = drain(stream); + assert!(!terminated); +} + +#[test] +fn a_responder_sees_the_request_and_dropping_the_stream_stops_the_script() { + let (mut engine, handle, model) = loaded(); + handle.respond_with(|request| { + Script::stop_with(&[request.prompt.as_str()], Usage::default()) + }); + let mut stream = engine.start_generation(&model, request("r1")).unwrap(); + let (events, _) = drain(&mut stream); + assert_eq!(events[0], GenerationEvent::TextDelta { text: "p".into() }); + drop(stream); + + handle.respond_with(|_| Script::hanging_after(&["z"])); + let stream = engine.start_generation(&model, request("r2")).unwrap(); + drop(stream); + for _ in 0..200 { + if !handle.is_generating() { + return; + } + thread::sleep(Duration::from_millis(5)); + } + panic!("a dropped stream must release the generation"); +} diff --git a/crates/context/src/context_policy.rs b/crates/context/src/context_policy.rs index 14f5f45c..fe706acc 100644 --- a/crates/context/src/context_policy.rs +++ b/crates/context/src/context_policy.rs @@ -292,137 +292,4 @@ pub fn resolve_context(req: &ContextRequest) -> Result ContextRequest { - ContextRequest::new(slots, ctx, fmt, vram) - } - - #[test] - fn two_by_256k_needs_no_scaling_one_by_512k_needs_yarn_2() { - let a = resolve_context(&req(2, 262_144, KvFormat::Q4_0, 32 * GIB)).unwrap(); - assert!(!a.rope_active); - assert_eq!(a.total_cells, 524_288); - assert_eq!(a.rope_table_rows, 262_144); - let b = resolve_context(&req(1, 524_288, KvFormat::Q4_0, 32 * GIB)).unwrap(); - assert!(b.rope_active); - assert_eq!(b.rope.kind, RopeScalingType::YaRN); - assert_eq!(b.rope.factor, 2.0); - assert_eq!(b.rope.ext_factor, 1.0); - assert_eq!(b.total_cells, 524_288); - assert_eq!(b.rope_table_bytes, 134_217_728); - // identical planner view of the KV: same total cells; the state differs by the slot count - assert_eq!(a.plan.kv_bytes, b.plan.kv_bytes); - assert_eq!(a.plan.state_bytes, 2 * b.plan.state_bytes); - } - - #[test] - fn int8_does_not_close_on_the_default_pool_but_does_on_32_gib() { - let small = resolve_context(&req(1, 524_288, KvFormat::Int8, 5_943_000_000)).unwrap_err(); - assert!(small.is_planner_rejection()); - assert!( - small - .to_string() - .starts_with("max-context 524288 needs 6962774016 B of the 5943000000 B VRAM pool") - ); - assert!(resolve_context(&req(1, 524_288, KvFormat::Int8, 32 * GIB)).is_ok()); - } - - #[test] - fn explicit_none_past_trained_is_refused() { - let mut r = req(1, 524_288, KvFormat::Q4_0, 32 * GIB); - r.rope_scaling = Some(RopeScalingType::None); - assert_eq!( - resolve_context(&r), - Err(PolicyError::Setup(SetupRopeError::NoneBeyondTrained)) - ); - // per-slot, not total: 2 x 256K with explicit none is fine - let mut r = req(2, 262_144, KvFormat::Q4_0, 32 * GIB); - r.rope_scaling = Some(RopeScalingType::None); - assert!(resolve_context(&r).is_ok()); - } - - #[test] - fn stray_scale_inside_trained_range_is_refused() { - let mut r = req(2, 262_144, KvFormat::Q4_0, 32 * GIB); - r.rope_scale = Some(2.0); - assert_eq!( - resolve_context(&r), - Err(PolicyError::Setup(SetupRopeError::ScaleWithoutMethod)) - ); - } - - #[test] - fn explicit_method_and_factor_are_kept_verbatim() { - let mut r = req(1, 524_288, KvFormat::Q4_0, 32 * GIB); - r.rope_scaling = Some(RopeScalingType::Linear); - r.rope_scale = Some(3.0); - let e = resolve_context(&r).unwrap(); - assert_eq!(e.rope.kind, RopeScalingType::Linear); - assert_eq!(e.rope.factor, 3.0); - assert_eq!(e.rope.ext_factor, 0.0); - } - - #[test] - fn request_errors() { - assert_eq!( - resolve_context(&req(0, 1, KvFormat::Int8, GIB)), - Err(PolicyError::ZeroSlots) - ); - assert_eq!( - resolve_context(&req(1, 0, KvFormat::Int8, GIB)), - Err(PolicyError::ZeroContext) - ); - assert!(matches!( - resolve_context(&req(1, 524_289, KvFormat::Int8, 64 * GIB)), - Err(PolicyError::ContextTooLarge { .. }) - )); - let mut r = req(1, 262_144, KvFormat::Int8Keyless, 32 * GIB); - assert_eq!( - resolve_context(&r), - Err(PolicyError::ExperimentalKvFormat(KvFormat::Int8Keyless)) - ); - r.allow_experimental = true; - assert!(resolve_context(&r).is_ok()); - // slot multiplication overflow is reported, not wrapped - assert_eq!( - resolve_context(&req(u64::MAX, 2, KvFormat::Int8, GIB)), - Err(PolicyError::Plan(PlanError::Overflow)) - ); - } - - #[test] - fn bad_rope_knobs_are_refused() { - let mut r = req(1, 524_288, KvFormat::Q4_0, 32 * GIB); - r.rope_knobs.yarn_beta_fast = f64::NAN; - assert_eq!( - resolve_context(&r), - Err(PolicyError::Rope(RopeKnobError::NotFinite)) - ); - } - - #[test] - fn state_scales_with_slots_and_override_is_respected() { - let one = resolve_context(&req(1, 65_536, KvFormat::Int8, 12_000_000_000)).unwrap(); - let two = resolve_context(&req(2, 65_536, KvFormat::Int8, 12_000_000_000)).unwrap(); - assert_eq!(two.plan.state_bytes, 2 * one.plan.state_bytes); - let mut r = req(2, 65_536, KvFormat::Int8, 12_000_000_000); - r.vram.state_bytes_per_slot = Some(1); - assert_eq!(resolve_context(&r).unwrap().plan.state_bytes, 2); - } - - #[test] - fn advisory_flags_the_indexer_term_gap() { - // Q4_0 1 x 512K on 8 GB: planner is the judge; the advisory only annotates - let e = resolve_context(&req(1, 524_288, KvFormat::Q4_0, 6_100_000_000)); - if let Ok(e) = e { - assert_eq!( - e.engine_estimate_exceeds_pool, - e.engine_estimate.total > e.plan.vram_budget - ); - } - } -} +mod tests; diff --git a/crates/context/src/context_policy/tests.rs b/crates/context/src/context_policy/tests.rs new file mode 100644 index 00000000..ab002037 --- /dev/null +++ b/crates/context/src/context_policy/tests.rs @@ -0,0 +1,134 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +const GIB: u64 = 1 << 30; + +fn req(slots: u64, ctx: u64, fmt: KvFormat, vram: u64) -> ContextRequest { + ContextRequest::new(slots, ctx, fmt, vram) +} + +#[test] +fn two_by_256k_needs_no_scaling_one_by_512k_needs_yarn_2() { + let a = resolve_context(&req(2, 262_144, KvFormat::Q4_0, 32 * GIB)).unwrap(); + assert!(!a.rope_active); + assert_eq!(a.total_cells, 524_288); + assert_eq!(a.rope_table_rows, 262_144); + let b = resolve_context(&req(1, 524_288, KvFormat::Q4_0, 32 * GIB)).unwrap(); + assert!(b.rope_active); + assert_eq!(b.rope.kind, RopeScalingType::YaRN); + assert_eq!(b.rope.factor, 2.0); + assert_eq!(b.rope.ext_factor, 1.0); + assert_eq!(b.total_cells, 524_288); + assert_eq!(b.rope_table_bytes, 134_217_728); + // identical planner view of the KV: same total cells; the state differs by the slot count + assert_eq!(a.plan.kv_bytes, b.plan.kv_bytes); + assert_eq!(a.plan.state_bytes, 2 * b.plan.state_bytes); +} + +#[test] +fn int8_does_not_close_on_the_default_pool_but_does_on_32_gib() { + let small = resolve_context(&req(1, 524_288, KvFormat::Int8, 5_943_000_000)).unwrap_err(); + assert!(small.is_planner_rejection()); + assert!( + small + .to_string() + .starts_with("max-context 524288 needs 6962774016 B of the 5943000000 B VRAM pool") + ); + assert!(resolve_context(&req(1, 524_288, KvFormat::Int8, 32 * GIB)).is_ok()); +} + +#[test] +fn explicit_none_past_trained_is_refused() { + let mut r = req(1, 524_288, KvFormat::Q4_0, 32 * GIB); + r.rope_scaling = Some(RopeScalingType::None); + assert_eq!( + resolve_context(&r), + Err(PolicyError::Setup(SetupRopeError::NoneBeyondTrained)) + ); + // per-slot, not total: 2 x 256K with explicit none is fine + let mut r = req(2, 262_144, KvFormat::Q4_0, 32 * GIB); + r.rope_scaling = Some(RopeScalingType::None); + assert!(resolve_context(&r).is_ok()); +} + +#[test] +fn stray_scale_inside_trained_range_is_refused() { + let mut r = req(2, 262_144, KvFormat::Q4_0, 32 * GIB); + r.rope_scale = Some(2.0); + assert_eq!( + resolve_context(&r), + Err(PolicyError::Setup(SetupRopeError::ScaleWithoutMethod)) + ); +} + +#[test] +fn explicit_method_and_factor_are_kept_verbatim() { + let mut r = req(1, 524_288, KvFormat::Q4_0, 32 * GIB); + r.rope_scaling = Some(RopeScalingType::Linear); + r.rope_scale = Some(3.0); + let e = resolve_context(&r).unwrap(); + assert_eq!(e.rope.kind, RopeScalingType::Linear); + assert_eq!(e.rope.factor, 3.0); + assert_eq!(e.rope.ext_factor, 0.0); +} + +#[test] +fn request_errors() { + assert_eq!( + resolve_context(&req(0, 1, KvFormat::Int8, GIB)), + Err(PolicyError::ZeroSlots) + ); + assert_eq!( + resolve_context(&req(1, 0, KvFormat::Int8, GIB)), + Err(PolicyError::ZeroContext) + ); + assert!(matches!( + resolve_context(&req(1, 524_289, KvFormat::Int8, 64 * GIB)), + Err(PolicyError::ContextTooLarge { .. }) + )); + let mut r = req(1, 262_144, KvFormat::Int8Keyless, 32 * GIB); + assert_eq!( + resolve_context(&r), + Err(PolicyError::ExperimentalKvFormat(KvFormat::Int8Keyless)) + ); + r.allow_experimental = true; + assert!(resolve_context(&r).is_ok()); + // slot multiplication overflow is reported, not wrapped + assert_eq!( + resolve_context(&req(u64::MAX, 2, KvFormat::Int8, GIB)), + Err(PolicyError::Plan(PlanError::Overflow)) + ); +} + +#[test] +fn bad_rope_knobs_are_refused() { + let mut r = req(1, 524_288, KvFormat::Q4_0, 32 * GIB); + r.rope_knobs.yarn_beta_fast = f64::NAN; + assert_eq!( + resolve_context(&r), + Err(PolicyError::Rope(RopeKnobError::NotFinite)) + ); +} + +#[test] +fn state_scales_with_slots_and_override_is_respected() { + let one = resolve_context(&req(1, 65_536, KvFormat::Int8, 12_000_000_000)).unwrap(); + let two = resolve_context(&req(2, 65_536, KvFormat::Int8, 12_000_000_000)).unwrap(); + assert_eq!(two.plan.state_bytes, 2 * one.plan.state_bytes); + let mut r = req(2, 65_536, KvFormat::Int8, 12_000_000_000); + r.vram.state_bytes_per_slot = Some(1); + assert_eq!(resolve_context(&r).unwrap().plan.state_bytes, 2); +} + +#[test] +fn advisory_flags_the_indexer_term_gap() { + // Q4_0 1 x 512K on 8 GB: planner is the judge; the advisory only annotates + let e = resolve_context(&req(1, 524_288, KvFormat::Q4_0, 6_100_000_000)); + if let Ok(e) = e { + assert_eq!( + e.engine_estimate_exceeds_pool, + e.engine_estimate.total > e.plan.vram_budget + ); + } +} diff --git a/crates/context/src/geometry.rs b/crates/context/src/geometry.rs index 8bf3b739..192ce4a5 100644 --- a/crates/context/src/geometry.rs +++ b/crates/context/src/geometry.rs @@ -278,144 +278,4 @@ pub const RESIDENT_RUNS: [usize; 4] = [16_777_216, 16_777_216, 524_288, 524_288] pub const RESIDENT_RUNS_BYTES: usize = 34_603_008; #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn trained_geometry_reproduces_every_frozen_literal() { - let g = QsaGeometry::TRAINED; - assert_eq!(g.cells(), 262_144); - assert_eq!(g.pages(), 65_536); - assert_eq!(g.page_table_bytes(), 262_144); - assert_eq!(g.pooled_rows(), 65_537); // qsa_prompt_index SIZES[0] = 65537 * 128 * 4 - assert_eq!(g.max_blocks(), 65_538); // qsa_prompt_index MAX_BLOCKS - assert_eq!(g.host_payload_bytes(), Ok(276_824_064)); // QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES - assert_eq!(g.mapped_host_bytes(), Ok(276_825_088)); // QSA_PROMPT_MAPPED_HOST_BYTES, host BYTES - assert_eq!( - g.stage_runs(), - Ok([134_217_728, 134_217_728, 4_194_304, 4_194_304]) - ); - assert_eq!( - g.stage_offsets(), - Ok([0, 134_217_728, 268_435_456, 272_629_760]) - ); - assert_eq!(g.stage_bytes(), Ok(277_086_212)); // QSA_PROMPT_STAGE_BYTES - assert_eq!(g.resident_bytes(0), Ok(34_865_152)); // QSA_PROMPT_RESIDENT_BYTES - MAP_BYTES - assert_eq!(g.canonical_metadata_bytes(), Ok(65_536 * 160 + 4096)); - assert_eq!(g.index_image_bytes(), Ok((65_536 + 1) * 128 * 4 + 2048)); - assert_eq!(RESIDENT_RUNS.iter().sum::(), RESIDENT_RUNS_BYTES); - assert_eq!(RESIDENT_RUNS[0], RESIDENT_PAGES * 2048); - assert_eq!(RESIDENT_RUNS[2], RESIDENT_PAGES * 64); - assert_eq!(g.rope_table_bytes(64), Ok(67_108_864)); - } - - #[test] - fn resident_window_follows_kv_plan_and_reproduces_the_frozen_pool_at_the_default() { - let g = QsaGeometry::TRAINED; - assert_eq!( - g.resident_pages_for(KV_RESIDENT_DEFAULT_CELLS), - Ok(RESIDENT_PAGES) - ); - assert_eq!(resident_runs(RESIDENT_PAGES), Ok(RESIDENT_RUNS)); - assert_eq!(stream_map_bytes(RESIDENT_PAGES), Ok(163_904)); - assert_eq!( - g.resident_bytes_with(RESIDENT_PAGES, 163_904), - g.resident_bytes(163_904) - ); - // max(resident, qsa_kv_resident_min()) rounded up to whole pages - assert_eq!(g.resident_pages_for(1), Ok(5120)); - assert_eq!(g.resident_pages_for(20_480), Ok(5120)); - assert_eq!(g.resident_pages_for(20_481), Ok(5121)); - // 0: the whole context resident - assert_eq!(g.resident_pages_for(0), Ok(65_536)); - assert_eq!( - QsaGeometry::new(MAX_CELLS).unwrap().resident_pages_for(0), - Ok(131_072) - ); - // a tiny context cannot be fully resident with fewer slots than the resolve block - assert_eq!( - QsaGeometry::new(1024).unwrap().resident_pages_for(0), - Err(GeometryError::Resident(0)) - ); - assert_eq!( - g.resident_pages_for(MAX_CELLS + 4), - Err(GeometryError::Resident(MAX_CELLS + 4)) - ); - // production profile: 12 layers x (32768 cells x 1056 B) of VRAM KV - assert_eq!( - resident_runs(RESIDENT_PAGES).unwrap().iter().sum::(), - 32_768 * KV_CELL_BYTES - ); - } - - #[test] - fn production_profile_footprint() { - // --max-context 262144 --kv int8 --kv-resident 32768 (the default here) - let f = QsaGeometry::TRAINED.kv_stream_footprint(32_768).unwrap(); - assert_eq!(f.resident_pages, 8192); - assert_eq!(f.layer_vram_bytes, 34_603_008 + 262_144 + 163_904); - assert_eq!(f.vram_bytes, 12 * 35_029_056); - assert_eq!(f.pinned_host_bytes, 12 * 276_825_088); - assert_eq!(f.stage_bytes, 277_086_212); - // the smallest window frees 12 x 3072 pages x 4224 B of VRAM for expert slots - let small = QsaGeometry::TRAINED.kv_stream_footprint(20_480).unwrap(); - assert_eq!(f.vram_bytes - small.vram_bytes, 12 * 3072 * (4224 + 20)); - assert!( - f.to_string() - .starts_with("kv int8 context=262144 resident=32768 cells (8192 pages/layer)") - ); - } - - #[test] - fn run_cell_bytes_are_the_original_kv_cell() { - assert_eq!(RUN_CELL_BYTES.iter().sum::(), KV_CELL_BYTES); - // PAGE bytes of the host image: a page of 4 cells - assert_eq!(PAGE_CELLS * KV_CELL_BYTES, 4224); - } - - #[test] - fn charter_512k_scales_every_cell_linear_size_by_exactly_two() { - let a = QsaGeometry::TRAINED; - let b = QsaGeometry::new(MAX_CELLS).unwrap(); - assert_eq!(b.pages(), 131_072); - assert_eq!(b.page_table_bytes(), 524_288); - assert_eq!( - b.host_payload_bytes().unwrap(), - 2 * a.host_payload_bytes().unwrap() - ); - assert_eq!(b.mapped_host_bytes(), Ok(553_649_152)); - assert_eq!( - b.stage_runs(), - Ok([268_435_456, 268_435_456, 8_388_608, 8_388_608]) - ); - assert_eq!( - b.stage_offsets(), - Ok([0, 268_435_456, 536_870_912, 545_259_520]) - ); - // staging pool: runs + table + status - assert_eq!(b.stage_bytes(), Ok(2 * 276_824_064 + 524_288 + 4)); - // the resident runs do not grow, only the table does - assert_eq!(b.resident_bytes(0), Ok(RESIDENT_RUNS_BYTES + 524_288)); - assert_eq!(b.rope_table_bytes(64), Ok(134_217_728)); - // 12 layers of mapped host memory (NativeQsaResources::mapped) - assert_eq!(12 * b.mapped_host_bytes().unwrap(), 6_643_789_824); - } - - #[test] - fn invalid_cell_counts_are_refused() { - for n in [0, 1, 3, 262_145, MAX_CELLS + 4] { - assert_eq!(QsaGeometry::new(n), Err(GeometryError::Cells(n))); - } - assert!(QsaGeometry::new(4).is_ok()); - assert!(QsaGeometry::new(393_216).is_ok()); - } - - #[test] - fn boundary_positions_against_the_cell_count() { - for (cells, last, one_past) in [(262_144, 262_143, 262_144), (524_288, 524_287, 524_288)] { - let g = QsaGeometry::new(cells).unwrap(); - assert!(g.admits_end(last + 1), "position {last} is the last cell"); - assert!(!g.admits_end(one_past + 1), "position {one_past} is out"); - } - } -} +mod tests; diff --git a/crates/context/src/geometry/tests.rs b/crates/context/src/geometry/tests.rs new file mode 100644 index 00000000..fb172af3 --- /dev/null +++ b/crates/context/src/geometry/tests.rs @@ -0,0 +1,141 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn trained_geometry_reproduces_every_frozen_literal() { + let g = QsaGeometry::TRAINED; + assert_eq!(g.cells(), 262_144); + assert_eq!(g.pages(), 65_536); + assert_eq!(g.page_table_bytes(), 262_144); + assert_eq!(g.pooled_rows(), 65_537); // qsa_prompt_index SIZES[0] = 65537 * 128 * 4 + assert_eq!(g.max_blocks(), 65_538); // qsa_prompt_index MAX_BLOCKS + assert_eq!(g.host_payload_bytes(), Ok(276_824_064)); // QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES + assert_eq!(g.mapped_host_bytes(), Ok(276_825_088)); // QSA_PROMPT_MAPPED_HOST_BYTES, host BYTES + assert_eq!( + g.stage_runs(), + Ok([134_217_728, 134_217_728, 4_194_304, 4_194_304]) + ); + assert_eq!( + g.stage_offsets(), + Ok([0, 134_217_728, 268_435_456, 272_629_760]) + ); + assert_eq!(g.stage_bytes(), Ok(277_086_212)); // QSA_PROMPT_STAGE_BYTES + assert_eq!(g.resident_bytes(0), Ok(34_865_152)); // QSA_PROMPT_RESIDENT_BYTES - MAP_BYTES + assert_eq!(g.canonical_metadata_bytes(), Ok(65_536 * 160 + 4096)); + assert_eq!(g.index_image_bytes(), Ok((65_536 + 1) * 128 * 4 + 2048)); + assert_eq!(RESIDENT_RUNS.iter().sum::(), RESIDENT_RUNS_BYTES); + assert_eq!(RESIDENT_RUNS[0], RESIDENT_PAGES * 2048); + assert_eq!(RESIDENT_RUNS[2], RESIDENT_PAGES * 64); + assert_eq!(g.rope_table_bytes(64), Ok(67_108_864)); +} + +#[test] +fn resident_window_follows_kv_plan_and_reproduces_the_frozen_pool_at_the_default() { + let g = QsaGeometry::TRAINED; + assert_eq!( + g.resident_pages_for(KV_RESIDENT_DEFAULT_CELLS), + Ok(RESIDENT_PAGES) + ); + assert_eq!(resident_runs(RESIDENT_PAGES), Ok(RESIDENT_RUNS)); + assert_eq!(stream_map_bytes(RESIDENT_PAGES), Ok(163_904)); + assert_eq!( + g.resident_bytes_with(RESIDENT_PAGES, 163_904), + g.resident_bytes(163_904) + ); + // max(resident, qsa_kv_resident_min()) rounded up to whole pages + assert_eq!(g.resident_pages_for(1), Ok(5120)); + assert_eq!(g.resident_pages_for(20_480), Ok(5120)); + assert_eq!(g.resident_pages_for(20_481), Ok(5121)); + // 0: the whole context resident + assert_eq!(g.resident_pages_for(0), Ok(65_536)); + assert_eq!( + QsaGeometry::new(MAX_CELLS).unwrap().resident_pages_for(0), + Ok(131_072) + ); + // a tiny context cannot be fully resident with fewer slots than the resolve block + assert_eq!( + QsaGeometry::new(1024).unwrap().resident_pages_for(0), + Err(GeometryError::Resident(0)) + ); + assert_eq!( + g.resident_pages_for(MAX_CELLS + 4), + Err(GeometryError::Resident(MAX_CELLS + 4)) + ); + // production profile: 12 layers x (32768 cells x 1056 B) of VRAM KV + assert_eq!( + resident_runs(RESIDENT_PAGES).unwrap().iter().sum::(), + 32_768 * KV_CELL_BYTES + ); +} + +#[test] +fn production_profile_footprint() { + // --max-context 262144 --kv int8 --kv-resident 32768 (the default here) + let f = QsaGeometry::TRAINED.kv_stream_footprint(32_768).unwrap(); + assert_eq!(f.resident_pages, 8192); + assert_eq!(f.layer_vram_bytes, 34_603_008 + 262_144 + 163_904); + assert_eq!(f.vram_bytes, 12 * 35_029_056); + assert_eq!(f.pinned_host_bytes, 12 * 276_825_088); + assert_eq!(f.stage_bytes, 277_086_212); + // the smallest window frees 12 x 3072 pages x 4224 B of VRAM for expert slots + let small = QsaGeometry::TRAINED.kv_stream_footprint(20_480).unwrap(); + assert_eq!(f.vram_bytes - small.vram_bytes, 12 * 3072 * (4224 + 20)); + assert!( + f.to_string() + .starts_with("kv int8 context=262144 resident=32768 cells (8192 pages/layer)") + ); +} + +#[test] +fn run_cell_bytes_are_the_original_kv_cell() { + assert_eq!(RUN_CELL_BYTES.iter().sum::(), KV_CELL_BYTES); + // PAGE bytes of the host image: a page of 4 cells + assert_eq!(PAGE_CELLS * KV_CELL_BYTES, 4224); +} + +#[test] +fn charter_512k_scales_every_cell_linear_size_by_exactly_two() { + let a = QsaGeometry::TRAINED; + let b = QsaGeometry::new(MAX_CELLS).unwrap(); + assert_eq!(b.pages(), 131_072); + assert_eq!(b.page_table_bytes(), 524_288); + assert_eq!( + b.host_payload_bytes().unwrap(), + 2 * a.host_payload_bytes().unwrap() + ); + assert_eq!(b.mapped_host_bytes(), Ok(553_649_152)); + assert_eq!( + b.stage_runs(), + Ok([268_435_456, 268_435_456, 8_388_608, 8_388_608]) + ); + assert_eq!( + b.stage_offsets(), + Ok([0, 268_435_456, 536_870_912, 545_259_520]) + ); + // staging pool: runs + table + status + assert_eq!(b.stage_bytes(), Ok(2 * 276_824_064 + 524_288 + 4)); + // the resident runs do not grow, only the table does + assert_eq!(b.resident_bytes(0), Ok(RESIDENT_RUNS_BYTES + 524_288)); + assert_eq!(b.rope_table_bytes(64), Ok(134_217_728)); + // 12 layers of mapped host memory (NativeQsaResources::mapped) + assert_eq!(12 * b.mapped_host_bytes().unwrap(), 6_643_789_824); +} + +#[test] +fn invalid_cell_counts_are_refused() { + for n in [0, 1, 3, 262_145, MAX_CELLS + 4] { + assert_eq!(QsaGeometry::new(n), Err(GeometryError::Cells(n))); + } + assert!(QsaGeometry::new(4).is_ok()); + assert!(QsaGeometry::new(393_216).is_ok()); +} + +#[test] +fn boundary_positions_against_the_cell_count() { + for (cells, last, one_past) in [(262_144, 262_143, 262_144), (524_288, 524_287, 524_288)] { + let g = QsaGeometry::new(cells).unwrap(); + assert!(g.admits_end(last + 1), "position {last} is the last cell"); + assert!(!g.admits_end(one_past + 1), "position {one_past} is out"); + } +} diff --git a/crates/context/src/memory_plan.rs b/crates/context/src/memory_plan.rs index 6ba8cb66..1d1febff 100644 --- a/crates/context/src/memory_plan.rs +++ b/crates/context/src/memory_plan.rs @@ -464,107 +464,4 @@ pub fn engine_resident_estimate( } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn real_geometry_constants() { - let g = Geometry::default(); - assert_eq!( - state_bytes(&g).unwrap(), - 36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4) - ); - assert_eq!(state_bytes(&g).unwrap(), 117_669_888); - // 12 layers x (1056 + 32) - assert_eq!(kv_bytes_per_token_int8(&g).unwrap(), 13_056); - } - - #[test] - fn per_cell_bytes_on_real_shapes() { - let s = KvShapes::real(); - assert_eq!(kv_cell_bytes(&s, KvFormat::Fp16).unwrap(), 2048); - assert_eq!(kv_cell_bytes(&s, KvFormat::Int8).unwrap(), 1056); - assert_eq!(kv_cell_bytes(&s, KvFormat::Q4_0).unwrap(), 576); - assert_eq!(kv_cell_bytes(&s, KvFormat::K8V4).unwrap(), 816); - assert_eq!(kv_cell_bytes(&s, KvFormat::Int8Keyless).unwrap(), 528); - } - - #[test] - fn int8_generic_equals_literal() { - for g in [ - Geometry::default(), - Geometry { - n_kv_heads: 4, - head_dim: 128, - n_qsa_layers: 9, - ..Geometry::default() - }, - ] { - assert_eq!( - kv_bytes_per_token(&g, KvFormat::Int8).unwrap(), - kv_bytes_per_token_int8(&g).unwrap() - ); - } - } - - #[test] - fn pool_derivation_quirks() { - let c = Costs::default(); - assert_eq!(cli_pool(12_000_000_000, &c).unwrap(), 12_000_000_000); - // derived 0 becomes the default pool - let heavy = Costs { - dense_bytes: 13_000_000_000, - ..c - }; - assert_eq!(cli_pool(12_000_000_000, &heavy).unwrap(), vram_pool_bytes()); - assert_eq!(cli_pool(0, &c).unwrap(), vram_pool_bytes()); - } - - #[test] - fn does_not_close_messages() { - let g = Geometry::default(); - let c = Costs::default(); - let e = make_plan(524_288, &g, &c, 5_943_000_000).unwrap_err(); - assert_eq!( - e.to_string(), - "max-context 524288 needs 6845104128 B of the 5943000000 B VRAM pool; reduce --max-context" - ); - // exactly full pool: zero cache slots - let exact = 13_056 * 1000; - let e = make_plan(1000, &g, &c, exact).unwrap_err(); - assert_eq!( - e.to_string(), - "no room for even one expert cache slot at max-context 1000" - ); - } - - #[test] - fn overflow_is_reported_not_wrapped() { - let g = Geometry::default(); - assert_eq!( - make_plan(u64::MAX, &g, &Costs::default(), 1), - Err(PlanError::Overflow) - ); - } - - #[test] - fn q4_makes_both_charter_profiles_close_where_int8_does_not() { - let g = Geometry::default(); - let c = Costs { - state_bytes: state_bytes(&g).unwrap(), - ..Costs::default() - }; - let pool = 5_943_000_000; - assert!(make_plan_with_format(524_288, &g, KvFormat::Int8, &c, pool).is_err()); - assert!(make_plan_with_format(524_288, &g, KvFormat::Q4_0, &c, pool).is_ok()); - } - - #[test] - fn engine_estimate_exposes_fp32_indexer_store() { - let g = Geometry::default(); - let e = engine_resident_estimate(&g, KvFormat::Int8, 1, 32_768, None).unwrap(); - // 12 layers x (3*128*4 + 128*4 + (32768/4 + 2)*128*4) bytes: the "50 MiB at 32K" of qsa.hpp - assert_eq!(e.indexer_stores, 12 * (1536 + 512 + 8194 * 512)); - assert!(e.indexer_stores > 50_000_000 && e.indexer_stores < 51_000_000); - } -} +mod tests; diff --git a/crates/context/src/memory_plan/tests.rs b/crates/context/src/memory_plan/tests.rs new file mode 100644 index 00000000..fc7e098d --- /dev/null +++ b/crates/context/src/memory_plan/tests.rs @@ -0,0 +1,104 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn real_geometry_constants() { + let g = Geometry::default(); + assert_eq!( + state_bytes(&g).unwrap(), + 36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4) + ); + assert_eq!(state_bytes(&g).unwrap(), 117_669_888); + // 12 layers x (1056 + 32) + assert_eq!(kv_bytes_per_token_int8(&g).unwrap(), 13_056); +} + +#[test] +fn per_cell_bytes_on_real_shapes() { + let s = KvShapes::real(); + assert_eq!(kv_cell_bytes(&s, KvFormat::Fp16).unwrap(), 2048); + assert_eq!(kv_cell_bytes(&s, KvFormat::Int8).unwrap(), 1056); + assert_eq!(kv_cell_bytes(&s, KvFormat::Q4_0).unwrap(), 576); + assert_eq!(kv_cell_bytes(&s, KvFormat::K8V4).unwrap(), 816); + assert_eq!(kv_cell_bytes(&s, KvFormat::Int8Keyless).unwrap(), 528); +} + +#[test] +fn int8_generic_equals_literal() { + for g in [ + Geometry::default(), + Geometry { + n_kv_heads: 4, + head_dim: 128, + n_qsa_layers: 9, + ..Geometry::default() + }, + ] { + assert_eq!( + kv_bytes_per_token(&g, KvFormat::Int8).unwrap(), + kv_bytes_per_token_int8(&g).unwrap() + ); + } +} + +#[test] +fn pool_derivation_quirks() { + let c = Costs::default(); + assert_eq!(cli_pool(12_000_000_000, &c).unwrap(), 12_000_000_000); + // derived 0 becomes the default pool + let heavy = Costs { + dense_bytes: 13_000_000_000, + ..c + }; + assert_eq!(cli_pool(12_000_000_000, &heavy).unwrap(), vram_pool_bytes()); + assert_eq!(cli_pool(0, &c).unwrap(), vram_pool_bytes()); +} + +#[test] +fn does_not_close_messages() { + let g = Geometry::default(); + let c = Costs::default(); + let e = make_plan(524_288, &g, &c, 5_943_000_000).unwrap_err(); + assert_eq!( + e.to_string(), + "max-context 524288 needs 6845104128 B of the 5943000000 B VRAM pool; reduce --max-context" + ); + // exactly full pool: zero cache slots + let exact = 13_056 * 1000; + let e = make_plan(1000, &g, &c, exact).unwrap_err(); + assert_eq!( + e.to_string(), + "no room for even one expert cache slot at max-context 1000" + ); +} + +#[test] +fn overflow_is_reported_not_wrapped() { + let g = Geometry::default(); + assert_eq!( + make_plan(u64::MAX, &g, &Costs::default(), 1), + Err(PlanError::Overflow) + ); +} + +#[test] +fn q4_makes_both_charter_profiles_close_where_int8_does_not() { + let g = Geometry::default(); + let c = Costs { + state_bytes: state_bytes(&g).unwrap(), + ..Costs::default() + }; + let pool = 5_943_000_000; + assert!(make_plan_with_format(524_288, &g, KvFormat::Int8, &c, pool).is_err()); + assert!(make_plan_with_format(524_288, &g, KvFormat::Q4_0, &c, pool).is_ok()); +} + +#[test] +fn engine_estimate_exposes_fp32_indexer_store() { + let g = Geometry::default(); + let e = engine_resident_estimate(&g, KvFormat::Int8, 1, 32_768, None).unwrap(); + // 12 layers x (3*128*4 + 128*4 + (32768/4 + 2)*128*4) bytes: the "50 MiB at 32K" of qsa.hpp + assert_eq!(e.indexer_stores, 12 * (1536 + 512 + 8194 * 512)); + assert!(e.indexer_stores > 50_000_000 && e.indexer_stores < 51_000_000); +} diff --git a/crates/context/src/rope_scaling.rs b/crates/context/src/rope_scaling.rs index 241c59b9..59c16001 100644 --- a/crates/context/src/rope_scaling.rs +++ b/crates/context/src/rope_scaling.rs @@ -671,251 +671,4 @@ pub fn setup_resolve_rope( } #[cfg(test)] -mod tests { - use super::*; - - fn yarn(factor: f64) -> RopeScaling { - RopeScaling { - kind: RopeScalingType::YaRN, - factor, - ext_factor: 1.0, - ..RopeScaling::default() - } - } - - #[test] - fn default_is_identity() { - let d = RopeScaling::default(); - assert_eq!(d.freq_scale(), 1.0); - assert_eq!(d.mscale(), 1.0); - assert_eq!(d.kernel_args(64), RopeKernelArgs::default()); - assert_eq!(d.validate(), Ok(())); - } - - #[test] - fn mscale_matches_yarn_temperature_for_factor_two() { - let s = yarn(2.0); - let want = 1.0 + 0.1 * 2.0f64.ln(); - assert!((s.mscale() - want).abs() < 1e-15); - } - - #[test] - fn corr_dims_are_clamped() { - let s = yarn(2.0); - let cd = s.corr_dims(4); - assert!(cd[0] >= 0.0 && cd[1] <= 3.0); - } - - #[test] - fn non_finite_values_are_rejected_before_range_checks() { - let mut s = yarn(2.0); - s.factor = f64::NAN; - assert_eq!(s.validate(), Err(RopeScalingError::Factor)); - s = yarn(2.0); - s.freq_base = f64::INFINITY; - assert_eq!(s.validate(), Err(RopeScalingError::FreqBase)); - s = yarn(2.0); - s.beta_slow = f64::NAN; - assert_eq!(s.validate(), Err(RopeScalingError::Betas)); - s = yarn(2.0); - s.attn_factor = f64::NAN; - assert_eq!(s.validate(), Err(RopeScalingError::AttnFactor)); - // none ignores every knob except the base - let n = RopeScaling { - factor: f64::NAN, - beta_fast: -1.0, - ..RopeScaling::default() - }; - assert_eq!(n.validate(), Ok(())); - } - - #[test] - fn table_is_prefix_stable_and_chunkable() { - let s = yarn(2.0); - let big = build_rope_table(64, &s, 300).unwrap(); - let small = build_rope_table(64, &s, 17).unwrap(); - assert_eq!(&big.cos[..small.cos.len()], &small.cos[..]); - assert_eq!(&big.sin[..small.sin.len()], &small.sin[..]); - let mut c = vec![0.0; 10 * 32]; - let mut sn = vec![0.0; 10 * 32]; - fill_rope_table(64, &s, 123, &mut c, &mut sn).unwrap(); - assert_eq!(&big.cos[123 * 32..133 * 32], &c[..]); - assert_eq!(&big.sin[123 * 32..133 * 32], &sn[..]); - } - - #[test] - fn position_zero_exposes_mscale() { - let t = build_rope_table(64, &yarn(2.0), 2).unwrap(); - let ms = yarn(2.0).mscale() as f32; - assert!(t.row_cos(0).iter().all(|&c| (c - ms).abs() <= f32::EPSILON)); - assert!(t.row_sin(0).iter().all(|&s| s == 0.0)); - } - - #[test] - fn bad_shapes_and_configs_are_refused() { - assert_eq!( - build_rope_table(63, &RopeScaling::default(), 1), - Err(RopeTableError::NRot(63)) - ); - assert_eq!( - build_rope_table(0, &RopeScaling::default(), 1), - Err(RopeTableError::NRot(0)) - ); - let bad = yarn(0.5); - assert!(matches!( - build_rope_table(64, &bad, 1), - Err(RopeTableError::Config(RopeScalingError::Factor)) - )); - let mut c = vec![0.0; 33]; - let mut s = vec![0.0; 33]; - assert_eq!( - fill_rope_table(64, &RopeScaling::default(), 0, &mut c, &mut s), - Err(RopeTableError::BufferLength) - ); - } - - #[test] - fn table_bytes_for_charter_contexts() { - assert_eq!(rope_table_bytes(64, 524_288), Some(134_217_728)); - assert_eq!(rope_table_bytes(64, 262_144), Some(67_108_864)); - } - - #[test] - fn setup_resolution_matches_setup_py() { - use RopeScalingType::{Linear, YaRN}; - let nn = Some(RopeScalingType::None); - let t = TRAINED_CONTEXT; - assert_eq!(setup_resolve_rope(t, None, None, t), Ok(None)); - assert_eq!(setup_resolve_rope(t, nn, None, t), Ok(None)); - assert_eq!( - setup_resolve_rope(t, None, Some(2.0), t), - Err(SetupRopeError::ScaleWithoutMethod) - ); - assert_eq!( - setup_resolve_rope(t, Some(Linear), None, t), - Ok(Some((Linear, 1.0))) - ); - assert_eq!( - setup_resolve_rope(524_288, None, None, t), - Ok(Some((YaRN, 2.0))) - ); - assert_eq!( - setup_resolve_rope(393_216, None, None, t), - Ok(Some((YaRN, 1.5))) - ); - assert_eq!( - setup_resolve_rope(524_288, Some(Linear), Some(3.0), t), - Ok(Some((Linear, 3.0))) - ); - assert_eq!( - setup_resolve_rope(524_288, nn, None, t), - Err(SetupRopeError::NoneBeyondTrained) - ); - } - - #[test] - fn knob_resolution_follows_generate_cpp() { - // flag absent everywhere: stock model - let r = resolve_rope_scaling(&RopeKnobs::default(), &ModelRopeKeys::default()).unwrap(); - assert_eq!(r.scaling, RopeScaling::default()); - assert!(!r.inert_knobs_ignored); - - // yarn factor 2: ext auto = 1 - let k = RopeKnobs { - scaling: Some(RopeScalingType::YaRN), - rope_scale: 2.0, - ..RopeKnobs::default() - }; - let r = resolve_rope_scaling(&k, &ModelRopeKeys::default()).unwrap(); - assert_eq!(r.scaling.kind, RopeScalingType::YaRN); - assert_eq!(r.scaling.factor, 2.0); - assert_eq!(r.scaling.ext_factor, 1.0); - - // linear: ext auto = 0 - let k = RopeKnobs { - scaling: Some(RopeScalingType::Linear), - rope_scale: 2.0, - ..RopeKnobs::default() - }; - assert_eq!( - resolve_rope_scaling(&k, &ModelRopeKeys::default()) - .unwrap() - .scaling - .ext_factor, - 0.0 - ); - - // model file supplies defaults; an explicit none opts out and notes the dropped knobs - let model = ModelRopeKeys { - scaling_type: Some("yarn".into()), - factor: 2.0, - freq_base: 5e6, - orig_ctx: 131_072.0, - }; - let r = resolve_rope_scaling(&RopeKnobs::default(), &model).unwrap(); - assert_eq!(r.scaling.kind, RopeScalingType::YaRN); - assert_eq!(r.scaling.factor, 2.0); - assert_eq!(r.scaling.freq_base, 5e6); - assert_eq!(r.scaling.orig_ctx, 131_072.0); - let k = RopeKnobs { - scaling: Some(RopeScalingType::None), - rope_scale: 2.0, - ..RopeKnobs::default() - }; - let r = resolve_rope_scaling(&k, &model).unwrap(); - assert_eq!(r.scaling.kind, RopeScalingType::None); - assert_eq!(r.scaling.freq_base, 5e6); - assert_eq!(r.scaling.factor, 1.0); - assert!(r.inert_knobs_ignored); - - // refusals - let bad_scale = RopeKnobs { - rope_scale: 0.5, - ..RopeKnobs::default() - }; - assert_eq!( - resolve_rope_scaling(&bad_scale, &model), - Err(RopeKnobError::ScaleBelowOne) - ); - let nan = RopeKnobs { - yarn_beta_fast: f64::NAN, - ..RopeKnobs::default() - }; - assert_eq!( - resolve_rope_scaling(&nan, &model), - Err(RopeKnobError::NotFinite) - ); - let base1 = RopeKnobs { - rope_freq_base: 1.0, - ..RopeKnobs::default() - }; - assert_eq!( - resolve_rope_scaling(&base1, &model), - Err(RopeKnobError::FreqBase) - ); - let neg = RopeKnobs { - yarn_attn_factor: 0.0, - ..RopeKnobs::default() - }; - assert_eq!(resolve_rope_scaling(&neg, &model), Err(RopeKnobError::Knob)); - let weird = ModelRopeKeys { - scaling_type: Some("longrope".into()), - ..ModelRopeKeys::default() - }; - assert_eq!( - resolve_rope_scaling(&RopeKnobs::default(), &weird), - Err(RopeKnobError::ModelType("longrope".into())) - ); - // a resolved factor that is fine per-flag but invalid as a whole - let k = RopeKnobs { - scaling: Some(RopeScalingType::YaRN), - rope_scale: 2.0, - rope_freq_scale: 1e6, - ..RopeKnobs::default() - }; - assert_eq!( - resolve_rope_scaling(&k, &ModelRopeKeys::default()), - Err(RopeKnobError::Invalid(RopeScalingError::Mscale)) - ); - } -} +mod tests; diff --git a/crates/context/src/rope_scaling/tests.rs b/crates/context/src/rope_scaling/tests.rs new file mode 100644 index 00000000..4bdf06cd --- /dev/null +++ b/crates/context/src/rope_scaling/tests.rs @@ -0,0 +1,248 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn yarn(factor: f64) -> RopeScaling { + RopeScaling { + kind: RopeScalingType::YaRN, + factor, + ext_factor: 1.0, + ..RopeScaling::default() + } +} + +#[test] +fn default_is_identity() { + let d = RopeScaling::default(); + assert_eq!(d.freq_scale(), 1.0); + assert_eq!(d.mscale(), 1.0); + assert_eq!(d.kernel_args(64), RopeKernelArgs::default()); + assert_eq!(d.validate(), Ok(())); +} + +#[test] +fn mscale_matches_yarn_temperature_for_factor_two() { + let s = yarn(2.0); + let want = 1.0 + 0.1 * 2.0f64.ln(); + assert!((s.mscale() - want).abs() < 1e-15); +} + +#[test] +fn corr_dims_are_clamped() { + let s = yarn(2.0); + let cd = s.corr_dims(4); + assert!(cd[0] >= 0.0 && cd[1] <= 3.0); +} + +#[test] +fn non_finite_values_are_rejected_before_range_checks() { + let mut s = yarn(2.0); + s.factor = f64::NAN; + assert_eq!(s.validate(), Err(RopeScalingError::Factor)); + s = yarn(2.0); + s.freq_base = f64::INFINITY; + assert_eq!(s.validate(), Err(RopeScalingError::FreqBase)); + s = yarn(2.0); + s.beta_slow = f64::NAN; + assert_eq!(s.validate(), Err(RopeScalingError::Betas)); + s = yarn(2.0); + s.attn_factor = f64::NAN; + assert_eq!(s.validate(), Err(RopeScalingError::AttnFactor)); + // none ignores every knob except the base + let n = RopeScaling { + factor: f64::NAN, + beta_fast: -1.0, + ..RopeScaling::default() + }; + assert_eq!(n.validate(), Ok(())); +} + +#[test] +fn table_is_prefix_stable_and_chunkable() { + let s = yarn(2.0); + let big = build_rope_table(64, &s, 300).unwrap(); + let small = build_rope_table(64, &s, 17).unwrap(); + assert_eq!(&big.cos[..small.cos.len()], &small.cos[..]); + assert_eq!(&big.sin[..small.sin.len()], &small.sin[..]); + let mut c = vec![0.0; 10 * 32]; + let mut sn = vec![0.0; 10 * 32]; + fill_rope_table(64, &s, 123, &mut c, &mut sn).unwrap(); + assert_eq!(&big.cos[123 * 32..133 * 32], &c[..]); + assert_eq!(&big.sin[123 * 32..133 * 32], &sn[..]); +} + +#[test] +fn position_zero_exposes_mscale() { + let t = build_rope_table(64, &yarn(2.0), 2).unwrap(); + let ms = yarn(2.0).mscale() as f32; + assert!(t.row_cos(0).iter().all(|&c| (c - ms).abs() <= f32::EPSILON)); + assert!(t.row_sin(0).iter().all(|&s| s == 0.0)); +} + +#[test] +fn bad_shapes_and_configs_are_refused() { + assert_eq!( + build_rope_table(63, &RopeScaling::default(), 1), + Err(RopeTableError::NRot(63)) + ); + assert_eq!( + build_rope_table(0, &RopeScaling::default(), 1), + Err(RopeTableError::NRot(0)) + ); + let bad = yarn(0.5); + assert!(matches!( + build_rope_table(64, &bad, 1), + Err(RopeTableError::Config(RopeScalingError::Factor)) + )); + let mut c = vec![0.0; 33]; + let mut s = vec![0.0; 33]; + assert_eq!( + fill_rope_table(64, &RopeScaling::default(), 0, &mut c, &mut s), + Err(RopeTableError::BufferLength) + ); +} + +#[test] +fn table_bytes_for_charter_contexts() { + assert_eq!(rope_table_bytes(64, 524_288), Some(134_217_728)); + assert_eq!(rope_table_bytes(64, 262_144), Some(67_108_864)); +} + +#[test] +fn setup_resolution_matches_setup_py() { + use RopeScalingType::{Linear, YaRN}; + let nn = Some(RopeScalingType::None); + let t = TRAINED_CONTEXT; + assert_eq!(setup_resolve_rope(t, None, None, t), Ok(None)); + assert_eq!(setup_resolve_rope(t, nn, None, t), Ok(None)); + assert_eq!( + setup_resolve_rope(t, None, Some(2.0), t), + Err(SetupRopeError::ScaleWithoutMethod) + ); + assert_eq!( + setup_resolve_rope(t, Some(Linear), None, t), + Ok(Some((Linear, 1.0))) + ); + assert_eq!( + setup_resolve_rope(524_288, None, None, t), + Ok(Some((YaRN, 2.0))) + ); + assert_eq!( + setup_resolve_rope(393_216, None, None, t), + Ok(Some((YaRN, 1.5))) + ); + assert_eq!( + setup_resolve_rope(524_288, Some(Linear), Some(3.0), t), + Ok(Some((Linear, 3.0))) + ); + assert_eq!( + setup_resolve_rope(524_288, nn, None, t), + Err(SetupRopeError::NoneBeyondTrained) + ); +} + +#[test] +fn knob_resolution_follows_generate_cpp() { + // flag absent everywhere: stock model + let r = resolve_rope_scaling(&RopeKnobs::default(), &ModelRopeKeys::default()).unwrap(); + assert_eq!(r.scaling, RopeScaling::default()); + assert!(!r.inert_knobs_ignored); + + // yarn factor 2: ext auto = 1 + let k = RopeKnobs { + scaling: Some(RopeScalingType::YaRN), + rope_scale: 2.0, + ..RopeKnobs::default() + }; + let r = resolve_rope_scaling(&k, &ModelRopeKeys::default()).unwrap(); + assert_eq!(r.scaling.kind, RopeScalingType::YaRN); + assert_eq!(r.scaling.factor, 2.0); + assert_eq!(r.scaling.ext_factor, 1.0); + + // linear: ext auto = 0 + let k = RopeKnobs { + scaling: Some(RopeScalingType::Linear), + rope_scale: 2.0, + ..RopeKnobs::default() + }; + assert_eq!( + resolve_rope_scaling(&k, &ModelRopeKeys::default()) + .unwrap() + .scaling + .ext_factor, + 0.0 + ); + + // model file supplies defaults; an explicit none opts out and notes the dropped knobs + let model = ModelRopeKeys { + scaling_type: Some("yarn".into()), + factor: 2.0, + freq_base: 5e6, + orig_ctx: 131_072.0, + }; + let r = resolve_rope_scaling(&RopeKnobs::default(), &model).unwrap(); + assert_eq!(r.scaling.kind, RopeScalingType::YaRN); + assert_eq!(r.scaling.factor, 2.0); + assert_eq!(r.scaling.freq_base, 5e6); + assert_eq!(r.scaling.orig_ctx, 131_072.0); + let k = RopeKnobs { + scaling: Some(RopeScalingType::None), + rope_scale: 2.0, + ..RopeKnobs::default() + }; + let r = resolve_rope_scaling(&k, &model).unwrap(); + assert_eq!(r.scaling.kind, RopeScalingType::None); + assert_eq!(r.scaling.freq_base, 5e6); + assert_eq!(r.scaling.factor, 1.0); + assert!(r.inert_knobs_ignored); + + // refusals + let bad_scale = RopeKnobs { + rope_scale: 0.5, + ..RopeKnobs::default() + }; + assert_eq!( + resolve_rope_scaling(&bad_scale, &model), + Err(RopeKnobError::ScaleBelowOne) + ); + let nan = RopeKnobs { + yarn_beta_fast: f64::NAN, + ..RopeKnobs::default() + }; + assert_eq!( + resolve_rope_scaling(&nan, &model), + Err(RopeKnobError::NotFinite) + ); + let base1 = RopeKnobs { + rope_freq_base: 1.0, + ..RopeKnobs::default() + }; + assert_eq!( + resolve_rope_scaling(&base1, &model), + Err(RopeKnobError::FreqBase) + ); + let neg = RopeKnobs { + yarn_attn_factor: 0.0, + ..RopeKnobs::default() + }; + assert_eq!(resolve_rope_scaling(&neg, &model), Err(RopeKnobError::Knob)); + let weird = ModelRopeKeys { + scaling_type: Some("longrope".into()), + ..ModelRopeKeys::default() + }; + assert_eq!( + resolve_rope_scaling(&RopeKnobs::default(), &weird), + Err(RopeKnobError::ModelType("longrope".into())) + ); + // a resolved factor that is fine per-flag but invalid as a whole + let k = RopeKnobs { + scaling: Some(RopeScalingType::YaRN), + rope_scale: 2.0, + rope_freq_scale: 1e6, + ..RopeKnobs::default() + }; + assert_eq!( + resolve_rope_scaling(&k, &ModelRopeKeys::default()), + Err(RopeKnobError::Invalid(RopeScalingError::Mscale)) + ); +} diff --git a/crates/cuda-driver/src/closed_kernels.rs b/crates/cuda-driver/src/closed_kernels.rs index a1ac98da..3fed4784 100644 --- a/crates/cuda-driver/src/closed_kernels.rs +++ b/crates/cuda-driver/src/closed_kernels.rs @@ -490,408 +490,4 @@ pub fn s_gemv_slots( } #[cfg(test)] -mod tests { - use super::*; - use crate::s_gemv_legacy as sg; - - /// `count_params`: parameter kinds of `extern "C" __global__ ... name(...)` in a `.cu` text. - fn kinds_in(source: &str, name: &str) -> Vec<&'static str> { - let at = source - .find(&format!(" {name}(")) - .unwrap_or_else(|| panic!("{name} not in source")); - let rest = &source[at + name.len() + 2..]; - let close = rest.find(") {").expect("parameter list end"); - rest[..close] - .split(',') - .map(|param| { - let p = param.trim(); - if p.contains('*') { - "ptr" - } else if p.starts_with("long long") || p.starts_with("uint64_t") { - "i64" - } else if p.starts_with("int ") { - "i32" - } else if p.starts_with("float ") { - "f32" - } else { - panic!("unrecognised parameter `{p}` of {name}") - } - }) - .collect() - } - - /// The S-form entries are generated by macros: expand the two argument macros to find their parameter kinds. - fn macro_kinds(source: &str, macro_name: &str) -> Vec<&'static str> { - let at = source - .find(&format!("#define {macro_name} ")) - .expect("macro"); - let body = source[at..] - .lines() - .take(3) - .collect::>() - .join(" ") - .replace('\\', " "); - let params = body.split_once(macro_name).unwrap().1.trim_start(); - // the macro text ends at its last parameter ("int has_offset"); stop before the next `#define` - let params = params.split("#define").next().unwrap(); - params - .split(',') - .map(|p| { - let p = p.trim(); - if p.contains('*') { - "ptr" - } else if p.starts_with("long long") { - "i64" - } else if p.starts_with("int ") { - "i32" - } else { - panic!("unrecognised macro parameter `{p}`") - } - }) - .collect() - } - - fn arg_kinds(entry: &Entry) -> Vec<&'static str> { - entry - .args - .iter() - .map(|a| match a { - Arg::Ptr | Arg::PtrOpt => "ptr", - Arg::I32 => "i32", - Arg::I64 => "i64", - Arg::F32 => "f32", - }) - .collect() - } - - #[test] - fn flash_and_poison_signatures_match_their_cuda_source() { - for program in [Program::NativeFlashAttn, Program::DevicePoison] { - for entry in program.entries() { - let name = entry.name.to_str().unwrap(); - assert_eq!(kinds_in(program.source(), name), arg_kinds(entry), "{name}"); - assert!(entry.args.len() <= MAX_ENTRY_ARGUMENTS); - } - } - assert!( - Program::NativeFlashAttn - .source() - .contains("__launch_bounds__(128, 1)") - ); - assert_eq!(flash::LAUNCH.block[0] * flash::LAUNCH.block[1], 128); - } - - #[test] - fn s_gemv_signatures_match_their_cuda_source() { - let source = Program::SGemvLegacy.source(); - let fp16 = macro_kinds(source, "LELEKA_S_FP16_ARGS"); - let q8 = macro_kinds(source, "LELEKA_S_Q8_ARGS"); - assert_eq!( - fp16, - [ - "ptr", "ptr", "ptr", "ptr", "ptr", "i64", "i64", "i32", "i32", "i32", "i32" - ] - ); - assert_eq!(q8, fp16); - for (index, entry) in S_GEMV_ENTRIES.iter().enumerate() { - let name = entry.name.to_str().unwrap(); - assert_eq!(name, Kernel::ALL_ENTRIES[index]); - let want = arg_kinds(entry); - let got: Vec<&str> = if name.starts_with("leleka_s_gemv_split_") { - // spelled out in LELEKA_S_GEMV_SPLIT: the fp16 form plus group_shift and threads_per_row - let mut k = fp16.clone(); - k.splice(10..10, ["i32"]); - k.push("i32"); - k - } else if name.starts_with("leleka_s_gemv_q8") && name.contains("split") { - q8.clone() - } else if name.starts_with("leleka_s_gemv_") { - fp16.clone() - } else { - kinds_in(source, name) - }; - assert_eq!(got, want, "{name}"); - } - } - - #[test] - fn index_constants_and_planners_point_at_the_named_entries() { - let name = |p: Program, i: usize| p.entries()[i].name.to_str().unwrap(); - assert_eq!(name(Program::NativeFlashAttn, FLASH_SHORT), flash::ENTRY); - assert_eq!( - name(Program::DevicePoison, POISON_F32), - crate::device_arena::ENTRY_POISON - ); - let form = SForm { - code_bits: 4, - code_bias: -8, - group_elems: 32, - ..SForm::default() - }; - let plan = sg::plan_s_gemv_split(512, 8, &form, 64, false) - .unwrap() - .unwrap(); - assert_eq!( - name(Program::SGemvLegacy, s_gemv_entry_index(plan.kernel)), - "leleka_s_gemv_split_4" - ); - for (i, e) in Kernel::ALL_ENTRIES.iter().enumerate() { - assert_eq!(S_GEMV_ENTRIES[i].name.to_str().unwrap(), *e); - } - } - - #[test] - fn every_planned_launch_conforms_to_its_entry() { - let forms = [ - SForm { - code_bits: 2, - code_bias: -1, - group_elems: 64, - ..SForm::default() - }, - SForm { - code_bits: 4, - code_bias: -8, - group_elems: 32, - has_offset: true, - ..SForm::default() - }, - SForm { - code_bits: 8, - code_bias: -128, - group_elems: 64, - codebook: sg::Codebook::Iq4Nl, - ..SForm::default() - }, - ]; - let mut planned = 0; - for form in forms { - for offset in [false, true] { - if form.has_offset && !offset { - continue; - } - let (n_in, n_out) = (1024, 6); - let mut plans: Vec = Vec::new(); - plans.extend(sg::plan_s_gemv(n_in, n_out, &form, offset).ok().flatten()); - plans.extend( - sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset) - .ok() - .flatten(), - ); - plans.extend(sg::plan_s_gemv_q8k(n_in, n_out, &form).ok().flatten()); - plans.extend(sg::plan_s_gemv_q8k_split(n_in, n_out, &form).ok().flatten()); - plans.extend( - sg::plan_s_gemv_q8_0_split(n_in, n_out, &form) - .ok() - .flatten(), - ); - for plan in plans { - let entry = &S_GEMV_ENTRIES[s_gemv_entry_index(plan.kernel)]; - let slots = s_gemv_slots(&plan, &form, n_in, n_out, offset); - assert!(conforms(entry, &slots), "{:?}", plan.kernel); - let bytes = s_operand_bytes(plan.kernel, &form, n_in, n_out).unwrap(); - assert_eq!(bytes.offset.is_some(), form.has_offset); - assert_eq!(bytes.y, 24); - planned += 1; - } - } - } - for plan in [ - sg::plan_s2_gemv(1024, 6).unwrap().unwrap(), - sg::plan_s2_gemv_quads(1024, 6, 64).unwrap().unwrap(), - sg::plan_s2_gemv_q8(1024, 6, 64).unwrap().unwrap(), - sg::plan_s2_gemv_fast(1024, 6, 64, true).unwrap().unwrap(), - sg::plan_s2_gemv_fast(1024, 6, 64, false).unwrap().unwrap(), - ] { - let entry = &S_GEMV_ENTRIES[s_gemv_entry_index(plan.kernel)]; - let slots = s_gemv_slots(&plan, &SForm::default(), 1024, 6, false); - assert!(conforms(entry, &slots), "{:?}", plan.kernel); - planned += 1; - } - assert!(planned >= 20, "{planned}"); - } - - #[test] - fn slot_values_follow_the_oracle_driver() { - // oracle/drivers/s_gemv_legacy.cpp: split passes (bias, codebook, group, shift_of(group), has_offset, tpr) - let form = SForm { - code_bits: 4, - code_bias: -8, - group_elems: 32, - codebook: sg::Codebook::Iq4Nl, - has_offset: true, - ..SForm::default() - }; - let plan = sg::plan_s_gemv_split(512, 8, &form, 64, true) - .unwrap() - .unwrap(); - let slots = s_gemv_slots(&plan, &form, 512, 8, true); - assert_eq!( - slots, - vec![ - Slot::Ptr(Role::X), - Slot::Ptr(Role::Codes), - Slot::Ptr(Role::Scales), - Slot::Ptr(Role::Offset), - Slot::Ptr(Role::Y), - Slot::I64(512), - Slot::I64(8), - Slot::I32(-8), - Slot::I32(1), - Slot::I32(32), - Slot::I32(5), - Slot::I32(1), - Slot::I32(64), - ] - ); - assert_eq!( - ( - plan.launch.grid, - plan.launch.block, - plan.launch.dynamic_shared - ), - ([8, 1, 1], [64, 1, 1], 256) - ); - // the Q8 split kernels take the shift in place of the group - let plan = sg::plan_s_gemv_q8k_split(512, 8, &form).unwrap().unwrap(); - let slots = s_gemv_slots(&plan, &form, 512, 8, true); - assert_eq!( - &slots[7..], - &[Slot::I32(-8), Slot::I32(1), Slot::I32(5), Slot::I32(1)] - ); - // a form without an offset passes a null offset pointer - let none = SForm { - has_offset: false, - ..form - }; - let plan = sg::plan_s_gemv(512, 8, &none, false).unwrap().unwrap(); - assert_eq!(s_gemv_slots(&plan, &none, 512, 8, false)[3], Slot::Null); - } - - #[test] - fn operand_sizes_follow_the_pack_format() { - let form = SForm { - code_bits: 4, - code_bias: -8, - group_elems: 32, - has_offset: true, - ..SForm::default() - }; - let b = s_operand_bytes(Kernel::SGemvSplit(4), &form, 512, 8).unwrap(); - assert_eq!( - (b.x, b.codes, b.scales, b.offset, b.y), - (1024, 8 * 256, 8 * 16 * 4, Some(8 * 16 * 4), 32) - ); - let b = s_operand_bytes(Kernel::SGemvQ8k(4), &form, 512, 8).unwrap(); - assert_eq!(b.x, 2 * 292); - let b = s_operand_bytes(Kernel::SGemvQ80Split(4), &form, 512, 8).unwrap(); - assert_eq!(b.x, 16 * 34); - let b = s_operand_bytes(Kernel::S2GemvQ8, &SForm::default(), 512, 8).unwrap(); - assert_eq!( - (b.x, b.codes, b.scales, b.offset), - (16 * 34, 8 * 128, 8 * 8 * 4, None) - ); - assert!(s_operand_bytes(Kernel::SGemv(2), &SForm::default(), 0, 8).is_err()); - assert!( - s_operand_bytes( - Kernel::SGemv(2), - &SForm { - group_elems: 64, - ..SForm::default() - }, - 100, - 8 - ) - .is_err() - ); - } - - #[test] - fn flash_and_poison_slots_and_sizes() { - let slots = flash_slots(256, true); - assert!(conforms(&FLASH_ENTRIES[0], &slots)); - assert_eq!( - slots[4..7], - [Slot::I32(256), Slot::I32(256), Slot::F32(0.0625)] - ); - assert_eq!(flash_slots(256, false)[9], Slot::Null); - assert!(conforms(&FLASH_ENTRIES[0], &flash_slots(7, false))); - let b = flash_bytes(4096).unwrap(); - assert_eq!( - (b.q, b.kv, b.step, b.out, b.status, b.mask), - (24576, 4096 * 1024, 16, 24576, 4, 512) - ); - assert!(flash_bytes(255).is_err()); - let slots = poison_slots(1000).unwrap(); - assert_eq!(slots, vec![Slot::Ptr(Role::Poison), Slot::I64(1000)]); - assert!(conforms(&POISON_ENTRIES[0], &slots)); - assert!(poison_slots(u64::MAX).is_err()); - // a mismatching scalar kind never conforms - assert!(!conforms( - &POISON_ENTRIES[0], - &[Slot::Ptr(Role::Poison), Slot::I32(1)] - )); - assert!(!conforms(&POISON_ENTRIES[0], &[Slot::Ptr(Role::Poison)])); - } - - #[test] - fn sealed_assets_match_their_pins_and_export_every_entry() { - use crate::sealed_ptx::test_support::{ - assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, - without_terminator, - }; - for program in Program::ALL { - // Sealed with nvcc 13.2.86 on 2026-10-15; this checks structure and the pin only (no numerical claim, - // GPU load is verified separately by the host smokes). - let ptx = program.ptx(); - let names = program.entries().iter().map(|e| e.name.to_str().unwrap()); - assert_real_sm120_ptx(program.name(), ptx, names); - assert_nvcc_13_2_86(program.name(), ptx); - let pin = program.pin(); - assert_ne!(pin.source_sha256, [0; 32], "{}", program.name()); - assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name()); - assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name()); - assert_eq!(pin.source_sha256, qwen_ffi::sha256(program.source().as_bytes()), "{}", program.name()); - assert_eq!(admit(program), Ok(()), "{}", program.name()); - // the guard still refuses every deviation, on synthetic copies of the real PTX - let refuse = Err(ExperimentalError::Unpinned(program.name())); - assert_eq!(admit_ptx(program, one_byte_corrupted(ptx), pin), refuse); - assert_eq!(admit_ptx(program, one_byte_shorter(ptx), pin), refuse); - assert_eq!(admit_ptx(program, one_byte_longer(ptx), pin), refuse); - assert_eq!(admit_ptx(program, with_embedded_nul(ptx), pin), refuse); - assert_eq!(admit_ptx(program, without_terminator(ptx), pin), refuse); - let mut wrong_digest = *pin; - wrong_digest.ptx_sha256[0] ^= 1; - assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse); - for zeroed in [ - PtxPin { source_sha256: [0; 32], ..*pin }, - PtxPin { ptx_sha256: [0; 32], ..*pin }, - ] { - assert_eq!(admit_ptx(program, ptx, &zeroed), refuse); - } - } - // a matching pin admits; any difference refuses - static GOOD: &[u8] = b".version 8.7\n.target sm_120\n\0"; - let pin = PtxPin { - source_sha256: [1; 32], - ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]), - }; - assert_eq!(admit_ptx(Program::DevicePoison, GOOD, &pin), Ok(())); - let wrong = PtxPin { - ptx_sha256: [2; 32], - ..pin - }; - assert!(admit_ptx(Program::DevicePoison, GOOD, &wrong).is_err()); - assert!( - admit_ptx( - Program::DevicePoison, - GOOD, - &PtxPin { - source_sha256: [0; 32], - ..pin - } - ) - .is_err() - ); - } -} +mod tests; diff --git a/crates/cuda-driver/src/closed_kernels/tests.rs b/crates/cuda-driver/src/closed_kernels/tests.rs new file mode 100644 index 00000000..b44ae45a --- /dev/null +++ b/crates/cuda-driver/src/closed_kernels/tests.rs @@ -0,0 +1,405 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::s_gemv_legacy as sg; + +/// `count_params`: parameter kinds of `extern "C" __global__ ... name(...)` in a `.cu` text. +fn kinds_in(source: &str, name: &str) -> Vec<&'static str> { + let at = source + .find(&format!(" {name}(")) + .unwrap_or_else(|| panic!("{name} not in source")); + let rest = &source[at + name.len() + 2..]; + let close = rest.find(") {").expect("parameter list end"); + rest[..close] + .split(',') + .map(|param| { + let p = param.trim(); + if p.contains('*') { + "ptr" + } else if p.starts_with("long long") || p.starts_with("uint64_t") { + "i64" + } else if p.starts_with("int ") { + "i32" + } else if p.starts_with("float ") { + "f32" + } else { + panic!("unrecognised parameter `{p}` of {name}") + } + }) + .collect() +} + +/// The S-form entries are generated by macros: expand the two argument macros to find their parameter kinds. +fn macro_kinds(source: &str, macro_name: &str) -> Vec<&'static str> { + let at = source + .find(&format!("#define {macro_name} ")) + .expect("macro"); + let body = source[at..] + .lines() + .take(3) + .collect::>() + .join(" ") + .replace('\\', " "); + let params = body.split_once(macro_name).unwrap().1.trim_start(); + // the macro text ends at its last parameter ("int has_offset"); stop before the next `#define` + let params = params.split("#define").next().unwrap(); + params + .split(',') + .map(|p| { + let p = p.trim(); + if p.contains('*') { + "ptr" + } else if p.starts_with("long long") { + "i64" + } else if p.starts_with("int ") { + "i32" + } else { + panic!("unrecognised macro parameter `{p}`") + } + }) + .collect() +} + +fn arg_kinds(entry: &Entry) -> Vec<&'static str> { + entry + .args + .iter() + .map(|a| match a { + Arg::Ptr | Arg::PtrOpt => "ptr", + Arg::I32 => "i32", + Arg::I64 => "i64", + Arg::F32 => "f32", + }) + .collect() +} + +#[test] +fn flash_and_poison_signatures_match_their_cuda_source() { + for program in [Program::NativeFlashAttn, Program::DevicePoison] { + for entry in program.entries() { + let name = entry.name.to_str().unwrap(); + assert_eq!(kinds_in(program.source(), name), arg_kinds(entry), "{name}"); + assert!(entry.args.len() <= MAX_ENTRY_ARGUMENTS); + } + } + assert!( + Program::NativeFlashAttn + .source() + .contains("__launch_bounds__(128, 1)") + ); + assert_eq!(flash::LAUNCH.block[0] * flash::LAUNCH.block[1], 128); +} + +#[test] +fn s_gemv_signatures_match_their_cuda_source() { + let source = Program::SGemvLegacy.source(); + let fp16 = macro_kinds(source, "LELEKA_S_FP16_ARGS"); + let q8 = macro_kinds(source, "LELEKA_S_Q8_ARGS"); + assert_eq!( + fp16, + [ + "ptr", "ptr", "ptr", "ptr", "ptr", "i64", "i64", "i32", "i32", "i32", "i32" + ] + ); + assert_eq!(q8, fp16); + for (index, entry) in S_GEMV_ENTRIES.iter().enumerate() { + let name = entry.name.to_str().unwrap(); + assert_eq!(name, Kernel::ALL_ENTRIES[index]); + let want = arg_kinds(entry); + let got: Vec<&str> = if name.starts_with("leleka_s_gemv_split_") { + // spelled out in LELEKA_S_GEMV_SPLIT: the fp16 form plus group_shift and threads_per_row + let mut k = fp16.clone(); + k.splice(10..10, ["i32"]); + k.push("i32"); + k + } else if name.starts_with("leleka_s_gemv_q8") && name.contains("split") { + q8.clone() + } else if name.starts_with("leleka_s_gemv_") { + fp16.clone() + } else { + kinds_in(source, name) + }; + assert_eq!(got, want, "{name}"); + } +} + +#[test] +fn index_constants_and_planners_point_at_the_named_entries() { + let name = |p: Program, i: usize| p.entries()[i].name.to_str().unwrap(); + assert_eq!(name(Program::NativeFlashAttn, FLASH_SHORT), flash::ENTRY); + assert_eq!( + name(Program::DevicePoison, POISON_F32), + crate::device_arena::ENTRY_POISON + ); + let form = SForm { + code_bits: 4, + code_bias: -8, + group_elems: 32, + ..SForm::default() + }; + let plan = sg::plan_s_gemv_split(512, 8, &form, 64, false) + .unwrap() + .unwrap(); + assert_eq!( + name(Program::SGemvLegacy, s_gemv_entry_index(plan.kernel)), + "leleka_s_gemv_split_4" + ); + for (i, e) in Kernel::ALL_ENTRIES.iter().enumerate() { + assert_eq!(S_GEMV_ENTRIES[i].name.to_str().unwrap(), *e); + } +} + +#[test] +fn every_planned_launch_conforms_to_its_entry() { + let forms = [ + SForm { + code_bits: 2, + code_bias: -1, + group_elems: 64, + ..SForm::default() + }, + SForm { + code_bits: 4, + code_bias: -8, + group_elems: 32, + has_offset: true, + ..SForm::default() + }, + SForm { + code_bits: 8, + code_bias: -128, + group_elems: 64, + codebook: sg::Codebook::Iq4Nl, + ..SForm::default() + }, + ]; + let mut planned = 0; + for form in forms { + for offset in [false, true] { + if form.has_offset && !offset { + continue; + } + let (n_in, n_out) = (1024, 6); + let mut plans: Vec = Vec::new(); + plans.extend(sg::plan_s_gemv(n_in, n_out, &form, offset).ok().flatten()); + plans.extend( + sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset) + .ok() + .flatten(), + ); + plans.extend(sg::plan_s_gemv_q8k(n_in, n_out, &form).ok().flatten()); + plans.extend(sg::plan_s_gemv_q8k_split(n_in, n_out, &form).ok().flatten()); + plans.extend( + sg::plan_s_gemv_q8_0_split(n_in, n_out, &form) + .ok() + .flatten(), + ); + for plan in plans { + let entry = &S_GEMV_ENTRIES[s_gemv_entry_index(plan.kernel)]; + let slots = s_gemv_slots(&plan, &form, n_in, n_out, offset); + assert!(conforms(entry, &slots), "{:?}", plan.kernel); + let bytes = s_operand_bytes(plan.kernel, &form, n_in, n_out).unwrap(); + assert_eq!(bytes.offset.is_some(), form.has_offset); + assert_eq!(bytes.y, 24); + planned += 1; + } + } + } + for plan in [ + sg::plan_s2_gemv(1024, 6).unwrap().unwrap(), + sg::plan_s2_gemv_quads(1024, 6, 64).unwrap().unwrap(), + sg::plan_s2_gemv_q8(1024, 6, 64).unwrap().unwrap(), + sg::plan_s2_gemv_fast(1024, 6, 64, true).unwrap().unwrap(), + sg::plan_s2_gemv_fast(1024, 6, 64, false).unwrap().unwrap(), + ] { + let entry = &S_GEMV_ENTRIES[s_gemv_entry_index(plan.kernel)]; + let slots = s_gemv_slots(&plan, &SForm::default(), 1024, 6, false); + assert!(conforms(entry, &slots), "{:?}", plan.kernel); + planned += 1; + } + assert!(planned >= 20, "{planned}"); +} + +#[test] +fn slot_values_follow_the_oracle_driver() { + // oracle/drivers/s_gemv_legacy.cpp: split passes (bias, codebook, group, shift_of(group), has_offset, tpr) + let form = SForm { + code_bits: 4, + code_bias: -8, + group_elems: 32, + codebook: sg::Codebook::Iq4Nl, + has_offset: true, + ..SForm::default() + }; + let plan = sg::plan_s_gemv_split(512, 8, &form, 64, true) + .unwrap() + .unwrap(); + let slots = s_gemv_slots(&plan, &form, 512, 8, true); + assert_eq!( + slots, + vec![ + Slot::Ptr(Role::X), + Slot::Ptr(Role::Codes), + Slot::Ptr(Role::Scales), + Slot::Ptr(Role::Offset), + Slot::Ptr(Role::Y), + Slot::I64(512), + Slot::I64(8), + Slot::I32(-8), + Slot::I32(1), + Slot::I32(32), + Slot::I32(5), + Slot::I32(1), + Slot::I32(64), + ] + ); + assert_eq!( + ( + plan.launch.grid, + plan.launch.block, + plan.launch.dynamic_shared + ), + ([8, 1, 1], [64, 1, 1], 256) + ); + // the Q8 split kernels take the shift in place of the group + let plan = sg::plan_s_gemv_q8k_split(512, 8, &form).unwrap().unwrap(); + let slots = s_gemv_slots(&plan, &form, 512, 8, true); + assert_eq!( + &slots[7..], + &[Slot::I32(-8), Slot::I32(1), Slot::I32(5), Slot::I32(1)] + ); + // a form without an offset passes a null offset pointer + let none = SForm { + has_offset: false, + ..form + }; + let plan = sg::plan_s_gemv(512, 8, &none, false).unwrap().unwrap(); + assert_eq!(s_gemv_slots(&plan, &none, 512, 8, false)[3], Slot::Null); +} + +#[test] +fn operand_sizes_follow_the_pack_format() { + let form = SForm { + code_bits: 4, + code_bias: -8, + group_elems: 32, + has_offset: true, + ..SForm::default() + }; + let b = s_operand_bytes(Kernel::SGemvSplit(4), &form, 512, 8).unwrap(); + assert_eq!( + (b.x, b.codes, b.scales, b.offset, b.y), + (1024, 8 * 256, 8 * 16 * 4, Some(8 * 16 * 4), 32) + ); + let b = s_operand_bytes(Kernel::SGemvQ8k(4), &form, 512, 8).unwrap(); + assert_eq!(b.x, 2 * 292); + let b = s_operand_bytes(Kernel::SGemvQ80Split(4), &form, 512, 8).unwrap(); + assert_eq!(b.x, 16 * 34); + let b = s_operand_bytes(Kernel::S2GemvQ8, &SForm::default(), 512, 8).unwrap(); + assert_eq!( + (b.x, b.codes, b.scales, b.offset), + (16 * 34, 8 * 128, 8 * 8 * 4, None) + ); + assert!(s_operand_bytes(Kernel::SGemv(2), &SForm::default(), 0, 8).is_err()); + assert!( + s_operand_bytes( + Kernel::SGemv(2), + &SForm { + group_elems: 64, + ..SForm::default() + }, + 100, + 8 + ) + .is_err() + ); +} + +#[test] +fn flash_and_poison_slots_and_sizes() { + let slots = flash_slots(256, true); + assert!(conforms(&FLASH_ENTRIES[0], &slots)); + assert_eq!( + slots[4..7], + [Slot::I32(256), Slot::I32(256), Slot::F32(0.0625)] + ); + assert_eq!(flash_slots(256, false)[9], Slot::Null); + assert!(conforms(&FLASH_ENTRIES[0], &flash_slots(7, false))); + let b = flash_bytes(4096).unwrap(); + assert_eq!( + (b.q, b.kv, b.step, b.out, b.status, b.mask), + (24576, 4096 * 1024, 16, 24576, 4, 512) + ); + assert!(flash_bytes(255).is_err()); + let slots = poison_slots(1000).unwrap(); + assert_eq!(slots, vec![Slot::Ptr(Role::Poison), Slot::I64(1000)]); + assert!(conforms(&POISON_ENTRIES[0], &slots)); + assert!(poison_slots(u64::MAX).is_err()); + // a mismatching scalar kind never conforms + assert!(!conforms( + &POISON_ENTRIES[0], + &[Slot::Ptr(Role::Poison), Slot::I32(1)] + )); + assert!(!conforms(&POISON_ENTRIES[0], &[Slot::Ptr(Role::Poison)])); +} + +#[test] +fn sealed_assets_match_their_pins_and_export_every_entry() { + use crate::sealed_ptx::test_support::{ + assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, + without_terminator, + }; + for program in Program::ALL { + // Sealed with nvcc 13.2.86 on 2026-10-15; this checks structure and the pin only (no numerical claim, + // GPU load is verified separately by the host smokes). + let ptx = program.ptx(); + let names = program.entries().iter().map(|e| e.name.to_str().unwrap()); + assert_real_sm120_ptx(program.name(), ptx, names); + assert_nvcc_13_2_86(program.name(), ptx); + let pin = program.pin(); + assert_ne!(pin.source_sha256, [0; 32], "{}", program.name()); + assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name()); + assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name()); + assert_eq!(pin.source_sha256, qwen_ffi::sha256(program.source().as_bytes()), "{}", program.name()); + assert_eq!(admit(program), Ok(()), "{}", program.name()); + // the guard still refuses every deviation, on synthetic copies of the real PTX + let refuse = Err(ExperimentalError::Unpinned(program.name())); + assert_eq!(admit_ptx(program, one_byte_corrupted(ptx), pin), refuse); + assert_eq!(admit_ptx(program, one_byte_shorter(ptx), pin), refuse); + assert_eq!(admit_ptx(program, one_byte_longer(ptx), pin), refuse); + assert_eq!(admit_ptx(program, with_embedded_nul(ptx), pin), refuse); + assert_eq!(admit_ptx(program, without_terminator(ptx), pin), refuse); + let mut wrong_digest = *pin; + wrong_digest.ptx_sha256[0] ^= 1; + assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse); + for zeroed in [ + PtxPin { source_sha256: [0; 32], ..*pin }, + PtxPin { ptx_sha256: [0; 32], ..*pin }, + ] { + assert_eq!(admit_ptx(program, ptx, &zeroed), refuse); + } + } + // a matching pin admits; any difference refuses + static GOOD: &[u8] = b".version 8.7\n.target sm_120\n\0"; + let pin = PtxPin { + source_sha256: [1; 32], + ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]), + }; + assert_eq!(admit_ptx(Program::DevicePoison, GOOD, &pin), Ok(())); + let wrong = PtxPin { + ptx_sha256: [2; 32], + ..pin + }; + assert!(admit_ptx(Program::DevicePoison, GOOD, &wrong).is_err()); + assert!( + admit_ptx( + Program::DevicePoison, + GOOD, + &PtxPin { + source_sha256: [0; 32], + ..pin + } + ) + .is_err() + ); +} diff --git a/crates/cuda-driver/src/device_slab.rs b/crates/cuda-driver/src/device_slab.rs index 4639040f..ea82950a 100644 --- a/crates/cuda-driver/src/device_slab.rs +++ b/crates/cuda-driver/src/device_slab.rs @@ -242,180 +242,4 @@ impl<'ctx> DeviceBuffer<'ctx> { } #[cfg(test)] -mod tests { - use super::*; - use crate::vram_ledger::driver_bytes; - - const MIB: usize = 1 << 20; - - fn packer() -> Packer { - Packer::new(SlabPolicy::DENSE).unwrap() - } - - #[test] - fn the_policy_refuses_what_the_driver_cannot_honour() { - assert!(SlabPolicy::DENSE.validate().is_ok()); - for bad in [ - SlabPolicy { slab_bytes: 0, ..SlabPolicy::DENSE }, - SlabPolicy { slab_bytes: 3 * MIB, ..SlabPolicy::DENSE }, - SlabPolicy { align: 100, ..SlabPolicy::DENSE }, - SlabPolicy { align: 128, ..SlabPolicy::DENSE }, - SlabPolicy { direct_above: 0, ..SlabPolicy::DENSE }, - SlabPolicy { direct_above: 128 * MIB, ..SlabPolicy::DENSE }, - ] { - assert_eq!(bad.validate(), Err(Error::InvalidSize), "{bad:?}"); - } - assert_eq!(packer().place(0), Err(Error::InvalidSize)); - } - - #[test] - fn requests_fill_a_slab_in_order_aligned_and_a_full_slab_opens_the_next() { - let mut p = packer(); - assert_eq!(p.place(100).unwrap(), Placement::NewSlab { slab: 0 }); - assert_eq!(p.place(1000).unwrap(), Placement::Slab { slab: 0, offset: 512 }); - assert_eq!(p.place(512).unwrap(), Placement::Slab { slab: 0, offset: 1536 }); - assert_eq!(p.place(10 * MIB).unwrap(), Placement::Slab { slab: 0, offset: 2048 }); - // 4 x 15 MiB do not fit behind that: the slab holds 64 MiB - let mut slabs = std::collections::BTreeSet::new(); - for _ in 0..4 { - match p.place(15 * MIB).unwrap() { - Placement::Slab { slab, .. } | Placement::NewSlab { slab } => { - slabs.insert(slab); - } - Placement::Direct => panic!("15 MiB is carved"), - } - } - assert_eq!(slabs.into_iter().collect::>(), vec![0, 1]); - } - - #[test] - fn a_later_small_request_fills_the_hole_an_earlier_big_one_left() { - let mut p = Packer::new(SlabPolicy { direct_above: 64 * MIB, ..SlabPolicy::DENSE }).unwrap(); - assert_eq!(p.place(60 * MIB).unwrap(), Placement::NewSlab { slab: 0 }); - // 5 MiB does not fit the 4 MiB left of slab 0: slab 1 - assert_eq!(p.place(5 * MIB).unwrap(), Placement::NewSlab { slab: 1 }); - // 1 MiB does fit slab 0's tail: first fit goes back - assert_eq!(p.place(MIB).unwrap(), Placement::Slab { slab: 0, offset: 60 * MIB }); - } - - #[test] - fn requests_above_the_direct_limit_keep_their_own_allocation() { - let mut p = packer(); - assert_eq!(p.place(16 * MIB).unwrap(), Placement::NewSlab { slab: 0 }); - assert_eq!(p.place(16 * MIB + 1).unwrap(), Placement::Direct); - assert_eq!(p.place(50 * MIB).unwrap(), Placement::Direct); - assert_eq!(p.totals(), (16 * MIB, 1)); - } - - #[test] - fn no_two_ranges_overlap_every_range_stays_inside_its_slab() { - // a deterministic mix of dense-weight sizes: tiny norms, 0.3-9 MiB matrices, the odd 2.5 MiB router - let mut sizes = Vec::new(); - let mut state = 0x9e37_79b9u32; - for i in 0..2000 { - state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - let size = match i % 7 { - 0 => 2560 * 4, - 1 => 2560 * 512 * 2 / 1000 * 1000 + (state as usize % 4096), - 2 => 5 * MIB / 2, - 3 => 300 * 1024 + (state as usize % (200 * 1024)), - _ => MIB / 2 + (state as usize % (9 * MIB)), - }; - sizes.push(size.max(1)); - } - let mut p = packer(); - let mut ranges: Vec<(usize, usize, usize)> = Vec::new(); // slab, start, end - for &size in &sizes { - match p.place(size).unwrap() { - Placement::Slab { slab, offset } => ranges.push((slab, offset, offset + size)), - Placement::NewSlab { slab } => ranges.push((slab, 0, size)), - Placement::Direct => {} - } - } - for &(_, start, end) in &ranges { - assert!(start % 512 == 0 && end <= SlabPolicy::DENSE.slab_bytes); - } - let mut sorted = ranges.clone(); - sorted.sort(); - for pair in sorted.windows(2) { - if pair[0].0 == pair[1].0 { - assert!(pair[0].2 <= pair[1].1, "{pair:?} overlap"); - } - } - } - - #[test] - fn packing_the_dense_weights_takes_much_less_device_memory_than_one_allocation_each() { - // 36 GDN layers x (qkv 6.3 MiB, z 3.1, out 3.1, alpha/beta 0.01), 12 QSA x 6 matrices of 1.3-4.7 MiB, 48 routers of 2.5 MiB, - // and 97 gated-residual triples of 0.3 MiB: all sizes the driver rounds one by one - let mut sizes: Vec = Vec::new(); - for _ in 0..36 { - sizes.extend([6_600_000, 3_300_000, 3_300_000, 10_240, 10_240, 4096, 4096, 4096, 4096]); - } - for _ in 0..12 { - sizes.extend([4_900_000, 1_400_000, 1_400_000, 2_600_000, 650_000, 4_900_000, 2560 * 4, 2560 * 4, 2560 * 4, 2560 * 4]); - } - sizes.extend(std::iter::repeat_n(5 * MIB / 2, 48)); - sizes.extend(std::iter::repeat_n(330_000, 97 * 3)); - sizes.push(50 * MIB); - sizes.push(2560 * 2560 * 2); - let requested: usize = sizes.iter().sum(); - let separate: usize = sizes.iter().map(|&b| driver_bytes(b)).sum(); - let mut p = packer(); - let mut direct = 0usize; - for &size in &sizes { - if p.place(size).unwrap() == Placement::Direct { - direct += driver_bytes(size); - } - } - let (_, slabs) = p.totals(); - let packed = slabs * SlabPolicy::DENSE.slab_bytes + direct; - assert!(separate > requested + 60 * MIB, "rounding must be visible in the model: {separate} vs {requested}"); - assert!(packed < separate - 60 * MIB, "packing saves the rounding: {packed} vs {separate}"); - // the holes behind the last items of each slab and the last slab's tail are the only cost - assert!(packed <= requested + requested / 16 + SlabPolicy::DENSE.slab_bytes, "{packed} vs {requested}"); - } - - /// Needs a CUDA device (`cargo test -p leleka-cuda-driver --features cuda-driver --lib -- --ignored device_slab`). - #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - #[test] - #[ignore = "needs a CUDA device"] - fn device_slab_views_keep_their_bytes_apart_and_charge_only_the_slab() { - let driver = crate::Driver::load().unwrap(); - let context = driver.device(0).unwrap().create_context(256 << 20).unwrap(); - let mut slabs = SlabAllocator::new(&context, SlabPolicy::DENSE).unwrap(); - let sizes = [4096usize, 3 * MIB, 700_001, 5 * MIB / 2, 17 * MIB, 1]; - let mut buffers = Vec::new(); - for (i, &size) in sizes.iter().enumerate() { - let mut buffer = slabs.allocate(size).unwrap(); - assert_eq!(buffer.len(), size); - let bytes: Vec = (0..size).map(|k| (k as u8).wrapping_mul(31).wrapping_add(i as u8 * 17 + 1)).collect(); - buffer.copy_from(&bytes).unwrap(); - buffers.push((buffer, bytes)); - } - // only the first five are carved: the 17 MiB request keeps its own allocation - assert_eq!(buffers.iter().filter(|(b, _)| b.is_carved()).count(), 5); - let stats = slabs.stats(); - assert_eq!((stats.slabs, stats.carved, stats.direct), (1, 5, 1)); - assert_eq!(context.allocated_bytes(), SlabPolicy::DENSE.slab_bytes + 17 * MIB); - for (buffer, bytes) in &buffers { - let mut back = vec![0u8; bytes.len()]; - buffer.copy_to(&mut back).unwrap(); - assert!(&back == bytes, "a view read back different bytes"); - } - // overwriting one view leaves its neighbours alone - let (first, _) = &mut buffers[0]; - first.copy_from(&vec![0xAB; 4096]).unwrap(); - for (buffer, bytes) in buffers.iter().skip(1) { - let mut back = vec![0u8; bytes.len()]; - buffer.copy_to(&mut back).unwrap(); - assert!(&back == bytes, "a neighbour changed"); - } - for (buffer, _) in buffers { - buffer.release().unwrap(); - } - // the allocator still shares nothing: the slab goes with it - slabs.release().unwrap(); - assert_eq!(context.allocated_bytes(), 0); - } -} +mod tests; diff --git a/crates/cuda-driver/src/device_slab/tests.rs b/crates/cuda-driver/src/device_slab/tests.rs new file mode 100644 index 00000000..bb7a7ed8 --- /dev/null +++ b/crates/cuda-driver/src/device_slab/tests.rs @@ -0,0 +1,177 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::vram_ledger::driver_bytes; + +const MIB: usize = 1 << 20; + +fn packer() -> Packer { + Packer::new(SlabPolicy::DENSE).unwrap() +} + +#[test] +fn the_policy_refuses_what_the_driver_cannot_honour() { + assert!(SlabPolicy::DENSE.validate().is_ok()); + for bad in [ + SlabPolicy { slab_bytes: 0, ..SlabPolicy::DENSE }, + SlabPolicy { slab_bytes: 3 * MIB, ..SlabPolicy::DENSE }, + SlabPolicy { align: 100, ..SlabPolicy::DENSE }, + SlabPolicy { align: 128, ..SlabPolicy::DENSE }, + SlabPolicy { direct_above: 0, ..SlabPolicy::DENSE }, + SlabPolicy { direct_above: 128 * MIB, ..SlabPolicy::DENSE }, + ] { + assert_eq!(bad.validate(), Err(Error::InvalidSize), "{bad:?}"); + } + assert_eq!(packer().place(0), Err(Error::InvalidSize)); +} + +#[test] +fn requests_fill_a_slab_in_order_aligned_and_a_full_slab_opens_the_next() { + let mut p = packer(); + assert_eq!(p.place(100).unwrap(), Placement::NewSlab { slab: 0 }); + assert_eq!(p.place(1000).unwrap(), Placement::Slab { slab: 0, offset: 512 }); + assert_eq!(p.place(512).unwrap(), Placement::Slab { slab: 0, offset: 1536 }); + assert_eq!(p.place(10 * MIB).unwrap(), Placement::Slab { slab: 0, offset: 2048 }); + // 4 x 15 MiB do not fit behind that: the slab holds 64 MiB + let mut slabs = std::collections::BTreeSet::new(); + for _ in 0..4 { + match p.place(15 * MIB).unwrap() { + Placement::Slab { slab, .. } | Placement::NewSlab { slab } => { + slabs.insert(slab); + } + Placement::Direct => panic!("15 MiB is carved"), + } + } + assert_eq!(slabs.into_iter().collect::>(), vec![0, 1]); +} + +#[test] +fn a_later_small_request_fills_the_hole_an_earlier_big_one_left() { + let mut p = Packer::new(SlabPolicy { direct_above: 64 * MIB, ..SlabPolicy::DENSE }).unwrap(); + assert_eq!(p.place(60 * MIB).unwrap(), Placement::NewSlab { slab: 0 }); + // 5 MiB does not fit the 4 MiB left of slab 0: slab 1 + assert_eq!(p.place(5 * MIB).unwrap(), Placement::NewSlab { slab: 1 }); + // 1 MiB does fit slab 0's tail: first fit goes back + assert_eq!(p.place(MIB).unwrap(), Placement::Slab { slab: 0, offset: 60 * MIB }); +} + +#[test] +fn requests_above_the_direct_limit_keep_their_own_allocation() { + let mut p = packer(); + assert_eq!(p.place(16 * MIB).unwrap(), Placement::NewSlab { slab: 0 }); + assert_eq!(p.place(16 * MIB + 1).unwrap(), Placement::Direct); + assert_eq!(p.place(50 * MIB).unwrap(), Placement::Direct); + assert_eq!(p.totals(), (16 * MIB, 1)); +} + +#[test] +fn no_two_ranges_overlap_every_range_stays_inside_its_slab() { + // a deterministic mix of dense-weight sizes: tiny norms, 0.3-9 MiB matrices, the odd 2.5 MiB router + let mut sizes = Vec::new(); + let mut state = 0x9e37_79b9u32; + for i in 0..2000 { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let size = match i % 7 { + 0 => 2560 * 4, + 1 => 2560 * 512 * 2 / 1000 * 1000 + (state as usize % 4096), + 2 => 5 * MIB / 2, + 3 => 300 * 1024 + (state as usize % (200 * 1024)), + _ => MIB / 2 + (state as usize % (9 * MIB)), + }; + sizes.push(size.max(1)); + } + let mut p = packer(); + let mut ranges: Vec<(usize, usize, usize)> = Vec::new(); // slab, start, end + for &size in &sizes { + match p.place(size).unwrap() { + Placement::Slab { slab, offset } => ranges.push((slab, offset, offset + size)), + Placement::NewSlab { slab } => ranges.push((slab, 0, size)), + Placement::Direct => {} + } + } + for &(_, start, end) in &ranges { + assert!(start % 512 == 0 && end <= SlabPolicy::DENSE.slab_bytes); + } + let mut sorted = ranges.clone(); + sorted.sort(); + for pair in sorted.windows(2) { + if pair[0].0 == pair[1].0 { + assert!(pair[0].2 <= pair[1].1, "{pair:?} overlap"); + } + } +} + +#[test] +fn packing_the_dense_weights_takes_much_less_device_memory_than_one_allocation_each() { + // 36 GDN layers x (qkv 6.3 MiB, z 3.1, out 3.1, alpha/beta 0.01), 12 QSA x 6 matrices of 1.3-4.7 MiB, 48 routers of 2.5 MiB, + // and 97 gated-residual triples of 0.3 MiB: all sizes the driver rounds one by one + let mut sizes: Vec = Vec::new(); + for _ in 0..36 { + sizes.extend([6_600_000, 3_300_000, 3_300_000, 10_240, 10_240, 4096, 4096, 4096, 4096]); + } + for _ in 0..12 { + sizes.extend([4_900_000, 1_400_000, 1_400_000, 2_600_000, 650_000, 4_900_000, 2560 * 4, 2560 * 4, 2560 * 4, 2560 * 4]); + } + sizes.extend(std::iter::repeat_n(5 * MIB / 2, 48)); + sizes.extend(std::iter::repeat_n(330_000, 97 * 3)); + sizes.push(50 * MIB); + sizes.push(2560 * 2560 * 2); + let requested: usize = sizes.iter().sum(); + let separate: usize = sizes.iter().map(|&b| driver_bytes(b)).sum(); + let mut p = packer(); + let mut direct = 0usize; + for &size in &sizes { + if p.place(size).unwrap() == Placement::Direct { + direct += driver_bytes(size); + } + } + let (_, slabs) = p.totals(); + let packed = slabs * SlabPolicy::DENSE.slab_bytes + direct; + assert!(separate > requested + 60 * MIB, "rounding must be visible in the model: {separate} vs {requested}"); + assert!(packed < separate - 60 * MIB, "packing saves the rounding: {packed} vs {separate}"); + // the holes behind the last items of each slab and the last slab's tail are the only cost + assert!(packed <= requested + requested / 16 + SlabPolicy::DENSE.slab_bytes, "{packed} vs {requested}"); +} + +/// Needs a CUDA device (`cargo test -p leleka-cuda-driver --features cuda-driver --lib -- --ignored device_slab`). +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[test] +#[ignore = "needs a CUDA device"] +fn device_slab_views_keep_their_bytes_apart_and_charge_only_the_slab() { + let driver = crate::Driver::load().unwrap(); + let context = driver.device(0).unwrap().create_context(256 << 20).unwrap(); + let mut slabs = SlabAllocator::new(&context, SlabPolicy::DENSE).unwrap(); + let sizes = [4096usize, 3 * MIB, 700_001, 5 * MIB / 2, 17 * MIB, 1]; + let mut buffers = Vec::new(); + for (i, &size) in sizes.iter().enumerate() { + let mut buffer = slabs.allocate(size).unwrap(); + assert_eq!(buffer.len(), size); + let bytes: Vec = (0..size).map(|k| (k as u8).wrapping_mul(31).wrapping_add(i as u8 * 17 + 1)).collect(); + buffer.copy_from(&bytes).unwrap(); + buffers.push((buffer, bytes)); + } + // only the first five are carved: the 17 MiB request keeps its own allocation + assert_eq!(buffers.iter().filter(|(b, _)| b.is_carved()).count(), 5); + let stats = slabs.stats(); + assert_eq!((stats.slabs, stats.carved, stats.direct), (1, 5, 1)); + assert_eq!(context.allocated_bytes(), SlabPolicy::DENSE.slab_bytes + 17 * MIB); + for (buffer, bytes) in &buffers { + let mut back = vec![0u8; bytes.len()]; + buffer.copy_to(&mut back).unwrap(); + assert!(&back == bytes, "a view read back different bytes"); + } + // overwriting one view leaves its neighbours alone + let (first, _) = &mut buffers[0]; + first.copy_from(&vec![0xAB; 4096]).unwrap(); + for (buffer, bytes) in buffers.iter().skip(1) { + let mut back = vec![0u8; bytes.len()]; + buffer.copy_to(&mut back).unwrap(); + assert!(&back == bytes, "a neighbour changed"); + } + for (buffer, _) in buffers { + buffer.release().unwrap(); + } + // the allocator still shares nothing: the slab goes with it + slabs.release().unwrap(); + assert_eq!(context.allocated_bytes(), 0); +} diff --git a/crates/cuda-driver/src/experimental.rs b/crates/cuda-driver/src/experimental.rs index 746a20f0..0510e238 100644 --- a/crates/cuda-driver/src/experimental.rs +++ b/crates/cuda-driver/src/experimental.rs @@ -759,378 +759,4 @@ impl Context<'_> { } #[cfg(test)] -mod tests { - use super::*; - - fn count_params(source: &str, name: &str) -> (Vec<&'static str>, u32) { - let at = source - .find(&format!(" {name}(")) - .unwrap_or_else(|| panic!("{name} not in source")); - let head = &source[..at]; - let decl = head - .rfind("extern \"C\" __global__") - .expect("extern C entry"); - let bounds = head[decl..] - .split("__launch_bounds__(") - .nth(1) - .expect("launch bounds"); - let threads: u32 = bounds.split(')').next().unwrap().trim().parse().unwrap(); - let rest = &source[at + name.len() + 2..]; - let close = rest.find(") {").expect("parameter list end"); - let kinds = rest[..close] - .split(',') - .map(|param| { - let p = param.trim(); - if p.contains('*') { - "ptr" - } else if p.starts_with("long long") { - "i64" - } else if p.starts_with("int ") { - "i32" - } else if p.starts_with("float ") { - "f32" - } else { - panic!("unrecognised parameter `{p}` of {name}") - } - }) - .collect(); - (kinds, threads) - } - - #[test] - fn every_entry_signature_matches_its_cuda_source() { - let mut checked = 0; - for program in Program::ALL { - for entry in program.entries() { - let name = entry.name.to_str().unwrap(); - let (kinds, threads) = count_params(program.source(), name); - let want: Vec<&str> = entry - .args - .iter() - .map(|a| match a { - Arg::Ptr | Arg::PtrOpt => "ptr", - Arg::I32 => "i32", - Arg::I64 => "i64", - Arg::F32 => "f32", - }) - .collect(); - assert_eq!(kinds, want, "{name}"); - assert_eq!( - threads, - entry.block.iter().product::(), - "{name} launch bounds" - ); - assert!(entry.args.len() <= MAX_ENTRY_ARGUMENTS, "{name}"); - checked += 1; - } - } - assert_eq!(checked, 17); - } - - #[test] - fn index_constants_point_at_the_named_entries() { - let n = |p: Program, i: usize| p.entries()[i].name.to_str().unwrap(); - assert_eq!(n(Program::KvQ4, FWHT256), "leleka_fwht256_f32"); - assert_eq!(n(Program::KvQ4, Q4_APPEND_STEP), "leleka_kv_append_q4_step"); - assert_eq!( - n(Program::KvQ4, Q4_APPEND_BATCH), - "leleka_kv_append_q4_batch" - ); - assert_eq!(n(Program::KvQ4, Q4_GATHER_STEP), "leleka_kv_gather_q4_step"); - assert_eq!(n(Program::KvQ8, Q8_APPEND_STEP), "leleka_kv_append_q8_step"); - assert_eq!(n(Program::KvQ8, Q8_GATHER_STEP), "leleka_kv_gather_q8_step"); - assert_eq!(n(Program::KvStream, STREAM_RESET), "leleka_kv_stream_reset"); - assert_eq!( - n(Program::KvStream, STREAM_RESOLVE), - "leleka_kv_stream_resolve" - ); - assert_eq!(n(Program::KvStream, STREAM_COPY), "leleka_kv_stream_copy"); - assert_eq!(n(Program::KvStream, RING_TABLE), "leleka_kv_ring_table"); - assert_eq!(n(Program::KvStream, COPY_U4), "leleka_kv_copy_u4"); - assert_eq!( - n(Program::Keyless, KEYLESS_ROUTE), - "leleka_keyless_route_query" - ); - assert_eq!( - n(Program::QsaAttn, ATTN_CHUNK_M2), - "leleka_qsa_attn_chunk_m2" - ); - assert_eq!( - n(Program::QsaAttn, ATTN_CHUNK_M3), - "leleka_qsa_attn_chunk_m3" - ); - assert_eq!( - n(Program::QsaAttn, ATTN_CHUNK_M4), - "leleka_qsa_attn_chunk_m4" - ); - assert_eq!(n(Program::QsaAttn, ATTN_MERGE), "leleka_qsa_attn_merge"); - assert_eq!(n(Program::Cvec, CVEC_APPLY), "leleka_cvec_apply"); - } - - #[test] - fn every_mode_is_off_by_default_and_programs_need_an_explicit_one() { - let none = OptIn::default(); - assert!(none.is_empty()); - assert_eq!(none.digest_text(), ""); - for program in Program::ALL { - assert!(!none.enables(program)); - assert_eq!( - admit(program, &none), - Err(ExperimentalError::NotEnabled(program.name())) - ); - assert!(!program.needed_by().is_empty()); - } - let q4 = OptIn::default().with(Mode::KvQ40); - assert!(q4.enables(Program::KvQ4) && q4.enables(Program::QsaAttn)); - assert!( - !q4.enables(Program::KvStream) - && !q4.enables(Program::Cvec) - && !q4.enables(Program::KvQ8) - ); - let k = OptIn::default().with(Mode::KeylessVOnly); - assert!( - k.enables(Program::Keyless) && k.enables(Program::KvQ8) && !k.enables(Program::KvQ4) - ); - assert_eq!( - OptIn::default() - .with(Mode::KvStreamed) - .with(Mode::KvQ40) - .digest_text(), - "kv-q4_0,kv-streamed" - ); - // every mode reaches at least one program, and the names are unique - for mode in Mode::ALL { - assert!( - Program::ALL.iter().any(|p| p.needed_by().contains(&mode)), - "{mode:?}" - ); - } - let names: std::collections::BTreeSet<_> = Mode::ALL.iter().map(|m| m.name()).collect(); - assert_eq!(names.len(), Mode::ALL.len()); - } - - #[test] - fn sealed_assets_match_their_pins_and_export_every_entry() { - use crate::sealed_ptx::test_support::{ - assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, - without_terminator, - }; - let all = OptIn::NONE - .with(Mode::KvQ40) - .with(Mode::KvK8V4) - .with(Mode::KeylessVOnly) - .with(Mode::KvStreamed) - .with(Mode::ControlVectors); - for program in Program::ALL { - // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim, GPU load is - // verified separately by the host smokes). - let ptx = program.ptx(); - let names = program.entries().iter().map(|e| e.name.to_str().unwrap()); - assert_real_sm120_ptx(program.name(), ptx, names); - assert_nvcc_13_2_86(program.name(), ptx); - let pin = program.pin(); - assert_ne!(pin.source_sha256, [0; 32], "{}", program.name()); - assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name()); - assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name()); - // a program re-synced after the seal (PENDING_RESEAL) keeps its old PTX and refuses to open - let expected = if PENDING_RESEAL.contains(&program) { - Err(ExperimentalError::Unpinned(program.name())) - } else { - Ok(()) - }; - assert_eq!(admit(program, &all), expected, "{}", program.name()); - // the opt-in gate still comes first - assert_eq!( - admit(program, &OptIn::NONE), - Err(ExperimentalError::NotEnabled(program.name())) - ); - // the pin guard still refuses every deviation, on synthetic copies of the real PTX - let refuse = Err(ExperimentalError::Unpinned(program.name())); - assert_eq!(admit_ptx(program, one_byte_corrupted(ptx), pin), refuse); - assert_eq!(admit_ptx(program, one_byte_shorter(ptx), pin), refuse); - assert_eq!(admit_ptx(program, one_byte_longer(ptx), pin), refuse); - assert_eq!(admit_ptx(program, with_embedded_nul(ptx), pin), refuse); - assert_eq!(admit_ptx(program, without_terminator(ptx), pin), refuse); - let mut wrong_digest = *pin; - wrong_digest.ptx_sha256[0] ^= 1; - assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse); - for zeroed in [ - PtxPin { source_sha256: [0; 32], ..*pin }, - PtxPin { ptx_sha256: [0; 32], ..*pin }, - ] { - assert_eq!(admit_ptx(program, ptx, &zeroed), refuse); - } - } - } - - #[test] - fn pending_reseal_lists_exactly_the_unsealed_sources() { - for program in Program::ALL { - assert_eq!( - source_is_sealed(program), - !PENDING_RESEAL.contains(&program), - "{}: PENDING_RESEAL and the source digest of the pin disagree (after a server reseal the list must shrink, after a .cu edit without reseal it must grow)", - program.name() - ); - } - for (i, program) in PENDING_RESEAL.iter().enumerate() { - assert!( - !PENDING_RESEAL[i + 1..].contains(program), - "{} listed twice", - program.name() - ); - } - } - - #[test] - fn a_program_whose_source_is_newer_than_its_ptx_refuses_even_with_a_matching_ptx_digest() { - let all = OptIn::NONE - .with(Mode::KvQ40) - .with(Mode::KvK8V4) - .with(Mode::KeylessVOnly) - .with(Mode::KvStreamed) - .with(Mode::ControlVectors); - for &program in PENDING_RESEAL { - // the PTX bytes are the sealed ones and match their digest ... - assert_eq!(admit_ptx(program, program.ptx(), program.pin()), Ok(())); - // ... but they were not built from the checked-in source: admit fails closed - assert!(!source_is_sealed(program)); - assert_eq!( - admit(program, &all), - Err(ExperimentalError::Unpinned(program.name())) - ); - } - } - - #[test] - fn a_matching_pin_admits_and_any_difference_refuses() { - static GOOD: &[u8] = b".version 8.7\n.target sm_120\n\0"; - let pin = PtxPin { - source_sha256: [1; 32], - ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]), - }; - assert_eq!(admit_ptx(Program::Cvec, GOOD, &pin), Ok(())); - let wrong = PtxPin { - ptx_sha256: [2; 32], - ..pin - }; - assert_eq!( - admit_ptx(Program::Cvec, GOOD, &wrong), - Err(ExperimentalError::Unpinned("cvec")) - ); - let half = PtxPin { - source_sha256: [0; 32], - ..pin - }; - assert_eq!( - admit_ptx(Program::Cvec, GOOD, &half), - Err(ExperimentalError::Unpinned("cvec")) - ); - static NO_NUL: &[u8] = b".version 8.7\n"; - let p2 = PtxPin { - source_sha256: [1; 32], - ptx_sha256: qwen_ffi::sha256(NO_NUL), - }; - assert!(admit_ptx(Program::Cvec, NO_NUL, &p2).is_err()); - static EMBEDDED: &[u8] = b"a\0b\0"; - let p3 = PtxPin { - source_sha256: [1; 32], - ptx_sha256: qwen_ffi::sha256(b"a\0b"), - }; - assert!(admit_ptx(Program::Cvec, EMBEDDED, &p3).is_err()); - } - - #[test] - fn kv_geometry_matches_the_originals_host_wrappers() { - let s = KvShape::real(); - assert_eq!(fwht_grid(1), Ok([1, 1, 1])); - assert_eq!(fwht_grid(4), Ok([1, 1, 1])); - assert_eq!(fwht_grid(5), Ok([2, 1, 1])); - assert!(fwht_grid(0).is_err()); - assert_eq!(q4_step_grid(&s), Ok([2, 8, 2])); - assert_eq!(q4_batch_grid(7, &s), Ok([7, 2, 8])); - assert!(q4_batch_grid(0, &s).is_err()); - // 3 ids * 2 heads * 8 blocks = 48 blocks, 4 per grid block - assert_eq!(q4_gather_grid(3, &s), Ok([12, 1, 1])); - assert_eq!(q4_gather_grid(1, &s), Ok([4, 1, 1])); - assert_eq!(q8_step_grid(&s, true), Ok([2, 4, 2])); - assert_eq!(q8_step_grid(&s, false), Ok([2, 4, 1])); - // 5 ids * 2 heads * 64 float4 = 640 threads - assert_eq!(q8_gather_grid(5, &s), Ok([3, 1, 1])); - let odd = KvShape { head_dim: 192, ..s }; - assert!(odd.check_q8().is_ok() && odd.check_q4().is_err() && odd.check_attn().is_err()); - assert!(KvShape { head_dim: 100, ..s }.check_q8().is_err()); - assert!(KvShape { kv_heads: 0, ..s }.check_q4().is_err()); - assert!(KvShape { page_size: 0, ..s }.check_q8().is_err()); - assert_eq!(copy_u4_grid(1), Ok([1, 1, 1])); - assert_eq!(copy_u4_grid(129), Ok([2, 1, 1])); - assert_eq!(copy_u4_grid(1 << 40), Ok([4096, 1, 1])); - assert_eq!(attn_chunk_grid(64, &s, 3), Ok([1, 2, 3])); - assert_eq!(attn_chunk_grid(65, &s, 1), Ok([2, 2, 1])); - assert_eq!(attn_merge_grid(&s, 4), Ok([24, 4, 1])); - assert!(attn_chunk_grid(0, &s, 1).is_err() && attn_chunk_grid(64, &s, 65_536).is_err()); - assert_eq!(keyless_grid(3, 24), Ok([72, 1, 1])); - assert!(keyless_grid(0, 24).is_err()); - assert_eq!(keyless_matrices_bytes(24), 24 * 65_536 * 4); - assert_eq!(cvec_grid(4, 3, 2560), Ok([4, 3, 1])); - assert!( - cvec_grid(4, 3, 4097).is_err() - && cvec_grid(4, 3, 0).is_err() - && cvec_grid(0, 3, 2560).is_err() - ); - } - - #[test] - fn byte_sizes_agree_with_the_reference_layouts() { - use leleka_experimental_ref::layout::{KvFormat, kv_pool_bytes, pool_arrays}; - let s = KvShape::real(); - let q = QsaShapes::real(); - let pages = 11; - let arrays = pool_arrays(KvFormat::Q4_0, &q, pages); - assert_eq!(arrays[0].bytes, s.q4_bytes(pages)); - assert_eq!(arrays[1].bytes, s.q4_bytes(pages)); - let arrays = pool_arrays(KvFormat::Int8, &q, pages); - assert_eq!(arrays[0].bytes, s.q8_code_bytes(pages)); - assert_eq!(arrays[2].bytes, s.q8_scale_bytes(pages)); - let k8v4 = pool_arrays(KvFormat::K8V4, &q, pages); - assert_eq!( - (k8v4[0].bytes, k8v4[1].bytes, k8v4[2].bytes), - ( - s.q8_code_bytes(pages), - s.q8_scale_bytes(pages), - s.q4_bytes(pages) - ) - ); - // 576 B per cell and layer for Q4_0, one page = 4 cells - assert_eq!( - kv_pool_bytes(KvFormat::Q4_0, &q, pages), - pages * 4 * 576 + 64 - ); - assert_eq!(s.q4_bytes(pages) * 2, pages * 4 * 576); - assert_eq!(s.gather_scratch_bytes(2048), 2048 * 2 * 256 * 2); - assert_eq!(attn_scratch_floats(2048, &s), 32 * 24 * 258 + 64); - assert_eq!(fwht_bytes(24), 24 * 1024); - assert_eq!(s.as_qsa(), q); - } - - #[test] - fn stream_resolve_guards_are_the_originals() { - let s = KvShape::real(); - assert_eq!(check_stream_resolve(&s, 5120, 1, 2048), Ok(())); - assert!( - matches!(check_stream_resolve(&s, 1023, 1, 8), Err(ExperimentalError::Invalid(m)) if m.contains("fewer slots")) - ); - assert!( - matches!(check_stream_resolve(&s, 1024, 8, 4096), Err(ExperimentalError::Invalid(m)) if m.contains("distinct blocks")) - ); - assert!(check_stream_resolve(&s, 5120, 0, 8).is_err()); - let misaligned = KvShape { - kv_heads: 1, - page_size: 1, - ..s - }; - assert!( - matches!(check_stream_resolve(&misaligned, 5120, 1, 8), Err(ExperimentalError::Invalid(m)) if m.contains("16 bytes")) - ); - } -} +mod tests; diff --git a/crates/cuda-driver/src/experimental/tests.rs b/crates/cuda-driver/src/experimental/tests.rs new file mode 100644 index 00000000..1c4baa75 --- /dev/null +++ b/crates/cuda-driver/src/experimental/tests.rs @@ -0,0 +1,375 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn count_params(source: &str, name: &str) -> (Vec<&'static str>, u32) { + let at = source + .find(&format!(" {name}(")) + .unwrap_or_else(|| panic!("{name} not in source")); + let head = &source[..at]; + let decl = head + .rfind("extern \"C\" __global__") + .expect("extern C entry"); + let bounds = head[decl..] + .split("__launch_bounds__(") + .nth(1) + .expect("launch bounds"); + let threads: u32 = bounds.split(')').next().unwrap().trim().parse().unwrap(); + let rest = &source[at + name.len() + 2..]; + let close = rest.find(") {").expect("parameter list end"); + let kinds = rest[..close] + .split(',') + .map(|param| { + let p = param.trim(); + if p.contains('*') { + "ptr" + } else if p.starts_with("long long") { + "i64" + } else if p.starts_with("int ") { + "i32" + } else if p.starts_with("float ") { + "f32" + } else { + panic!("unrecognised parameter `{p}` of {name}") + } + }) + .collect(); + (kinds, threads) +} + +#[test] +fn every_entry_signature_matches_its_cuda_source() { + let mut checked = 0; + for program in Program::ALL { + for entry in program.entries() { + let name = entry.name.to_str().unwrap(); + let (kinds, threads) = count_params(program.source(), name); + let want: Vec<&str> = entry + .args + .iter() + .map(|a| match a { + Arg::Ptr | Arg::PtrOpt => "ptr", + Arg::I32 => "i32", + Arg::I64 => "i64", + Arg::F32 => "f32", + }) + .collect(); + assert_eq!(kinds, want, "{name}"); + assert_eq!( + threads, + entry.block.iter().product::(), + "{name} launch bounds" + ); + assert!(entry.args.len() <= MAX_ENTRY_ARGUMENTS, "{name}"); + checked += 1; + } + } + assert_eq!(checked, 17); +} + +#[test] +fn index_constants_point_at_the_named_entries() { + let n = |p: Program, i: usize| p.entries()[i].name.to_str().unwrap(); + assert_eq!(n(Program::KvQ4, FWHT256), "leleka_fwht256_f32"); + assert_eq!(n(Program::KvQ4, Q4_APPEND_STEP), "leleka_kv_append_q4_step"); + assert_eq!( + n(Program::KvQ4, Q4_APPEND_BATCH), + "leleka_kv_append_q4_batch" + ); + assert_eq!(n(Program::KvQ4, Q4_GATHER_STEP), "leleka_kv_gather_q4_step"); + assert_eq!(n(Program::KvQ8, Q8_APPEND_STEP), "leleka_kv_append_q8_step"); + assert_eq!(n(Program::KvQ8, Q8_GATHER_STEP), "leleka_kv_gather_q8_step"); + assert_eq!(n(Program::KvStream, STREAM_RESET), "leleka_kv_stream_reset"); + assert_eq!( + n(Program::KvStream, STREAM_RESOLVE), + "leleka_kv_stream_resolve" + ); + assert_eq!(n(Program::KvStream, STREAM_COPY), "leleka_kv_stream_copy"); + assert_eq!(n(Program::KvStream, RING_TABLE), "leleka_kv_ring_table"); + assert_eq!(n(Program::KvStream, COPY_U4), "leleka_kv_copy_u4"); + assert_eq!( + n(Program::Keyless, KEYLESS_ROUTE), + "leleka_keyless_route_query" + ); + assert_eq!( + n(Program::QsaAttn, ATTN_CHUNK_M2), + "leleka_qsa_attn_chunk_m2" + ); + assert_eq!( + n(Program::QsaAttn, ATTN_CHUNK_M3), + "leleka_qsa_attn_chunk_m3" + ); + assert_eq!( + n(Program::QsaAttn, ATTN_CHUNK_M4), + "leleka_qsa_attn_chunk_m4" + ); + assert_eq!(n(Program::QsaAttn, ATTN_MERGE), "leleka_qsa_attn_merge"); + assert_eq!(n(Program::Cvec, CVEC_APPLY), "leleka_cvec_apply"); +} + +#[test] +fn every_mode_is_off_by_default_and_programs_need_an_explicit_one() { + let none = OptIn::default(); + assert!(none.is_empty()); + assert_eq!(none.digest_text(), ""); + for program in Program::ALL { + assert!(!none.enables(program)); + assert_eq!( + admit(program, &none), + Err(ExperimentalError::NotEnabled(program.name())) + ); + assert!(!program.needed_by().is_empty()); + } + let q4 = OptIn::default().with(Mode::KvQ40); + assert!(q4.enables(Program::KvQ4) && q4.enables(Program::QsaAttn)); + assert!( + !q4.enables(Program::KvStream) + && !q4.enables(Program::Cvec) + && !q4.enables(Program::KvQ8) + ); + let k = OptIn::default().with(Mode::KeylessVOnly); + assert!( + k.enables(Program::Keyless) && k.enables(Program::KvQ8) && !k.enables(Program::KvQ4) + ); + assert_eq!( + OptIn::default() + .with(Mode::KvStreamed) + .with(Mode::KvQ40) + .digest_text(), + "kv-q4_0,kv-streamed" + ); + // every mode reaches at least one program, and the names are unique + for mode in Mode::ALL { + assert!( + Program::ALL.iter().any(|p| p.needed_by().contains(&mode)), + "{mode:?}" + ); + } + let names: std::collections::BTreeSet<_> = Mode::ALL.iter().map(|m| m.name()).collect(); + assert_eq!(names.len(), Mode::ALL.len()); +} + +#[test] +fn sealed_assets_match_their_pins_and_export_every_entry() { + use crate::sealed_ptx::test_support::{ + assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, + without_terminator, + }; + let all = OptIn::NONE + .with(Mode::KvQ40) + .with(Mode::KvK8V4) + .with(Mode::KeylessVOnly) + .with(Mode::KvStreamed) + .with(Mode::ControlVectors); + for program in Program::ALL { + // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim, GPU load is + // verified separately by the host smokes). + let ptx = program.ptx(); + let names = program.entries().iter().map(|e| e.name.to_str().unwrap()); + assert_real_sm120_ptx(program.name(), ptx, names); + assert_nvcc_13_2_86(program.name(), ptx); + let pin = program.pin(); + assert_ne!(pin.source_sha256, [0; 32], "{}", program.name()); + assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name()); + assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name()); + // a program re-synced after the seal (PENDING_RESEAL) keeps its old PTX and refuses to open + let expected = if PENDING_RESEAL.contains(&program) { + Err(ExperimentalError::Unpinned(program.name())) + } else { + Ok(()) + }; + assert_eq!(admit(program, &all), expected, "{}", program.name()); + // the opt-in gate still comes first + assert_eq!( + admit(program, &OptIn::NONE), + Err(ExperimentalError::NotEnabled(program.name())) + ); + // the pin guard still refuses every deviation, on synthetic copies of the real PTX + let refuse = Err(ExperimentalError::Unpinned(program.name())); + assert_eq!(admit_ptx(program, one_byte_corrupted(ptx), pin), refuse); + assert_eq!(admit_ptx(program, one_byte_shorter(ptx), pin), refuse); + assert_eq!(admit_ptx(program, one_byte_longer(ptx), pin), refuse); + assert_eq!(admit_ptx(program, with_embedded_nul(ptx), pin), refuse); + assert_eq!(admit_ptx(program, without_terminator(ptx), pin), refuse); + let mut wrong_digest = *pin; + wrong_digest.ptx_sha256[0] ^= 1; + assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse); + for zeroed in [ + PtxPin { source_sha256: [0; 32], ..*pin }, + PtxPin { ptx_sha256: [0; 32], ..*pin }, + ] { + assert_eq!(admit_ptx(program, ptx, &zeroed), refuse); + } + } +} + +#[test] +fn pending_reseal_lists_exactly_the_unsealed_sources() { + for program in Program::ALL { + assert_eq!( + source_is_sealed(program), + !PENDING_RESEAL.contains(&program), + "{}: PENDING_RESEAL and the source digest of the pin disagree (after a server reseal the list must shrink, after a .cu edit without reseal it must grow)", + program.name() + ); + } + for (i, program) in PENDING_RESEAL.iter().enumerate() { + assert!( + !PENDING_RESEAL[i + 1..].contains(program), + "{} listed twice", + program.name() + ); + } +} + +#[test] +fn a_program_whose_source_is_newer_than_its_ptx_refuses_even_with_a_matching_ptx_digest() { + let all = OptIn::NONE + .with(Mode::KvQ40) + .with(Mode::KvK8V4) + .with(Mode::KeylessVOnly) + .with(Mode::KvStreamed) + .with(Mode::ControlVectors); + for &program in PENDING_RESEAL { + // the PTX bytes are the sealed ones and match their digest ... + assert_eq!(admit_ptx(program, program.ptx(), program.pin()), Ok(())); + // ... but they were not built from the checked-in source: admit fails closed + assert!(!source_is_sealed(program)); + assert_eq!( + admit(program, &all), + Err(ExperimentalError::Unpinned(program.name())) + ); + } +} + +#[test] +fn a_matching_pin_admits_and_any_difference_refuses() { + static GOOD: &[u8] = b".version 8.7\n.target sm_120\n\0"; + let pin = PtxPin { + source_sha256: [1; 32], + ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]), + }; + assert_eq!(admit_ptx(Program::Cvec, GOOD, &pin), Ok(())); + let wrong = PtxPin { + ptx_sha256: [2; 32], + ..pin + }; + assert_eq!( + admit_ptx(Program::Cvec, GOOD, &wrong), + Err(ExperimentalError::Unpinned("cvec")) + ); + let half = PtxPin { + source_sha256: [0; 32], + ..pin + }; + assert_eq!( + admit_ptx(Program::Cvec, GOOD, &half), + Err(ExperimentalError::Unpinned("cvec")) + ); + static NO_NUL: &[u8] = b".version 8.7\n"; + let p2 = PtxPin { + source_sha256: [1; 32], + ptx_sha256: qwen_ffi::sha256(NO_NUL), + }; + assert!(admit_ptx(Program::Cvec, NO_NUL, &p2).is_err()); + static EMBEDDED: &[u8] = b"a\0b\0"; + let p3 = PtxPin { + source_sha256: [1; 32], + ptx_sha256: qwen_ffi::sha256(b"a\0b"), + }; + assert!(admit_ptx(Program::Cvec, EMBEDDED, &p3).is_err()); +} + +#[test] +fn kv_geometry_matches_the_originals_host_wrappers() { + let s = KvShape::real(); + assert_eq!(fwht_grid(1), Ok([1, 1, 1])); + assert_eq!(fwht_grid(4), Ok([1, 1, 1])); + assert_eq!(fwht_grid(5), Ok([2, 1, 1])); + assert!(fwht_grid(0).is_err()); + assert_eq!(q4_step_grid(&s), Ok([2, 8, 2])); + assert_eq!(q4_batch_grid(7, &s), Ok([7, 2, 8])); + assert!(q4_batch_grid(0, &s).is_err()); + // 3 ids * 2 heads * 8 blocks = 48 blocks, 4 per grid block + assert_eq!(q4_gather_grid(3, &s), Ok([12, 1, 1])); + assert_eq!(q4_gather_grid(1, &s), Ok([4, 1, 1])); + assert_eq!(q8_step_grid(&s, true), Ok([2, 4, 2])); + assert_eq!(q8_step_grid(&s, false), Ok([2, 4, 1])); + // 5 ids * 2 heads * 64 float4 = 640 threads + assert_eq!(q8_gather_grid(5, &s), Ok([3, 1, 1])); + let odd = KvShape { head_dim: 192, ..s }; + assert!(odd.check_q8().is_ok() && odd.check_q4().is_err() && odd.check_attn().is_err()); + assert!(KvShape { head_dim: 100, ..s }.check_q8().is_err()); + assert!(KvShape { kv_heads: 0, ..s }.check_q4().is_err()); + assert!(KvShape { page_size: 0, ..s }.check_q8().is_err()); + assert_eq!(copy_u4_grid(1), Ok([1, 1, 1])); + assert_eq!(copy_u4_grid(129), Ok([2, 1, 1])); + assert_eq!(copy_u4_grid(1 << 40), Ok([4096, 1, 1])); + assert_eq!(attn_chunk_grid(64, &s, 3), Ok([1, 2, 3])); + assert_eq!(attn_chunk_grid(65, &s, 1), Ok([2, 2, 1])); + assert_eq!(attn_merge_grid(&s, 4), Ok([24, 4, 1])); + assert!(attn_chunk_grid(0, &s, 1).is_err() && attn_chunk_grid(64, &s, 65_536).is_err()); + assert_eq!(keyless_grid(3, 24), Ok([72, 1, 1])); + assert!(keyless_grid(0, 24).is_err()); + assert_eq!(keyless_matrices_bytes(24), 24 * 65_536 * 4); + assert_eq!(cvec_grid(4, 3, 2560), Ok([4, 3, 1])); + assert!( + cvec_grid(4, 3, 4097).is_err() + && cvec_grid(4, 3, 0).is_err() + && cvec_grid(0, 3, 2560).is_err() + ); +} + +#[test] +fn byte_sizes_agree_with_the_reference_layouts() { + use leleka_experimental_ref::layout::{KvFormat, kv_pool_bytes, pool_arrays}; + let s = KvShape::real(); + let q = QsaShapes::real(); + let pages = 11; + let arrays = pool_arrays(KvFormat::Q4_0, &q, pages); + assert_eq!(arrays[0].bytes, s.q4_bytes(pages)); + assert_eq!(arrays[1].bytes, s.q4_bytes(pages)); + let arrays = pool_arrays(KvFormat::Int8, &q, pages); + assert_eq!(arrays[0].bytes, s.q8_code_bytes(pages)); + assert_eq!(arrays[2].bytes, s.q8_scale_bytes(pages)); + let k8v4 = pool_arrays(KvFormat::K8V4, &q, pages); + assert_eq!( + (k8v4[0].bytes, k8v4[1].bytes, k8v4[2].bytes), + ( + s.q8_code_bytes(pages), + s.q8_scale_bytes(pages), + s.q4_bytes(pages) + ) + ); + // 576 B per cell and layer for Q4_0, one page = 4 cells + assert_eq!( + kv_pool_bytes(KvFormat::Q4_0, &q, pages), + pages * 4 * 576 + 64 + ); + assert_eq!(s.q4_bytes(pages) * 2, pages * 4 * 576); + assert_eq!(s.gather_scratch_bytes(2048), 2048 * 2 * 256 * 2); + assert_eq!(attn_scratch_floats(2048, &s), 32 * 24 * 258 + 64); + assert_eq!(fwht_bytes(24), 24 * 1024); + assert_eq!(s.as_qsa(), q); +} + +#[test] +fn stream_resolve_guards_are_the_originals() { + let s = KvShape::real(); + assert_eq!(check_stream_resolve(&s, 5120, 1, 2048), Ok(())); + assert!( + matches!(check_stream_resolve(&s, 1023, 1, 8), Err(ExperimentalError::Invalid(m)) if m.contains("fewer slots")) + ); + assert!( + matches!(check_stream_resolve(&s, 1024, 8, 4096), Err(ExperimentalError::Invalid(m)) if m.contains("distinct blocks")) + ); + assert!(check_stream_resolve(&s, 5120, 0, 8).is_err()); + let misaligned = KvShape { + kv_heads: 1, + page_size: 1, + ..s + }; + assert!( + matches!(check_stream_resolve(&misaligned, 5120, 1, 8), Err(ExperimentalError::Invalid(m)) if m.contains("16 bytes")) + ); +} diff --git a/crates/cuda-driver/src/kar_decode_levels.rs b/crates/cuda-driver/src/kar_decode_levels.rs index a5673f4f..efec40fb 100644 --- a/crates/cuda-driver/src/kar_decode_levels.rs +++ b/crates/cuda-driver/src/kar_decode_levels.rs @@ -361,341 +361,4 @@ pub fn check_status(bits: u32) -> Result<()> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn hand_computed_window_layout() { - // Level 3, group 64, elements 37..338: words 1..11 (10), groups 0..6 (6). - let g = DecodeGeometry::for_window(3, 64, 37, 301).unwrap(); - assert_eq!( - g, - DecodeGeometry { - level: 3, - group: 64, - count: 301, - head32: 5, - head_group: 37, - scales_offset: 64, - planes_offset: 80, // round_up(64 + 6*2, 16) - plane_stride_words: 12, // round_up(10, 4) - window_words: 10, - window_groups: 6, - packet_bytes: 80 + 3 * 12 * 4, - } - ); - g.validate().unwrap(); - assert_eq!(g.grid(), 2); - assert_eq!((g.packet_len(), g.output_len()), (224, 1204)); - assert_eq!(g.scalars(), [3, 3, 301, 5, 37, 64, 64, 80, 12, 10, 6, 224]); - } - - #[test] - fn level_group_and_count_bounds() { - for level in [0, 1, 6, 8, u32::MAX] { - assert!(DecodeGeometry::for_window(level, 32, 0, 1).is_err()); - } - for level in 2..=5 { - assert!(DecodeGeometry::for_window(level, 32, 0, 1).is_ok()); - } - for group in [0, 1, 16, 31, 33, 48, 1056, u32::MAX] { - assert!( - DecodeGeometry::for_window(2, group, 0, 1).is_err(), - "{group}" - ); - } - for group in [32, 64, 96, 128, 1024] { - assert!(DecodeGeometry::for_window(2, group, 0, 1).is_ok()); - } - assert!(DecodeGeometry::for_window(2, 32, 0, 0).is_err()); - assert!(DecodeGeometry::for_window(2, 32, 0, MAX_RANGE_ELEMENTS).is_ok()); - assert!(DecodeGeometry::for_window(2, 32, 0, MAX_RANGE_ELEMENTS + 1).is_err()); - assert!(DecodeGeometry::for_window(2, 32, u64::MAX, 1).is_err()); - assert!(DecodeGeometry::for_window(2, 32, u64::MAX - 5, 10).is_err()); - } - - #[test] - fn every_layout_from_for_window_validates_and_fits_u32() { - let mut seed = 0x9e37_79b9_7f4a_7c15u64; - let mut next = || { - seed ^= seed >> 12; - seed ^= seed << 25; - seed ^= seed >> 27; - seed.wrapping_mul(0x2545_f491_4f6c_dd1d) - }; - for _ in 0..2000 { - let level = 2 + (next() % 4) as u32; - let group = 32 * (1 + (next() % 32) as u32); - let start = next() % (1 << 40); - let count = 1 + next() % 100_000; - let g = DecodeGeometry::for_window(level, group, start, count).unwrap(); - g.validate().unwrap(); - assert_eq!(g.head32 as u64, start % 32); - assert_eq!(g.head_group as u64, start % u64::from(group)); - assert!(g.packet_bytes as u64 >= BOOK_REGION_BYTES); - assert_eq!(g.planes_offset % 16, 0); - } - // Largest packet: level 5, full range, worst-case unaligned start. - let g = DecodeGeometry::for_window(5, 32, 31, MAX_RANGE_ELEMENTS).unwrap(); - g.validate().unwrap(); - assert!(g.packet_bytes < 1 << 31); - } - - #[test] - fn validate_rejects_each_corruption() { - let good = DecodeGeometry::for_window(4, 96, 100, 700).unwrap(); - good.validate().unwrap(); - let cases: [(&str, DecodeGeometry); 14] = [ - ("level 1", DecodeGeometry { level: 1, ..good }), - ("level 6", DecodeGeometry { level: 6, ..good }), - ("count 0", DecodeGeometry { count: 0, ..good }), - ( - "count max+1", - DecodeGeometry { - count: MAX_RANGE_ELEMENTS as u32 + 1, - ..good - }, - ), - ("group 0", DecodeGeometry { group: 0, ..good }), - ("group 33", DecodeGeometry { group: 33, ..good }), - ("head32", DecodeGeometry { head32: 32, ..good }), - ( - "head_group", - DecodeGeometry { - head_group: good.group, - ..good - }, - ), - ( - "words short", - DecodeGeometry { - window_words: good.window_words - 1, - ..good - }, - ), - ( - "groups short", - DecodeGeometry { - window_groups: good.window_groups - 1, - ..good - }, - ), - ( - "stride", - DecodeGeometry { - plane_stride_words: good.plane_stride_words - 1, - ..good - }, - ), - ( - "planes misaligned", - DecodeGeometry { - planes_offset: good.planes_offset + 2, - ..good - }, - ), - ( - "packet short", - DecodeGeometry { - packet_bytes: good.packet_bytes - 4, - ..good - }, - ), - ( - "scales odd", - DecodeGeometry { - scales_offset: 65, - ..good - }, - ), - ]; - for (name, bad) in cases { - assert!(bad.validate().is_err(), "{name}"); - } - } - - #[test] - fn multiply_geometry_bounds() { - let ok = MultiplyGeometry { - columns: 2048, - rows: 512, - tokens: 8, - }; - ok.validate().unwrap(); - assert_eq!(ok.weights_len(), 2048 * 512 * 4); - assert_eq!(ok.input_len(), 2048 * 8 * 4); - assert_eq!(ok.output_len(), 512 * 8 * 4); - for bad in [ - MultiplyGeometry { columns: 0, ..ok }, - MultiplyGeometry { rows: 0, ..ok }, - MultiplyGeometry { tokens: 0, ..ok }, - MultiplyGeometry { tokens: 9, ..ok }, - MultiplyGeometry { - columns: (MAX_COLUMNS + 1) as u32, - rows: 1, - tokens: 1, - }, - MultiplyGeometry { - columns: 4096, - rows: 4097, - tokens: 1, - }, - ] { - assert!(bad.validate().is_err(), "{bad:?}"); - } - } - - #[test] - fn expert_shape_requires_consistent_single_token_matrices() { - let m = |columns, rows| MultiplyGeometry { - columns, - rows, - tokens: 1, - }; - let shape = - ExpertShape::from_matrices(&m(2560, 640), &m(2560, 640), &m(640, 2560)).unwrap(); - assert_eq!( - shape, - ExpertShape { - hidden: 2560, - ff: 640 - } - ); - let bad: [(MultiplyGeometry, MultiplyGeometry, MultiplyGeometry); 5] = [ - (m(2560, 640), m(2560, 641), m(640, 2560)), - (m(2560, 640), m(2560, 640), m(641, 2560)), - (m(2560, 640), m(2560, 640), m(640, 2561)), - ( - m(2560, 640), - m(2560, 640), - MultiplyGeometry { - tokens: 2, - ..m(640, 2560) - }, - ), - (m(0, 640), m(0, 640), m(640, 0)), - ]; - for (g, u, d) in bad { - assert!(ExpertShape::from_matrices(&g, &u, &d).is_err()); - } - } - - #[test] - fn status_word_is_fail_closed() { - assert!(check_status(0).is_ok()); - for bits in [1, 2, 4, 3, 7] { - assert_eq!(check_status(bits), Err(KarDecodeError::DeviceStatus(bits))); - } - } - - #[test] - fn sealed_ptx_matches_its_pin_and_every_admission_deviation_fails() { - use crate::sealed_ptx::test_support::{ - assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, - without_terminator, - }; - let ptx = KAR_DECODE_LEVELS_PTX; - // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim, GPU load is - // verified separately by the host smokes). - assert_real_sm120_ptx( - "kar_decode_levels", - ptx, - [ENTRY_DECODE, ENTRY_MULTIPLY, ENTRY_SWIGLU].map(|e| e.to_str().unwrap()), - ); - assert_nvcc_13_2_86("kar_decode_levels", ptx); - assert_ne!(KAR_DECODE_LEVELS_PIN.source_sha256, [0; 32]); - assert_ne!(KAR_DECODE_LEVELS_PIN.ptx_sha256, [0; 32]); - assert_eq!( - KAR_DECODE_LEVELS_PIN.ptx_sha256, - qwen_ffi::sha256(&ptx[..ptx.len() - 1]) - ); - assert_eq!( - KAR_DECODE_LEVELS_PIN.source_sha256, - qwen_ffi::sha256(include_str!("kar_decode_levels.cu").as_bytes()) - ); - assert_eq!(admit_ptx(ptx, &KAR_DECODE_LEVELS_PIN), Ok(())); - // The guard still refuses every deviation, on synthetic copies of the real PTX. - let pin = &KAR_DECODE_LEVELS_PIN; - for copy in [ - one_byte_corrupted(ptx), - one_byte_shorter(ptx), - one_byte_longer(ptx), - with_embedded_nul(ptx), - without_terminator(ptx), - ] { - assert_eq!(admit_ptx(copy, pin), Err(KarDecodeError::Unpinned)); - } - let mut wrong_digest = *pin; - wrong_digest.ptx_sha256[0] ^= 1; - assert_eq!(admit_ptx(ptx, &wrong_digest), Err(KarDecodeError::Unpinned)); - // A computed digest alone is not qualification: a zero source pin or a - // zero PTX pin still refuses, and a wrong digest refuses. - let digest = qwen_ffi::sha256(&ptx[..ptx.len() - 1]); - for pin in [ - PtxPin { - source_sha256: [0; 32], - ptx_sha256: digest, - }, - PtxPin { - source_sha256: [1; 32], - ptx_sha256: [0; 32], - }, - PtxPin { - source_sha256: [1; 32], - ptx_sha256: [2; 32], - }, - ] { - assert_eq!(admit_ptx(ptx, &pin), Err(KarDecodeError::Unpinned)); - } - // Only a complete matching pin (a test-local one) admits these bytes. - let matching = PtxPin { - source_sha256: [1; 32], - ptx_sha256: digest, - }; - assert_eq!(admit_ptx(ptx, &matching), Ok(())); - // Malformed bytes (embedded NUL, no terminator, non-ASCII) never admit. - static EMBEDDED_NUL: [u8; 4] = [b'a', 0, b'b', 0]; - static NO_TERMINATOR: [u8; 3] = *b"abc"; - static NON_ASCII: [u8; 3] = [b'a', 0xc3, 0]; - for bytes in [&EMBEDDED_NUL[..], &NO_TERMINATOR[..], &NON_ASCII[..]] { - let pin = PtxPin { - source_sha256: [1; 32], - ptx_sha256: qwen_ffi::sha256(&bytes[..bytes.len() - 1]), - }; - assert!(admit_ptx(bytes, &pin).is_err()); - } - } - - #[test] - fn rust_constants_match_the_cuda_source() { - let source = include_str!("kar_decode_levels.cu"); - for (name, value) in [ - ("kMinLevel", MIN_LEVEL.to_string()), - ("kMaxLevel", MAX_LEVEL.to_string()), - ("kBlockThreads", BLOCK_THREADS.to_string()), - ("kMaxCount", format!("{}u", MAX_RANGE_ELEMENTS)), - ("kMaxTokens", MAX_TOKENS.to_string()), - ("kMaxColumns", format!("{}u", MAX_COLUMNS)), - ("kMaxSwiglu", format!("{}u", MAX_SWIGLU_VALUES)), - ("kBookRegionBytes", BOOK_REGION_BYTES.to_string()), - ("kStatusBadArgument", STATUS_BAD_ARGUMENT.to_string()), - ("kStatusNonfiniteInput", STATUS_NONFINITE_INPUT.to_string()), - ( - "kStatusNonfiniteOutput", - STATUS_NONFINITE_OUTPUT.to_string(), - ), - ] { - let needle = format!("{name} = {value};"); - assert!(source.contains(&needle), "missing `{needle}`"); - } - for entry in [ENTRY_DECODE, ENTRY_MULTIPLY, ENTRY_SWIGLU] { - let needle = format!("__launch_bounds__(256) void {}(", entry.to_str().unwrap()); - assert!(source.contains(&needle), "missing entry {needle}"); - } - // Scalar-argument arity of the decode kernel: 3 pointers + 12 scalars. - let at = source.find("void leleka_kar_decode_levels_f32(").unwrap(); - let signature = &source[at..at + source[at..].find(") {").unwrap()]; - assert_eq!(signature.matches("uint32_t ").count(), 12); - assert_eq!(signature.matches("__restrict__").count(), 3); - } -} +mod tests; diff --git a/crates/cuda-driver/src/kar_decode_levels/tests.rs b/crates/cuda-driver/src/kar_decode_levels/tests.rs new file mode 100644 index 00000000..0157e500 --- /dev/null +++ b/crates/cuda-driver/src/kar_decode_levels/tests.rs @@ -0,0 +1,338 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn hand_computed_window_layout() { + // Level 3, group 64, elements 37..338: words 1..11 (10), groups 0..6 (6). + let g = DecodeGeometry::for_window(3, 64, 37, 301).unwrap(); + assert_eq!( + g, + DecodeGeometry { + level: 3, + group: 64, + count: 301, + head32: 5, + head_group: 37, + scales_offset: 64, + planes_offset: 80, // round_up(64 + 6*2, 16) + plane_stride_words: 12, // round_up(10, 4) + window_words: 10, + window_groups: 6, + packet_bytes: 80 + 3 * 12 * 4, + } + ); + g.validate().unwrap(); + assert_eq!(g.grid(), 2); + assert_eq!((g.packet_len(), g.output_len()), (224, 1204)); + assert_eq!(g.scalars(), [3, 3, 301, 5, 37, 64, 64, 80, 12, 10, 6, 224]); +} + +#[test] +fn level_group_and_count_bounds() { + for level in [0, 1, 6, 8, u32::MAX] { + assert!(DecodeGeometry::for_window(level, 32, 0, 1).is_err()); + } + for level in 2..=5 { + assert!(DecodeGeometry::for_window(level, 32, 0, 1).is_ok()); + } + for group in [0, 1, 16, 31, 33, 48, 1056, u32::MAX] { + assert!( + DecodeGeometry::for_window(2, group, 0, 1).is_err(), + "{group}" + ); + } + for group in [32, 64, 96, 128, 1024] { + assert!(DecodeGeometry::for_window(2, group, 0, 1).is_ok()); + } + assert!(DecodeGeometry::for_window(2, 32, 0, 0).is_err()); + assert!(DecodeGeometry::for_window(2, 32, 0, MAX_RANGE_ELEMENTS).is_ok()); + assert!(DecodeGeometry::for_window(2, 32, 0, MAX_RANGE_ELEMENTS + 1).is_err()); + assert!(DecodeGeometry::for_window(2, 32, u64::MAX, 1).is_err()); + assert!(DecodeGeometry::for_window(2, 32, u64::MAX - 5, 10).is_err()); +} + +#[test] +fn every_layout_from_for_window_validates_and_fits_u32() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = || { + seed ^= seed >> 12; + seed ^= seed << 25; + seed ^= seed >> 27; + seed.wrapping_mul(0x2545_f491_4f6c_dd1d) + }; + for _ in 0..2000 { + let level = 2 + (next() % 4) as u32; + let group = 32 * (1 + (next() % 32) as u32); + let start = next() % (1 << 40); + let count = 1 + next() % 100_000; + let g = DecodeGeometry::for_window(level, group, start, count).unwrap(); + g.validate().unwrap(); + assert_eq!(g.head32 as u64, start % 32); + assert_eq!(g.head_group as u64, start % u64::from(group)); + assert!(g.packet_bytes as u64 >= BOOK_REGION_BYTES); + assert_eq!(g.planes_offset % 16, 0); + } + // Largest packet: level 5, full range, worst-case unaligned start. + let g = DecodeGeometry::for_window(5, 32, 31, MAX_RANGE_ELEMENTS).unwrap(); + g.validate().unwrap(); + assert!(g.packet_bytes < 1 << 31); +} + +#[test] +fn validate_rejects_each_corruption() { + let good = DecodeGeometry::for_window(4, 96, 100, 700).unwrap(); + good.validate().unwrap(); + let cases: [(&str, DecodeGeometry); 14] = [ + ("level 1", DecodeGeometry { level: 1, ..good }), + ("level 6", DecodeGeometry { level: 6, ..good }), + ("count 0", DecodeGeometry { count: 0, ..good }), + ( + "count max+1", + DecodeGeometry { + count: MAX_RANGE_ELEMENTS as u32 + 1, + ..good + }, + ), + ("group 0", DecodeGeometry { group: 0, ..good }), + ("group 33", DecodeGeometry { group: 33, ..good }), + ("head32", DecodeGeometry { head32: 32, ..good }), + ( + "head_group", + DecodeGeometry { + head_group: good.group, + ..good + }, + ), + ( + "words short", + DecodeGeometry { + window_words: good.window_words - 1, + ..good + }, + ), + ( + "groups short", + DecodeGeometry { + window_groups: good.window_groups - 1, + ..good + }, + ), + ( + "stride", + DecodeGeometry { + plane_stride_words: good.plane_stride_words - 1, + ..good + }, + ), + ( + "planes misaligned", + DecodeGeometry { + planes_offset: good.planes_offset + 2, + ..good + }, + ), + ( + "packet short", + DecodeGeometry { + packet_bytes: good.packet_bytes - 4, + ..good + }, + ), + ( + "scales odd", + DecodeGeometry { + scales_offset: 65, + ..good + }, + ), + ]; + for (name, bad) in cases { + assert!(bad.validate().is_err(), "{name}"); + } +} + +#[test] +fn multiply_geometry_bounds() { + let ok = MultiplyGeometry { + columns: 2048, + rows: 512, + tokens: 8, + }; + ok.validate().unwrap(); + assert_eq!(ok.weights_len(), 2048 * 512 * 4); + assert_eq!(ok.input_len(), 2048 * 8 * 4); + assert_eq!(ok.output_len(), 512 * 8 * 4); + for bad in [ + MultiplyGeometry { columns: 0, ..ok }, + MultiplyGeometry { rows: 0, ..ok }, + MultiplyGeometry { tokens: 0, ..ok }, + MultiplyGeometry { tokens: 9, ..ok }, + MultiplyGeometry { + columns: (MAX_COLUMNS + 1) as u32, + rows: 1, + tokens: 1, + }, + MultiplyGeometry { + columns: 4096, + rows: 4097, + tokens: 1, + }, + ] { + assert!(bad.validate().is_err(), "{bad:?}"); + } +} + +#[test] +fn expert_shape_requires_consistent_single_token_matrices() { + let m = |columns, rows| MultiplyGeometry { + columns, + rows, + tokens: 1, + }; + let shape = + ExpertShape::from_matrices(&m(2560, 640), &m(2560, 640), &m(640, 2560)).unwrap(); + assert_eq!( + shape, + ExpertShape { + hidden: 2560, + ff: 640 + } + ); + let bad: [(MultiplyGeometry, MultiplyGeometry, MultiplyGeometry); 5] = [ + (m(2560, 640), m(2560, 641), m(640, 2560)), + (m(2560, 640), m(2560, 640), m(641, 2560)), + (m(2560, 640), m(2560, 640), m(640, 2561)), + ( + m(2560, 640), + m(2560, 640), + MultiplyGeometry { + tokens: 2, + ..m(640, 2560) + }, + ), + (m(0, 640), m(0, 640), m(640, 0)), + ]; + for (g, u, d) in bad { + assert!(ExpertShape::from_matrices(&g, &u, &d).is_err()); + } +} + +#[test] +fn status_word_is_fail_closed() { + assert!(check_status(0).is_ok()); + for bits in [1, 2, 4, 3, 7] { + assert_eq!(check_status(bits), Err(KarDecodeError::DeviceStatus(bits))); + } +} + +#[test] +fn sealed_ptx_matches_its_pin_and_every_admission_deviation_fails() { + use crate::sealed_ptx::test_support::{ + assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, + without_terminator, + }; + let ptx = KAR_DECODE_LEVELS_PTX; + // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim, GPU load is + // verified separately by the host smokes). + assert_real_sm120_ptx( + "kar_decode_levels", + ptx, + [ENTRY_DECODE, ENTRY_MULTIPLY, ENTRY_SWIGLU].map(|e| e.to_str().unwrap()), + ); + assert_nvcc_13_2_86("kar_decode_levels", ptx); + assert_ne!(KAR_DECODE_LEVELS_PIN.source_sha256, [0; 32]); + assert_ne!(KAR_DECODE_LEVELS_PIN.ptx_sha256, [0; 32]); + assert_eq!( + KAR_DECODE_LEVELS_PIN.ptx_sha256, + qwen_ffi::sha256(&ptx[..ptx.len() - 1]) + ); + assert_eq!( + KAR_DECODE_LEVELS_PIN.source_sha256, + qwen_ffi::sha256(include_str!("../kar_decode_levels.cu").as_bytes()) + ); + assert_eq!(admit_ptx(ptx, &KAR_DECODE_LEVELS_PIN), Ok(())); + // The guard still refuses every deviation, on synthetic copies of the real PTX. + let pin = &KAR_DECODE_LEVELS_PIN; + for copy in [ + one_byte_corrupted(ptx), + one_byte_shorter(ptx), + one_byte_longer(ptx), + with_embedded_nul(ptx), + without_terminator(ptx), + ] { + assert_eq!(admit_ptx(copy, pin), Err(KarDecodeError::Unpinned)); + } + let mut wrong_digest = *pin; + wrong_digest.ptx_sha256[0] ^= 1; + assert_eq!(admit_ptx(ptx, &wrong_digest), Err(KarDecodeError::Unpinned)); + // A computed digest alone is not qualification: a zero source pin or a + // zero PTX pin still refuses, and a wrong digest refuses. + let digest = qwen_ffi::sha256(&ptx[..ptx.len() - 1]); + for pin in [ + PtxPin { + source_sha256: [0; 32], + ptx_sha256: digest, + }, + PtxPin { + source_sha256: [1; 32], + ptx_sha256: [0; 32], + }, + PtxPin { + source_sha256: [1; 32], + ptx_sha256: [2; 32], + }, + ] { + assert_eq!(admit_ptx(ptx, &pin), Err(KarDecodeError::Unpinned)); + } + // Only a complete matching pin (a test-local one) admits these bytes. + let matching = PtxPin { + source_sha256: [1; 32], + ptx_sha256: digest, + }; + assert_eq!(admit_ptx(ptx, &matching), Ok(())); + // Malformed bytes (embedded NUL, no terminator, non-ASCII) never admit. + static EMBEDDED_NUL: [u8; 4] = [b'a', 0, b'b', 0]; + static NO_TERMINATOR: [u8; 3] = *b"abc"; + static NON_ASCII: [u8; 3] = [b'a', 0xc3, 0]; + for bytes in [&EMBEDDED_NUL[..], &NO_TERMINATOR[..], &NON_ASCII[..]] { + let pin = PtxPin { + source_sha256: [1; 32], + ptx_sha256: qwen_ffi::sha256(&bytes[..bytes.len() - 1]), + }; + assert!(admit_ptx(bytes, &pin).is_err()); + } +} + +#[test] +fn rust_constants_match_the_cuda_source() { + let source = include_str!("../kar_decode_levels.cu"); + for (name, value) in [ + ("kMinLevel", MIN_LEVEL.to_string()), + ("kMaxLevel", MAX_LEVEL.to_string()), + ("kBlockThreads", BLOCK_THREADS.to_string()), + ("kMaxCount", format!("{}u", MAX_RANGE_ELEMENTS)), + ("kMaxTokens", MAX_TOKENS.to_string()), + ("kMaxColumns", format!("{}u", MAX_COLUMNS)), + ("kMaxSwiglu", format!("{}u", MAX_SWIGLU_VALUES)), + ("kBookRegionBytes", BOOK_REGION_BYTES.to_string()), + ("kStatusBadArgument", STATUS_BAD_ARGUMENT.to_string()), + ("kStatusNonfiniteInput", STATUS_NONFINITE_INPUT.to_string()), + ( + "kStatusNonfiniteOutput", + STATUS_NONFINITE_OUTPUT.to_string(), + ), + ] { + let needle = format!("{name} = {value};"); + assert!(source.contains(&needle), "missing `{needle}`"); + } + for entry in [ENTRY_DECODE, ENTRY_MULTIPLY, ENTRY_SWIGLU] { + let needle = format!("__launch_bounds__(256) void {}(", entry.to_str().unwrap()); + assert!(source.contains(&needle), "missing entry {needle}"); + } + // Scalar-argument arity of the decode kernel: 3 pointers + 12 scalars. + let at = source.find("void leleka_kar_decode_levels_f32(").unwrap(); + let signature = &source[at..at + source[at..].find(") {").unwrap()]; + assert_eq!(signature.matches("uint32_t ").count(), 12); + assert_eq!(signature.matches("__restrict__").count(), 3); +} diff --git a/crates/cuda-driver/src/mmq_original_host_stage.rs b/crates/cuda-driver/src/mmq_original_host_stage.rs index 5c3e3c00..a0d30443 100644 --- a/crates/cuda-driver/src/mmq_original_host_stage.rs +++ b/crates/cuda-driver/src/mmq_original_host_stage.rs @@ -472,154 +472,5 @@ impl Drop for HostStage { } #[cfg(test)] -mod tests { - use super::*; - #[test] - fn scales_finite_matches_the_one_fp16_field_rule() { - for (kind, block) in [(18u32, 98usize), (21, 110), (22, 82), (23, 136), (20, 18), (42, 18)] { - let mut bytes = vec![0x11u8; block * 3]; - assert!(scales_finite(kind, &bytes)); - for bits in [0x7c00u16, 0x7e00, 0xfc00, 0x7c01, 0xffff] { - bytes[block..block + 2].copy_from_slice(&bits.to_le_bytes()); - assert!(!scales_finite(kind, &bytes), "kind {kind} bits {bits:#x}"); - } - bytes[block..block + 2].copy_from_slice(&0x7bffu16.to_le_bytes()); - assert!(scales_finite(kind, &bytes)); - assert!(!scales_finite(kind, &bytes[..block + 1]), "partial block"); - } - assert!(!scales_finite(8, &[0u8; 34])); - } - - /// A stage over zeroed heap buffers and no CUDA: the helper protocol (claims, ring reuse, `finish`) is host code. - fn manual_stage(ring: usize, buffer_bytes: usize, threads: usize) -> HostStage { - let layout = std::alloc::Layout::from_size_align(buffer_bytes.next_multiple_of(4096), 4096).unwrap(); - let mut allocations = Vec::new(); - let mut buffers = Vec::new(); - for _ in 0..ring { - // SAFETY: non-zero size, valid power-of-two alignment. - let pointer = unsafe { std::alloc::alloc_zeroed(layout) }; - assert!(!pointer.is_null()); - allocations.push((pointer, layout)); - buffers.push(pointer as usize); - } - let shared = Arc::new(Shared { - wake: Mutex::new(Wake { generation: 0, jobs: Arc::from(Vec::new()), quit: false }), - cv: Condvar::new(), - head: AtomicU64::new(0), - ready: (0..MAX_JOBS).map(|_| AtomicU32::new(0)).collect(), - released: AtomicUsize::new(0), - active: AtomicUsize::new(0), - buffers: buffers.into_boxed_slice(), - buffer_bytes, - }); - let handles = (0..threads) - .map(|_| { - let shared = Arc::clone(&shared); - thread::spawn(move || shared.work()) - }) - .collect(); - HostStage { - shared, - threads: handles, - allocations, - registered: Vec::new(), - api: None, - generation: 0, - jobs: 0, - sizes: Vec::new(), - issued: 0, - poisoned: false, - job_list: None, - verified: 0, - } - } - /// Three Q2_0/IQ4_NL-sized (kind 20, 18-byte) blocks with a finite FP16 scale (1.0) and `fill` payload. - fn blocks(fill: u8) -> Vec { - let mut bytes = vec![fill; 54]; - for block in bytes.as_chunks_mut::<18>().0.iter_mut() { - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - } - bytes - } - fn job(bytes: &[u8]) -> Job { - let piece = |i: usize| (bytes[i * 18..].as_ptr() as usize, 18, 20); - Job { pieces: [piece(0), piece(1), piece(2)], priority: 0 } - } - - /// `wait` hands out `length` bytes of a page-locked buffer that production allocates uninitialised: a length - /// beyond what the job's helper copied would expose bytes nobody wrote (or a previous job's). - #[test] - fn wait_refuses_a_length_beyond_the_bytes_the_job_copied() { - let mut stage = manual_stage(2, 108, 2); - let (a, b) = (blocks(0x11), blocks(0x22)); - stage.start(vec![job(&a), job(&b)]).unwrap(); - assert_eq!(stage.wait(0, 54, || Ok(0)).unwrap(), &a[..]); - stage.issued(0); - assert!(stage.wait(1, 108, || Ok(0)).is_err(), "108 bytes of a 54-byte job"); - assert_eq!(stage.wait(1, 54, || Ok(0)).unwrap(), &b[..]); - stage.issued(1); - stage.finish(); - stage.close().unwrap(); - } - - /// `finish` is also the early-return path of a layer whose earlier DMAs may still be reading the ring. A helper - /// already holding job 2's claim but waiting for buffer 0's DMA (`released`) must be cancelled by it, not - /// released by `finish`'s own `released = MAX` store into overwriting that buffer. - #[test] - fn finish_cancels_a_helper_that_waits_for_a_buffer_still_being_read() { - let mut stage = manual_stage(2, 54, 3); - let (a, b, c) = (blocks(0x11), blocks(0x22), blocks(0x33)); - stage.start(vec![job(&a), job(&b), job(&c)]).unwrap(); - assert_eq!(stage.wait(0, 54, || Ok(0)).unwrap(), &a[..]); - stage.issued(0); - assert_eq!(stage.wait(1, 54, || Ok(0)).unwrap(), &b[..]); - stage.issued(1); - // all three claimed: job 2 spins on `released > 0` (job 0's DMA never completes here) - while stage.shared.head.load(Ordering::Acquire) & 0xffff != 3 { - thread::yield_now(); - } - thread::sleep(std::time::Duration::from_millis(50)); - stage.finish(); - // SAFETY: `finish` returned with `active == 0`: no helper touches the buffer any more. - let buffer = unsafe { std::slice::from_raw_parts(stage.shared.buffers[0] as *const u8, 54) }; - assert_eq!(buffer, &a[..], "job 2 must not copy into buffer 0 after finish"); - assert_eq!(stage.shared.ready[2].load(Ordering::Acquire), 0); - stage.close().unwrap(); - } - - /// `finish` must not return while a helper that claimed a job BEFORE it can still read the bank (the caller releases - /// the bank right after). That is a store-buffering (Dekker) pair -- `finish`: store `head`, load `active`; helper: - /// increment `active`, claim from `head` -- which needs SeqCst on all four accesses. The window is a few nanoseconds, so - /// this is a statistical guard: the bank is poisoned (scale bytes 0xff) right after `finish`, and a straggler's late copy - /// would show up as 0xff bytes in a ring buffer. HONEST LIMIT: with the four orderings reverted to AcqRel/Release/Acquire - /// it did not fail in 80 runs x 4000 rounds on an i9-11900H, whereas deleting the `active` wait in `finish` failed 2 of 40 runs: - /// it guards gross regressions, not the store-buffering window itself; that rests on the memory-model argument. - #[test] - fn finish_leaves_no_helper_copying_from_a_released_bank() { - const JOBS: usize = 8; // == ring: every claimed job copies at once (no waiting for a DMA) - let mut stage = manual_stage(JOBS, 54, 6); - for round in 0..4000usize { - let mut bank: Vec> = (0..JOBS).map(|_| blocks(0x11)).collect(); - let jobs: Vec = bank.iter().map(|bytes| job(bytes)).collect(); - stage.start(jobs).unwrap(); - // sweep `finish` across the helpers' wake-up and claim window (0..~40 us) - for _ in 0..(round * 7919) % 1000 { - std::hint::spin_loop(); - } - stage.finish(); - for bytes in &mut bank { - bytes.fill(0xff); - } - // give a (buggy) straggler time to complete the copy it started - for _ in 0..50 { - std::hint::spin_loop(); - } - for &buffer in stage.shared.buffers.iter() { - // SAFETY: `finish` returned with `active == 0`, so no helper may touch the ring buffers any more. - let bytes = unsafe { std::slice::from_raw_parts(buffer as *const u8, 54) }; - assert!(!bytes.contains(&0xff), "round {round}: a helper copied from the bank after finish returned"); - } - } - stage.close().unwrap(); - } -} +#[path = "mmq_original_host_stage/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/mmq_original_host_stage/tests.rs b/crates/cuda-driver/src/mmq_original_host_stage/tests.rs new file mode 100644 index 00000000..e34f7ac1 --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_host_stage/tests.rs @@ -0,0 +1,151 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +#[test] +fn scales_finite_matches_the_one_fp16_field_rule() { + for (kind, block) in [(18u32, 98usize), (21, 110), (22, 82), (23, 136), (20, 18), (42, 18)] { + let mut bytes = vec![0x11u8; block * 3]; + assert!(scales_finite(kind, &bytes)); + for bits in [0x7c00u16, 0x7e00, 0xfc00, 0x7c01, 0xffff] { + bytes[block..block + 2].copy_from_slice(&bits.to_le_bytes()); + assert!(!scales_finite(kind, &bytes), "kind {kind} bits {bits:#x}"); + } + bytes[block..block + 2].copy_from_slice(&0x7bffu16.to_le_bytes()); + assert!(scales_finite(kind, &bytes)); + assert!(!scales_finite(kind, &bytes[..block + 1]), "partial block"); + } + assert!(!scales_finite(8, &[0u8; 34])); +} + +/// A stage over zeroed heap buffers and no CUDA: the helper protocol (claims, ring reuse, `finish`) is host code. +fn manual_stage(ring: usize, buffer_bytes: usize, threads: usize) -> HostStage { + let layout = std::alloc::Layout::from_size_align(buffer_bytes.next_multiple_of(4096), 4096).unwrap(); + let mut allocations = Vec::new(); + let mut buffers = Vec::new(); + for _ in 0..ring { + // SAFETY: non-zero size, valid power-of-two alignment. + let pointer = unsafe { std::alloc::alloc_zeroed(layout) }; + assert!(!pointer.is_null()); + allocations.push((pointer, layout)); + buffers.push(pointer as usize); + } + let shared = Arc::new(Shared { + wake: Mutex::new(Wake { generation: 0, jobs: Arc::from(Vec::new()), quit: false }), + cv: Condvar::new(), + head: AtomicU64::new(0), + ready: (0..MAX_JOBS).map(|_| AtomicU32::new(0)).collect(), + released: AtomicUsize::new(0), + active: AtomicUsize::new(0), + buffers: buffers.into_boxed_slice(), + buffer_bytes, + }); + let handles = (0..threads) + .map(|_| { + let shared = Arc::clone(&shared); + thread::spawn(move || shared.work()) + }) + .collect(); + HostStage { + shared, + threads: handles, + allocations, + registered: Vec::new(), + api: None, + generation: 0, + jobs: 0, + sizes: Vec::new(), + issued: 0, + poisoned: false, + job_list: None, + verified: 0, + } +} +/// Three Q2_0/IQ4_NL-sized (kind 20, 18-byte) blocks with a finite FP16 scale (1.0) and `fill` payload. +fn blocks(fill: u8) -> Vec { + let mut bytes = vec![fill; 54]; + for block in bytes.as_chunks_mut::<18>().0.iter_mut() { + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + } + bytes +} +fn job(bytes: &[u8]) -> Job { + let piece = |i: usize| (bytes[i * 18..].as_ptr() as usize, 18, 20); + Job { pieces: [piece(0), piece(1), piece(2)], priority: 0 } +} + +/// `wait` hands out `length` bytes of a page-locked buffer that production allocates uninitialised: a length +/// beyond what the job's helper copied would expose bytes nobody wrote (or a previous job's). +#[test] +fn wait_refuses_a_length_beyond_the_bytes_the_job_copied() { + let mut stage = manual_stage(2, 108, 2); + let (a, b) = (blocks(0x11), blocks(0x22)); + stage.start(vec![job(&a), job(&b)]).unwrap(); + assert_eq!(stage.wait(0, 54, || Ok(0)).unwrap(), &a[..]); + stage.issued(0); + assert!(stage.wait(1, 108, || Ok(0)).is_err(), "108 bytes of a 54-byte job"); + assert_eq!(stage.wait(1, 54, || Ok(0)).unwrap(), &b[..]); + stage.issued(1); + stage.finish(); + stage.close().unwrap(); +} + +/// `finish` is also the early-return path of a layer whose earlier DMAs may still be reading the ring. A helper +/// already holding job 2's claim but waiting for buffer 0's DMA (`released`) must be cancelled by it, not +/// released by `finish`'s own `released = MAX` store into overwriting that buffer. +#[test] +fn finish_cancels_a_helper_that_waits_for_a_buffer_still_being_read() { + let mut stage = manual_stage(2, 54, 3); + let (a, b, c) = (blocks(0x11), blocks(0x22), blocks(0x33)); + stage.start(vec![job(&a), job(&b), job(&c)]).unwrap(); + assert_eq!(stage.wait(0, 54, || Ok(0)).unwrap(), &a[..]); + stage.issued(0); + assert_eq!(stage.wait(1, 54, || Ok(0)).unwrap(), &b[..]); + stage.issued(1); + // all three claimed: job 2 spins on `released > 0` (job 0's DMA never completes here) + while stage.shared.head.load(Ordering::Acquire) & 0xffff != 3 { + thread::yield_now(); + } + thread::sleep(std::time::Duration::from_millis(50)); + stage.finish(); + // SAFETY: `finish` returned with `active == 0`: no helper touches the buffer any more. + let buffer = unsafe { std::slice::from_raw_parts(stage.shared.buffers[0] as *const u8, 54) }; + assert_eq!(buffer, &a[..], "job 2 must not copy into buffer 0 after finish"); + assert_eq!(stage.shared.ready[2].load(Ordering::Acquire), 0); + stage.close().unwrap(); +} + +/// `finish` must not return while a helper that claimed a job BEFORE it can still read the bank (the caller releases +/// the bank right after). That is a store-buffering (Dekker) pair -- `finish`: store `head`, load `active`; helper: +/// increment `active`, claim from `head` -- which needs SeqCst on all four accesses. The window is a few nanoseconds, so +/// this is a statistical guard: the bank is poisoned (scale bytes 0xff) right after `finish`, and a straggler's late copy +/// would show up as 0xff bytes in a ring buffer. HONEST LIMIT: with the four orderings reverted to AcqRel/Release/Acquire +/// it did not fail in 80 runs x 4000 rounds on an i9-11900H, whereas deleting the `active` wait in `finish` failed 2 of 40 runs: +/// it guards gross regressions, not the store-buffering window itself; that rests on the memory-model argument. +#[test] +fn finish_leaves_no_helper_copying_from_a_released_bank() { + const JOBS: usize = 8; // == ring: every claimed job copies at once (no waiting for a DMA) + let mut stage = manual_stage(JOBS, 54, 6); + for round in 0..4000usize { + let mut bank: Vec> = (0..JOBS).map(|_| blocks(0x11)).collect(); + let jobs: Vec = bank.iter().map(|bytes| job(bytes)).collect(); + stage.start(jobs).unwrap(); + // sweep `finish` across the helpers' wake-up and claim window (0..~40 us) + for _ in 0..(round * 7919) % 1000 { + std::hint::spin_loop(); + } + stage.finish(); + for bytes in &mut bank { + bytes.fill(0xff); + } + // give a (buggy) straggler time to complete the copy it started + for _ in 0..50 { + std::hint::spin_loop(); + } + for &buffer in stage.shared.buffers.iter() { + // SAFETY: `finish` returned with `active == 0`, so no helper may touch the ring buffers any more. + let bytes = unsafe { std::slice::from_raw_parts(buffer as *const u8, 54) }; + assert!(!bytes.contains(&0xff), "round {round}: a helper copied from the bank after finish returned"); + } + } + stage.close().unwrap(); +} diff --git a/crates/cuda-driver/src/mtp_original_full_ffi.rs b/crates/cuda-driver/src/mtp_original_full_ffi.rs index 8585eed6..f687fd68 100644 --- a/crates/cuda-driver/src/mtp_original_full_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_full_ffi.rs @@ -384,24 +384,5 @@ impl Module { } } #[cfg(test)] -mod tests { - use super::*; - /// `copy2d` hands the driver a raw descriptor of fixed extents; the two owners it names (`TailLayout` roles - /// 0 = qfull and 1 = qcur, both whole device owners) must cover the last byte it touches for every T. - #[test] - fn q_split_descriptor_stays_inside_both_tail_owners() { - let d = Copy2D::q_split(0x1000, 0x2000_0000); - assert!(d.width <= d.src_pitch && d.width <= d.dst_pitch); - let src_end = (d.height - 1) * d.src_pitch + d.width; - let dst_end = (d.height - 1) * d.dst_pitch + d.width; - for t in 1..=8 { - let layout = super::super::TailLayout::new(248_320, t, false).expect("tail layout"); - assert!(src_end <= layout.sizes[0], "T={t}: source span {src_end} > {}", layout.sizes[0]); - assert!(dst_end <= layout.sizes[1], "T={t}: destination span {dst_end} > {}", layout.sizes[1]); - } - // device -> device through UVA addresses only: no host pointer or array may be smuggled in. - assert_eq!((d.src_type, d.dst_type), (2, 2)); - assert!(d.src_host.is_null() && d.dst_host.is_null() && d.src_array.is_null() && d.dst_array.is_null()); - assert_eq!((d.src_x, d.src_y, d.dst_x, d.dst_y), (0, 0, 0, 0)); - } -} +#[path = "mtp_original_full_ffi/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/mtp_original_full_ffi/tests.rs b/crates/cuda-driver/src/mtp_original_full_ffi/tests.rs new file mode 100644 index 00000000..9d97bf0d --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_ffi/tests.rs @@ -0,0 +1,21 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +/// `copy2d` hands the driver a raw descriptor of fixed extents; the two owners it names (`TailLayout` roles +/// 0 = qfull and 1 = qcur, both whole device owners) must cover the last byte it touches for every T. +#[test] +fn q_split_descriptor_stays_inside_both_tail_owners() { + let d = Copy2D::q_split(0x1000, 0x2000_0000); + assert!(d.width <= d.src_pitch && d.width <= d.dst_pitch); + let src_end = (d.height - 1) * d.src_pitch + d.width; + let dst_end = (d.height - 1) * d.dst_pitch + d.width; + for t in 1..=8 { + let layout = super::super::TailLayout::new(248_320, t, false).expect("tail layout"); + assert!(src_end <= layout.sizes[0], "T={t}: source span {src_end} > {}", layout.sizes[0]); + assert!(dst_end <= layout.sizes[1], "T={t}: destination span {dst_end} > {}", layout.sizes[1]); + } + // device -> device through UVA addresses only: no host pointer or array may be smuggled in. + assert_eq!((d.src_type, d.dst_type), (2, 2)); + assert!(d.src_host.is_null() && d.dst_host.is_null() && d.src_array.is_null() && d.dst_array.is_null()); + assert_eq!((d.src_x, d.src_y, d.dst_x, d.dst_y), (0, 0, 0, 0)); +} diff --git a/crates/cuda-driver/src/original_conversation_state.rs b/crates/cuda-driver/src/original_conversation_state.rs index 85feca8d..41c525bc 100644 --- a/crates/cuda-driver/src/original_conversation_state.rs +++ b/crates/cuda-driver/src/original_conversation_state.rs @@ -347,78 +347,5 @@ impl<'ctx> OriginalSessionState<'ctx> { } #[cfg(test)] -mod tests { - use super::super::{OriginalSessionGeometry, OriginalSessionKvPolicy, OriginalSessionLayout}; - use super::*; - - fn policy() -> OriginalSessionKvPolicy { - OriginalSessionKvPolicy { - resident_cells: 0, - main_off: false, - ring_off: false, - ring_cells: 0, - without_key: false, - int8: true, - int8_rotate: false, - q4: false, - hybrid: false, - } - } - - // The Original geometry's running-state sizes, pinned against the - // compiled C++ `conversation_state_sizes` (golden/state_golden.json: - // whole = [117669888, 368640, 1536, 512, 4]). - #[test] - fn running_state_regions_match_the_original_conversation_sizes() { - let layout = - OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap(); - let facts = layout.conversation_facts(); - assert_eq!((facts.qsa_alloc, facts.gdn_alloc), (12, 36)); - assert_eq!(facts.gdn_state_bytes, 117_669_888); - assert_eq!(facts.ple_hist_bytes, 368_640); - assert_eq!(facts.qsa.len(), 12); - for (j, q) in facts.qsa.iter().enumerate() { - let span = |kind| layout.conversation_span(OriginalRegion::Idx { owned: j, kind }).unwrap().unwrap(); - assert_eq!(span(OriginalIdxKind::Tail).bytes, 1536); - assert_eq!(span(OriginalIdxKind::Dead).bytes, 512); - assert_eq!(span(OriginalIdxKind::BlockPos).bytes, 4); - assert!(q.has("idx_pooled") && q.has("page_table")); - } - } - - #[test] - fn kv_regions_follow_the_state_format_and_streaming_mode() { - let layout = - OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap(); - let kv = |pool, resident| { - layout.conversation_span(OriginalRegion::Kv { layer: OriginalKvLayer::Owned(0), pool, resident }) - }; - // INT8, resident: K/V codes and both scale pools are arena spans. - for pool in [OriginalKvPool::K, OriginalKvPool::V, OriginalKvPool::KScale, OriginalKvPool::VScale, OriginalKvPool::Pooled] { - assert!(kv(pool, false).unwrap().is_some(), "{pool:?}"); - } - // The drafter's K/V is never in the session arena. - assert_eq!( - layout - .conversation_span(OriginalRegion::Kv { - layer: OriginalKvLayer::Draft, - pool: OriginalKvPool::K, - resident: false - }) - .unwrap(), - None - ); - // Out-of-range owned layer is refused. - assert!(layout.conversation_span(OriginalRegion::Idx { owned: 12, kind: OriginalIdxKind::Tail }).is_err()); - // Every span lies inside the session. - for j in 0..12 { - for pool in [OriginalKvPool::K, OriginalKvPool::V, OriginalKvPool::Pooled] { - let s = layout - .conversation_span(OriginalRegion::Kv { layer: OriginalKvLayer::Owned(j), pool, resident: false }) - .unwrap() - .unwrap(); - assert!(s.end().unwrap() <= layout.session_bytes); - } - } - } -} +#[path = "original_conversation_state/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_conversation_state/tests.rs b/crates/cuda-driver/src/original_conversation_state/tests.rs new file mode 100644 index 00000000..513ad14e --- /dev/null +++ b/crates/cuda-driver/src/original_conversation_state/tests.rs @@ -0,0 +1,75 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::super::{OriginalSessionGeometry, OriginalSessionKvPolicy, OriginalSessionLayout}; +use super::*; + +fn policy() -> OriginalSessionKvPolicy { + OriginalSessionKvPolicy { + resident_cells: 0, + main_off: false, + ring_off: false, + ring_cells: 0, + without_key: false, + int8: true, + int8_rotate: false, + q4: false, + hybrid: false, + } +} + +// The Original geometry's running-state sizes, pinned against the +// compiled C++ `conversation_state_sizes` (golden/state_golden.json: +// whole = [117669888, 368640, 1536, 512, 4]). +#[test] +fn running_state_regions_match_the_original_conversation_sizes() { + let layout = + OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap(); + let facts = layout.conversation_facts(); + assert_eq!((facts.qsa_alloc, facts.gdn_alloc), (12, 36)); + assert_eq!(facts.gdn_state_bytes, 117_669_888); + assert_eq!(facts.ple_hist_bytes, 368_640); + assert_eq!(facts.qsa.len(), 12); + for (j, q) in facts.qsa.iter().enumerate() { + let span = |kind| layout.conversation_span(OriginalRegion::Idx { owned: j, kind }).unwrap().unwrap(); + assert_eq!(span(OriginalIdxKind::Tail).bytes, 1536); + assert_eq!(span(OriginalIdxKind::Dead).bytes, 512); + assert_eq!(span(OriginalIdxKind::BlockPos).bytes, 4); + assert!(q.has("idx_pooled") && q.has("page_table")); + } +} + +#[test] +fn kv_regions_follow_the_state_format_and_streaming_mode() { + let layout = + OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap(); + let kv = |pool, resident| { + layout.conversation_span(OriginalRegion::Kv { layer: OriginalKvLayer::Owned(0), pool, resident }) + }; + // INT8, resident: K/V codes and both scale pools are arena spans. + for pool in [OriginalKvPool::K, OriginalKvPool::V, OriginalKvPool::KScale, OriginalKvPool::VScale, OriginalKvPool::Pooled] { + assert!(kv(pool, false).unwrap().is_some(), "{pool:?}"); + } + // The drafter's K/V is never in the session arena. + assert_eq!( + layout + .conversation_span(OriginalRegion::Kv { + layer: OriginalKvLayer::Draft, + pool: OriginalKvPool::K, + resident: false + }) + .unwrap(), + None + ); + // Out-of-range owned layer is refused. + assert!(layout.conversation_span(OriginalRegion::Idx { owned: 12, kind: OriginalIdxKind::Tail }).is_err()); + // Every span lies inside the session. + for j in 0..12 { + for pool in [OriginalKvPool::K, OriginalKvPool::V, OriginalKvPool::Pooled] { + let s = layout + .conversation_span(OriginalRegion::Kv { layer: OriginalKvLayer::Owned(j), pool, resident: false }) + .unwrap() + .unwrap(); + assert!(s.end().unwrap() <= layout.session_bytes); + } + } +} diff --git a/crates/cuda-driver/src/original_expert_stager.rs b/crates/cuda-driver/src/original_expert_stager.rs index fcf54a6f..767af3f3 100644 --- a/crates/cuda-driver/src/original_expert_stager.rs +++ b/crates/cuda-driver/src/original_expert_stager.rs @@ -1191,71 +1191,4 @@ impl OriginalExpertStager<'_> { } #[cfg(test)] -mod tests { - use super::*; - - /// `stop` is the fence after which the caller releases the sources the workers copy from. A worker that claimed - /// before it must have left (`active == 0`) when it returns; a claim that completes AFTER it returned would copy - /// from released memory. The window is a few nanoseconds (store-buffering on `head`/`active`), so this is a - /// statistical guard: helpers run the real claim prologue and, once `stop` returned, a flag marks the source released. - #[test] - fn stop_leaves_no_worker_claiming_after_it_returns() { - let shared = Arc::new(Shared { - work: Mutex::new(Work { generation: 0, quit: false, jobs: Vec::new() }), - cv: Condvar::new(), - head: AtomicU64::new(0), - issued: AtomicUsize::new(0), - active: AtomicUsize::new(0), - ready: Vec::new(), - started: AtomicUsize::new(0), - failed: AtomicBool::new(false), - error: Mutex::new(None), - slots: Vec::new(), - }); - let released = Arc::new(AtomicBool::new(false)); - let late = Arc::new(AtomicUsize::new(0)); - let quit = Arc::new(AtomicBool::new(false)); - let round = Arc::new(std::sync::atomic::AtomicU32::new(0)); - let helpers: Vec<_> = (0..6) - .map(|_| { - let (shared, released, late, quit, round) = - (shared.clone(), released.clone(), late.clone(), quit.clone(), round.clone()); - thread::spawn(move || { - while !quit.load(Ordering::Acquire) { - let generation = round.load(Ordering::Acquire); - if let Some((active, _job)) = shared.enter_claim(generation) { - // the "copy from the source", then a check that the source was not released meanwhile - for _ in 0..200 { - std::hint::spin_loop(); - } - if released.load(Ordering::SeqCst) { - late.fetch_add(1, Ordering::SeqCst); - } - drop(active); - } else { - std::hint::spin_loop(); - } - } - }) - }) - .collect(); - for generation in 1..=100_000u32 { - round.store(generation, Ordering::Release); - shared.head.store((u64::from(generation) << 32) | (4000 << 16), Ordering::Release); - for _ in 0..20 { - std::hint::spin_loop(); - } - shared.stop(generation); - released.store(true, Ordering::SeqCst); - for _ in 0..400 { - std::hint::spin_loop(); - } - released.store(false, Ordering::SeqCst); - } - quit.store(true, Ordering::Release); - for helper in helpers { - helper.join().unwrap(); - } - assert_eq!(late.load(Ordering::SeqCst), 0, "a worker claimed after stop returned"); - } -} +mod tests; diff --git a/crates/cuda-driver/src/original_expert_stager/tests.rs b/crates/cuda-driver/src/original_expert_stager/tests.rs new file mode 100644 index 00000000..93875d08 --- /dev/null +++ b/crates/cuda-driver/src/original_expert_stager/tests.rs @@ -0,0 +1,68 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +/// `stop` is the fence after which the caller releases the sources the workers copy from. A worker that claimed +/// before it must have left (`active == 0`) when it returns; a claim that completes AFTER it returned would copy +/// from released memory. The window is a few nanoseconds (store-buffering on `head`/`active`), so this is a +/// statistical guard: helpers run the real claim prologue and, once `stop` returned, a flag marks the source released. +#[test] +fn stop_leaves_no_worker_claiming_after_it_returns() { + let shared = Arc::new(Shared { + work: Mutex::new(Work { generation: 0, quit: false, jobs: Vec::new() }), + cv: Condvar::new(), + head: AtomicU64::new(0), + issued: AtomicUsize::new(0), + active: AtomicUsize::new(0), + ready: Vec::new(), + started: AtomicUsize::new(0), + failed: AtomicBool::new(false), + error: Mutex::new(None), + slots: Vec::new(), + }); + let released = Arc::new(AtomicBool::new(false)); + let late = Arc::new(AtomicUsize::new(0)); + let quit = Arc::new(AtomicBool::new(false)); + let round = Arc::new(std::sync::atomic::AtomicU32::new(0)); + let helpers: Vec<_> = (0..6) + .map(|_| { + let (shared, released, late, quit, round) = + (shared.clone(), released.clone(), late.clone(), quit.clone(), round.clone()); + thread::spawn(move || { + while !quit.load(Ordering::Acquire) { + let generation = round.load(Ordering::Acquire); + if let Some((active, _job)) = shared.enter_claim(generation) { + // the "copy from the source", then a check that the source was not released meanwhile + for _ in 0..200 { + std::hint::spin_loop(); + } + if released.load(Ordering::SeqCst) { + late.fetch_add(1, Ordering::SeqCst); + } + drop(active); + } else { + std::hint::spin_loop(); + } + } + }) + }) + .collect(); + for generation in 1..=100_000u32 { + round.store(generation, Ordering::Release); + shared.head.store((u64::from(generation) << 32) | (4000 << 16), Ordering::Release); + for _ in 0..20 { + std::hint::spin_loop(); + } + shared.stop(generation); + released.store(true, Ordering::SeqCst); + for _ in 0..400 { + std::hint::spin_loop(); + } + released.store(false, Ordering::SeqCst); + } + quit.store(true, Ordering::Release); + for helper in helpers { + helper.join().unwrap(); + } + assert_eq!(late.load(Ordering::SeqCst), 0, "a worker claimed after stop returned"); +} diff --git a/crates/cuda-driver/src/original_expert_stager_ffi.rs b/crates/cuda-driver/src/original_expert_stager_ffi.rs index e123151a..0ab24df9 100644 --- a/crates/cuda-driver/src/original_expert_stager_ffi.rs +++ b/crates/cuda-driver/src/original_expert_stager_ffi.rs @@ -476,70 +476,5 @@ impl CopyJob { } #[cfg(test)] -mod tests { - use super::*; - - /// A `CopyJob` keeps only raw addresses; its own checks are what bound the worker's `copy_nonoverlapping`. - #[test] - fn copy_job_is_bounded_by_the_slot_and_refuses_empty_or_overlapping_parts() { - let (a, b, c) = ([1u8; 4], [2u8; 6], [3u8; 2]); - assert!(CopyJob::from_slices([&a, &b, &c], 11).is_err(), "12 bytes into an 11-byte slot"); - assert!(CopyJob::from_slices([&a, &[], &c], 64).is_err(), "empty part"); - let job = CopyJob::from_slices([&a, &b, &c], 12).unwrap(); - assert_eq!(job.bytes(), 12); - let mut slot = vec![0u8; 12]; - let at = |bytes| WorkerSlot { address: slot.as_ptr() as usize, bytes, event: 0 }; - assert!(job.copy_to(at(11)).is_err(), "slot smaller than the job"); - assert!(slot.iter().all(|b| *b == 0), "nothing written on refusal"); - assert!(job.copy_to(WorkerSlot { address: 0, bytes: 12, event: 0 }).is_err()); - job.copy_to(WorkerSlot { address: slot.as_mut_ptr() as usize, bytes: 12, event: 0 }).unwrap(); - assert_eq!(slot, [1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3]); - // a destination that overlaps a source is refused before any byte moves - let mut shared = vec![9u8; 16]; - let overlapping = CopyJob::from_slices([&shared[0..4], &shared[4..10], &shared[10..12]], 12).unwrap(); - let base = shared.as_mut_ptr() as usize; - assert!(overlapping.copy_to(WorkerSlot { address: base + 2, bytes: 12, event: 0 }).is_err()); - assert!(shared.iter().all(|b| *b == 9)); - } - - /// `part` is the only way a worker source slice is made from the mapping. - #[test] - fn expert_file_map_part_is_bounded_by_the_mapping() { - #[cfg(windows)] - let ptr = { - use std::os::windows::io::AsRawHandle; - let path = std::env::temp_dir().join(format!("leleka-expert-map-{}.bin", std::process::id())); - std::fs::write(&path, vec![7u8; 8192]).unwrap(); - let file = std::fs::File::open(&path).unwrap(); - // SAFETY: a live handle; the view is unmapped by the map's own Drop (the file may be deleted afterwards). - let view = unsafe { libc::map_file_readonly(file.as_raw_handle().cast(), 0, 8192) }; - drop(file); - let _ = std::fs::remove_file(&path); - view - }; - #[cfg(unix)] - // SAFETY: anonymous private mapping; unmapped by the map's own Drop. - let ptr = unsafe { - libc::mmap( - std::ptr::null_mut(), - 8192, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, - -1, - 0, - ) - }; - #[cfg(unix)] - assert_ne!(ptr, libc::MAP_FAILED); - #[cfg(windows)] - assert!(!ptr.is_null()); - let map = ExpertFileMap { address: ptr as usize, bytes: 8192 }; - assert_eq!(map.part(0, 8192).unwrap().len(), 8192); - assert_eq!(map.part(8191, 1).unwrap().len(), 1); - assert!(map.part(0, 8193).is_err()); - assert!(map.part(8192, 1).is_err()); - assert!(map.part(8191, 2).is_err()); - assert!(map.part(u64::MAX, 1).is_err()); - assert!(map.part(1, usize::MAX).is_err()); - } -} +#[path = "original_expert_stager_ffi/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_expert_stager_ffi/tests.rs b/crates/cuda-driver/src/original_expert_stager_ffi/tests.rs new file mode 100644 index 00000000..a37b6f7b --- /dev/null +++ b/crates/cuda-driver/src/original_expert_stager_ffi/tests.rs @@ -0,0 +1,67 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +/// A `CopyJob` keeps only raw addresses; its own checks are what bound the worker's `copy_nonoverlapping`. +#[test] +fn copy_job_is_bounded_by_the_slot_and_refuses_empty_or_overlapping_parts() { + let (a, b, c) = ([1u8; 4], [2u8; 6], [3u8; 2]); + assert!(CopyJob::from_slices([&a, &b, &c], 11).is_err(), "12 bytes into an 11-byte slot"); + assert!(CopyJob::from_slices([&a, &[], &c], 64).is_err(), "empty part"); + let job = CopyJob::from_slices([&a, &b, &c], 12).unwrap(); + assert_eq!(job.bytes(), 12); + let mut slot = vec![0u8; 12]; + let at = |bytes| WorkerSlot { address: slot.as_ptr() as usize, bytes, event: 0 }; + assert!(job.copy_to(at(11)).is_err(), "slot smaller than the job"); + assert!(slot.iter().all(|b| *b == 0), "nothing written on refusal"); + assert!(job.copy_to(WorkerSlot { address: 0, bytes: 12, event: 0 }).is_err()); + job.copy_to(WorkerSlot { address: slot.as_mut_ptr() as usize, bytes: 12, event: 0 }).unwrap(); + assert_eq!(slot, [1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3]); + // a destination that overlaps a source is refused before any byte moves + let mut shared = vec![9u8; 16]; + let overlapping = CopyJob::from_slices([&shared[0..4], &shared[4..10], &shared[10..12]], 12).unwrap(); + let base = shared.as_mut_ptr() as usize; + assert!(overlapping.copy_to(WorkerSlot { address: base + 2, bytes: 12, event: 0 }).is_err()); + assert!(shared.iter().all(|b| *b == 9)); +} + +/// `part` is the only way a worker source slice is made from the mapping. +#[test] +fn expert_file_map_part_is_bounded_by_the_mapping() { + #[cfg(windows)] + let ptr = { + use std::os::windows::io::AsRawHandle; + let path = std::env::temp_dir().join(format!("leleka-expert-map-{}.bin", std::process::id())); + std::fs::write(&path, vec![7u8; 8192]).unwrap(); + let file = std::fs::File::open(&path).unwrap(); + // SAFETY: a live handle; the view is unmapped by the map's own Drop (the file may be deleted afterwards). + let view = unsafe { libc::map_file_readonly(file.as_raw_handle().cast(), 0, 8192) }; + drop(file); + let _ = std::fs::remove_file(&path); + view + }; + #[cfg(unix)] + // SAFETY: anonymous private mapping; unmapped by the map's own Drop. + let ptr = unsafe { + libc::mmap( + std::ptr::null_mut(), + 8192, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + #[cfg(unix)] + assert_ne!(ptr, libc::MAP_FAILED); + #[cfg(windows)] + assert!(!ptr.is_null()); + let map = ExpertFileMap { address: ptr as usize, bytes: 8192 }; + assert_eq!(map.part(0, 8192).unwrap().len(), 8192); + assert_eq!(map.part(8191, 1).unwrap().len(), 1); + assert!(map.part(0, 8193).is_err()); + assert!(map.part(8192, 1).is_err()); + assert!(map.part(8191, 2).is_err()); + assert!(map.part(u64::MAX, 1).is_err()); + assert!(map.part(1, usize::MAX).is_err()); +} diff --git a/crates/cuda-driver/src/original_file_expert_source_ffi.rs b/crates/cuda-driver/src/original_file_expert_source_ffi.rs index 43b3e3a0..8f46ce46 100644 --- a/crates/cuda-driver/src/original_file_expert_source_ffi.rs +++ b/crates/cuda-driver/src/original_file_expert_source_ffi.rs @@ -451,68 +451,5 @@ pub(crate) fn partial_pin_cap(value: Option<&str>) -> usize { } #[cfg(test)] -mod tests { - use super::*; - - fn arena(bytes: usize) -> Arena { - // SAFETY: zeroed allocation of a non-zero size; released by `release` below. - let p = unsafe { libc::calloc(1, bytes) }; - assert!(!p.is_null()); - Arena { address: p as usize, bytes, alias: 0, full_pin: false, partial: 0, locked: 0, lock_off: 0 } - } - fn release(arena: Arena) { - // SAFETY: the block `arena` above allocated, freed once. - unsafe { libc::free(arena.address as P) }; - } - - /// Every raw view of the arena (`write` record, `part`, `overwrite`) is bounded by the allocation. - #[test] - fn arena_write_part_and_overwrite_stay_inside_the_block() { - let a = arena(64); - let (x, y, z) = ([1u8; 8], [2u8; 8], [3u8; 8]); - assert!(a.write(41, [&x, &y, &z]).is_err(), "41 + 24 > 64"); - assert!(a.write(usize::MAX - 3, [&x, &y, &z]).is_err(), "offset overflow"); - assert!(a.write(0, [&x, &[], &z]).is_err(), "empty part"); - a.write(40, [&x, &y, &z]).unwrap().run().unwrap(); - assert_eq!(a.part(40, 24).unwrap(), [&x[..], &y, &z].concat()); - assert!(a.part(41, 24).is_err()); - assert!(a.part(usize::MAX, 2).is_err()); - assert!(a.overwrite(61, &[0u8; 4]).is_err()); - assert!(a.overwrite(0, &[]).is_err()); - a.overwrite(60, &[7u8; 4]).unwrap(); - assert_eq!(a.part(60, 4).unwrap(), [7u8; 4]); - let inside = a.part(0, 8).unwrap(); - assert!(a.overwrite(4, inside).is_err(), "source overlapping the destination"); - release(a); - } - - /// A `Copy` record is raw addresses; `run` refuses overlap, null/empty pieces and oversize before moving a byte. - #[test] - fn copy_records_refuse_overlap_empty_null_and_oversize_parts() { - let mut out = vec![0u8; 12]; - let base = out.as_ptr() as usize; - let src = [5u8; 12]; - let at = |i: usize| src[i..].as_ptr() as usize; - assert!(copy_parts_record([(at(0), 4), (at(4), 4), (at(8), 5)], &mut out).is_err(), "13 > 12"); - assert!(copy_parts_record([(at(0), 4), (0, 4), (at(8), 4)], &mut out).is_err(), "null piece"); - assert!(copy_parts_record([(at(0), 4), (at(4), 0), (at(8), 4)], &mut out).is_err(), "empty piece"); - assert!(copy_parts_record([(at(0), 4), (usize::MAX - 1, 4), (at(8), 4)], &mut out).is_err(), "address overflow"); - assert!(copy_parts_to([(base + 2, 4), (at(4), 4), (at(8), 4)], &mut out).is_err(), "source overlapping the output"); - assert!(out.iter().all(|b| *b == 0)); - copy_parts_to([(at(0), 4), (at(4), 4), (at(8), 4)], &mut out).unwrap(); - assert_eq!(out, src); - } - - #[test] - fn partial_pin_cap_parses_a_positive_prefix_and_falls_back_to_24_gib() { - const GIB: usize = 1 << 30; - assert_eq!(partial_pin_cap(None), 24 * GIB); - assert_eq!(partial_pin_cap(Some("")), 24 * GIB); - assert_eq!(partial_pin_cap(Some("-3")), 24 * GIB); - assert_eq!(partial_pin_cap(Some("nan")), 24 * GIB); - assert_eq!(partial_pin_cap(Some("0.5")), GIB / 2); - assert_eq!(partial_pin_cap(Some(" 2x")), 2 * GIB); - assert_eq!(partial_pin_cap(Some("1e999")), usize::MAX); - assert_eq!(partial_pin_cap(Some("1\0")), 24 * GIB, "an interior NUL cannot be passed to strtod"); - } -} +#[path = "original_file_expert_source_ffi/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_file_expert_source_ffi/tests.rs b/crates/cuda-driver/src/original_file_expert_source_ffi/tests.rs new file mode 100644 index 00000000..9e19f175 --- /dev/null +++ b/crates/cuda-driver/src/original_file_expert_source_ffi/tests.rs @@ -0,0 +1,65 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn arena(bytes: usize) -> Arena { + // SAFETY: zeroed allocation of a non-zero size; released by `release` below. + let p = unsafe { libc::calloc(1, bytes) }; + assert!(!p.is_null()); + Arena { address: p as usize, bytes, alias: 0, full_pin: false, partial: 0, locked: 0, lock_off: 0 } +} +fn release(arena: Arena) { + // SAFETY: the block `arena` above allocated, freed once. + unsafe { libc::free(arena.address as P) }; +} + +/// Every raw view of the arena (`write` record, `part`, `overwrite`) is bounded by the allocation. +#[test] +fn arena_write_part_and_overwrite_stay_inside_the_block() { + let a = arena(64); + let (x, y, z) = ([1u8; 8], [2u8; 8], [3u8; 8]); + assert!(a.write(41, [&x, &y, &z]).is_err(), "41 + 24 > 64"); + assert!(a.write(usize::MAX - 3, [&x, &y, &z]).is_err(), "offset overflow"); + assert!(a.write(0, [&x, &[], &z]).is_err(), "empty part"); + a.write(40, [&x, &y, &z]).unwrap().run().unwrap(); + assert_eq!(a.part(40, 24).unwrap(), [&x[..], &y, &z].concat()); + assert!(a.part(41, 24).is_err()); + assert!(a.part(usize::MAX, 2).is_err()); + assert!(a.overwrite(61, &[0u8; 4]).is_err()); + assert!(a.overwrite(0, &[]).is_err()); + a.overwrite(60, &[7u8; 4]).unwrap(); + assert_eq!(a.part(60, 4).unwrap(), [7u8; 4]); + let inside = a.part(0, 8).unwrap(); + assert!(a.overwrite(4, inside).is_err(), "source overlapping the destination"); + release(a); +} + +/// A `Copy` record is raw addresses; `run` refuses overlap, null/empty pieces and oversize before moving a byte. +#[test] +fn copy_records_refuse_overlap_empty_null_and_oversize_parts() { + let mut out = vec![0u8; 12]; + let base = out.as_ptr() as usize; + let src = [5u8; 12]; + let at = |i: usize| src[i..].as_ptr() as usize; + assert!(copy_parts_record([(at(0), 4), (at(4), 4), (at(8), 5)], &mut out).is_err(), "13 > 12"); + assert!(copy_parts_record([(at(0), 4), (0, 4), (at(8), 4)], &mut out).is_err(), "null piece"); + assert!(copy_parts_record([(at(0), 4), (at(4), 0), (at(8), 4)], &mut out).is_err(), "empty piece"); + assert!(copy_parts_record([(at(0), 4), (usize::MAX - 1, 4), (at(8), 4)], &mut out).is_err(), "address overflow"); + assert!(copy_parts_to([(base + 2, 4), (at(4), 4), (at(8), 4)], &mut out).is_err(), "source overlapping the output"); + assert!(out.iter().all(|b| *b == 0)); + copy_parts_to([(at(0), 4), (at(4), 4), (at(8), 4)], &mut out).unwrap(); + assert_eq!(out, src); +} + +#[test] +fn partial_pin_cap_parses_a_positive_prefix_and_falls_back_to_24_gib() { + const GIB: usize = 1 << 30; + assert_eq!(partial_pin_cap(None), 24 * GIB); + assert_eq!(partial_pin_cap(Some("")), 24 * GIB); + assert_eq!(partial_pin_cap(Some("-3")), 24 * GIB); + assert_eq!(partial_pin_cap(Some("nan")), 24 * GIB); + assert_eq!(partial_pin_cap(Some("0.5")), GIB / 2); + assert_eq!(partial_pin_cap(Some(" 2x")), 2 * GIB); + assert_eq!(partial_pin_cap(Some("1e999")), usize::MAX); + assert_eq!(partial_pin_cap(Some("1\0")), 24 * GIB, "an interior NUL cannot be passed to strtod"); +} diff --git a/crates/cuda-driver/src/original_mtp_draft_vocab.rs b/crates/cuda-driver/src/original_mtp_draft_vocab.rs index 55eccbea..35181fa5 100644 --- a/crates/cuda-driver/src/original_mtp_draft_vocab.rs +++ b/crates/cuda-driver/src/original_mtp_draft_vocab.rs @@ -255,342 +255,4 @@ pub(crate) fn describe(selection: &Selection) -> Option { } #[cfg(test)] -mod tests { - use super::*; - use crate::original_mtp_coupled::subset_inverse; - use crate::original_mtp_rt::{ - fixtures::{TempDir, write}, - observed_draft_vocab_bytes_with, read_draft_vocab_with, validate_subset, - }; - - fn raw(ids: &[i32]) -> Vec { - ids.iter().flat_map(|i| i.to_le_bytes()).collect() - } - - #[test] - fn setting_parses_names_paths_and_the_default_spellings() { - for off in [None, Some(""), Some("0"), Some("off"), Some("default")] { - assert_eq!( - Setting::parse(off.map(OsStr::new)), - Setting::Default, - "{off:?}" - ); - } - assert_eq!(Setting::parse(Some(OsStr::new("en"))), Setting::Named(1)); - assert_eq!( - Setting::parse(Some(OsStr::new("cyrillic"))), - Setting::Named(2) - ); - assert_eq!(Setting::parse(Some(OsStr::new("fr"))), Setting::Named(3)); - assert_eq!( - Setting::parse(Some(OsStr::new("/data/x/draft_vocab_en.bin"))), - Setting::Path(PathBuf::from("/data/x/draft_vocab_en.bin")) - ); - // case matters: "EN" is a (missing) path, not the English subset - assert_eq!( - Setting::parse(Some(OsStr::new("EN"))), - Setting::Path(PathBuf::from("EN")) - ); - } - - #[test] - fn recorded_table_is_consistent() { - assert_eq!(KNOWN[0].name, "default"); - assert_eq!(KNOWN[0].file, "draft_vocab.bin"); - for k in &KNOWN { - assert_eq!(k.sha256.len(), 64, "{}", k.name); - assert!( - k.sha256 - .bytes() - .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()), - "{}", - k.name - ); - assert_eq!( - k.file, - if k.name == "default" { - "draft_vocab.bin".to_string() - } else { - format!("draft_vocab_{}.bin", k.name) - } - ); - assert!(k.ids as u64 <= DRAFT_VOCAB_MAX_IDS); - } - let mut digests: Vec<_> = KNOWN.iter().map(|k| k.sha256).collect(); - digests.sort_unstable(); - digests.dedup(); - assert_eq!(digests.len(), KNOWN.len()); - // sha256 of the empty input pins the hex spelling used for the comparison - assert_eq!( - hex(&Sha256::digest(b"")), - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - ); - } - - #[test] - fn default_setting_reads_nothing_and_logs_nothing() { - let dir = TempDir::new("dv-default"); - write(&dir, "draft_vocab_en.bin", &raw(&[1, 2, 3])); - let selection = select(&dir.0, &Setting::Default).unwrap(); - assert_eq!(selection, Selection::Default); - assert_eq!(describe(&selection), None); - assert_eq!(subset(&selection), None); - } - - #[test] - fn missing_file_falls_back_to_the_default_file_with_a_log_line() { - let dir = TempDir::new("dv-missing"); - let ids = [7i32, 3, 9]; - write(&dir, "draft_vocab.bin", &raw(&ids)); - for setting in [Setting::Named(1), Setting::Path(dir.0.join("nowhere.bin"))] { - let selection = select(&dir.0, &setting).unwrap(); - assert!( - matches!(selection, Selection::Fallback { .. }), - "{setting:?}" - ); - assert!(describe(&selection).unwrap().contains("FALLBACK")); - assert_eq!(subset(&selection), None); - // the reserve probe and the reader then see rt/draft_vocab.bin - assert_eq!(probe_bytes(&dir.0, &selection), Some(12)); - } - assert_eq!( - read_draft_vocab_with(&dir.0, &Setting::Named(1)).unwrap(), - DraftVocab::Subset(ids.to_vec()) - ); - assert_eq!( - observed_draft_vocab_bytes_with(&dir.0, &Setting::Named(1)), - Some(12) - ); - } - - /// A table whose digests belong to synthetic files, so the accepted path runs without the upstream data. - fn table_for(default: &[u8], en: &[u8]) -> [KnownSubset; 2] { - let leak = |bytes: &[u8]| -> &'static str { - Box::leak(hex(&Sha256::digest(bytes)).into_boxed_str()) - }; - [ - KnownSubset { - name: "default", - file: "draft_vocab.bin", - sha256: leak(default), - ids: default.len() / 4, - }, - KnownSubset { - name: "en", - file: "draft_vocab_en.bin", - sha256: leak(en), - ids: en.len() / 4, - }, - ] - } - - #[test] - fn matching_digest_is_accepted_and_reads_the_selected_ids() { - let dir = TempDir::new("dv-ok"); - let default_ids = [40i32, 3, 9, 63, 0, 17]; - let english_ids = [0i32, 3, 9, 17]; - let (default, en) = (raw(&default_ids), raw(&english_ids)); - write(&dir, "draft_vocab.bin", &default); - write(&dir, "draft_vocab_en.bin", &en); - write(&dir, "elsewhere.bin", &en); - let table = table_for(&default, &en); - for setting in [ - Setting::Named(1), - Setting::Path(dir.0.join("elsewhere.bin")), - ] { - let selection = select_in(&dir.0, &setting, &table).unwrap(); - let Selection::Verified { label, bytes, .. } = &selection else { - panic!("{selection:?}") - }; - assert_eq!((*label, bytes.len()), ("en", 16)); - assert_eq!( - crate::original_mtp_rt::read_selected_draft_vocab(&dir.0, &selection).unwrap(), - DraftVocab::Subset(english_ids.to_vec()) - ); - assert_eq!(probe_bytes(&dir.0, &selection), Some(16)); - let line = describe(&selection).unwrap(); - assert!( - line.contains("subset=en") && line.contains("ids=4"), - "{line}" - ); - } - // the digest of another recorded subset does not satisfy a name: `en` pointing at the default bytes is refused - write(&dir, "draft_vocab_en.bin", &default); - assert!(matches!( - select_in(&dir.0, &Setting::Named(1), &table).unwrap_err(), - RtError::DraftVocabSelection(_) - )); - // but the same file given as a path is a recorded subset (the default one) - let by_path = select_in( - &dir.0, - &Setting::Path(dir.0.join("draft_vocab_en.bin")), - &table, - ) - .unwrap(); - assert!(matches!( - by_path, - Selection::Verified { - label: "default", - .. - } - )); - // a changed byte is refused - let mut changed = en.clone(); - changed[0] ^= 1; - write(&dir, "elsewhere.bin", &changed); - assert!(select_in(&dir.0, &Setting::Path(dir.0.join("elsewhere.bin")), &table).is_err()); - } - - #[test] - fn wrong_digest_is_refused_for_a_name_and_for_a_path() { - let dir = TempDir::new("dv-digest"); - let bytes = raw(&[1, 2, 3, 4]); - write(&dir, "draft_vocab_en.bin", &bytes); - write(&dir, "other.bin", &bytes); - let digest = hex(&Sha256::digest(&bytes)); - for setting in [Setting::Named(1), Setting::Path(dir.0.join("other.bin"))] { - let error = select(&dir.0, &setting).unwrap_err(); - let RtError::DraftVocabSelection(text) = &error else { - panic!("{error:?}") - }; - assert!(text.contains(&digest), "{text}"); - assert!(text.contains("refused"), "{text}"); - // the load path surfaces the same refusal and the reserve probe does not claim a size for it - assert_eq!(read_draft_vocab_with(&dir.0, &setting).unwrap_err(), error); - assert_eq!(observed_draft_vocab_bytes_with(&dir.0, &setting), None); - } - } - - #[test] - fn malformed_files_are_refused_not_ignored() { - let dir = TempDir::new("dv-shape"); - for (name, bytes) in [ - ("empty.bin", &b""[..]), - ("odd.bin", &b"abcdef"[..]), - ("three.bin", &b"abc"[..]), - ] { - write(&dir, name, bytes); - let error = select(&dir.0, &Setting::Path(dir.0.join(name))).unwrap_err(); - assert!( - matches!(error, RtError::DraftVocabSelection(_)), - "{name}: {error:?}" - ); - } - // a directory is not a subset file - std::fs::create_dir(dir.0.join("dir.bin")).unwrap(); - assert!(matches!( - select(&dir.0, &Setting::Path(dir.0.join("dir.bin"))).unwrap_err(), - RtError::DraftVocabSelection(_) - )); - write( - &dir, - "huge.bin", - &vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4], - ); - assert_eq!( - select(&dir.0, &Setting::Path(dir.0.join("huge.bin"))).unwrap_err(), - RtError::DraftVocabTooLarge - ); - } - - #[cfg(unix)] - #[test] - fn symlink_is_refused() { - let dir = TempDir::new("dv-link"); - write(&dir, "real.bin", &raw(&[1])); - std::os::unix::fs::symlink(dir.0.join("real.bin"), dir.0.join("link.bin")).unwrap(); - assert!(matches!( - select(&dir.0, &Setting::Path(dir.0.join("link.bin"))).unwrap_err(), - RtError::DraftVocabSelection(_) - )); - } - - /// Subset index -> token id -> subset index, and the ids no subset row can propose. Synthetic ids with the shape of - /// the real files (ascending English subset inside an unordered, larger default list). - #[test] - fn draft_tokens_round_trip_to_full_ids() { - let vocabulary = 64usize; - let default: Vec = vec![40, 3, 9, 63, 0, 17, 22, 5, 31, 12]; - let english: Vec = vec![0, 3, 5, 9, 17, 31]; - for ids in [&default, &english] { - validate_subset(ids, vocabulary).unwrap(); - let inverse = subset_inverse(vocabulary, ids).unwrap(); - for (index, &id) in ids.iter().enumerate() { - // draft row index -> full vocabulary id (the device `sub_to_id` gather) -> row index (`id_to_sub`) - assert_eq!(inverse[id as usize], index as i32, "id {id}"); - assert_eq!(ids[inverse[id as usize] as usize], id); - } - let inside: std::collections::HashSet = ids.iter().copied().collect(); - for id in 0..vocabulary as i32 { - assert_eq!(inverse[id as usize] >= 0, inside.contains(&id), "id {id}"); - } - } - // the restricted subset can propose exactly its own ids: a token the default list can draft and `en` cannot - let wide = subset_inverse(vocabulary, &default).unwrap(); - let narrow = subset_inverse(vocabulary, &english).unwrap(); - for dropped in default.iter().filter(|id| !english.contains(id)) { - assert!( - wide[*dropped as usize] >= 0 && narrow[*dropped as usize] < 0, - "id {dropped}" - ); - } - // an id past the vocabulary is refused before any device gather reads a head row with it - assert_eq!( - validate_subset(&[0, 64], vocabulary), - Err(RtError::DraftVocabOutOfRange) - ); - } - - /// The real upstream files, when `LELEKA_TEST_DRAFT_VOCAB_DIR` names a directory holding `draft_vocab*.bin` - /// (`git show 41cf05a0:data/draft_vocab_en.bin` of remote strata-upstream; the files stay out of Git). - /// Checks the recorded digests, the id counts and that every subset is a valid, duplicate-free list inside the - /// 248,320-row vocabulary; for `en` also that it is ascending and contained in the default list. - #[test] - fn recorded_digests_match_the_upstream_files_when_present() { - let Some(dir) = std::env::var_os("LELEKA_TEST_DRAFT_VOCAB_DIR").map(PathBuf::from) else { - eprintln!("LELEKA_TEST_DRAFT_VOCAB_DIR is not set: real-file check skipped"); - return; - }; - let vocabulary = 248_320usize; - let mut lists = Vec::new(); - for (index, k) in KNOWN.iter().enumerate() { - let setting = if index == 0 { - Setting::Path(dir.join(k.file)) - } else { - Setting::Named(index) - }; - let selection = select(&dir, &setting).unwrap(); - let Selection::Verified { - label, - sha256, - bytes, - .. - } = &selection - else { - panic!("{} {selection:?}", k.name) - }; - assert_eq!((*label, *sha256), (k.name, k.sha256)); - let ids = ids_of(bytes); - assert_eq!(ids.len(), k.ids); - validate_subset(&ids, vocabulary).unwrap(); - let inverse = subset_inverse(vocabulary, &ids).unwrap(); - assert_eq!( - inverse.iter().filter(|i| **i >= 0).count(), - ids.len(), - "{}: duplicate ids", - k.name - ); - for (row, &id) in ids.iter().enumerate() { - assert_eq!(inverse[id as usize], row as i32); - } - lists.push(ids); - } - let default: std::collections::HashSet = lists[0].iter().copied().collect(); - assert!(lists[1].windows(2).all(|w| w[0] < w[1]), "en is ascending"); - assert!( - lists[1].iter().all(|id| default.contains(id)), - "en is inside the default list" - ); - assert_eq!(lists[0].len() - lists[1].len(), 65_774); - } -} +mod tests; diff --git a/crates/cuda-driver/src/original_mtp_draft_vocab/tests.rs b/crates/cuda-driver/src/original_mtp_draft_vocab/tests.rs new file mode 100644 index 00000000..0a303102 --- /dev/null +++ b/crates/cuda-driver/src/original_mtp_draft_vocab/tests.rs @@ -0,0 +1,339 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::original_mtp_coupled::subset_inverse; +use crate::original_mtp_rt::{ + fixtures::{TempDir, write}, + observed_draft_vocab_bytes_with, read_draft_vocab_with, validate_subset, +}; + +fn raw(ids: &[i32]) -> Vec { + ids.iter().flat_map(|i| i.to_le_bytes()).collect() +} + +#[test] +fn setting_parses_names_paths_and_the_default_spellings() { + for off in [None, Some(""), Some("0"), Some("off"), Some("default")] { + assert_eq!( + Setting::parse(off.map(OsStr::new)), + Setting::Default, + "{off:?}" + ); + } + assert_eq!(Setting::parse(Some(OsStr::new("en"))), Setting::Named(1)); + assert_eq!( + Setting::parse(Some(OsStr::new("cyrillic"))), + Setting::Named(2) + ); + assert_eq!(Setting::parse(Some(OsStr::new("fr"))), Setting::Named(3)); + assert_eq!( + Setting::parse(Some(OsStr::new("/data/x/draft_vocab_en.bin"))), + Setting::Path(PathBuf::from("/data/x/draft_vocab_en.bin")) + ); + // case matters: "EN" is a (missing) path, not the English subset + assert_eq!( + Setting::parse(Some(OsStr::new("EN"))), + Setting::Path(PathBuf::from("EN")) + ); +} + +#[test] +fn recorded_table_is_consistent() { + assert_eq!(KNOWN[0].name, "default"); + assert_eq!(KNOWN[0].file, "draft_vocab.bin"); + for k in &KNOWN { + assert_eq!(k.sha256.len(), 64, "{}", k.name); + assert!( + k.sha256 + .bytes() + .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()), + "{}", + k.name + ); + assert_eq!( + k.file, + if k.name == "default" { + "draft_vocab.bin".to_string() + } else { + format!("draft_vocab_{}.bin", k.name) + } + ); + assert!(k.ids as u64 <= DRAFT_VOCAB_MAX_IDS); + } + let mut digests: Vec<_> = KNOWN.iter().map(|k| k.sha256).collect(); + digests.sort_unstable(); + digests.dedup(); + assert_eq!(digests.len(), KNOWN.len()); + // sha256 of the empty input pins the hex spelling used for the comparison + assert_eq!( + hex(&Sha256::digest(b"")), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); +} + +#[test] +fn default_setting_reads_nothing_and_logs_nothing() { + let dir = TempDir::new("dv-default"); + write(&dir, "draft_vocab_en.bin", &raw(&[1, 2, 3])); + let selection = select(&dir.0, &Setting::Default).unwrap(); + assert_eq!(selection, Selection::Default); + assert_eq!(describe(&selection), None); + assert_eq!(subset(&selection), None); +} + +#[test] +fn missing_file_falls_back_to_the_default_file_with_a_log_line() { + let dir = TempDir::new("dv-missing"); + let ids = [7i32, 3, 9]; + write(&dir, "draft_vocab.bin", &raw(&ids)); + for setting in [Setting::Named(1), Setting::Path(dir.0.join("nowhere.bin"))] { + let selection = select(&dir.0, &setting).unwrap(); + assert!( + matches!(selection, Selection::Fallback { .. }), + "{setting:?}" + ); + assert!(describe(&selection).unwrap().contains("FALLBACK")); + assert_eq!(subset(&selection), None); + // the reserve probe and the reader then see rt/draft_vocab.bin + assert_eq!(probe_bytes(&dir.0, &selection), Some(12)); + } + assert_eq!( + read_draft_vocab_with(&dir.0, &Setting::Named(1)).unwrap(), + DraftVocab::Subset(ids.to_vec()) + ); + assert_eq!( + observed_draft_vocab_bytes_with(&dir.0, &Setting::Named(1)), + Some(12) + ); +} + +/// A table whose digests belong to synthetic files, so the accepted path runs without the upstream data. +fn table_for(default: &[u8], en: &[u8]) -> [KnownSubset; 2] { + let leak = |bytes: &[u8]| -> &'static str { + Box::leak(hex(&Sha256::digest(bytes)).into_boxed_str()) + }; + [ + KnownSubset { + name: "default", + file: "draft_vocab.bin", + sha256: leak(default), + ids: default.len() / 4, + }, + KnownSubset { + name: "en", + file: "draft_vocab_en.bin", + sha256: leak(en), + ids: en.len() / 4, + }, + ] +} + +#[test] +fn matching_digest_is_accepted_and_reads_the_selected_ids() { + let dir = TempDir::new("dv-ok"); + let default_ids = [40i32, 3, 9, 63, 0, 17]; + let english_ids = [0i32, 3, 9, 17]; + let (default, en) = (raw(&default_ids), raw(&english_ids)); + write(&dir, "draft_vocab.bin", &default); + write(&dir, "draft_vocab_en.bin", &en); + write(&dir, "elsewhere.bin", &en); + let table = table_for(&default, &en); + for setting in [ + Setting::Named(1), + Setting::Path(dir.0.join("elsewhere.bin")), + ] { + let selection = select_in(&dir.0, &setting, &table).unwrap(); + let Selection::Verified { label, bytes, .. } = &selection else { + panic!("{selection:?}") + }; + assert_eq!((*label, bytes.len()), ("en", 16)); + assert_eq!( + crate::original_mtp_rt::read_selected_draft_vocab(&dir.0, &selection).unwrap(), + DraftVocab::Subset(english_ids.to_vec()) + ); + assert_eq!(probe_bytes(&dir.0, &selection), Some(16)); + let line = describe(&selection).unwrap(); + assert!( + line.contains("subset=en") && line.contains("ids=4"), + "{line}" + ); + } + // the digest of another recorded subset does not satisfy a name: `en` pointing at the default bytes is refused + write(&dir, "draft_vocab_en.bin", &default); + assert!(matches!( + select_in(&dir.0, &Setting::Named(1), &table).unwrap_err(), + RtError::DraftVocabSelection(_) + )); + // but the same file given as a path is a recorded subset (the default one) + let by_path = select_in( + &dir.0, + &Setting::Path(dir.0.join("draft_vocab_en.bin")), + &table, + ) + .unwrap(); + assert!(matches!( + by_path, + Selection::Verified { + label: "default", + .. + } + )); + // a changed byte is refused + let mut changed = en.clone(); + changed[0] ^= 1; + write(&dir, "elsewhere.bin", &changed); + assert!(select_in(&dir.0, &Setting::Path(dir.0.join("elsewhere.bin")), &table).is_err()); +} + +#[test] +fn wrong_digest_is_refused_for_a_name_and_for_a_path() { + let dir = TempDir::new("dv-digest"); + let bytes = raw(&[1, 2, 3, 4]); + write(&dir, "draft_vocab_en.bin", &bytes); + write(&dir, "other.bin", &bytes); + let digest = hex(&Sha256::digest(&bytes)); + for setting in [Setting::Named(1), Setting::Path(dir.0.join("other.bin"))] { + let error = select(&dir.0, &setting).unwrap_err(); + let RtError::DraftVocabSelection(text) = &error else { + panic!("{error:?}") + }; + assert!(text.contains(&digest), "{text}"); + assert!(text.contains("refused"), "{text}"); + // the load path surfaces the same refusal and the reserve probe does not claim a size for it + assert_eq!(read_draft_vocab_with(&dir.0, &setting).unwrap_err(), error); + assert_eq!(observed_draft_vocab_bytes_with(&dir.0, &setting), None); + } +} + +#[test] +fn malformed_files_are_refused_not_ignored() { + let dir = TempDir::new("dv-shape"); + for (name, bytes) in [ + ("empty.bin", &b""[..]), + ("odd.bin", &b"abcdef"[..]), + ("three.bin", &b"abc"[..]), + ] { + write(&dir, name, bytes); + let error = select(&dir.0, &Setting::Path(dir.0.join(name))).unwrap_err(); + assert!( + matches!(error, RtError::DraftVocabSelection(_)), + "{name}: {error:?}" + ); + } + // a directory is not a subset file + std::fs::create_dir(dir.0.join("dir.bin")).unwrap(); + assert!(matches!( + select(&dir.0, &Setting::Path(dir.0.join("dir.bin"))).unwrap_err(), + RtError::DraftVocabSelection(_) + )); + write( + &dir, + "huge.bin", + &vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4], + ); + assert_eq!( + select(&dir.0, &Setting::Path(dir.0.join("huge.bin"))).unwrap_err(), + RtError::DraftVocabTooLarge + ); +} + +#[cfg(unix)] +#[test] +fn symlink_is_refused() { + let dir = TempDir::new("dv-link"); + write(&dir, "real.bin", &raw(&[1])); + std::os::unix::fs::symlink(dir.0.join("real.bin"), dir.0.join("link.bin")).unwrap(); + assert!(matches!( + select(&dir.0, &Setting::Path(dir.0.join("link.bin"))).unwrap_err(), + RtError::DraftVocabSelection(_) + )); +} + +/// Subset index -> token id -> subset index, and the ids no subset row can propose. Synthetic ids with the shape of +/// the real files (ascending English subset inside an unordered, larger default list). +#[test] +fn draft_tokens_round_trip_to_full_ids() { + let vocabulary = 64usize; + let default: Vec = vec![40, 3, 9, 63, 0, 17, 22, 5, 31, 12]; + let english: Vec = vec![0, 3, 5, 9, 17, 31]; + for ids in [&default, &english] { + validate_subset(ids, vocabulary).unwrap(); + let inverse = subset_inverse(vocabulary, ids).unwrap(); + for (index, &id) in ids.iter().enumerate() { + // draft row index -> full vocabulary id (the device `sub_to_id` gather) -> row index (`id_to_sub`) + assert_eq!(inverse[id as usize], index as i32, "id {id}"); + assert_eq!(ids[inverse[id as usize] as usize], id); + } + let inside: std::collections::HashSet = ids.iter().copied().collect(); + for id in 0..vocabulary as i32 { + assert_eq!(inverse[id as usize] >= 0, inside.contains(&id), "id {id}"); + } + } + // the restricted subset can propose exactly its own ids: a token the default list can draft and `en` cannot + let wide = subset_inverse(vocabulary, &default).unwrap(); + let narrow = subset_inverse(vocabulary, &english).unwrap(); + for dropped in default.iter().filter(|id| !english.contains(id)) { + assert!( + wide[*dropped as usize] >= 0 && narrow[*dropped as usize] < 0, + "id {dropped}" + ); + } + // an id past the vocabulary is refused before any device gather reads a head row with it + assert_eq!( + validate_subset(&[0, 64], vocabulary), + Err(RtError::DraftVocabOutOfRange) + ); +} + +/// The real upstream files, when `LELEKA_TEST_DRAFT_VOCAB_DIR` names a directory holding `draft_vocab*.bin` +/// (`git show 41cf05a0:data/draft_vocab_en.bin` of remote strata-upstream; the files stay out of Git). +/// Checks the recorded digests, the id counts and that every subset is a valid, duplicate-free list inside the +/// 248,320-row vocabulary; for `en` also that it is ascending and contained in the default list. +#[test] +fn recorded_digests_match_the_upstream_files_when_present() { + let Some(dir) = std::env::var_os("LELEKA_TEST_DRAFT_VOCAB_DIR").map(PathBuf::from) else { + eprintln!("LELEKA_TEST_DRAFT_VOCAB_DIR is not set: real-file check skipped"); + return; + }; + let vocabulary = 248_320usize; + let mut lists = Vec::new(); + for (index, k) in KNOWN.iter().enumerate() { + let setting = if index == 0 { + Setting::Path(dir.join(k.file)) + } else { + Setting::Named(index) + }; + let selection = select(&dir, &setting).unwrap(); + let Selection::Verified { + label, + sha256, + bytes, + .. + } = &selection + else { + panic!("{} {selection:?}", k.name) + }; + assert_eq!((*label, *sha256), (k.name, k.sha256)); + let ids = ids_of(bytes); + assert_eq!(ids.len(), k.ids); + validate_subset(&ids, vocabulary).unwrap(); + let inverse = subset_inverse(vocabulary, &ids).unwrap(); + assert_eq!( + inverse.iter().filter(|i| **i >= 0).count(), + ids.len(), + "{}: duplicate ids", + k.name + ); + for (row, &id) in ids.iter().enumerate() { + assert_eq!(inverse[id as usize], row as i32); + } + lists.push(ids); + } + let default: std::collections::HashSet = lists[0].iter().copied().collect(); + assert!(lists[1].windows(2).all(|w| w[0] < w[1]), "en is ascending"); + assert!( + lists[1].iter().all(|id| default.contains(id)), + "en is inside the default list" + ); + assert_eq!(lists[0].len() - lists[1].len(), 65_774); +} diff --git a/crates/cuda-driver/src/original_mtp_loader.rs b/crates/cuda-driver/src/original_mtp_loader.rs index bbf71ae6..7a0cfd5e 100644 --- a/crates/cuda-driver/src/original_mtp_loader.rs +++ b/crates/cuda-driver/src/original_mtp_loader.rs @@ -501,245 +501,4 @@ impl OriginalMtpLoadPlan { } #[cfg(test)] -mod tests { - use super::*; - - fn kv() -> OriginalMtpKvStartup { - OriginalMtpKvStartup { - resident_cells: 20480, - ring_off: false, - main_off: false, - int8: true, - hybrid: false, - q4: false, - int8_rotated: false, - } - } - fn capture() -> OriginalMtpCapture { - OriginalMtpCapture { - device: 0, - n_expert: 512, - top_k: 10, - max_cells: 262_144, - max_t: 4, - window: 32_768, - vocabulary: 248_320, - kv: kv(), - coupled_requested: false, - } - } - - /// `StateLayout::new` of mtp_original_ring_state.rs, restated as numbers. - fn ring_state_bytes(max_t: u64, resident: bool) -> u64 { - let slots = if resident { 262_144 / 4 } else { (32_768 + 4 * max_t + 64).div_ceil(4) }; - let pooled = if resident { 262_144 / 4 + 2 } else { 2 }; - let raw = slots * 4224 + 128 + 65_536 * 4 + 1536 + 512 + pooled * 512 + 16 + 32 + 96; - raw.div_ceil(16) * 16 + 256 - } - - #[test] - fn plan_accepts_the_shipped_profile_and_matches_the_retained_ring_layout() { - for max_t in 1..=8 { - let plan = OriginalMtpLoadPlan::new(OriginalMtpCapture { max_t, ..capture() }, 116_099_072).unwrap(); - let kv = plan.kv(); - assert_eq!(kv.mode, KvMode::WindowRing); - assert_eq!(kv.format, KvFormat::Int8 { rotated: false }); - assert_eq!(kv.slots, (32_768 + 4 * max_t + 64).div_ceil(4)); - assert_eq!(kv.pooled_rows, 2); - assert_eq!(kv.effective_window, 32_768); - assert_eq!(plan.effective_window(), 32_768); - assert_eq!(kv.state_device_allocation, ring_state_bytes(max_t, false), "T={max_t}"); - assert_eq!(kv.authoritative_host_allocation, kv.pages * 4 * 1056 + 1024); - assert_eq!(plan.staging()[0], max_t * 4 + 64); - assert_eq!(plan.weight_bank().device_bytes, 116_099_072 + 707_788_800); - // the pinned-host retry plan equals the fully resident retained layout - let retry = plan.admit_ring(true).unwrap(); - assert_eq!(retry.mode, KvMode::Resident); - assert_eq!(retry.slots, 65_536); - assert_eq!(retry.state_device_allocation, ring_state_bytes(max_t, true), "T={max_t}"); - assert_eq!(retry.authoritative_host_allocation, 0); - assert_eq!(plan.admit_ring(false).unwrap().mode, KvMode::WindowRing); - } - } - - #[test] - fn hybrid_selects_int8_and_whole_q4_is_refused_for_the_retained_owner() { - let hybrid = OriginalMtpKvStartup { int8: false, hybrid: true, int8_rotated: true, ..kv() }; - let plan = OriginalMtpLoadPlan::new(OriginalMtpCapture { kv: hybrid, ..capture() }, 1).unwrap(); - assert_eq!(plan.kv().format, KvFormat::Int8 { rotated: true }); - for refused in [ - OriginalMtpKvStartup { q4: true, ..kv() }, - OriginalMtpKvStartup { int8: false, hybrid: false, ..kv() }, - ] { - assert_eq!( - OriginalMtpLoadPlan::new(OriginalMtpCapture { kv: refused, ..capture() }, 1).unwrap_err(), - LoaderError::ClosedProfile("draft K/V format") - ); - } - } - - #[test] - fn captures_outside_the_closed_profile_are_refused_with_a_reason() { - let cases: [(OriginalMtpCapture, LoaderError); 12] = [ - (OriginalMtpCapture { max_t: 0, ..capture() }, LoaderError::MaxTOutOfRange), - (OriginalMtpCapture { max_t: 9, ..capture() }, LoaderError::MaxTOutOfRange), - (OriginalMtpCapture { device: -1, ..capture() }, LoaderError::ClosedProfile("device ordinal")), - (OriginalMtpCapture { n_expert: 256, ..capture() }, LoaderError::ClosedProfile("expert count")), - (OriginalMtpCapture { top_k: 8, ..capture() }, LoaderError::ClosedProfile("routed expert count")), - (OriginalMtpCapture { max_cells: 131_072, ..capture() }, LoaderError::ClosedProfile("session cell capacity")), - (OriginalMtpCapture { window: 0, ..capture() }, LoaderError::ClosedProfile("draft attention window")), - (OriginalMtpCapture { window: 16_384, ..capture() }, LoaderError::ClosedProfile("draft attention window")), - (OriginalMtpCapture { vocabulary: 0, ..capture() }, LoaderError::ClosedProfile("vocabulary")), - (OriginalMtpCapture { vocabulary: 262_145, ..capture() }, LoaderError::ClosedProfile("vocabulary")), - // resident (no ring: kv streaming off) and streamed-main plans have no retained owner - ( - OriginalMtpCapture { kv: OriginalMtpKvStartup { ring_off: true, ..kv() }, ..capture() }, - LoaderError::ClosedProfile("draft K/V mode"), - ), - ( - OriginalMtpCapture { kv: OriginalMtpKvStartup { resident_cells: 0, ..kv() }, ..capture() }, - LoaderError::ClosedProfile("draft K/V mode"), - ), - ]; - for (input, expected) in cases { - assert_eq!(OriginalMtpLoadPlan::new(input, 1).unwrap_err(), expected, "{input:?}"); - assert!(expected.message().starts_with("mtp: ")); - } - assert_eq!(LoaderError::MaxTOutOfRange.message(), "mtp: max_t out of range"); - } - - #[test] - fn bank_plan_counts_expert_chunks_like_the_original_loop() { - let plan = WeightBankPlan::new(116_099_072, 512).unwrap(); - assert_eq!(plan.expert_device_bytes, 707_788_800); - assert_eq!(plan.device_bytes, 823_887_872); - assert_eq!(plan.expert_host_peak, 64 << 20); - let reads: Vec<_> = plan.expert_reads().collect(); - assert_eq!(reads.len(), 11); - assert!(reads[..10].iter().all(|r| r.bytes == 64 << 20)); - assert_eq!(reads[10].bytes, 707_788_800 - 10 * (64 << 20)); - assert_eq!(reads.iter().map(|r| r.bytes).sum::(), 707_788_800); - assert!(reads.windows(2).all(|w| w[0].offset + w[0].bytes == w[1].offset)); - assert_eq!(WeightBankPlan::new(1, 0).unwrap().expert_reads().count(), 0); - assert_eq!(WeightBankPlan::new(u64::MAX, 1).unwrap_err(), LoaderError::Overflow); - assert_eq!(WeightBankPlan::new(0, u64::MAX).unwrap_err(), LoaderError::Overflow); - } - - #[test] - fn bind_reserve_is_the_literal_upper_estimate() { - let plan = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); - let logits = 4 * 248_320 * 4; - assert_eq!(plan.bind_reserve(None, 1440).unwrap(), logits); - // a valid subset file adds the gathered rows plus the id list; invalid sizes are ignored - assert_eq!(plan.bind_reserve(Some(400), 1440).unwrap(), logits + 100 * 1440 + 400); - for ignored in [0, 3, 6] { - assert_eq!(plan.bind_reserve(Some(ignored), 1440).unwrap(), logits); - } - let coupled = OriginalMtpLoadPlan::new(OriginalMtpCapture { coupled_requested: true, ..capture() }, 1).unwrap(); - assert_eq!( - coupled.bind_reserve(None, 1440).unwrap(), - logits + 248_320 * 4 + (4096 + 4) * 4 + 64 * 64 * 8 + 4096 - ); - } - - #[test] - fn standalone_reserve_matches_the_plan_method_and_checks_its_inputs() { - let plan = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); - assert_eq!( - original_mtp_bind_reserve(&capture(), Some(400), 1440).unwrap(), - plan.bind_reserve(Some(400), 1440).unwrap() - ); - assert_eq!( - original_mtp_bind_reserve(&OriginalMtpCapture { vocabulary: 0, ..capture() }, None, 1).unwrap_err(), - LoaderError::ClosedProfile("vocabulary") - ); - assert_eq!( - original_mtp_bind_reserve(&OriginalMtpCapture { max_t: 0, ..capture() }, None, 1).unwrap_err(), - LoaderError::Geometry - ); - assert_eq!(OriginalMtpKvStartup::ring_int8(20480), kv()); - } - - #[test] - fn coupled_setup_plan_follows_setup_coupled() { - let off = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); - assert!(matches!(off.coupled(None).unwrap(), CoupledPlan::Off)); - let on = OriginalMtpLoadPlan::new(OriginalMtpCapture { coupled_requested: true, ..capture() }, 1).unwrap(); - match on.coupled(None).unwrap() { - CoupledPlan::Allocate { params, ring, scratch, inverse_map, mapped_params, mapped_history, device_total } => { - assert_eq!((params, ring, mapped_params, mapped_history), (64, (4096 + 4) * 4, 64, 4096 * 4)); - assert_eq!(scratch, 61 * 64 * 8); // ceil(248320 / 4096) = 61 split lists - assert_eq!(inverse_map, 0); - assert_eq!(device_total, params + ring + scratch); - } - other => panic!("{other:?}"), - } - match on.coupled(Some(1000)).unwrap() { - CoupledPlan::Allocate { scratch, inverse_map, .. } => { - assert_eq!(scratch, 64 * 8 / 1); // one split list - assert_eq!(inverse_map, 248_320 * 4); - } - other => panic!("{other:?}"), - } - // 65 lists or a zero-width subset: successful argmax fallback, not coupled-ready - assert!(matches!( - coupled_plan(true, 4, 262_145, None).unwrap(), - CoupledPlan::ArgmaxVocabularyTooWide - )); - assert!(matches!(coupled_plan(true, 4, 10, Some(0)).unwrap(), CoupledPlan::ArgmaxVocabularyTooWide)); - assert!(matches!(coupled_plan(true, 4, 262_144, None).unwrap(), CoupledPlan::Allocate { .. })); - assert_eq!(coupled_plan(true, 0, 10, None).unwrap_err(), LoaderError::Geometry); - assert_eq!(coupled_plan(false, 9, 10, None).unwrap_err(), LoaderError::Geometry); - } - - #[test] - fn staging_and_kv_geometry_validation() { - let s = mapped_staging(4, 24).unwrap(); - assert_eq!(s, [80, 192, 4 * 24 * 8 + 64, 64, 80, 80]); - assert_eq!(mapped_staging(0, 24).unwrap_err(), LoaderError::Geometry); - assert_eq!(mapped_staging(4, 0).unwrap_err(), LoaderError::Geometry); - let base = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); - assert_eq!(base.kv_inputs.plan().unwrap().mode, KvMode::WindowRing); - for bad in [ - KvInputs { head_dim: 128, ..base.kv_inputs }, - KvInputs { heads: 25, ..base.kv_inputs }, - KvInputs { max_cells: 0, ..base.kv_inputs }, - KvInputs { max_t: 9, ..base.kv_inputs }, - KvInputs { index_dim: 0, ..base.kv_inputs }, - ] { - assert_eq!(bad.plan().unwrap_err(), LoaderError::Geometry); - } - // window 0 with a resident budget streams the main KV, as mtp.cpp does - let streamed = KvInputs { requested_window: 0, ..base.kv_inputs }.plan().unwrap(); - assert_eq!(streamed.mode, KvMode::Streamed); - assert_eq!(streamed.slots, 20_480 / 4); - assert!(streamed.authoritative_host_allocation > 0); - // overflow stays an error rather than a wrap - let huge = KvInputs { max_cells: u64::MAX / 2, ..base.kv_inputs }; - assert!(huge.plan().is_err()); - // the orders are documented once each - assert_eq!(LOAD_ORDER.len(), 11); - assert_eq!(RELEASE_ORDER.len(), 13); - assert_eq!(REQUIRED_Q8_NAMES.len(), 9); - } - - /// The pure constants above restate the closed owners. This compile-checked - /// test (runs on Linux/CI, not on the macOS harness) pins them to the - /// session geometry and ring window the retained code actually uses. - #[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" - ))] - #[test] - fn closed_profile_constants_match_the_retained_owners() { - let g = crate::original_session_state::OriginalSessionGeometry::original(); - assert_eq!(g.experts as u64, PROFILE_N_EXPERT); - assert_eq!(g.heads as u64, PROFILE_HEADS); - assert_eq!(g.kv_heads as u64, PROFILE_KV_HEADS); - assert_eq!(g.head_dim as u64, PROFILE_HEAD_DIM); - assert_eq!(g.index_dim as u64, PROFILE_INDEX_DIM); - assert_eq!(crate::MTP_ORIGINAL_WINDOW as i64, CLOSED_WINDOW); - assert_eq!(EXPERT_BLOB_BYTES, 3 * (2560 * 640 * 18 / 64)); - } -} +mod tests; diff --git a/crates/cuda-driver/src/original_mtp_loader/tests.rs b/crates/cuda-driver/src/original_mtp_loader/tests.rs new file mode 100644 index 00000000..00657a57 --- /dev/null +++ b/crates/cuda-driver/src/original_mtp_loader/tests.rs @@ -0,0 +1,242 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn kv() -> OriginalMtpKvStartup { + OriginalMtpKvStartup { + resident_cells: 20480, + ring_off: false, + main_off: false, + int8: true, + hybrid: false, + q4: false, + int8_rotated: false, + } +} +fn capture() -> OriginalMtpCapture { + OriginalMtpCapture { + device: 0, + n_expert: 512, + top_k: 10, + max_cells: 262_144, + max_t: 4, + window: 32_768, + vocabulary: 248_320, + kv: kv(), + coupled_requested: false, + } +} + +/// `StateLayout::new` of mtp_original_ring_state.rs, restated as numbers. +fn ring_state_bytes(max_t: u64, resident: bool) -> u64 { + let slots = if resident { 262_144 / 4 } else { (32_768 + 4 * max_t + 64).div_ceil(4) }; + let pooled = if resident { 262_144 / 4 + 2 } else { 2 }; + let raw = slots * 4224 + 128 + 65_536 * 4 + 1536 + 512 + pooled * 512 + 16 + 32 + 96; + raw.div_ceil(16) * 16 + 256 +} + +#[test] +fn plan_accepts_the_shipped_profile_and_matches_the_retained_ring_layout() { + for max_t in 1..=8 { + let plan = OriginalMtpLoadPlan::new(OriginalMtpCapture { max_t, ..capture() }, 116_099_072).unwrap(); + let kv = plan.kv(); + assert_eq!(kv.mode, KvMode::WindowRing); + assert_eq!(kv.format, KvFormat::Int8 { rotated: false }); + assert_eq!(kv.slots, (32_768 + 4 * max_t + 64).div_ceil(4)); + assert_eq!(kv.pooled_rows, 2); + assert_eq!(kv.effective_window, 32_768); + assert_eq!(plan.effective_window(), 32_768); + assert_eq!(kv.state_device_allocation, ring_state_bytes(max_t, false), "T={max_t}"); + assert_eq!(kv.authoritative_host_allocation, kv.pages * 4 * 1056 + 1024); + assert_eq!(plan.staging()[0], max_t * 4 + 64); + assert_eq!(plan.weight_bank().device_bytes, 116_099_072 + 707_788_800); + // the pinned-host retry plan equals the fully resident retained layout + let retry = plan.admit_ring(true).unwrap(); + assert_eq!(retry.mode, KvMode::Resident); + assert_eq!(retry.slots, 65_536); + assert_eq!(retry.state_device_allocation, ring_state_bytes(max_t, true), "T={max_t}"); + assert_eq!(retry.authoritative_host_allocation, 0); + assert_eq!(plan.admit_ring(false).unwrap().mode, KvMode::WindowRing); + } +} + +#[test] +fn hybrid_selects_int8_and_whole_q4_is_refused_for_the_retained_owner() { + let hybrid = OriginalMtpKvStartup { int8: false, hybrid: true, int8_rotated: true, ..kv() }; + let plan = OriginalMtpLoadPlan::new(OriginalMtpCapture { kv: hybrid, ..capture() }, 1).unwrap(); + assert_eq!(plan.kv().format, KvFormat::Int8 { rotated: true }); + for refused in [ + OriginalMtpKvStartup { q4: true, ..kv() }, + OriginalMtpKvStartup { int8: false, hybrid: false, ..kv() }, + ] { + assert_eq!( + OriginalMtpLoadPlan::new(OriginalMtpCapture { kv: refused, ..capture() }, 1).unwrap_err(), + LoaderError::ClosedProfile("draft K/V format") + ); + } +} + +#[test] +fn captures_outside_the_closed_profile_are_refused_with_a_reason() { + let cases: [(OriginalMtpCapture, LoaderError); 12] = [ + (OriginalMtpCapture { max_t: 0, ..capture() }, LoaderError::MaxTOutOfRange), + (OriginalMtpCapture { max_t: 9, ..capture() }, LoaderError::MaxTOutOfRange), + (OriginalMtpCapture { device: -1, ..capture() }, LoaderError::ClosedProfile("device ordinal")), + (OriginalMtpCapture { n_expert: 256, ..capture() }, LoaderError::ClosedProfile("expert count")), + (OriginalMtpCapture { top_k: 8, ..capture() }, LoaderError::ClosedProfile("routed expert count")), + (OriginalMtpCapture { max_cells: 131_072, ..capture() }, LoaderError::ClosedProfile("session cell capacity")), + (OriginalMtpCapture { window: 0, ..capture() }, LoaderError::ClosedProfile("draft attention window")), + (OriginalMtpCapture { window: 16_384, ..capture() }, LoaderError::ClosedProfile("draft attention window")), + (OriginalMtpCapture { vocabulary: 0, ..capture() }, LoaderError::ClosedProfile("vocabulary")), + (OriginalMtpCapture { vocabulary: 262_145, ..capture() }, LoaderError::ClosedProfile("vocabulary")), + // resident (no ring: kv streaming off) and streamed-main plans have no retained owner + ( + OriginalMtpCapture { kv: OriginalMtpKvStartup { ring_off: true, ..kv() }, ..capture() }, + LoaderError::ClosedProfile("draft K/V mode"), + ), + ( + OriginalMtpCapture { kv: OriginalMtpKvStartup { resident_cells: 0, ..kv() }, ..capture() }, + LoaderError::ClosedProfile("draft K/V mode"), + ), + ]; + for (input, expected) in cases { + assert_eq!(OriginalMtpLoadPlan::new(input, 1).unwrap_err(), expected, "{input:?}"); + assert!(expected.message().starts_with("mtp: ")); + } + assert_eq!(LoaderError::MaxTOutOfRange.message(), "mtp: max_t out of range"); +} + +#[test] +fn bank_plan_counts_expert_chunks_like_the_original_loop() { + let plan = WeightBankPlan::new(116_099_072, 512).unwrap(); + assert_eq!(plan.expert_device_bytes, 707_788_800); + assert_eq!(plan.device_bytes, 823_887_872); + assert_eq!(plan.expert_host_peak, 64 << 20); + let reads: Vec<_> = plan.expert_reads().collect(); + assert_eq!(reads.len(), 11); + assert!(reads[..10].iter().all(|r| r.bytes == 64 << 20)); + assert_eq!(reads[10].bytes, 707_788_800 - 10 * (64 << 20)); + assert_eq!(reads.iter().map(|r| r.bytes).sum::(), 707_788_800); + assert!(reads.windows(2).all(|w| w[0].offset + w[0].bytes == w[1].offset)); + assert_eq!(WeightBankPlan::new(1, 0).unwrap().expert_reads().count(), 0); + assert_eq!(WeightBankPlan::new(u64::MAX, 1).unwrap_err(), LoaderError::Overflow); + assert_eq!(WeightBankPlan::new(0, u64::MAX).unwrap_err(), LoaderError::Overflow); +} + +#[test] +fn bind_reserve_is_the_literal_upper_estimate() { + let plan = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); + let logits = 4 * 248_320 * 4; + assert_eq!(plan.bind_reserve(None, 1440).unwrap(), logits); + // a valid subset file adds the gathered rows plus the id list; invalid sizes are ignored + assert_eq!(plan.bind_reserve(Some(400), 1440).unwrap(), logits + 100 * 1440 + 400); + for ignored in [0, 3, 6] { + assert_eq!(plan.bind_reserve(Some(ignored), 1440).unwrap(), logits); + } + let coupled = OriginalMtpLoadPlan::new(OriginalMtpCapture { coupled_requested: true, ..capture() }, 1).unwrap(); + assert_eq!( + coupled.bind_reserve(None, 1440).unwrap(), + logits + 248_320 * 4 + (4096 + 4) * 4 + 64 * 64 * 8 + 4096 + ); +} + +#[test] +fn standalone_reserve_matches_the_plan_method_and_checks_its_inputs() { + let plan = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); + assert_eq!( + original_mtp_bind_reserve(&capture(), Some(400), 1440).unwrap(), + plan.bind_reserve(Some(400), 1440).unwrap() + ); + assert_eq!( + original_mtp_bind_reserve(&OriginalMtpCapture { vocabulary: 0, ..capture() }, None, 1).unwrap_err(), + LoaderError::ClosedProfile("vocabulary") + ); + assert_eq!( + original_mtp_bind_reserve(&OriginalMtpCapture { max_t: 0, ..capture() }, None, 1).unwrap_err(), + LoaderError::Geometry + ); + assert_eq!(OriginalMtpKvStartup::ring_int8(20480), kv()); +} + +#[test] +fn coupled_setup_plan_follows_setup_coupled() { + let off = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); + assert!(matches!(off.coupled(None).unwrap(), CoupledPlan::Off)); + let on = OriginalMtpLoadPlan::new(OriginalMtpCapture { coupled_requested: true, ..capture() }, 1).unwrap(); + match on.coupled(None).unwrap() { + CoupledPlan::Allocate { params, ring, scratch, inverse_map, mapped_params, mapped_history, device_total } => { + assert_eq!((params, ring, mapped_params, mapped_history), (64, (4096 + 4) * 4, 64, 4096 * 4)); + assert_eq!(scratch, 61 * 64 * 8); // ceil(248320 / 4096) = 61 split lists + assert_eq!(inverse_map, 0); + assert_eq!(device_total, params + ring + scratch); + } + other => panic!("{other:?}"), + } + match on.coupled(Some(1000)).unwrap() { + CoupledPlan::Allocate { scratch, inverse_map, .. } => { + assert_eq!(scratch, 64 * 8 / 1); // one split list + assert_eq!(inverse_map, 248_320 * 4); + } + other => panic!("{other:?}"), + } + // 65 lists or a zero-width subset: successful argmax fallback, not coupled-ready + assert!(matches!( + coupled_plan(true, 4, 262_145, None).unwrap(), + CoupledPlan::ArgmaxVocabularyTooWide + )); + assert!(matches!(coupled_plan(true, 4, 10, Some(0)).unwrap(), CoupledPlan::ArgmaxVocabularyTooWide)); + assert!(matches!(coupled_plan(true, 4, 262_144, None).unwrap(), CoupledPlan::Allocate { .. })); + assert_eq!(coupled_plan(true, 0, 10, None).unwrap_err(), LoaderError::Geometry); + assert_eq!(coupled_plan(false, 9, 10, None).unwrap_err(), LoaderError::Geometry); +} + +#[test] +fn staging_and_kv_geometry_validation() { + let s = mapped_staging(4, 24).unwrap(); + assert_eq!(s, [80, 192, 4 * 24 * 8 + 64, 64, 80, 80]); + assert_eq!(mapped_staging(0, 24).unwrap_err(), LoaderError::Geometry); + assert_eq!(mapped_staging(4, 0).unwrap_err(), LoaderError::Geometry); + let base = OriginalMtpLoadPlan::new(capture(), 1).unwrap(); + assert_eq!(base.kv_inputs.plan().unwrap().mode, KvMode::WindowRing); + for bad in [ + KvInputs { head_dim: 128, ..base.kv_inputs }, + KvInputs { heads: 25, ..base.kv_inputs }, + KvInputs { max_cells: 0, ..base.kv_inputs }, + KvInputs { max_t: 9, ..base.kv_inputs }, + KvInputs { index_dim: 0, ..base.kv_inputs }, + ] { + assert_eq!(bad.plan().unwrap_err(), LoaderError::Geometry); + } + // window 0 with a resident budget streams the main KV, as mtp.cpp does + let streamed = KvInputs { requested_window: 0, ..base.kv_inputs }.plan().unwrap(); + assert_eq!(streamed.mode, KvMode::Streamed); + assert_eq!(streamed.slots, 20_480 / 4); + assert!(streamed.authoritative_host_allocation > 0); + // overflow stays an error rather than a wrap + let huge = KvInputs { max_cells: u64::MAX / 2, ..base.kv_inputs }; + assert!(huge.plan().is_err()); + // the orders are documented once each + assert_eq!(LOAD_ORDER.len(), 11); + assert_eq!(RELEASE_ORDER.len(), 13); + assert_eq!(REQUIRED_Q8_NAMES.len(), 9); +} + +/// The pure constants above restate the closed owners. This compile-checked +/// test (runs on Linux/CI, not on the macOS harness) pins them to the +/// session geometry and ring window the retained code actually uses. +#[cfg(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +#[test] +fn closed_profile_constants_match_the_retained_owners() { + let g = crate::original_session_state::OriginalSessionGeometry::original(); + assert_eq!(g.experts as u64, PROFILE_N_EXPERT); + assert_eq!(g.heads as u64, PROFILE_HEADS); + assert_eq!(g.kv_heads as u64, PROFILE_KV_HEADS); + assert_eq!(g.head_dim as u64, PROFILE_HEAD_DIM); + assert_eq!(g.index_dim as u64, PROFILE_INDEX_DIM); + assert_eq!(crate::MTP_ORIGINAL_WINDOW as i64, CLOSED_WINDOW); + assert_eq!(EXPERT_BLOB_BYTES, 3 * (2560 * 640 * 18 / 64)); +} diff --git a/crates/cuda-driver/src/original_mtp_rt.rs b/crates/cuda-driver/src/original_mtp_rt.rs index 7145db90..eae795b5 100644 --- a/crates/cuda-driver/src/original_mtp_rt.rs +++ b/crates/cuda-driver/src/original_mtp_rt.rs @@ -620,438 +620,4 @@ pub(crate) mod fixtures { } #[cfg(test)] -mod tests { - use super::fixtures::*; - use super::*; - - const REQUIRED: &[&str] = &[ - "fc_embedding.weight", - "fc_hidden.weight", - "self_attn.q_proj.weight", - "self_attn.k_proj.weight", - "self_attn.v_proj.weight", - "self_attn.o_proj.weight", - "mlp.shared_expert.gate_proj.weight", - "mlp.shared_expert.up_proj.weight", - "mlp.shared_expert.down_proj.weight", - ]; - - #[test] - fn parses_getline_loop_and_skips_empty_lines() { - let (text, blob) = dense(); - let index = DenseIndex::parse(&format!("\n{text}\n\n")).unwrap(); - assert_eq!(index.tensors().len(), TENSORS.len()); - index.validate_extents(blob.len() as u64).unwrap(); - index.check_required(REQUIRED).unwrap(); - let q = index - .find("self_attn.q_proj.weight", OriginalMtpTensorKind::Q8_0) - .unwrap(); - assert_eq!((q.rows, q.columns, q.bytes), (3, 32, 102)); - assert_eq!(q.offset % 256, 0); - // kind-specific lookup: a bf16 tensor is not a q8 one. - assert!( - index - .find("mlp.gate.weight", OriginalMtpTensorKind::Q8_0) - .is_none() - ); - assert!( - index - .find("mlp.gate.weight", OriginalMtpTensorKind::Bf16) - .is_some() - ); - // CRLF and a missing final newline parse like std::getline + >>. - let crlf = text.replace('\n', "\r\n"); - assert_eq!( - DenseIndex::parse(&crlf).unwrap().tensors().len(), - TENSORS.len() - ); - assert_eq!( - DenseIndex::parse(text.trim_end()).unwrap().tensors().len(), - TENSORS.len() - ); - assert_eq!(DenseIndex::parse("").unwrap().tensors().len(), 0); - } - - #[test] - fn malformed_index_lines_carry_the_original_message() { - let (text, _) = dense(); - for bad in [ - "name q8_0 1 32 0\n".to_owned(), // five fields - "name q8_0 1 32 0 34 extra\n".to_owned(), // seven fields - "name q8_0 x 32 0 34\n".to_owned(), - "name q8_0 -1 32 0 34\n".to_owned(), - "name q8_0 +1 32 0 34\n".to_owned(), - " \n".to_owned(), // whitespace-only is not "empty" - format!("{text}tail\n"), - ] { - let error = DenseIndex::parse(&bad).unwrap_err(); - assert!( - matches!(error, RtError::MalformedLine(_)), - "{bad:?} -> {error:?}" - ); - assert!( - error - .message() - .starts_with("mtp: malformed dense.txt line: ") - ); - } - assert_eq!( - DenseIndex::parse("n é 1 1 0 1\n").unwrap_err(), - RtError::IndexNotAscii - ); - assert!(matches!( - DenseIndex::parse("a.b-c q8_0 1 32 0 34\n"), - Err(RtError::InvalidName(_)) - )); - assert!(matches!( - DenseIndex::parse("a q4 1 32 0 34\n"), - Err(RtError::UnknownKind(_)) - )); - assert!(matches!( - DenseIndex::parse("a f32 1 4 0 16\na bf16 1 4 256 8\n"), - Err(RtError::DuplicateTensor(_)) - )); - let many: String = (0..=MAX_TENSORS) - .map(|i| format!("t{i} f32 1 1 0 4\n")) - .collect(); - assert_eq!( - DenseIndex::parse(&many).unwrap_err(), - RtError::TooManyTensors - ); - } - - #[test] - fn extent_validation_is_exact_and_bounded() { - let (text, blob) = dense(); - let end = blob.len() as u64; - let index = DenseIndex::parse(&text).unwrap(); - assert!(index.validate_extents(end - 1).is_err()); - index.validate_extents(end + 5).unwrap(); - for edit in [ - ( - "self_attn.q_proj.weight q8_0 3 32", - "self_attn.q_proj.weight q8_0 3 31", - ), - ( - "self_attn.q_proj.weight q8_0 3 32", - "self_attn.q_proj.weight q8_0 0 32", - ), - ("mlp.gate.weight bf16 5 8", "mlp.gate.weight bf16 6 8"), - ("fc_hidden.weight q8_0 2 64", "fc_hidden.weight q8_0 2 32"), - ( - "self_attn.k_norm.weight f32 1 8", - "self_attn.k_norm.weight f32 2 8", - ), - ] { - let broken = DenseIndex::parse(&text.replacen(edit.0, edit.1, 1)).unwrap(); - assert!( - matches!(broken.validate_extents(end), Err(RtError::Geometry(_))), - "{edit:?}" - ); - } - let beyond = DenseIndex::parse("x f32 1 4 4294967296 16\n").unwrap(); - assert!(matches!( - beyond.validate_extents(end), - Err(RtError::OutOfRange(_)) - )); - let wrap = DenseIndex::parse("x f32 1 4 18446744073709551615 16\n").unwrap(); - assert!(matches!( - wrap.validate_extents(end), - Err(RtError::OutOfRange(_)) - )); - let huge = DenseIndex::parse("x q8_0 4294967296 32 0 1\n").unwrap(); - assert!(matches!( - huge.validate_extents(u64::MAX), - Err(RtError::Geometry(_)) - )); - } - - #[test] - fn required_names_are_checked_in_source_order_by_kind() { - let (text, _) = dense(); - for (i, name) in REQUIRED.iter().enumerate() { - // dropping the line and retyping it as bf16 both make it "missing (q8_0)" - let dropped: String = text - .lines() - .filter(|l| !l.starts_with(&format!("{name} "))) - .map(|l| format!("{l}\n")) - .collect(); - let retyped = text.replacen(&format!("{name} q8_0"), &format!("{name} bf16"), 1); - for broken in [dropped, retyped] { - let index = DenseIndex::parse(&broken).unwrap(); - let error = index.check_required(REQUIRED).unwrap_err(); - assert_eq!(error, RtError::MissingRequired(REQUIRED[i])); - assert_eq!(error.message(), format!("mtp: {name} is missing (q8_0)")); - } - } - // two missing: the FIRST in source order is reported. - let two = DenseIndex::parse( - &text - .lines() - .filter(|l| { - !l.starts_with("fc_hidden.weight ") && !l.starts_with("fc_embedding.weight ") - }) - .map(|l| format!("{l}\n")) - .collect::(), - ) - .unwrap(); - assert_eq!( - two.check_required(REQUIRED).unwrap_err(), - RtError::MissingRequired(REQUIRED[0]) - ); - } - - #[test] - fn finite_admission_rejects_each_dtype() { - let (text, blob) = dense(); - let index = DenseIndex::parse(&text).unwrap(); - index.validate_finite(&blob).unwrap(); - for (name, offset_in_tensor, bytes) in [ - ("fc_embedding.weight", 0usize, [0x00u8, 0x7c]), // q8 f16 scale = inf - ("mlp.gate.weight", 2, [0x80, 0x7f]), // bf16 inf - ("attn_hyper_connection.hc_norm.weight", 4, [0x00, 0x80]), // f32 bytes below - ] { - let entry = index.tensors().iter().find(|t| t.name == name).unwrap(); - let mut broken = blob.clone(); - let at = entry.offset as usize + offset_in_tensor; - if name.starts_with("attn_hyper") { - broken[at..at + 4].copy_from_slice(&f32::NAN.to_le_bytes()); - } else { - broken[at..at + 2].copy_from_slice(&bytes); - } - assert_eq!( - index.validate_finite(&broken).unwrap_err(), - RtError::NonFinite(name.to_owned()) - ); - } - assert!(matches!( - index.validate_finite(&blob[..blob.len() - 1]), - Err(RtError::OutOfRange(_)) - )); - } - - #[test] - fn index_and_dense_readers_follow_original_file_semantics() { - let dir = TempDir::new("read"); - let (text, blob) = dense(); - let missing = read_index(&dir.0).unwrap_err(); - assert!( - missing - .message() - .contains("/dense.txt (run tools/mtp_rt.py)") - ); - write(&dir, "dense.txt", text.as_bytes()); - assert_eq!(read_index(&dir.0).unwrap().tensors().len(), TENSORS.len()); - assert_eq!( - read_dense(&dir.0).unwrap_err().message(), - "mtp: cannot read dense.bin" - ); - write(&dir, "dense.bin", &blob); - assert_eq!(read_dense(&dir.0).unwrap(), blob); - write(&dir, "dense.bin", b""); - assert!(read_dense(&dir.0).unwrap().is_empty()); // n == 0 succeeds like Original - write(&dir, "dense.txt", &vec![b' '; INDEX_LIMIT as usize + 1]); - assert_eq!(read_index(&dir.0).unwrap_err(), RtError::IndexTooLarge); - write(&dir, "dense.txt", "é".as_bytes()); - assert_eq!(read_index(&dir.0).unwrap_err(), RtError::IndexNotAscii); - } - - #[cfg(unix)] - #[test] - fn symlinked_and_non_regular_files_are_refused() { - let dir = TempDir::new("link"); - let (text, blob) = dense(); - write(&dir, "real.bin", &blob); - std::os::unix::fs::symlink(dir.0.join("real.bin"), dir.0.join("dense.bin")).unwrap(); - assert_eq!(read_dense(&dir.0).unwrap_err(), RtError::CannotReadDense); - write(&dir, "real.txt", text.as_bytes()); - std::os::unix::fs::symlink(dir.0.join("real.txt"), dir.0.join("dense.txt")).unwrap(); - assert!(matches!( - read_index(&dir.0), - Err(RtError::CannotOpenIndex { .. }) - )); - fs::create_dir(dir.0.join("experts.bin")).unwrap(); - let outcome = stream_experts::<()>(&dir.0, 4, 4, || Ok(()), |_, _| Ok(())); - assert_eq!(outcome, Err(StreamError::Rt(RtError::CannotOpenExperts))); - } - - #[test] - fn expert_stream_matches_the_chunk_plan_and_ignores_trailing_bytes() { - let dir = TempDir::new("experts"); - let blob = 1_382_400usize; - let bank = experts(3, blob); - let mut file = bank.clone(); - file.extend_from_slice(b"trailing bytes Original never reads"); - write(&dir, "experts.bin", &file); - let total = bank.len() as u64; - for chunk in [2usize << 20, 1 << 20, 4 << 20] { - let mut seen = Vec::new(); - let mut stored = vec![0u8; bank.len()]; - let allocated = std::cell::Cell::new(false); - stream_experts::<()>( - &dir.0, - total, - chunk, - || { - allocated.set(true); - Ok(()) - }, - |offset, data| { - assert!(allocated.get(), "allocation precedes the first read"); - seen.push((offset, data.len() as u64)); - stored[offset as usize..offset as usize + data.len()].copy_from_slice(data); - Ok(()) - }, - ) - .unwrap(); - assert_eq!(stored, bank); - let expected: Vec<_> = (0..total) - .step_by(chunk) - .map(|o| (o, (chunk as u64).min(total - o))) - .collect(); - assert_eq!(seen, expected); - } - } - - #[test] - fn expert_stream_error_paths_use_original_order_and_text() { - let dir = TempDir::new("experts-err"); - // open failure happens before the caller may allocate - let mut ran = false; - let outcome = stream_experts::<()>( - &dir.0, - 8, - 8, - || { - ran = true; - Ok(()) - }, - |_, _| Ok(()), - ); - assert_eq!(outcome, Err(StreamError::Rt(RtError::CannotOpenExperts))); - assert!(!ran); - write(&dir, "experts.bin", &[7u8; 20]); - // allocation failure reported by the callback wins before any read - let mut reads = 0; - let outcome = stream_experts( - &dir.0, - 20, - 8, - || Err("alloc"), - |_, _| { - reads += 1; - Ok(()) - }, - ); - assert_eq!(outcome, Err(StreamError::Sink("alloc"))); - assert_eq!(reads, 0); - // truncated: 20 bytes present, 21 requested - let mut chunks = 0; - let outcome = stream_experts::<()>( - &dir.0, - 21, - 8, - || Ok(()), - |_, _| { - chunks += 1; - Ok(()) - }, - ); - assert_eq!(outcome, Err(StreamError::Rt(RtError::ExpertsTruncated))); - assert_eq!(chunks, 2); // two complete chunks were delivered before the short read - assert_eq!( - RtError::ExpertsTruncated.message(), - "mtp: experts.bin is truncated" - ); - // a sink failure stops the loop - let outcome = stream_experts( - &dir.0, - 20, - 8, - || Ok(()), - |o, _| if o == 8 { Err("h2d") } else { Ok(()) }, - ); - assert_eq!(outcome, Err(StreamError::Sink("h2d"))); - assert!(matches!( - stream_experts::<()>(&dir.0, 20, 0, || Ok(()), |_, _| Ok(())), - Err(StreamError::Rt(RtError::Host)) - )); - assert_eq!(expert_bank_bytes(512, 1_382_400).unwrap(), 707_788_800); - assert_eq!( - expert_bank_bytes(u64::MAX, 2), - Err(RtError::ExpertSizeOverflow) - ); - } - - #[test] - fn expert_scale_scan_handles_chunk_boundaries_inside_blobs() { - let blob = 1_382_400u64; - let bank = experts(2, blob as usize); - for chunk in [1_000_000usize, 777_776, 1_382_400, 2_764_800] { - let mut offset = 0usize; - while offset < bank.len() { - let end = (offset + chunk).min(bank.len()); - assert!(expert_scales_finite( - offset as u64, - &bank[offset..end], - blob - )); - offset = end; - } - } - // an Inf scale half in the second blob is found from any chunking - for chunk in [1_000_000usize, 777_776, 2_764_800] { - let mut broken = bank.clone(); - let at = blob as usize + EXPERT_SCALE_OFFSET as usize + 1000; - broken[at] = 0x00; - broken[at + 1] = 0x7c; - let mut found = false; - let mut offset = 0usize; - while offset < broken.len() { - let end = (offset + chunk).min(broken.len()); - found |= !expert_scales_finite(offset as u64, &broken[offset..end], blob); - offset = end; - } - assert!(found, "chunk {chunk}"); - } - // an Inf in the Q2 code region is not a scale and is never examined - let mut codes = bank.clone(); - codes[10] = 0x00; - codes[11] = 0x7c; - assert!(expert_scales_finite(0, &codes, blob)); - assert!(!expert_scales_finite(1, &bank[1..3], blob)); // odd offset refused - } - - #[test] - fn draft_vocab_follows_the_original_size_filter() { - let dir = TempDir::new("vocab"); - assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(), DraftVocab::Absent); - assert_eq!(observed_draft_vocab_bytes_with(&dir.0, &dv::Setting::Default), None); - for bad in [&b""[..], &b"abc"[..], &b"abcdef"[..]] { - write(&dir, "draft_vocab.bin", bad); - assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(), DraftVocab::Absent); - // the bind_bytes probe still sees the file size (the caller filters) - assert_eq!(observed_draft_vocab_bytes_with(&dir.0, &dv::Setting::Default), Some(bad.len() as u64)); - } - let ids = [5i32, 0, 9, 5]; - let raw: Vec = ids.iter().flat_map(|i| i.to_le_bytes()).collect(); - write(&dir, "draft_vocab.bin", &raw); - assert_eq!( - read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(), - DraftVocab::Subset(ids.to_vec()) - ); - validate_subset(&ids, 10).unwrap(); - assert_eq!(validate_subset(&ids, 9), Err(RtError::DraftVocabOutOfRange)); - assert_eq!( - validate_subset(&[-1], 10), - Err(RtError::DraftVocabOutOfRange) - ); - assert_eq!(validate_subset(&[], 10), Err(RtError::DraftVocabOutOfRange)); - write( - &dir, - "draft_vocab.bin", - &vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4], - ); - assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default), Err(RtError::DraftVocabTooLarge)); - } -} +mod tests; diff --git a/crates/cuda-driver/src/original_mtp_rt/tests.rs b/crates/cuda-driver/src/original_mtp_rt/tests.rs new file mode 100644 index 00000000..eac11bb8 --- /dev/null +++ b/crates/cuda-driver/src/original_mtp_rt/tests.rs @@ -0,0 +1,435 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::fixtures::*; +use super::*; + +const REQUIRED: &[&str] = &[ + "fc_embedding.weight", + "fc_hidden.weight", + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "mlp.shared_expert.gate_proj.weight", + "mlp.shared_expert.up_proj.weight", + "mlp.shared_expert.down_proj.weight", +]; + +#[test] +fn parses_getline_loop_and_skips_empty_lines() { + let (text, blob) = dense(); + let index = DenseIndex::parse(&format!("\n{text}\n\n")).unwrap(); + assert_eq!(index.tensors().len(), TENSORS.len()); + index.validate_extents(blob.len() as u64).unwrap(); + index.check_required(REQUIRED).unwrap(); + let q = index + .find("self_attn.q_proj.weight", OriginalMtpTensorKind::Q8_0) + .unwrap(); + assert_eq!((q.rows, q.columns, q.bytes), (3, 32, 102)); + assert_eq!(q.offset % 256, 0); + // kind-specific lookup: a bf16 tensor is not a q8 one. + assert!( + index + .find("mlp.gate.weight", OriginalMtpTensorKind::Q8_0) + .is_none() + ); + assert!( + index + .find("mlp.gate.weight", OriginalMtpTensorKind::Bf16) + .is_some() + ); + // CRLF and a missing final newline parse like std::getline + >>. + let crlf = text.replace('\n', "\r\n"); + assert_eq!( + DenseIndex::parse(&crlf).unwrap().tensors().len(), + TENSORS.len() + ); + assert_eq!( + DenseIndex::parse(text.trim_end()).unwrap().tensors().len(), + TENSORS.len() + ); + assert_eq!(DenseIndex::parse("").unwrap().tensors().len(), 0); +} + +#[test] +fn malformed_index_lines_carry_the_original_message() { + let (text, _) = dense(); + for bad in [ + "name q8_0 1 32 0\n".to_owned(), // five fields + "name q8_0 1 32 0 34 extra\n".to_owned(), // seven fields + "name q8_0 x 32 0 34\n".to_owned(), + "name q8_0 -1 32 0 34\n".to_owned(), + "name q8_0 +1 32 0 34\n".to_owned(), + " \n".to_owned(), // whitespace-only is not "empty" + format!("{text}tail\n"), + ] { + let error = DenseIndex::parse(&bad).unwrap_err(); + assert!( + matches!(error, RtError::MalformedLine(_)), + "{bad:?} -> {error:?}" + ); + assert!( + error + .message() + .starts_with("mtp: malformed dense.txt line: ") + ); + } + assert_eq!( + DenseIndex::parse("n é 1 1 0 1\n").unwrap_err(), + RtError::IndexNotAscii + ); + assert!(matches!( + DenseIndex::parse("a.b-c q8_0 1 32 0 34\n"), + Err(RtError::InvalidName(_)) + )); + assert!(matches!( + DenseIndex::parse("a q4 1 32 0 34\n"), + Err(RtError::UnknownKind(_)) + )); + assert!(matches!( + DenseIndex::parse("a f32 1 4 0 16\na bf16 1 4 256 8\n"), + Err(RtError::DuplicateTensor(_)) + )); + let many: String = (0..=MAX_TENSORS) + .map(|i| format!("t{i} f32 1 1 0 4\n")) + .collect(); + assert_eq!( + DenseIndex::parse(&many).unwrap_err(), + RtError::TooManyTensors + ); +} + +#[test] +fn extent_validation_is_exact_and_bounded() { + let (text, blob) = dense(); + let end = blob.len() as u64; + let index = DenseIndex::parse(&text).unwrap(); + assert!(index.validate_extents(end - 1).is_err()); + index.validate_extents(end + 5).unwrap(); + for edit in [ + ( + "self_attn.q_proj.weight q8_0 3 32", + "self_attn.q_proj.weight q8_0 3 31", + ), + ( + "self_attn.q_proj.weight q8_0 3 32", + "self_attn.q_proj.weight q8_0 0 32", + ), + ("mlp.gate.weight bf16 5 8", "mlp.gate.weight bf16 6 8"), + ("fc_hidden.weight q8_0 2 64", "fc_hidden.weight q8_0 2 32"), + ( + "self_attn.k_norm.weight f32 1 8", + "self_attn.k_norm.weight f32 2 8", + ), + ] { + let broken = DenseIndex::parse(&text.replacen(edit.0, edit.1, 1)).unwrap(); + assert!( + matches!(broken.validate_extents(end), Err(RtError::Geometry(_))), + "{edit:?}" + ); + } + let beyond = DenseIndex::parse("x f32 1 4 4294967296 16\n").unwrap(); + assert!(matches!( + beyond.validate_extents(end), + Err(RtError::OutOfRange(_)) + )); + let wrap = DenseIndex::parse("x f32 1 4 18446744073709551615 16\n").unwrap(); + assert!(matches!( + wrap.validate_extents(end), + Err(RtError::OutOfRange(_)) + )); + let huge = DenseIndex::parse("x q8_0 4294967296 32 0 1\n").unwrap(); + assert!(matches!( + huge.validate_extents(u64::MAX), + Err(RtError::Geometry(_)) + )); +} + +#[test] +fn required_names_are_checked_in_source_order_by_kind() { + let (text, _) = dense(); + for (i, name) in REQUIRED.iter().enumerate() { + // dropping the line and retyping it as bf16 both make it "missing (q8_0)" + let dropped: String = text + .lines() + .filter(|l| !l.starts_with(&format!("{name} "))) + .map(|l| format!("{l}\n")) + .collect(); + let retyped = text.replacen(&format!("{name} q8_0"), &format!("{name} bf16"), 1); + for broken in [dropped, retyped] { + let index = DenseIndex::parse(&broken).unwrap(); + let error = index.check_required(REQUIRED).unwrap_err(); + assert_eq!(error, RtError::MissingRequired(REQUIRED[i])); + assert_eq!(error.message(), format!("mtp: {name} is missing (q8_0)")); + } + } + // two missing: the FIRST in source order is reported. + let two = DenseIndex::parse( + &text + .lines() + .filter(|l| { + !l.starts_with("fc_hidden.weight ") && !l.starts_with("fc_embedding.weight ") + }) + .map(|l| format!("{l}\n")) + .collect::(), + ) + .unwrap(); + assert_eq!( + two.check_required(REQUIRED).unwrap_err(), + RtError::MissingRequired(REQUIRED[0]) + ); +} + +#[test] +fn finite_admission_rejects_each_dtype() { + let (text, blob) = dense(); + let index = DenseIndex::parse(&text).unwrap(); + index.validate_finite(&blob).unwrap(); + for (name, offset_in_tensor, bytes) in [ + ("fc_embedding.weight", 0usize, [0x00u8, 0x7c]), // q8 f16 scale = inf + ("mlp.gate.weight", 2, [0x80, 0x7f]), // bf16 inf + ("attn_hyper_connection.hc_norm.weight", 4, [0x00, 0x80]), // f32 bytes below + ] { + let entry = index.tensors().iter().find(|t| t.name == name).unwrap(); + let mut broken = blob.clone(); + let at = entry.offset as usize + offset_in_tensor; + if name.starts_with("attn_hyper") { + broken[at..at + 4].copy_from_slice(&f32::NAN.to_le_bytes()); + } else { + broken[at..at + 2].copy_from_slice(&bytes); + } + assert_eq!( + index.validate_finite(&broken).unwrap_err(), + RtError::NonFinite(name.to_owned()) + ); + } + assert!(matches!( + index.validate_finite(&blob[..blob.len() - 1]), + Err(RtError::OutOfRange(_)) + )); +} + +#[test] +fn index_and_dense_readers_follow_original_file_semantics() { + let dir = TempDir::new("read"); + let (text, blob) = dense(); + let missing = read_index(&dir.0).unwrap_err(); + assert!( + missing + .message() + .contains("/dense.txt (run tools/mtp_rt.py)") + ); + write(&dir, "dense.txt", text.as_bytes()); + assert_eq!(read_index(&dir.0).unwrap().tensors().len(), TENSORS.len()); + assert_eq!( + read_dense(&dir.0).unwrap_err().message(), + "mtp: cannot read dense.bin" + ); + write(&dir, "dense.bin", &blob); + assert_eq!(read_dense(&dir.0).unwrap(), blob); + write(&dir, "dense.bin", b""); + assert!(read_dense(&dir.0).unwrap().is_empty()); // n == 0 succeeds like Original + write(&dir, "dense.txt", &vec![b' '; INDEX_LIMIT as usize + 1]); + assert_eq!(read_index(&dir.0).unwrap_err(), RtError::IndexTooLarge); + write(&dir, "dense.txt", "é".as_bytes()); + assert_eq!(read_index(&dir.0).unwrap_err(), RtError::IndexNotAscii); +} + +#[cfg(unix)] +#[test] +fn symlinked_and_non_regular_files_are_refused() { + let dir = TempDir::new("link"); + let (text, blob) = dense(); + write(&dir, "real.bin", &blob); + std::os::unix::fs::symlink(dir.0.join("real.bin"), dir.0.join("dense.bin")).unwrap(); + assert_eq!(read_dense(&dir.0).unwrap_err(), RtError::CannotReadDense); + write(&dir, "real.txt", text.as_bytes()); + std::os::unix::fs::symlink(dir.0.join("real.txt"), dir.0.join("dense.txt")).unwrap(); + assert!(matches!( + read_index(&dir.0), + Err(RtError::CannotOpenIndex { .. }) + )); + fs::create_dir(dir.0.join("experts.bin")).unwrap(); + let outcome = stream_experts::<()>(&dir.0, 4, 4, || Ok(()), |_, _| Ok(())); + assert_eq!(outcome, Err(StreamError::Rt(RtError::CannotOpenExperts))); +} + +#[test] +fn expert_stream_matches_the_chunk_plan_and_ignores_trailing_bytes() { + let dir = TempDir::new("experts"); + let blob = 1_382_400usize; + let bank = experts(3, blob); + let mut file = bank.clone(); + file.extend_from_slice(b"trailing bytes Original never reads"); + write(&dir, "experts.bin", &file); + let total = bank.len() as u64; + for chunk in [2usize << 20, 1 << 20, 4 << 20] { + let mut seen = Vec::new(); + let mut stored = vec![0u8; bank.len()]; + let allocated = std::cell::Cell::new(false); + stream_experts::<()>( + &dir.0, + total, + chunk, + || { + allocated.set(true); + Ok(()) + }, + |offset, data| { + assert!(allocated.get(), "allocation precedes the first read"); + seen.push((offset, data.len() as u64)); + stored[offset as usize..offset as usize + data.len()].copy_from_slice(data); + Ok(()) + }, + ) + .unwrap(); + assert_eq!(stored, bank); + let expected: Vec<_> = (0..total) + .step_by(chunk) + .map(|o| (o, (chunk as u64).min(total - o))) + .collect(); + assert_eq!(seen, expected); + } +} + +#[test] +fn expert_stream_error_paths_use_original_order_and_text() { + let dir = TempDir::new("experts-err"); + // open failure happens before the caller may allocate + let mut ran = false; + let outcome = stream_experts::<()>( + &dir.0, + 8, + 8, + || { + ran = true; + Ok(()) + }, + |_, _| Ok(()), + ); + assert_eq!(outcome, Err(StreamError::Rt(RtError::CannotOpenExperts))); + assert!(!ran); + write(&dir, "experts.bin", &[7u8; 20]); + // allocation failure reported by the callback wins before any read + let mut reads = 0; + let outcome = stream_experts( + &dir.0, + 20, + 8, + || Err("alloc"), + |_, _| { + reads += 1; + Ok(()) + }, + ); + assert_eq!(outcome, Err(StreamError::Sink("alloc"))); + assert_eq!(reads, 0); + // truncated: 20 bytes present, 21 requested + let mut chunks = 0; + let outcome = stream_experts::<()>( + &dir.0, + 21, + 8, + || Ok(()), + |_, _| { + chunks += 1; + Ok(()) + }, + ); + assert_eq!(outcome, Err(StreamError::Rt(RtError::ExpertsTruncated))); + assert_eq!(chunks, 2); // two complete chunks were delivered before the short read + assert_eq!( + RtError::ExpertsTruncated.message(), + "mtp: experts.bin is truncated" + ); + // a sink failure stops the loop + let outcome = stream_experts( + &dir.0, + 20, + 8, + || Ok(()), + |o, _| if o == 8 { Err("h2d") } else { Ok(()) }, + ); + assert_eq!(outcome, Err(StreamError::Sink("h2d"))); + assert!(matches!( + stream_experts::<()>(&dir.0, 20, 0, || Ok(()), |_, _| Ok(())), + Err(StreamError::Rt(RtError::Host)) + )); + assert_eq!(expert_bank_bytes(512, 1_382_400).unwrap(), 707_788_800); + assert_eq!( + expert_bank_bytes(u64::MAX, 2), + Err(RtError::ExpertSizeOverflow) + ); +} + +#[test] +fn expert_scale_scan_handles_chunk_boundaries_inside_blobs() { + let blob = 1_382_400u64; + let bank = experts(2, blob as usize); + for chunk in [1_000_000usize, 777_776, 1_382_400, 2_764_800] { + let mut offset = 0usize; + while offset < bank.len() { + let end = (offset + chunk).min(bank.len()); + assert!(expert_scales_finite( + offset as u64, + &bank[offset..end], + blob + )); + offset = end; + } + } + // an Inf scale half in the second blob is found from any chunking + for chunk in [1_000_000usize, 777_776, 2_764_800] { + let mut broken = bank.clone(); + let at = blob as usize + EXPERT_SCALE_OFFSET as usize + 1000; + broken[at] = 0x00; + broken[at + 1] = 0x7c; + let mut found = false; + let mut offset = 0usize; + while offset < broken.len() { + let end = (offset + chunk).min(broken.len()); + found |= !expert_scales_finite(offset as u64, &broken[offset..end], blob); + offset = end; + } + assert!(found, "chunk {chunk}"); + } + // an Inf in the Q2 code region is not a scale and is never examined + let mut codes = bank.clone(); + codes[10] = 0x00; + codes[11] = 0x7c; + assert!(expert_scales_finite(0, &codes, blob)); + assert!(!expert_scales_finite(1, &bank[1..3], blob)); // odd offset refused +} + +#[test] +fn draft_vocab_follows_the_original_size_filter() { + let dir = TempDir::new("vocab"); + assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(), DraftVocab::Absent); + assert_eq!(observed_draft_vocab_bytes_with(&dir.0, &dv::Setting::Default), None); + for bad in [&b""[..], &b"abc"[..], &b"abcdef"[..]] { + write(&dir, "draft_vocab.bin", bad); + assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(), DraftVocab::Absent); + // the bind_bytes probe still sees the file size (the caller filters) + assert_eq!(observed_draft_vocab_bytes_with(&dir.0, &dv::Setting::Default), Some(bad.len() as u64)); + } + let ids = [5i32, 0, 9, 5]; + let raw: Vec = ids.iter().flat_map(|i| i.to_le_bytes()).collect(); + write(&dir, "draft_vocab.bin", &raw); + assert_eq!( + read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(), + DraftVocab::Subset(ids.to_vec()) + ); + validate_subset(&ids, 10).unwrap(); + assert_eq!(validate_subset(&ids, 9), Err(RtError::DraftVocabOutOfRange)); + assert_eq!( + validate_subset(&[-1], 10), + Err(RtError::DraftVocabOutOfRange) + ); + assert_eq!(validate_subset(&[], 10), Err(RtError::DraftVocabOutOfRange)); + write( + &dir, + "draft_vocab.bin", + &vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4], + ); + assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default), Err(RtError::DraftVocabTooLarge)); +} diff --git a/crates/cuda-driver/src/original_prefill_schedule.rs b/crates/cuda-driver/src/original_prefill_schedule.rs index 9a09f7f3..6cf7e71c 100644 --- a/crates/cuda-driver/src/original_prefill_schedule.rs +++ b/crates/cuda-driver/src/original_prefill_schedule.rs @@ -620,236 +620,4 @@ pub fn check_trace(ops: &[SchedOp]) -> Result { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::Value; - - const GOLDEN: &str = include_str!("../oracle/fixtures/prefill_schedule_golden.json"); - - fn golden() -> Value { - serde_json::from_str(GOLDEN).expect("golden fixture parses") - } - fn u(v: &Value) -> usize { - v.as_u64().expect("number") as usize - } - - #[test] - fn golden_expert_stream_traces_match_the_extracted_original() { - let g = golden(); - let scenarios = g["ring"].as_array().unwrap(); - assert!(scenarios.len() >= 7); - for sc in scenarios { - let name = sc["name"].as_str().unwrap(); - let p = &sc["p"]; - let (n_layers, n_expert, lb, le) = (u(&p["n_layers"]), u(&p["n_expert"]), u(&p["lb"]), u(&p["le"])); - let (res_mod, res_rem) = (u(&p["resident_mod"]), u(&p["resident_rem"])); - let (pin_mod, tr_mod) = (u(&p["pinned_mod"]), u(&p["transient_mod"])); - let resident = move |_l: usize, e: usize| res_mod != 0 && e % res_mod == res_rem; - let pinned = move |_l: usize, e: usize| pin_mod != 0 && e % pin_mod == 0; - let transient = move |l: usize, e: usize| !(pin_mod != 0 && e % pin_mod == 0) && tr_mod != 0 && (e + l) % tr_mod == 0; - let view = SourceView { - n_layers, - n_expert, - cache_present: u(&p["cache_present"]) != 0, - resident: &resident, - pinned: &pinned, - transient: &transient, - }; - let orders: Vec> = p["orders"].as_array().unwrap().iter().map(|o| o.as_array().unwrap().iter().map(u).collect()).collect(); - let cfg = StreamConfig { ring: u(&p["ring"]), stager_ring: u(&p["stager_ring"]), rows: u(&p["rows"]), stream_all_min: STREAM_ALL_MIN_DEFAULT }; - let mut planner = Planner::new(); - for chunk in 0..u(&p["chunks"]) { - planner.plan_chunk(chunk, &cfg, &view, lb, le, &orders).unwrap_or_else(|e| panic!("{name}: {e:?}")); - } - let want: Vec<&str> = sc["ops"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); - let got: Vec = planner.ops.iter().map(ToString::to_string).collect(); - for (i, (w, gt)) in want.iter().zip(&got).enumerate() { - assert_eq!(w, gt, "{name}: first difference at op {i}"); - } - assert_eq!(want.len(), got.len(), "{name}: trace length"); - let stats = sc["stats"].as_array().unwrap(); - assert_eq!( - [planner.stats.experts_dma, planner.stats.experts_streamed, planner.stats.experts_resident], - [u(&stats[0]), u(&stats[1]), u(&stats[2])], - "{name}: statistics" - ); - let report = check_trace(&planner.ops).unwrap_or_else(|e| panic!("{name}: {e}")); - assert_eq!(report.copies, planner.stats.experts_streamed, "{name}"); - assert_eq!(report.releases, report.copies, "{name}: every copy released once"); - } - } - - #[test] - fn golden_ple_read_ahead_matches_the_extracted_original() { - for sc in golden()["ple"].as_array().unwrap() { - let name = sc["name"].as_str().unwrap(); - let params = sc["ple"].as_array().unwrap(); - let (n, chunk, gpu) = (u(¶ms[0]), u(¶ms[1]), u(¶ms[2]) != 0); - let mut machine = PleReadAhead::new(gpu); - let mut got = Vec::new(); - for (c0, _t, _p0) in chunks(n, chunk, 0) { - got.push(format!("H ple_chunk {c0}")); - got.extend(machine.chunk(c0, n, chunk).iter().map(ToString::to_string)); - } - let want: Vec<&str> = sc["ops"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); - assert_eq!(want, got.iter().map(String::as_str).collect::>(), "{name}"); - } - } - - #[test] - fn golden_fuse_rule_matches_the_extracted_original() { - let g = golden(); - let table = g["fuse"].as_array().unwrap(); - assert!(table.len() > 100); - let mut fused = 0; - for row in table { - let r: Vec = row.as_array().unwrap().iter().map(u).collect(); - let (le, ple_on, unfused, cvec, l, half, want) = (r[0], r[1] != 0, r[2] != 0, r[3] != 0, r[4], r[5], r[6] != 0); - assert_eq!(fuse_after_half(l, half, le, ple_on, unfused, cvec), want, "{r:?}"); - fused += usize::from(want); - } - assert!(fused > 0 && fused < table.len()); - // the Rust executor's selection: `fused && index != 0 && index != 47` for the FFN half, always for the attention half - for l in 0..48 { - assert!(fuse_after_half(l, 0, 48, true, false, false)); - assert_eq!(fuse_after_half(l, 1, 48, true, false, false), l != 0 && l != 47, "layer {l}"); - } - } - - #[test] - fn ring_slots_is_the_original_rule() { - let d = RingPolicy::default(); - assert_eq!(ring_slots(1024, &d), 384); - assert_eq!(ring_slots(8192, &d), 384); - assert_eq!(ring_slots(1023, &d), STAGE); - assert_eq!(ring_slots(256, &d), STAGE); - // a third of the experts unpinned: the 96-slot ring - assert_eq!(ring_slots(4096, &RingPolicy { pinned_share: 0.5, ..d }), 96); - assert_eq!(ring_slots(4096, &RingPolicy { pinned_share: 0.9, ..d }), 384); - // the layer split's override (#340) - assert_eq!(ring_slots(4096, &RingPolicy { ring_override: 200, ..d }), 200); - assert_eq!(ring_slots(4096, &RingPolicy { ring_override: 4, ..d }), 16, "the setter's value is clamped, not honoured as STAGE"); - assert_eq!(ring_slots(4096, &RingPolicy { ring_override: 9999, ..d }), RING_MAX); - // STRATA_PREFILL_RING wins, and exactly STAGE selects routed-only staging for any chunk size - assert_eq!(ring_slots(4096, &RingPolicy { env_ring: Some(100), ring_override: 200, ..d }), 100); - assert_eq!(ring_slots(4096, &RingPolicy { env_ring: Some(8), ..d }), STAGE); - assert_eq!(ring_slots(4096, &RingPolicy { env_ring: Some(0), ..d }), 16); - assert_eq!(ring_slots(4096, &RingPolicy { env_ring: Some(-5), ..d }), 16); - // STRATA_PREFILL_STREAM_MIN moves the threshold - assert_eq!(ring_slots(512, &RingPolicy { stream_all_min: 512, ..d }), 384); - assert_eq!(ring_slots(511, &RingPolicy { stream_all_min: 512, ..d }), STAGE); - } - - #[test] - fn chunk_loop_covers_the_prompt_in_order() { - assert_eq!(chunks(10, 4, 100), vec![(0, 4, 100), (4, 4, 104), (8, 2, 108)]); - assert_eq!(chunks(8, 4, 0), vec![(0, 4, 0), (4, 4, 4)]); - assert!(chunks(0, 4, 0).is_empty()); - let all = chunks(8193, 8192, 5); - assert_eq!(all.iter().map(|c| c.1).sum::(), 8193); - assert_eq!(all[1], (8192, 1, 8197)); - } - - #[test] - fn handoff_double_buffer_alternates_and_joins_one_run_behind() { - let mut h = Handoff::default(); - let steps: Vec<_> = (0..4).map(|_| h.end_of_chunk()).collect(); - assert_eq!(steps.iter().map(|s| s.buffer).collect::>(), vec![0, 1, 0, 1]); - assert_eq!(steps.iter().map(|s| s.join_previous).collect::>(), vec![false, true, true, true]); - assert!(h.finish()); - assert!(!h.finish()); - } - - #[test] - fn stream_sequence_orders_layers_then_experts_and_skips_resident() { - let resident = |l: usize, e: usize| (l + e) % 3 == 0; - let pinned = |_l: usize, e: usize| e % 2 == 0; - let transient = |_l: usize, e: usize| e == 5; - let view = SourceView { n_layers: 5, n_expert: 8, cache_present: true, resident: &resident, pinned: &pinned, transient: &transient }; - let seq = StreamSequence::build(&view, 1, 3); - assert_eq!(seq.seq_start.len(), 6); - assert_eq!(seq.seq_start[0], 0); - assert_eq!(seq.seq_start[1], 0); - assert_eq!(seq.seq_start[3], seq.entries.len()); - assert_eq!(seq.seq_start[5], seq.entries.len()); - assert!(seq.entries.windows(2).all(|w| (w[0].layer, w[0].expert) < (w[1].layer, w[1].expert))); - assert!(seq.entries.iter().all(|e| !resident(e.layer, e.expert))); - // jobs only for unpinned entries; transient flagged - assert!(seq.entries.iter().all(|e| e.job.is_some() == (e.expert % 2 == 1))); - assert!(seq.jobs.contains(&JobKind::Transient(1, 5)) || seq.jobs.contains(&JobKind::Transient(2, 5))); - // without a residency table nothing is skipped - let view = SourceView { cache_present: false, ..view }; - assert_eq!(StreamSequence::build(&view, 0, 5).entries.len(), 40); - } - - #[test] - fn the_checker_rejects_unsafe_schedules() { - // build a safe trace, then break it three ways - let none = |_: usize, _: usize| false; - let pinned = |_: usize, _: usize| true; - let view = SourceView { n_layers: 2, n_expert: 40, cache_present: false, resident: &none, pinned: &pinned, transient: &none }; - let cfg = StreamConfig { ring: 16, stager_ring: 16, rows: 2048, stream_all_min: 1024 }; - let orders = vec![(0..40).collect::>(), (0..40).collect::>()]; - let mut planner = Planner::new(); - planner.plan_chunk(0, &cfg, &view, 0, 2, &orders).unwrap(); - let good = planner.ops.clone(); - assert!(check_trace(&good).is_ok()); - // 1. drop the copy stream's wait on the previous occupant - let first_wait = good.iter().position(|o| matches!(o, SchedOp::CopyWaitUsed(_))).unwrap(); - let mut bad = good.clone(); - bad.remove(first_wait); - assert!(check_trace(&bad).unwrap_err().contains("did not wait")); - // 2. drop the compute stream's wait on the copy - let w = good.iter().position(|o| matches!(o, SchedOp::ComputeWaitCopied(_))).unwrap(); - let mut bad = good.clone(); - bad.remove(w); - assert!(check_trace(&bad).unwrap_err().contains("did not wait")); - // 3. issue one entry too early (before the slot's occupant is released): move the first overwrite's H2D up - let h = good.iter().enumerate().filter(|(_, o)| matches!(o, SchedOp::H2d { .. })).nth(16).unwrap().0; - let mut bad = good.clone(); - let moved: Vec<_> = bad.drain(h - 1..h + 2).collect(); // wait, h2d, record copied - let at = bad.iter().position(|o| matches!(o, SchedOp::Layer(0))).unwrap() + 1; - for (k, op) in moved.into_iter().enumerate() { - bad.insert(at + k, op); - } - assert!(check_trace(&bad).is_err()); - // 4. a final unreleased copy - let mut bad = good; - let last_release = bad.iter().rposition(|o| matches!(o, SchedOp::RecordUsed(_))).unwrap(); - bad.remove(last_release); - assert!(check_trace(&bad).unwrap_err().contains("unreleased")); - } - - #[test] - fn staged_path_never_uses_more_than_eight_slots_and_keeps_the_lookahead() { - let none = |_: usize, _: usize| false; - let pinned = |_: usize, e: usize| e % 2 == 0; - let view = SourceView { n_layers: 3, n_expert: 64, cache_present: false, resident: &none, pinned: &pinned, transient: &none }; - // ring 384 but only 100 rows: below stream_all_min, so the staged walk runs - let cfg = StreamConfig { ring: 384, stager_ring: 16, rows: 100, stream_all_min: 1024 }; - let order: Vec = (0..64).collect(); - let mut planner = Planner::new(); - planner.plan_chunk(0, &cfg, &view, 0, 3, &vec![order.clone(); 3]).unwrap(); - assert!(planner.ops.iter().all(|o| match o { - SchedOp::H2d { slot, .. } | SchedOp::RecordCopied(slot) | SchedOp::ComputeWaitCopied(slot) => *slot < STAGE, - _ => true, - })); - check_trace(&planner.ops).unwrap(); - // the first compute of a layer happens only after STAGE experts were staged ahead (lookahead 7 + the expert) - let layer0 = planner.ops.iter().position(|o| matches!(o, SchedOp::Layer(0))).unwrap(); - let first_compute = planner.ops[layer0..].iter().position(|o| matches!(o, SchedOp::Compute { .. })).unwrap(); - let copies_before = planner.ops[layer0..layer0 + first_compute].iter().filter(|o| matches!(o, SchedOp::RecordCopied(_))).count(); - assert_eq!(copies_before, STAGE); - } - - #[test] - fn rejects_unsorted_or_out_of_range_routing() { - let none = |_: usize, _: usize| false; - let view = SourceView { n_layers: 1, n_expert: 4, cache_present: false, resident: &none, pinned: &none, transient: &none }; - let cfg = StreamConfig { ring: 8, stager_ring: 16, rows: 10, stream_all_min: 1024 }; - assert_eq!(Planner::new().plan_chunk(0, &cfg, &view, 0, 1, &[vec![2, 1]]), Err(PlanError::OrderNotAscending)); - assert_eq!(Planner::new().plan_chunk(0, &cfg, &view, 0, 1, &[vec![0, 4]]), Err(PlanError::RoutedIdOutOfRange)); - let big = StreamConfig { ring: 513, ..cfg }; - assert_eq!(Planner::new().plan_chunk(0, &big, &view, 0, 1, &[vec![]]), Err(PlanError::RingTooLarge)); - } -} +mod tests; diff --git a/crates/cuda-driver/src/original_prefill_schedule/tests.rs b/crates/cuda-driver/src/original_prefill_schedule/tests.rs new file mode 100644 index 00000000..7475b90b --- /dev/null +++ b/crates/cuda-driver/src/original_prefill_schedule/tests.rs @@ -0,0 +1,233 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use serde_json::Value; + +const GOLDEN: &str = include_str!("../../oracle/fixtures/prefill_schedule_golden.json"); + +fn golden() -> Value { + serde_json::from_str(GOLDEN).expect("golden fixture parses") +} +fn u(v: &Value) -> usize { + v.as_u64().expect("number") as usize +} + +#[test] +fn golden_expert_stream_traces_match_the_extracted_original() { + let g = golden(); + let scenarios = g["ring"].as_array().unwrap(); + assert!(scenarios.len() >= 7); + for sc in scenarios { + let name = sc["name"].as_str().unwrap(); + let p = &sc["p"]; + let (n_layers, n_expert, lb, le) = (u(&p["n_layers"]), u(&p["n_expert"]), u(&p["lb"]), u(&p["le"])); + let (res_mod, res_rem) = (u(&p["resident_mod"]), u(&p["resident_rem"])); + let (pin_mod, tr_mod) = (u(&p["pinned_mod"]), u(&p["transient_mod"])); + let resident = move |_l: usize, e: usize| res_mod != 0 && e % res_mod == res_rem; + let pinned = move |_l: usize, e: usize| pin_mod != 0 && e % pin_mod == 0; + let transient = move |l: usize, e: usize| !(pin_mod != 0 && e % pin_mod == 0) && tr_mod != 0 && (e + l) % tr_mod == 0; + let view = SourceView { + n_layers, + n_expert, + cache_present: u(&p["cache_present"]) != 0, + resident: &resident, + pinned: &pinned, + transient: &transient, + }; + let orders: Vec> = p["orders"].as_array().unwrap().iter().map(|o| o.as_array().unwrap().iter().map(u).collect()).collect(); + let cfg = StreamConfig { ring: u(&p["ring"]), stager_ring: u(&p["stager_ring"]), rows: u(&p["rows"]), stream_all_min: STREAM_ALL_MIN_DEFAULT }; + let mut planner = Planner::new(); + for chunk in 0..u(&p["chunks"]) { + planner.plan_chunk(chunk, &cfg, &view, lb, le, &orders).unwrap_or_else(|e| panic!("{name}: {e:?}")); + } + let want: Vec<&str> = sc["ops"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); + let got: Vec = planner.ops.iter().map(ToString::to_string).collect(); + for (i, (w, gt)) in want.iter().zip(&got).enumerate() { + assert_eq!(w, gt, "{name}: first difference at op {i}"); + } + assert_eq!(want.len(), got.len(), "{name}: trace length"); + let stats = sc["stats"].as_array().unwrap(); + assert_eq!( + [planner.stats.experts_dma, planner.stats.experts_streamed, planner.stats.experts_resident], + [u(&stats[0]), u(&stats[1]), u(&stats[2])], + "{name}: statistics" + ); + let report = check_trace(&planner.ops).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(report.copies, planner.stats.experts_streamed, "{name}"); + assert_eq!(report.releases, report.copies, "{name}: every copy released once"); + } +} + +#[test] +fn golden_ple_read_ahead_matches_the_extracted_original() { + for sc in golden()["ple"].as_array().unwrap() { + let name = sc["name"].as_str().unwrap(); + let params = sc["ple"].as_array().unwrap(); + let (n, chunk, gpu) = (u(¶ms[0]), u(¶ms[1]), u(¶ms[2]) != 0); + let mut machine = PleReadAhead::new(gpu); + let mut got = Vec::new(); + for (c0, _t, _p0) in chunks(n, chunk, 0) { + got.push(format!("H ple_chunk {c0}")); + got.extend(machine.chunk(c0, n, chunk).iter().map(ToString::to_string)); + } + let want: Vec<&str> = sc["ops"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); + assert_eq!(want, got.iter().map(String::as_str).collect::>(), "{name}"); + } +} + +#[test] +fn golden_fuse_rule_matches_the_extracted_original() { + let g = golden(); + let table = g["fuse"].as_array().unwrap(); + assert!(table.len() > 100); + let mut fused = 0; + for row in table { + let r: Vec = row.as_array().unwrap().iter().map(u).collect(); + let (le, ple_on, unfused, cvec, l, half, want) = (r[0], r[1] != 0, r[2] != 0, r[3] != 0, r[4], r[5], r[6] != 0); + assert_eq!(fuse_after_half(l, half, le, ple_on, unfused, cvec), want, "{r:?}"); + fused += usize::from(want); + } + assert!(fused > 0 && fused < table.len()); + // the Rust executor's selection: `fused && index != 0 && index != 47` for the FFN half, always for the attention half + for l in 0..48 { + assert!(fuse_after_half(l, 0, 48, true, false, false)); + assert_eq!(fuse_after_half(l, 1, 48, true, false, false), l != 0 && l != 47, "layer {l}"); + } +} + +#[test] +fn ring_slots_is_the_original_rule() { + let d = RingPolicy::default(); + assert_eq!(ring_slots(1024, &d), 384); + assert_eq!(ring_slots(8192, &d), 384); + assert_eq!(ring_slots(1023, &d), STAGE); + assert_eq!(ring_slots(256, &d), STAGE); + // a third of the experts unpinned: the 96-slot ring + assert_eq!(ring_slots(4096, &RingPolicy { pinned_share: 0.5, ..d }), 96); + assert_eq!(ring_slots(4096, &RingPolicy { pinned_share: 0.9, ..d }), 384); + // the layer split's override (#340) + assert_eq!(ring_slots(4096, &RingPolicy { ring_override: 200, ..d }), 200); + assert_eq!(ring_slots(4096, &RingPolicy { ring_override: 4, ..d }), 16, "the setter's value is clamped, not honoured as STAGE"); + assert_eq!(ring_slots(4096, &RingPolicy { ring_override: 9999, ..d }), RING_MAX); + // STRATA_PREFILL_RING wins, and exactly STAGE selects routed-only staging for any chunk size + assert_eq!(ring_slots(4096, &RingPolicy { env_ring: Some(100), ring_override: 200, ..d }), 100); + assert_eq!(ring_slots(4096, &RingPolicy { env_ring: Some(8), ..d }), STAGE); + assert_eq!(ring_slots(4096, &RingPolicy { env_ring: Some(0), ..d }), 16); + assert_eq!(ring_slots(4096, &RingPolicy { env_ring: Some(-5), ..d }), 16); + // STRATA_PREFILL_STREAM_MIN moves the threshold + assert_eq!(ring_slots(512, &RingPolicy { stream_all_min: 512, ..d }), 384); + assert_eq!(ring_slots(511, &RingPolicy { stream_all_min: 512, ..d }), STAGE); +} + +#[test] +fn chunk_loop_covers_the_prompt_in_order() { + assert_eq!(chunks(10, 4, 100), vec![(0, 4, 100), (4, 4, 104), (8, 2, 108)]); + assert_eq!(chunks(8, 4, 0), vec![(0, 4, 0), (4, 4, 4)]); + assert!(chunks(0, 4, 0).is_empty()); + let all = chunks(8193, 8192, 5); + assert_eq!(all.iter().map(|c| c.1).sum::(), 8193); + assert_eq!(all[1], (8192, 1, 8197)); +} + +#[test] +fn handoff_double_buffer_alternates_and_joins_one_run_behind() { + let mut h = Handoff::default(); + let steps: Vec<_> = (0..4).map(|_| h.end_of_chunk()).collect(); + assert_eq!(steps.iter().map(|s| s.buffer).collect::>(), vec![0, 1, 0, 1]); + assert_eq!(steps.iter().map(|s| s.join_previous).collect::>(), vec![false, true, true, true]); + assert!(h.finish()); + assert!(!h.finish()); +} + +#[test] +fn stream_sequence_orders_layers_then_experts_and_skips_resident() { + let resident = |l: usize, e: usize| (l + e) % 3 == 0; + let pinned = |_l: usize, e: usize| e % 2 == 0; + let transient = |_l: usize, e: usize| e == 5; + let view = SourceView { n_layers: 5, n_expert: 8, cache_present: true, resident: &resident, pinned: &pinned, transient: &transient }; + let seq = StreamSequence::build(&view, 1, 3); + assert_eq!(seq.seq_start.len(), 6); + assert_eq!(seq.seq_start[0], 0); + assert_eq!(seq.seq_start[1], 0); + assert_eq!(seq.seq_start[3], seq.entries.len()); + assert_eq!(seq.seq_start[5], seq.entries.len()); + assert!(seq.entries.windows(2).all(|w| (w[0].layer, w[0].expert) < (w[1].layer, w[1].expert))); + assert!(seq.entries.iter().all(|e| !resident(e.layer, e.expert))); + // jobs only for unpinned entries; transient flagged + assert!(seq.entries.iter().all(|e| e.job.is_some() == (e.expert % 2 == 1))); + assert!(seq.jobs.contains(&JobKind::Transient(1, 5)) || seq.jobs.contains(&JobKind::Transient(2, 5))); + // without a residency table nothing is skipped + let view = SourceView { cache_present: false, ..view }; + assert_eq!(StreamSequence::build(&view, 0, 5).entries.len(), 40); +} + +#[test] +fn the_checker_rejects_unsafe_schedules() { + // build a safe trace, then break it three ways + let none = |_: usize, _: usize| false; + let pinned = |_: usize, _: usize| true; + let view = SourceView { n_layers: 2, n_expert: 40, cache_present: false, resident: &none, pinned: &pinned, transient: &none }; + let cfg = StreamConfig { ring: 16, stager_ring: 16, rows: 2048, stream_all_min: 1024 }; + let orders = vec![(0..40).collect::>(), (0..40).collect::>()]; + let mut planner = Planner::new(); + planner.plan_chunk(0, &cfg, &view, 0, 2, &orders).unwrap(); + let good = planner.ops.clone(); + assert!(check_trace(&good).is_ok()); + // 1. drop the copy stream's wait on the previous occupant + let first_wait = good.iter().position(|o| matches!(o, SchedOp::CopyWaitUsed(_))).unwrap(); + let mut bad = good.clone(); + bad.remove(first_wait); + assert!(check_trace(&bad).unwrap_err().contains("did not wait")); + // 2. drop the compute stream's wait on the copy + let w = good.iter().position(|o| matches!(o, SchedOp::ComputeWaitCopied(_))).unwrap(); + let mut bad = good.clone(); + bad.remove(w); + assert!(check_trace(&bad).unwrap_err().contains("did not wait")); + // 3. issue one entry too early (before the slot's occupant is released): move the first overwrite's H2D up + let h = good.iter().enumerate().filter(|(_, o)| matches!(o, SchedOp::H2d { .. })).nth(16).unwrap().0; + let mut bad = good.clone(); + let moved: Vec<_> = bad.drain(h - 1..h + 2).collect(); // wait, h2d, record copied + let at = bad.iter().position(|o| matches!(o, SchedOp::Layer(0))).unwrap() + 1; + for (k, op) in moved.into_iter().enumerate() { + bad.insert(at + k, op); + } + assert!(check_trace(&bad).is_err()); + // 4. a final unreleased copy + let mut bad = good; + let last_release = bad.iter().rposition(|o| matches!(o, SchedOp::RecordUsed(_))).unwrap(); + bad.remove(last_release); + assert!(check_trace(&bad).unwrap_err().contains("unreleased")); +} + +#[test] +fn staged_path_never_uses_more_than_eight_slots_and_keeps_the_lookahead() { + let none = |_: usize, _: usize| false; + let pinned = |_: usize, e: usize| e % 2 == 0; + let view = SourceView { n_layers: 3, n_expert: 64, cache_present: false, resident: &none, pinned: &pinned, transient: &none }; + // ring 384 but only 100 rows: below stream_all_min, so the staged walk runs + let cfg = StreamConfig { ring: 384, stager_ring: 16, rows: 100, stream_all_min: 1024 }; + let order: Vec = (0..64).collect(); + let mut planner = Planner::new(); + planner.plan_chunk(0, &cfg, &view, 0, 3, &vec![order.clone(); 3]).unwrap(); + assert!(planner.ops.iter().all(|o| match o { + SchedOp::H2d { slot, .. } | SchedOp::RecordCopied(slot) | SchedOp::ComputeWaitCopied(slot) => *slot < STAGE, + _ => true, + })); + check_trace(&planner.ops).unwrap(); + // the first compute of a layer happens only after STAGE experts were staged ahead (lookahead 7 + the expert) + let layer0 = planner.ops.iter().position(|o| matches!(o, SchedOp::Layer(0))).unwrap(); + let first_compute = planner.ops[layer0..].iter().position(|o| matches!(o, SchedOp::Compute { .. })).unwrap(); + let copies_before = planner.ops[layer0..layer0 + first_compute].iter().filter(|o| matches!(o, SchedOp::RecordCopied(_))).count(); + assert_eq!(copies_before, STAGE); +} + +#[test] +fn rejects_unsorted_or_out_of_range_routing() { + let none = |_: usize, _: usize| false; + let view = SourceView { n_layers: 1, n_expert: 4, cache_present: false, resident: &none, pinned: &none, transient: &none }; + let cfg = StreamConfig { ring: 8, stager_ring: 16, rows: 10, stream_all_min: 1024 }; + assert_eq!(Planner::new().plan_chunk(0, &cfg, &view, 0, 1, &[vec![2, 1]]), Err(PlanError::OrderNotAscending)); + assert_eq!(Planner::new().plan_chunk(0, &cfg, &view, 0, 1, &[vec![0, 4]]), Err(PlanError::RoutedIdOutOfRange)); + let big = StreamConfig { ring: 513, ..cfg }; + assert_eq!(Planner::new().plan_chunk(0, &big, &view, 0, 1, &[vec![]]), Err(PlanError::RingTooLarge)); +} diff --git a/crates/cuda-driver/src/original_verify_gpu_plan.rs b/crates/cuda-driver/src/original_verify_gpu_plan.rs index 8cd275bd..3b79ad1b 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan.rs @@ -369,61 +369,5 @@ fn dma_options_for(wsl: bool, windows: bool, env: impl Fn(&str) -> String) -> (b mod pcie_copy_smoke; #[cfg(test)] -mod tests { - use super::*; - - fn words(bytes: &[u8]) -> Vec { - bytes.chunks_exact(4).map(|c| i32::from_le_bytes(c.try_into().unwrap())).collect() - } - - #[test] - fn the_batch_copy_is_off_on_windows_and_wsl_and_the_switches_still_force_it() { - let env = |pairs: &'static [(&'static str, &'static str)]| move |name: &str| pairs.iter().find(|p| p.0 == name).map_or(String::new(), |p| p.1.to_string()); - // (many, batch, flag B by stream write) - assert_eq!(dma_options_for(false, false, env(&[])), (true, true, true), "Linux keeps everything on"); - assert_eq!(dma_options_for(false, true, env(&[])), (true, false, true), "native Windows: no batch, stream write kept"); - assert_eq!(dma_options_for(true, false, env(&[])), (true, false, false), "WSL2: neither"); - assert_eq!(dma_options_for(false, true, env(&[("LELEKA_PCIE_DMA_BATCH", "on")])).1, true); - assert_eq!(dma_options_for(true, false, env(&[("LELEKA_PCIE_FLAGB", "write")])).2, true); - assert_eq!(dma_options_for(false, false, env(&[("LELEKA_PCIE_DMA_BATCH", "off"), ("LELEKA_PCIE_DMA_MANY", "off"), ("LELEKA_PCIE_FLAGB", "host")])), (false, false, false)); - } - - #[test] - fn the_block_is_the_literal_gpu_plan_sink_carve() { - // a 3-row group of a max_t = 4 window: cap = 40, 30 entries - let layout = PlanLayout::new(40); - let vram: Vec<(u64, &[u16])> = vec![(0x1000, &[0, 13]), (0x2000, &[5])]; - let pcie: Vec<(u64, &[u16])> = vec![(0x9000, &[2, 21, 27]), (0x9800, &[29])]; - let w = words(&encode_plan_block(&layout, 40, 10, 30, &vram, &pcie).unwrap()); - assert_eq!(w.len(), layout.words); - assert_eq!(&w[..4], &[2, 7, 2, 0], "vram groups, gpu entries, pcie groups"); - assert_eq!(&w[layout.start..layout.start + 3], &[0, 2, 3]); - assert_eq!(&w[layout.dst..layout.dst + 7], &[0, 13, 5, 2, 21, 27, 29]); - assert_eq!(&w[layout.tok..layout.tok + 7], &[0, 1, 0, 0, 2, 2, 2]); - let u64_at = |at: usize| (w[at] as u32 as u64) | ((w[at + 1] as u32 as u64) << 32); - assert_eq!((u64_at(layout.ptr), u64_at(layout.ptr + 2)), (0x1000, 0x2000)); - assert_eq!((u64_at(layout.ptr2), u64_at(layout.ptr2 + 2)), (0x9000, 0x9800)); - assert_eq!(&w[layout.start2..layout.start2 + 3], &[3, 6, 7]); - } - - #[test] - fn an_empty_plan_is_the_run_loops_empty_plan() { - let layout = PlanLayout::new(80); - let w = words(&encode_plan_block(&layout, 80, 10, 80, &[], &[]).unwrap()); - assert!(w.iter().all(|&x| x == 0)); - } - - #[test] - fn a_corrupt_plan_is_refused_not_repaired() { - let layout = PlanLayout::new(40); - let one = |e: &'static [u16]| vec![(0x1000u64, e)]; - // entry outside the group's rows, repeated within and across groups, empty group, null pointer - assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[20]), &[]).is_err()); - assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[3, 3]), &[]).is_err()); - assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[3]), &one(&[3])).is_err()); - assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[]), &[]).is_err()); - assert!(encode_plan_block(&layout, 40, 10, 20, &[(0, &[1])], &[]).is_err()); - // more entries than the block holds - assert!(encode_plan_block(&layout, 40, 10, 50, &[], &[]).is_err()); - } -} +#[path = "original_verify_gpu_plan/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_verify_gpu_plan/tests.rs b/crates/cuda-driver/src/original_verify_gpu_plan/tests.rs new file mode 100644 index 00000000..1532c9c3 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_gpu_plan/tests.rs @@ -0,0 +1,58 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn words(bytes: &[u8]) -> Vec { + bytes.chunks_exact(4).map(|c| i32::from_le_bytes(c.try_into().unwrap())).collect() +} + +#[test] +fn the_batch_copy_is_off_on_windows_and_wsl_and_the_switches_still_force_it() { + let env = |pairs: &'static [(&'static str, &'static str)]| move |name: &str| pairs.iter().find(|p| p.0 == name).map_or(String::new(), |p| p.1.to_string()); + // (many, batch, flag B by stream write) + assert_eq!(dma_options_for(false, false, env(&[])), (true, true, true), "Linux keeps everything on"); + assert_eq!(dma_options_for(false, true, env(&[])), (true, false, true), "native Windows: no batch, stream write kept"); + assert_eq!(dma_options_for(true, false, env(&[])), (true, false, false), "WSL2: neither"); + assert_eq!(dma_options_for(false, true, env(&[("LELEKA_PCIE_DMA_BATCH", "on")])).1, true); + assert_eq!(dma_options_for(true, false, env(&[("LELEKA_PCIE_FLAGB", "write")])).2, true); + assert_eq!(dma_options_for(false, false, env(&[("LELEKA_PCIE_DMA_BATCH", "off"), ("LELEKA_PCIE_DMA_MANY", "off"), ("LELEKA_PCIE_FLAGB", "host")])), (false, false, false)); +} + +#[test] +fn the_block_is_the_literal_gpu_plan_sink_carve() { + // a 3-row group of a max_t = 4 window: cap = 40, 30 entries + let layout = PlanLayout::new(40); + let vram: Vec<(u64, &[u16])> = vec![(0x1000, &[0, 13]), (0x2000, &[5])]; + let pcie: Vec<(u64, &[u16])> = vec![(0x9000, &[2, 21, 27]), (0x9800, &[29])]; + let w = words(&encode_plan_block(&layout, 40, 10, 30, &vram, &pcie).unwrap()); + assert_eq!(w.len(), layout.words); + assert_eq!(&w[..4], &[2, 7, 2, 0], "vram groups, gpu entries, pcie groups"); + assert_eq!(&w[layout.start..layout.start + 3], &[0, 2, 3]); + assert_eq!(&w[layout.dst..layout.dst + 7], &[0, 13, 5, 2, 21, 27, 29]); + assert_eq!(&w[layout.tok..layout.tok + 7], &[0, 1, 0, 0, 2, 2, 2]); + let u64_at = |at: usize| (w[at] as u32 as u64) | ((w[at + 1] as u32 as u64) << 32); + assert_eq!((u64_at(layout.ptr), u64_at(layout.ptr + 2)), (0x1000, 0x2000)); + assert_eq!((u64_at(layout.ptr2), u64_at(layout.ptr2 + 2)), (0x9000, 0x9800)); + assert_eq!(&w[layout.start2..layout.start2 + 3], &[3, 6, 7]); +} + +#[test] +fn an_empty_plan_is_the_run_loops_empty_plan() { + let layout = PlanLayout::new(80); + let w = words(&encode_plan_block(&layout, 80, 10, 80, &[], &[]).unwrap()); + assert!(w.iter().all(|&x| x == 0)); +} + +#[test] +fn a_corrupt_plan_is_refused_not_repaired() { + let layout = PlanLayout::new(40); + let one = |e: &'static [u16]| vec![(0x1000u64, e)]; + // entry outside the group's rows, repeated within and across groups, empty group, null pointer + assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[20]), &[]).is_err()); + assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[3, 3]), &[]).is_err()); + assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[3]), &one(&[3])).is_err()); + assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[]), &[]).is_err()); + assert!(encode_plan_block(&layout, 40, 10, 20, &[(0, &[1])], &[]).is_err()); + // more entries than the block holds + assert!(encode_plan_block(&layout, 40, 10, 50, &[], &[]).is_err()); +} diff --git a/crates/cuda-driver/src/original_verify_window_gr.rs b/crates/cuda-driver/src/original_verify_window_gr.rs index 9a09793d..508c7d4e 100644 --- a/crates/cuda-driver/src/original_verify_window_gr.rs +++ b/crates/cuda-driver/src/original_verify_window_gr.rs @@ -931,509 +931,5 @@ impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> { } #[cfg(test)] -mod tests { - #[test] - fn the_tiled_down_projection_covers_every_row_and_token_with_four_two_token_tile_buffers() { - use super::*; - for tokens in 1..=8usize { - let (grid, shared) = tiled_down_geometry(tokens); - assert_eq!(grid[0], DOWN_BLOCKS, "41 blocks of 8 rows cover the 320 down rows and the 4 inject rows"); - assert_eq!(grid[0] as usize * 8, 328); - assert_eq!(grid[1] as usize * 2 >= tokens && (grid[1] as usize - 1) * 2 < tokens, true, "{tokens} tokens in {} groups of two", grid[1]); - assert_eq!(shared, 4 * tokens.min(2) as u32 * 5120); - assert!(shared <= 40_960); - } - } - - use super::*; - use super::super::kernels::{LayoutMap, test_geometry}; - - const BASE: u64 = 0x7000_0000_0000; - - fn arena() -> LayoutMap { - LayoutMap::new(BASE, test_geometry()) - } - fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { - BASE + (m.layout.span(name).unwrap().offset + offset) as u64 - } - fn weights() -> HcAddrs { - HcAddrs { norm: 0x1000_0000, down: 0x2000_0000, up: 0x3000_0000, inject: 0x4000_0000 } - } - fn words(l: &Launch) -> &[u64] { - match &l.args[..] { - [A::Words(w)] => w, - other => panic!("expected one by-value struct, got {other:?}"), - } - } - fn rows(begin: usize, end: usize, group: usize) -> Rows { - Rows { begin, end, group } - } - /// RTX-class sm_120: 99 KiB opt-in, 48 KiB default per block. - fn sm120(variant: GrVariant) -> GrConfig { - GrConfig::from_device(variant, true, 12, 0, 101_376, 49_152) - } - fn entry_declared(ptx: &str, e: &str) -> bool { - ptx.contains(&format!(".entry {e}(")) || ptx.contains(&format!(".visible .entry {e}(")) - } - - // ---------------------------------------------------------------------------------- assets - #[test] - fn assets_are_pinned_and_export_every_named_entry() { - for spec in assets() { - spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); - let text = String::from_utf8_lossy(spec.ptx); - for e in spec.entries { - assert!(entry_declared(&text, e), "{} lacks {e}", spec.name); - } - } - // the six fused-gr wrappers take ONE 912-byte by-value struct (the Original GrMulti) - let text = String::from_utf8_lossy(GR_FUSED.ptx); - for e in GR_FUSED.entries { - assert!(text.contains(&format!("{e}_param_0[912]")), "{e} is not a GrMulti-by-value entry"); - } - } - - #[test] - fn struct_layout_constants_match_fused_gr_args() { - // FusedGrArgs: R,R_out,bool(+pad),bo,inj,wn,wd,wu,wi,float(+pad),lo,rs,inject,mixed = 112 bytes - assert_eq!(ARGS_WORDS * 8, 112); - // GrMulti: 8 * 112 + xn pointer + int T (+pad) = 912 bytes - assert_eq!(MULTI_WORDS * 8, 912); - assert_eq!((XN_WORD, T_WORD), (112, 113)); - assert_eq!(1e-6f32.to_bits(), 0x358637BD); - } - - // ----------------------------------------------------------------- down_chunk replication - #[test] - fn down_chunk_on_big_cards_runs_the_2560_tile_with_all_eight_tokens() { - let c = sm120(GrVariant::Staged); - assert_eq!(c.tile, 2560); - // 8 * 2560 * 4 = 81920 <= 101376 -> attribute is the full want - assert_eq!(c.attr_down, Some(81_920)); - // staged: 2 * 8 * 1280 * 4 = 81920 - assert_eq!(c.attr_staged, Some(81_920)); - // capacity 101376 / 10240 = 9 -> clamped to 8, both kinds - assert_eq!((c.chunk_plain, c.chunk_staged), (8, 8)); - assert_eq!(c.usable_shared, 101_376); - } - - #[test] - fn down_chunk_on_turing_slices_staged_tokens_and_uses_the_1280_tile() { - // sm_75: 64 KiB opt-in - let c = GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152); - assert_eq!(c.tile, 1280); - assert_eq!(c.attr_down, Some(8 * 1280 * 4)); // 40960 fits - assert_eq!(c.attr_staged, Some(65_536)); // 81920 > opt-in -> opt-in - assert_eq!(c.chunk_plain, 8); // 65536 / 5120 = 12 -> 8 - assert_eq!(c.chunk_staged, 6); // 65536 / 10240 = 6 ("sm_75 carries 6 tokens") - } - - #[test] - fn down_chunk_below_volta_uses_the_per_block_limit_and_never_less_than_one_token() { - // sm_61 reports no usable opt-in: per-block limit 48 KiB - let c = GrConfig::from_device(GrVariant::Plain, true, 6, 1, 0, 49_152); - assert_eq!(c.tile, 2560); - assert_eq!((c.chunk_plain, c.chunk_staged), (4, 4)); // 49152 / 10240 - assert_eq!((c.attr_down, c.attr_staged), (None, None)); - // sm_60 answers a 64 KiB opt-in it does not keep: the limit is still per block - let c60 = GrConfig::from_device(GrVariant::Plain, true, 6, 0, 65_536, 49_152); - assert_eq!(c60.usable_shared, 49_152); - assert_eq!(c60.chunk_plain, 4); - assert_eq!((c60.attr_down, c60.attr_staged), (None, None)); - // a card that cannot hold one token still reports a chunk of 1 (the launch is then refused) - let tiny = GrConfig::from_device(GrVariant::Plain, true, 6, 1, 0, 4096); - assert_eq!((tiny.chunk_plain, tiny.chunk_staged), (1, 1)); - let m = arena(); - assert_eq!( - plan_hc_read(&m, &test_geometry(), &weights(), &tiny, HcHalf::Attention, false, rows(0, 2, 0)).unwrap_err(), - Error::InvalidProjectionShape - ); - } - - #[test] - fn shared_attributes_name_the_tile_kernel_of_the_card_and_the_staged_kernel() { - let big = shared_attributes(&sm120(GrVariant::Staged)); - assert_eq!(big.len(), 2); - assert_eq!((big[0].1, big[0].2), (E_DOWN2560, 81_920)); - assert_eq!((big[1].1, big[1].2), (E_STAGED, 81_920)); - assert!(big.iter().all(|a| std::ptr::eq(a.0, &GR_FUSED))); - let turing = shared_attributes(&GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152)); - assert_eq!((turing[0].1, turing[0].2), (E_DOWN1280, 40_960)); - assert_eq!((turing[1].1, turing[1].2), (E_STAGED, 65_536)); - } - - #[test] - fn variant_follows_strata_hc_split() { - assert_eq!(GrVariant::from_env_value(None), GrVariant::Staged); - assert_eq!(GrVariant::from_env_value(Some("")), GrVariant::Staged); - assert_eq!(GrVariant::from_env_value(Some("0")), GrVariant::Plain); - assert_eq!(GrVariant::from_env_value(Some("1")), GrVariant::Split); - assert_eq!(GrVariant::from_env_value(Some("2")), GrVariant::Staged); - } - - // ------------------------------------------------------------------------------- hc_read - #[test] - fn staged_read_of_eight_rows_is_three_launch_kinds_with_the_multi_struct() { - let m = arena(); - let g = test_geometry(); - let w = weights(); - let plan = plan_hc_read(&m, &g, &w, &sm120(GrVariant::Staged), HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); - // norm: split, one block per token and stream - assert_eq!((plan.norm.entry, plan.norm.grid, plan.norm.block, plan.norm.shared), (E_SPLIT, [8, 4, 1], [256, 1, 1], 0)); - // down: ONE launch, 41 blocks, dynamic shared = 8 tokens * 2 * 1280 * 4 - assert_eq!(plan.down.len(), 1); - let d = &plan.down[0]; - assert_eq!((d.entry, d.grid, d.block, d.shared), (E_STAGED, [41, 1, 1], [256, 1, 1], 81_920)); - // up: 160 blocks of 16 columns - assert_eq!((plan.up.entry, plan.up.grid, plan.up.block, plan.up.shared), (E_UP, [160, 1, 1], [256, 1, 1], 0)); - let full = words(&plan.norm).to_vec(); - assert_eq!(words(&plan.up), &full[..]); - assert_eq!(words(d), &full[..]); - assert_eq!(full.len(), 114); - // trailer: xn = xn_ + tb*HC*N*4, T = 8 - assert_eq!(full[112], at(&m, "xn", 0)); - assert_eq!(full[113], 8); - // token 3, attention half, apply - let a = &full[3 * 14..4 * 14]; - assert_eq!(a[0], at(&m, "R", 3 * 40_960)); - assert_eq!(a[1], a[0]); - assert_eq!(a[2], 1); - assert_eq!(a[3], at(&m, "bo", 3 * 10_240)); - assert_eq!(a[4], at(&m, "inj2", 3 * 16)); - assert_eq!(&a[5..9], &[w.norm, w.down, w.up, w.inject]); - assert_eq!(a[9], 0x358637BD); - assert_eq!(a[10], at(&m, "lo", 3 * 1280)); - assert_eq!(a[11], at(&m, "rs", 3 * 16)); - assert_eq!(a[12], at(&m, "inj", 3 * 16)); - assert_eq!(a[13], at(&m, "mixed", 3 * 10_240)); - // every distinct row has its own addresses - assert_ne!(full[0], full[14]); - } - - #[test] - fn ffn_half_swaps_the_injection_buffers_and_apply_is_carried() { - let m = arena(); - let g = test_geometry(); - let plan = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Staged), HcHalf::Ffn, false, rows(0, 1, 0)).unwrap(); - let a = &words(&plan.norm)[..14]; - assert_eq!(a[2], 0); - assert_eq!(a[4], at(&m, "inj", 0)); - assert_eq!(a[12], at(&m, "inj2", 0)); - // a single row: norm grid [1, 4] - assert_eq!(plan.norm.grid, [1, 4, 1]); - assert_eq!(words(&plan.norm)[113], 1); - assert_eq!(plan.down[0].shared, 10_240); - } - - #[test] - fn split_windows_read_their_own_rows_and_offset_the_scratch() { - let m = arena(); - let g = test_geometry(); - // T = 7 -> groups [0,4) and [4,7): (T+1)/2 = 4 - let g1 = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Staged), HcHalf::Ffn, true, rows(4, 7, 1)).unwrap(); - let w1 = words(&g1.norm); - assert_eq!(w1[112], at(&m, "xn", 4 * 40_960)); - assert_eq!(w1[113], 3); - assert_eq!(w1[0], at(&m, "R", 4 * 40_960)); - assert_eq!(w1[14 + 10], at(&m, "lo", 5 * 1280)); - assert_eq!(g1.norm.grid, [3, 4, 1]); - assert_eq!(g1.down[0].shared, 3 * 10_240); - // unused slots stay zero - assert!(w1[3 * 14..112].iter().all(|&x| x == 0)); - } - - #[test] - fn plain_and_split_variants_pick_the_norm_and_the_tile_kernel() { - let m = arena(); - let g = test_geometry(); - let plain = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Plain), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); - assert_eq!((plain.norm.entry, plain.norm.grid), (E_NORM, [5, 1, 1])); - assert_eq!((plain.down[0].entry, plain.down[0].shared), (E_DOWN2560, 5 * 2560 * 4)); - let split = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Split), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); - assert_eq!((split.norm.entry, split.norm.grid), (E_SPLIT, [5, 4, 1])); - assert_eq!(split.down[0].entry, E_DOWN2560); - let turing = GrConfig::from_device(GrVariant::Plain, true, 7, 5, 65_536, 49_152); - let t = plan_hc_read(&m, &g, &weights(), &turing, HcHalf::Attention, false, rows(0, 8, 0)).unwrap(); - assert_eq!((t.down[0].entry, t.down[0].shared), (E_DOWN1280, 8 * 1280 * 4)); - } - - #[test] - fn down_projection_is_chunked_by_the_card_capacity() { - let m = arena(); - let g = test_geometry(); - let turing = GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152); - let plan = plan_hc_read(&m, &g, &weights(), &turing, HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); - // 8 tokens, 6 per launch -> 6 + 2 - assert_eq!(plan.down.len(), 2); - assert_eq!((plan.down[0].shared, plan.down[1].shared), (61_440, 20_480)); - let full = words(&plan.norm).to_vec(); - let first = words(&plan.down[0]); - let second = words(&plan.down[1]); - // the first chunk is a FRESH struct: tokens 0..6, T = 6, same xn - assert_eq!(first[113], 6); - assert_eq!(first[112], full[112]); - assert_eq!(&first[..6 * 14], &full[..6 * 14]); - assert!(first[6 * 14..112].iter().all(|&x| x == 0)); - // the second: tokens 6..8 moved to slots 0..2, xn advanced by 6 * D floats, T = 2 - assert_eq!(second[113], 2); - assert_eq!(second[112], full[112] + 6 * 40_960); - assert_eq!(&second[..2 * 14], &full[6 * 14..8 * 14]); - assert!(second[2 * 14..112].iter().all(|&x| x == 0)); - // norm and up still see all eight tokens - assert_eq!(words(&plan.up), &full[..]); - assert_eq!(plan.norm.grid, [8, 4, 1]); - assert_eq!(plan.clone().launches().len(), 4); - // launches() keeps the Original order: norm, down..., up - let order: Vec<&str> = plan.launches().iter().map(|l| l.entry).collect(); - assert_eq!(order, [E_SPLIT, E_STAGED, E_STAGED, E_UP]); - } - - #[test] - fn hc_read_validates_rows_and_geometry() { - let m = arena(); - let g = test_geometry(); - let c = sm120(GrVariant::Staged); - let w = weights(); - assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(3, 3, 0)).is_err()); - assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(0, 9, 0)).is_err()); - assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(7, 9, 1)).is_err()); - let mut odd = g; - odd.hc = 8; - assert_eq!( - plan_hc_read(&m, &odd, &w, &c, HcHalf::Attention, false, rows(0, 1, 0)).unwrap_err(), - Error::InvalidQwenShape - ); - // every T = 1..=8 and both groups of the split window plan - for t in 1..=8usize { - let first = (t + 1) / 2; - let groups = if t >= 2 { vec![(0, first), (first, t)] } else { vec![(0, t)] }; - for (gi, (b, e)) in groups.into_iter().enumerate() { - let plan = plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, true, rows(b, e, gi)).unwrap(); - assert_eq!(words(&plan.up)[113], (e - b) as u64); - assert_eq!(plan.norm.grid[0], (e - b) as u32); - } - } - } - - // ----------------------------------------------------------------------------- final write - #[test] - fn final_write_is_native_post_in_place_per_row() { - let m = arena(); - let g = test_geometry(); - let l = plan_final_write(&m, &g, &sm120(GrVariant::Staged), rows(2, 5, 0)).unwrap(); - assert_eq!(l.len(), 3); - for (i, launch) in l.iter().enumerate() { - let t = 2 + i; - assert!(std::ptr::eq(launch.asset, &GR_POST)); - assert_eq!((launch.entry, launch.grid, launch.block, launch.shared), ("mtp_full_native_write", [40, 1, 1], [256, 1, 1], 0)); - assert_eq!( - launch.args, - vec![ - A::P(at(&m, "R", t * 40_960)), - A::P(at(&m, "bo", t * 10_240)), - A::P(at(&m, "inj2", t * 16)), - A::P(at(&m, "R", t * 40_960)), - A::I32(2560), - A::I32(4), - A::F32(0.25), - ] - ); - } - let mut non_native = sm120(GrVariant::Staged); - non_native.native_mmvf = false; - assert!(matches!( - plan_final_write(&m, &g, &non_native, rows(0, 1, 0)), - Err(Error::InvalidDriverValue(s)) if s.contains("final_write") - )); - } - - // ------------------------------------------------------------------------------------ head - #[test] - fn head_mix_is_the_native_unfused_gr_read_per_token() { - let m = arena(); - let g = test_geometry(); - let w = HeadAddrs { norm: 0xA000, down: 0xB000, up: 0xC000 }; - let mixed_base = 0x9999_0000u64; - let l = plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 3).unwrap(); - assert_eq!(l.len(), 15); - for t in 0..3usize { - let k = &l[t * 5..t * 5 + 5]; - let r = at(&m, "R", t * 40_960); - let xn = at(&m, "xn", t * 40_960); - let lo = at(&m, "lo", t * 1280); - let gated = at(&m, "parts", t * 10 * 2560 * 4); - let mixed = mixed_base + (t * 10_240) as u64; - // 1. native_gr_rms_norm_weighted: hc blocks of 1024 threads - assert_eq!((k[0].entry, k[0].grid, k[0].block), ("mtp_full_gr_norm", [4, 1, 1], [1024, 1, 1])); - assert_eq!(k[0].args, vec![A::P(r), A::P(0xA000), A::P(xn), A::I32(2560), A::F32(1e-6)]); - // 2. bf16_gemv_fp32_mmvf(xn, down -> lo, 10240 -> 320): mmvf block 256 - assert_eq!((k[1].entry, k[1].grid, k[1].block), ("mtp_full_mmvf256", [320, 1, 1], [256, 1, 1])); - assert_eq!(k[1].args, vec![A::P(xn), A::P(0xB000), A::P(lo), A::I32(10_240)]); - // 3. native_gr_down_silu(lo, 320, 1/4): ceil(320/256) = 2 blocks - assert_eq!((k[2].entry, k[2].grid, k[2].block), ("mtp_full_down_silu", [2, 1, 1], [256, 1, 1])); - assert_eq!(k[2].args, vec![A::P(lo), A::I32(320), A::F32(0.25)]); - // 4. bf16_gemv_fp32_mmvf(lo, up -> gated, 320 -> 10240): mmvf block 160 (ceil(320/320) = 1 iteration) - assert_eq!((k[3].entry, k[3].grid, k[3].block), ("mtp_full_mmvf160", [10_240, 1, 1], [160, 1, 1])); - assert_eq!(k[3].args, vec![A::P(lo), A::P(0xC000), A::P(gated), A::I32(320)]); - // 5. native_gr_pre_gated(xn, gated, mixed, n, hc, 1/4): 10 blocks - assert_eq!((k[4].entry, k[4].grid, k[4].block), ("mtp_full_pre_final", [10, 1, 1], [256, 1, 1])); - assert_eq!(k[4].args, vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(2560), A::I32(4), A::F32(0.25)]); - } - // the whole window: 1..=8 rows; none beyond max_t - assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 8).is_ok()); - assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 9).is_err()); - assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 0).is_err()); - let mut non_native = sm120(GrVariant::Staged); - non_native.native_mmvf = false; - assert!(matches!( - plan_head_mix(&m, &g, &w, &non_native, mixed_base, 1), - Err(Error::InvalidDriverValue(s)) if s.contains("head") - )); - } - - // ------------------------------------------------------------------------------------ PLE - fn ple_addrs(key: PleKey) -> PleAddrs { - PleAddrs { - key, - value: 0x5000_0000, - norm_key: 0x5100_0000, - norm_query: 0x5200_0000, - norm_conv: 0x5300_0000, - conv1d: 0x5400_0000, - scratch: 0x6000_0000, - history: 0x6100_0000, - } - } - - #[test] - fn ple_scratch_matches_ple_block_workspace_carving() { - // 5 * hc_dim + n_embd + hc floats: key, query, norm, gated, conv, value, gate - assert_eq!(PLE_SCRATCH_BYTES, 215_056); - assert_eq!(SCRATCH_QUERY, 40_960); - assert_eq!(SCRATCH_NORM, 81_920); - assert_eq!(SCRATCH_GATED, 122_880); - assert_eq!(SCRATCH_CONV, 163_840); - assert_eq!(SCRATCH_VALUE, 204_800); - assert_eq!(SCRATCH_GATE, 215_040); - assert_eq!(SCRATCH_GATE + 16, PLE_SCRATCH_BYTES as u64); - } - - #[test] - fn ple_row_with_a_bf16_key_follows_ple_block_native_order() { - let m = arena(); - let g = test_geometry(); - let a = ple_addrs(PleKey::Bf16(0x7000_0000)); - let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 2).unwrap(); - let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); - assert_eq!( - names, - [ - "mtp_full_native_write", // the pending layer-0 gr_write - "mtp_full_mmvf256", // key = ple_key @ emb (10240 x 2560) - "mtp_full_mmvf256", // value = ple_value @ emb (2560 x 2560) - "ple_rms", // key norm -> d_query - "ple_rms", // hidden norm -> d_norm - "ple_gate", - "ple_broadcast", - "ple_rms", // gated norm -> d_norm - "ple_conv", - "ple_history", - ] - ); - let r = at(&m, "R", 2 * 40_960); - let emb = at(&m, "ple", 2 * 10_240); - let s = 0x6000_0000u64; - assert_eq!(l[0].args[0], A::P(r)); - assert_eq!(l[0].args[3], A::P(r)); - // key: x = emb, y = scratch key (ldy = 10240), 2560 -> 10240 - assert_eq!(l[1].grid, [10_240, 1, 1]); - assert_eq!(l[1].args, vec![A::P(emb), A::P(0x7000_0000), A::P(s), A::I32(2560)]); - // value: y = scratch value, 2560 -> 2560 - assert_eq!(l[2].grid, [2560, 1, 1]); - assert_eq!(l[2].args, vec![A::P(emb), A::P(0x5000_0000), A::P(s + 204_800), A::I32(2560)]); - // postops: rms(key -> query), rms(hidden -> norm), gate(query, norm -> gate), ... - assert_eq!(l[3].args, vec![A::P(s), A::P(0x5100_0000), A::P(s + 40_960)]); - assert_eq!(l[4].args, vec![A::P(r), A::P(0x5200_0000), A::P(s + 81_920)]); - assert_eq!((l[3].grid, l[3].block), ([4, 1, 1], [1024, 1, 1])); - assert_eq!((l[5].grid, l[5].block), ([4, 1, 1], [512, 1, 1])); - assert_eq!(l[5].args, vec![A::P(s + 40_960), A::P(s + 81_920), A::P(s + 215_040), A::F32(1.0 / 2560f32.sqrt())]); - assert_eq!((l[6].grid, l[6].block), ([40, 1, 1], [256, 1, 1])); - assert_eq!(l[6].args, vec![A::P(s + 204_800), A::P(s + 215_040), A::P(s + 122_880), A::I32(1)]); - assert_eq!(l[7].args, vec![A::P(s + 122_880), A::P(0x5300_0000), A::P(s + 81_920)]); - // conv + residual: hidden = Rt in place - assert_eq!( - l[8].args, - vec![A::P(0x6100_0000), A::P(s + 81_920), A::P(0x5400_0000), A::P(r), A::P(s + 122_880), A::P(s + 163_840), A::I32(1)] - ); - assert_eq!((l[8].grid, l[8].block), ([40, 1, 1], [256, 1, 1])); - // history advance reads the normalized row from the workspace - assert_eq!(l[9].args, vec![A::P(0x6100_0000), A::P(s + 81_920), A::I32(1)]); - assert_eq!((l[9].grid, l[9].block), ([40, 1, 1], [256, 1, 1])); - for launch in &l[3..] { - assert!(std::ptr::eq(launch.asset, &PLE_BATCH)); - } - } - - #[test] - fn ple_row_with_a_native_key_quantizes_into_the_arena_and_runs_mmvq() { - let m = arena(); - let g = test_geometry(); - let a = ple_addrs(PleKey::Native { ty: 42, data: 0x7100_0000 }); - let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 0).unwrap(); - let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); - assert_eq!(&names[..4], &["mtp_full_native_write", "head_quant", "head_n42_s1", "mtp_full_mmvf256"]); - assert_eq!(l.len(), 11); - let q8 = at(&m, "xq", 0); - let emb = at(&m, "ple", 0); - assert_eq!(l[1].args, vec![A::P(emb), A::P(q8), A::I32(2560)]); - // 2560 / 64 = 40 blocks < 64 per iteration: the "small" layout, 4 rows per block - assert_eq!((l[2].grid, l[2].block), ([2560, 1, 1], [32, 4, 1])); - assert_eq!( - l[2].args, - vec![A::P(0x7100_0000), A::P(q8), A::P(0x6000_0000), A::I32(2560), A::I32(10_240)] - ); - // an unsupported native key type fails closed - let bad = ple_addrs(PleKey::Native { ty: 14, data: 1 }); - assert_eq!( - plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &bad, 0).unwrap_err(), - Error::UnsupportedQwenOperation - ); - } - - #[test] - fn ple_layer1_walks_the_group_rows_in_order_and_fails_closed_on_policy() { - let m = arena(); - let g = test_geometry(); - let a = ple_addrs(PleKey::Bf16(0x7000_0000)); - let c = sm120(GrVariant::Staged); - let out = plan_ple_layer1(&m, &g, &c, &PleConfig::mode17(), &a, rows(4, 7, 1)).unwrap(); - assert_eq!(out.iter().map(|(t, _)| *t).collect::>(), [4, 5, 6]); - assert!(out.iter().all(|(_, l)| l.len() == 10)); - let mut legacy = PleConfig::mode17(); - legacy.native_postops = false; - assert!(matches!( - plan_ple_layer1(&m, &g, &c, &legacy, &a, rows(0, 1, 0)), - Err(Error::InvalidDriverValue(s)) if s.contains("ple_layer1") - )); - legacy = PleConfig::mode17(); - legacy.native_value_bf16 = false; - assert!(plan_ple_row(&m, &g, &c, &legacy, &a, 0).is_err()); - assert!(plan_ple_row(&m, &g, &c, &PleConfig::mode17(), &a, 8).is_err()); - } - - // ---------------------------------------------------------------------------- byte sizes - #[test] - fn weight_byte_sizes_follow_the_hc_geometry() { - // hc=4, N=2560, hc_lr=320 - assert_eq!(HC_NORM_BYTES, 4 * 2560 * 4); - assert_eq!(HC_DOWN_BYTES, 320 * 4 * 2560 * 2); - assert_eq!(HC_UP_BYTES, 4 * 2560 * 320 * 2); - assert_eq!(HC_INJECT_BYTES, 4 * 4 * 2560 * 2); - assert_eq!(PLE_HISTORY_BYTES, 9 * 4 * 2560 * 4); - assert_eq!(PLE_VALUE_BYTES, 2560 * 2560 * 2); - assert_eq!(PLE_KEY_BF16_BYTES, 10_240 * 2560 * 2); - assert_eq!(PLE_CONV_BYTES, 4 * 10_240 * 2); - // a Q2_0 key: 64-element blocks of 18 bytes -> 40 blocks per row - assert_eq!(native_head_row_bytes(42, 2560).unwrap(), 40 * 18); - } -} +#[path = "original_verify_window_gr/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_verify_window_gr/tests.rs b/crates/cuda-driver/src/original_verify_window_gr/tests.rs new file mode 100644 index 00000000..0f37a43c --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_gr/tests.rs @@ -0,0 +1,506 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +#[test] +fn the_tiled_down_projection_covers_every_row_and_token_with_four_two_token_tile_buffers() { + use super::*; + for tokens in 1..=8usize { + let (grid, shared) = tiled_down_geometry(tokens); + assert_eq!(grid[0], DOWN_BLOCKS, "41 blocks of 8 rows cover the 320 down rows and the 4 inject rows"); + assert_eq!(grid[0] as usize * 8, 328); + assert_eq!(grid[1] as usize * 2 >= tokens && (grid[1] as usize - 1) * 2 < tokens, true, "{tokens} tokens in {} groups of two", grid[1]); + assert_eq!(shared, 4 * tokens.min(2) as u32 * 5120); + assert!(shared <= 40_960); + } +} + +use super::*; +use super::super::kernels::{LayoutMap, test_geometry}; + +const BASE: u64 = 0x7000_0000_0000; + +fn arena() -> LayoutMap { + LayoutMap::new(BASE, test_geometry()) +} +fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { + BASE + (m.layout.span(name).unwrap().offset + offset) as u64 +} +fn weights() -> HcAddrs { + HcAddrs { norm: 0x1000_0000, down: 0x2000_0000, up: 0x3000_0000, inject: 0x4000_0000 } +} +fn words(l: &Launch) -> &[u64] { + match &l.args[..] { + [A::Words(w)] => w, + other => panic!("expected one by-value struct, got {other:?}"), + } +} +fn rows(begin: usize, end: usize, group: usize) -> Rows { + Rows { begin, end, group } +} +/// RTX-class sm_120: 99 KiB opt-in, 48 KiB default per block. +fn sm120(variant: GrVariant) -> GrConfig { + GrConfig::from_device(variant, true, 12, 0, 101_376, 49_152) +} +fn entry_declared(ptx: &str, e: &str) -> bool { + ptx.contains(&format!(".entry {e}(")) || ptx.contains(&format!(".visible .entry {e}(")) +} + +// ---------------------------------------------------------------------------------- assets +#[test] +fn assets_are_pinned_and_export_every_named_entry() { + for spec in assets() { + spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); + let text = String::from_utf8_lossy(spec.ptx); + for e in spec.entries { + assert!(entry_declared(&text, e), "{} lacks {e}", spec.name); + } + } + // the six fused-gr wrappers take ONE 912-byte by-value struct (the Original GrMulti) + let text = String::from_utf8_lossy(GR_FUSED.ptx); + for e in GR_FUSED.entries { + assert!(text.contains(&format!("{e}_param_0[912]")), "{e} is not a GrMulti-by-value entry"); + } +} + +#[test] +fn struct_layout_constants_match_fused_gr_args() { + // FusedGrArgs: R,R_out,bool(+pad),bo,inj,wn,wd,wu,wi,float(+pad),lo,rs,inject,mixed = 112 bytes + assert_eq!(ARGS_WORDS * 8, 112); + // GrMulti: 8 * 112 + xn pointer + int T (+pad) = 912 bytes + assert_eq!(MULTI_WORDS * 8, 912); + assert_eq!((XN_WORD, T_WORD), (112, 113)); + assert_eq!(1e-6f32.to_bits(), 0x358637BD); +} + +// ----------------------------------------------------------------- down_chunk replication +#[test] +fn down_chunk_on_big_cards_runs_the_2560_tile_with_all_eight_tokens() { + let c = sm120(GrVariant::Staged); + assert_eq!(c.tile, 2560); + // 8 * 2560 * 4 = 81920 <= 101376 -> attribute is the full want + assert_eq!(c.attr_down, Some(81_920)); + // staged: 2 * 8 * 1280 * 4 = 81920 + assert_eq!(c.attr_staged, Some(81_920)); + // capacity 101376 / 10240 = 9 -> clamped to 8, both kinds + assert_eq!((c.chunk_plain, c.chunk_staged), (8, 8)); + assert_eq!(c.usable_shared, 101_376); +} + +#[test] +fn down_chunk_on_turing_slices_staged_tokens_and_uses_the_1280_tile() { + // sm_75: 64 KiB opt-in + let c = GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152); + assert_eq!(c.tile, 1280); + assert_eq!(c.attr_down, Some(8 * 1280 * 4)); // 40960 fits + assert_eq!(c.attr_staged, Some(65_536)); // 81920 > opt-in -> opt-in + assert_eq!(c.chunk_plain, 8); // 65536 / 5120 = 12 -> 8 + assert_eq!(c.chunk_staged, 6); // 65536 / 10240 = 6 ("sm_75 carries 6 tokens") +} + +#[test] +fn down_chunk_below_volta_uses_the_per_block_limit_and_never_less_than_one_token() { + // sm_61 reports no usable opt-in: per-block limit 48 KiB + let c = GrConfig::from_device(GrVariant::Plain, true, 6, 1, 0, 49_152); + assert_eq!(c.tile, 2560); + assert_eq!((c.chunk_plain, c.chunk_staged), (4, 4)); // 49152 / 10240 + assert_eq!((c.attr_down, c.attr_staged), (None, None)); + // sm_60 answers a 64 KiB opt-in it does not keep: the limit is still per block + let c60 = GrConfig::from_device(GrVariant::Plain, true, 6, 0, 65_536, 49_152); + assert_eq!(c60.usable_shared, 49_152); + assert_eq!(c60.chunk_plain, 4); + assert_eq!((c60.attr_down, c60.attr_staged), (None, None)); + // a card that cannot hold one token still reports a chunk of 1 (the launch is then refused) + let tiny = GrConfig::from_device(GrVariant::Plain, true, 6, 1, 0, 4096); + assert_eq!((tiny.chunk_plain, tiny.chunk_staged), (1, 1)); + let m = arena(); + assert_eq!( + plan_hc_read(&m, &test_geometry(), &weights(), &tiny, HcHalf::Attention, false, rows(0, 2, 0)).unwrap_err(), + Error::InvalidProjectionShape + ); +} + +#[test] +fn shared_attributes_name_the_tile_kernel_of_the_card_and_the_staged_kernel() { + let big = shared_attributes(&sm120(GrVariant::Staged)); + assert_eq!(big.len(), 2); + assert_eq!((big[0].1, big[0].2), (E_DOWN2560, 81_920)); + assert_eq!((big[1].1, big[1].2), (E_STAGED, 81_920)); + assert!(big.iter().all(|a| std::ptr::eq(a.0, &GR_FUSED))); + let turing = shared_attributes(&GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152)); + assert_eq!((turing[0].1, turing[0].2), (E_DOWN1280, 40_960)); + assert_eq!((turing[1].1, turing[1].2), (E_STAGED, 65_536)); +} + +#[test] +fn variant_follows_strata_hc_split() { + assert_eq!(GrVariant::from_env_value(None), GrVariant::Staged); + assert_eq!(GrVariant::from_env_value(Some("")), GrVariant::Staged); + assert_eq!(GrVariant::from_env_value(Some("0")), GrVariant::Plain); + assert_eq!(GrVariant::from_env_value(Some("1")), GrVariant::Split); + assert_eq!(GrVariant::from_env_value(Some("2")), GrVariant::Staged); +} + +// ------------------------------------------------------------------------------- hc_read +#[test] +fn staged_read_of_eight_rows_is_three_launch_kinds_with_the_multi_struct() { + let m = arena(); + let g = test_geometry(); + let w = weights(); + let plan = plan_hc_read(&m, &g, &w, &sm120(GrVariant::Staged), HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); + // norm: split, one block per token and stream + assert_eq!((plan.norm.entry, plan.norm.grid, plan.norm.block, plan.norm.shared), (E_SPLIT, [8, 4, 1], [256, 1, 1], 0)); + // down: ONE launch, 41 blocks, dynamic shared = 8 tokens * 2 * 1280 * 4 + assert_eq!(plan.down.len(), 1); + let d = &plan.down[0]; + assert_eq!((d.entry, d.grid, d.block, d.shared), (E_STAGED, [41, 1, 1], [256, 1, 1], 81_920)); + // up: 160 blocks of 16 columns + assert_eq!((plan.up.entry, plan.up.grid, plan.up.block, plan.up.shared), (E_UP, [160, 1, 1], [256, 1, 1], 0)); + let full = words(&plan.norm).to_vec(); + assert_eq!(words(&plan.up), &full[..]); + assert_eq!(words(d), &full[..]); + assert_eq!(full.len(), 114); + // trailer: xn = xn_ + tb*HC*N*4, T = 8 + assert_eq!(full[112], at(&m, "xn", 0)); + assert_eq!(full[113], 8); + // token 3, attention half, apply + let a = &full[3 * 14..4 * 14]; + assert_eq!(a[0], at(&m, "R", 3 * 40_960)); + assert_eq!(a[1], a[0]); + assert_eq!(a[2], 1); + assert_eq!(a[3], at(&m, "bo", 3 * 10_240)); + assert_eq!(a[4], at(&m, "inj2", 3 * 16)); + assert_eq!(&a[5..9], &[w.norm, w.down, w.up, w.inject]); + assert_eq!(a[9], 0x358637BD); + assert_eq!(a[10], at(&m, "lo", 3 * 1280)); + assert_eq!(a[11], at(&m, "rs", 3 * 16)); + assert_eq!(a[12], at(&m, "inj", 3 * 16)); + assert_eq!(a[13], at(&m, "mixed", 3 * 10_240)); + // every distinct row has its own addresses + assert_ne!(full[0], full[14]); +} + +#[test] +fn ffn_half_swaps_the_injection_buffers_and_apply_is_carried() { + let m = arena(); + let g = test_geometry(); + let plan = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Staged), HcHalf::Ffn, false, rows(0, 1, 0)).unwrap(); + let a = &words(&plan.norm)[..14]; + assert_eq!(a[2], 0); + assert_eq!(a[4], at(&m, "inj", 0)); + assert_eq!(a[12], at(&m, "inj2", 0)); + // a single row: norm grid [1, 4] + assert_eq!(plan.norm.grid, [1, 4, 1]); + assert_eq!(words(&plan.norm)[113], 1); + assert_eq!(plan.down[0].shared, 10_240); +} + +#[test] +fn split_windows_read_their_own_rows_and_offset_the_scratch() { + let m = arena(); + let g = test_geometry(); + // T = 7 -> groups [0,4) and [4,7): (T+1)/2 = 4 + let g1 = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Staged), HcHalf::Ffn, true, rows(4, 7, 1)).unwrap(); + let w1 = words(&g1.norm); + assert_eq!(w1[112], at(&m, "xn", 4 * 40_960)); + assert_eq!(w1[113], 3); + assert_eq!(w1[0], at(&m, "R", 4 * 40_960)); + assert_eq!(w1[14 + 10], at(&m, "lo", 5 * 1280)); + assert_eq!(g1.norm.grid, [3, 4, 1]); + assert_eq!(g1.down[0].shared, 3 * 10_240); + // unused slots stay zero + assert!(w1[3 * 14..112].iter().all(|&x| x == 0)); +} + +#[test] +fn plain_and_split_variants_pick_the_norm_and_the_tile_kernel() { + let m = arena(); + let g = test_geometry(); + let plain = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Plain), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); + assert_eq!((plain.norm.entry, plain.norm.grid), (E_NORM, [5, 1, 1])); + assert_eq!((plain.down[0].entry, plain.down[0].shared), (E_DOWN2560, 5 * 2560 * 4)); + let split = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Split), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); + assert_eq!((split.norm.entry, split.norm.grid), (E_SPLIT, [5, 4, 1])); + assert_eq!(split.down[0].entry, E_DOWN2560); + let turing = GrConfig::from_device(GrVariant::Plain, true, 7, 5, 65_536, 49_152); + let t = plan_hc_read(&m, &g, &weights(), &turing, HcHalf::Attention, false, rows(0, 8, 0)).unwrap(); + assert_eq!((t.down[0].entry, t.down[0].shared), (E_DOWN1280, 8 * 1280 * 4)); +} + +#[test] +fn down_projection_is_chunked_by_the_card_capacity() { + let m = arena(); + let g = test_geometry(); + let turing = GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152); + let plan = plan_hc_read(&m, &g, &weights(), &turing, HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); + // 8 tokens, 6 per launch -> 6 + 2 + assert_eq!(plan.down.len(), 2); + assert_eq!((plan.down[0].shared, plan.down[1].shared), (61_440, 20_480)); + let full = words(&plan.norm).to_vec(); + let first = words(&plan.down[0]); + let second = words(&plan.down[1]); + // the first chunk is a FRESH struct: tokens 0..6, T = 6, same xn + assert_eq!(first[113], 6); + assert_eq!(first[112], full[112]); + assert_eq!(&first[..6 * 14], &full[..6 * 14]); + assert!(first[6 * 14..112].iter().all(|&x| x == 0)); + // the second: tokens 6..8 moved to slots 0..2, xn advanced by 6 * D floats, T = 2 + assert_eq!(second[113], 2); + assert_eq!(second[112], full[112] + 6 * 40_960); + assert_eq!(&second[..2 * 14], &full[6 * 14..8 * 14]); + assert!(second[2 * 14..112].iter().all(|&x| x == 0)); + // norm and up still see all eight tokens + assert_eq!(words(&plan.up), &full[..]); + assert_eq!(plan.norm.grid, [8, 4, 1]); + assert_eq!(plan.clone().launches().len(), 4); + // launches() keeps the Original order: norm, down..., up + let order: Vec<&str> = plan.launches().iter().map(|l| l.entry).collect(); + assert_eq!(order, [E_SPLIT, E_STAGED, E_STAGED, E_UP]); +} + +#[test] +fn hc_read_validates_rows_and_geometry() { + let m = arena(); + let g = test_geometry(); + let c = sm120(GrVariant::Staged); + let w = weights(); + assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(3, 3, 0)).is_err()); + assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(0, 9, 0)).is_err()); + assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(7, 9, 1)).is_err()); + let mut odd = g; + odd.hc = 8; + assert_eq!( + plan_hc_read(&m, &odd, &w, &c, HcHalf::Attention, false, rows(0, 1, 0)).unwrap_err(), + Error::InvalidQwenShape + ); + // every T = 1..=8 and both groups of the split window plan + for t in 1..=8usize { + let first = (t + 1) / 2; + let groups = if t >= 2 { vec![(0, first), (first, t)] } else { vec![(0, t)] }; + for (gi, (b, e)) in groups.into_iter().enumerate() { + let plan = plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, true, rows(b, e, gi)).unwrap(); + assert_eq!(words(&plan.up)[113], (e - b) as u64); + assert_eq!(plan.norm.grid[0], (e - b) as u32); + } + } +} + +// ----------------------------------------------------------------------------- final write +#[test] +fn final_write_is_native_post_in_place_per_row() { + let m = arena(); + let g = test_geometry(); + let l = plan_final_write(&m, &g, &sm120(GrVariant::Staged), rows(2, 5, 0)).unwrap(); + assert_eq!(l.len(), 3); + for (i, launch) in l.iter().enumerate() { + let t = 2 + i; + assert!(std::ptr::eq(launch.asset, &GR_POST)); + assert_eq!((launch.entry, launch.grid, launch.block, launch.shared), ("mtp_full_native_write", [40, 1, 1], [256, 1, 1], 0)); + assert_eq!( + launch.args, + vec![ + A::P(at(&m, "R", t * 40_960)), + A::P(at(&m, "bo", t * 10_240)), + A::P(at(&m, "inj2", t * 16)), + A::P(at(&m, "R", t * 40_960)), + A::I32(2560), + A::I32(4), + A::F32(0.25), + ] + ); + } + let mut non_native = sm120(GrVariant::Staged); + non_native.native_mmvf = false; + assert!(matches!( + plan_final_write(&m, &g, &non_native, rows(0, 1, 0)), + Err(Error::InvalidDriverValue(s)) if s.contains("final_write") + )); +} + +// ------------------------------------------------------------------------------------ head +#[test] +fn head_mix_is_the_native_unfused_gr_read_per_token() { + let m = arena(); + let g = test_geometry(); + let w = HeadAddrs { norm: 0xA000, down: 0xB000, up: 0xC000 }; + let mixed_base = 0x9999_0000u64; + let l = plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 3).unwrap(); + assert_eq!(l.len(), 15); + for t in 0..3usize { + let k = &l[t * 5..t * 5 + 5]; + let r = at(&m, "R", t * 40_960); + let xn = at(&m, "xn", t * 40_960); + let lo = at(&m, "lo", t * 1280); + let gated = at(&m, "parts", t * 10 * 2560 * 4); + let mixed = mixed_base + (t * 10_240) as u64; + // 1. native_gr_rms_norm_weighted: hc blocks of 1024 threads + assert_eq!((k[0].entry, k[0].grid, k[0].block), ("mtp_full_gr_norm", [4, 1, 1], [1024, 1, 1])); + assert_eq!(k[0].args, vec![A::P(r), A::P(0xA000), A::P(xn), A::I32(2560), A::F32(1e-6)]); + // 2. bf16_gemv_fp32_mmvf(xn, down -> lo, 10240 -> 320): mmvf block 256 + assert_eq!((k[1].entry, k[1].grid, k[1].block), ("mtp_full_mmvf256", [320, 1, 1], [256, 1, 1])); + assert_eq!(k[1].args, vec![A::P(xn), A::P(0xB000), A::P(lo), A::I32(10_240)]); + // 3. native_gr_down_silu(lo, 320, 1/4): ceil(320/256) = 2 blocks + assert_eq!((k[2].entry, k[2].grid, k[2].block), ("mtp_full_down_silu", [2, 1, 1], [256, 1, 1])); + assert_eq!(k[2].args, vec![A::P(lo), A::I32(320), A::F32(0.25)]); + // 4. bf16_gemv_fp32_mmvf(lo, up -> gated, 320 -> 10240): mmvf block 160 (ceil(320/320) = 1 iteration) + assert_eq!((k[3].entry, k[3].grid, k[3].block), ("mtp_full_mmvf160", [10_240, 1, 1], [160, 1, 1])); + assert_eq!(k[3].args, vec![A::P(lo), A::P(0xC000), A::P(gated), A::I32(320)]); + // 5. native_gr_pre_gated(xn, gated, mixed, n, hc, 1/4): 10 blocks + assert_eq!((k[4].entry, k[4].grid, k[4].block), ("mtp_full_pre_final", [10, 1, 1], [256, 1, 1])); + assert_eq!(k[4].args, vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(2560), A::I32(4), A::F32(0.25)]); + } + // the whole window: 1..=8 rows; none beyond max_t + assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 8).is_ok()); + assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 9).is_err()); + assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 0).is_err()); + let mut non_native = sm120(GrVariant::Staged); + non_native.native_mmvf = false; + assert!(matches!( + plan_head_mix(&m, &g, &w, &non_native, mixed_base, 1), + Err(Error::InvalidDriverValue(s)) if s.contains("head") + )); +} + +// ------------------------------------------------------------------------------------ PLE +fn ple_addrs(key: PleKey) -> PleAddrs { + PleAddrs { + key, + value: 0x5000_0000, + norm_key: 0x5100_0000, + norm_query: 0x5200_0000, + norm_conv: 0x5300_0000, + conv1d: 0x5400_0000, + scratch: 0x6000_0000, + history: 0x6100_0000, + } +} + +#[test] +fn ple_scratch_matches_ple_block_workspace_carving() { + // 5 * hc_dim + n_embd + hc floats: key, query, norm, gated, conv, value, gate + assert_eq!(PLE_SCRATCH_BYTES, 215_056); + assert_eq!(SCRATCH_QUERY, 40_960); + assert_eq!(SCRATCH_NORM, 81_920); + assert_eq!(SCRATCH_GATED, 122_880); + assert_eq!(SCRATCH_CONV, 163_840); + assert_eq!(SCRATCH_VALUE, 204_800); + assert_eq!(SCRATCH_GATE, 215_040); + assert_eq!(SCRATCH_GATE + 16, PLE_SCRATCH_BYTES as u64); +} + +#[test] +fn ple_row_with_a_bf16_key_follows_ple_block_native_order() { + let m = arena(); + let g = test_geometry(); + let a = ple_addrs(PleKey::Bf16(0x7000_0000)); + let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 2).unwrap(); + let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); + assert_eq!( + names, + [ + "mtp_full_native_write", // the pending layer-0 gr_write + "mtp_full_mmvf256", // key = ple_key @ emb (10240 x 2560) + "mtp_full_mmvf256", // value = ple_value @ emb (2560 x 2560) + "ple_rms", // key norm -> d_query + "ple_rms", // hidden norm -> d_norm + "ple_gate", + "ple_broadcast", + "ple_rms", // gated norm -> d_norm + "ple_conv", + "ple_history", + ] + ); + let r = at(&m, "R", 2 * 40_960); + let emb = at(&m, "ple", 2 * 10_240); + let s = 0x6000_0000u64; + assert_eq!(l[0].args[0], A::P(r)); + assert_eq!(l[0].args[3], A::P(r)); + // key: x = emb, y = scratch key (ldy = 10240), 2560 -> 10240 + assert_eq!(l[1].grid, [10_240, 1, 1]); + assert_eq!(l[1].args, vec![A::P(emb), A::P(0x7000_0000), A::P(s), A::I32(2560)]); + // value: y = scratch value, 2560 -> 2560 + assert_eq!(l[2].grid, [2560, 1, 1]); + assert_eq!(l[2].args, vec![A::P(emb), A::P(0x5000_0000), A::P(s + 204_800), A::I32(2560)]); + // postops: rms(key -> query), rms(hidden -> norm), gate(query, norm -> gate), ... + assert_eq!(l[3].args, vec![A::P(s), A::P(0x5100_0000), A::P(s + 40_960)]); + assert_eq!(l[4].args, vec![A::P(r), A::P(0x5200_0000), A::P(s + 81_920)]); + assert_eq!((l[3].grid, l[3].block), ([4, 1, 1], [1024, 1, 1])); + assert_eq!((l[5].grid, l[5].block), ([4, 1, 1], [512, 1, 1])); + assert_eq!(l[5].args, vec![A::P(s + 40_960), A::P(s + 81_920), A::P(s + 215_040), A::F32(1.0 / 2560f32.sqrt())]); + assert_eq!((l[6].grid, l[6].block), ([40, 1, 1], [256, 1, 1])); + assert_eq!(l[6].args, vec![A::P(s + 204_800), A::P(s + 215_040), A::P(s + 122_880), A::I32(1)]); + assert_eq!(l[7].args, vec![A::P(s + 122_880), A::P(0x5300_0000), A::P(s + 81_920)]); + // conv + residual: hidden = Rt in place + assert_eq!( + l[8].args, + vec![A::P(0x6100_0000), A::P(s + 81_920), A::P(0x5400_0000), A::P(r), A::P(s + 122_880), A::P(s + 163_840), A::I32(1)] + ); + assert_eq!((l[8].grid, l[8].block), ([40, 1, 1], [256, 1, 1])); + // history advance reads the normalized row from the workspace + assert_eq!(l[9].args, vec![A::P(0x6100_0000), A::P(s + 81_920), A::I32(1)]); + assert_eq!((l[9].grid, l[9].block), ([40, 1, 1], [256, 1, 1])); + for launch in &l[3..] { + assert!(std::ptr::eq(launch.asset, &PLE_BATCH)); + } +} + +#[test] +fn ple_row_with_a_native_key_quantizes_into_the_arena_and_runs_mmvq() { + let m = arena(); + let g = test_geometry(); + let a = ple_addrs(PleKey::Native { ty: 42, data: 0x7100_0000 }); + let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 0).unwrap(); + let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); + assert_eq!(&names[..4], &["mtp_full_native_write", "head_quant", "head_n42_s1", "mtp_full_mmvf256"]); + assert_eq!(l.len(), 11); + let q8 = at(&m, "xq", 0); + let emb = at(&m, "ple", 0); + assert_eq!(l[1].args, vec![A::P(emb), A::P(q8), A::I32(2560)]); + // 2560 / 64 = 40 blocks < 64 per iteration: the "small" layout, 4 rows per block + assert_eq!((l[2].grid, l[2].block), ([2560, 1, 1], [32, 4, 1])); + assert_eq!( + l[2].args, + vec![A::P(0x7100_0000), A::P(q8), A::P(0x6000_0000), A::I32(2560), A::I32(10_240)] + ); + // an unsupported native key type fails closed + let bad = ple_addrs(PleKey::Native { ty: 14, data: 1 }); + assert_eq!( + plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &bad, 0).unwrap_err(), + Error::UnsupportedQwenOperation + ); +} + +#[test] +fn ple_layer1_walks_the_group_rows_in_order_and_fails_closed_on_policy() { + let m = arena(); + let g = test_geometry(); + let a = ple_addrs(PleKey::Bf16(0x7000_0000)); + let c = sm120(GrVariant::Staged); + let out = plan_ple_layer1(&m, &g, &c, &PleConfig::mode17(), &a, rows(4, 7, 1)).unwrap(); + assert_eq!(out.iter().map(|(t, _)| *t).collect::>(), [4, 5, 6]); + assert!(out.iter().all(|(_, l)| l.len() == 10)); + let mut legacy = PleConfig::mode17(); + legacy.native_postops = false; + assert!(matches!( + plan_ple_layer1(&m, &g, &c, &legacy, &a, rows(0, 1, 0)), + Err(Error::InvalidDriverValue(s)) if s.contains("ple_layer1") + )); + legacy = PleConfig::mode17(); + legacy.native_value_bf16 = false; + assert!(plan_ple_row(&m, &g, &c, &legacy, &a, 0).is_err()); + assert!(plan_ple_row(&m, &g, &c, &PleConfig::mode17(), &a, 8).is_err()); +} + +// ---------------------------------------------------------------------------- byte sizes +#[test] +fn weight_byte_sizes_follow_the_hc_geometry() { + // hc=4, N=2560, hc_lr=320 + assert_eq!(HC_NORM_BYTES, 4 * 2560 * 4); + assert_eq!(HC_DOWN_BYTES, 320 * 4 * 2560 * 2); + assert_eq!(HC_UP_BYTES, 4 * 2560 * 320 * 2); + assert_eq!(HC_INJECT_BYTES, 4 * 4 * 2560 * 2); + assert_eq!(PLE_HISTORY_BYTES, 9 * 4 * 2560 * 4); + assert_eq!(PLE_VALUE_BYTES, 2560 * 2560 * 2); + assert_eq!(PLE_KEY_BF16_BYTES, 10_240 * 2560 * 2); + assert_eq!(PLE_CONV_BYTES, 4 * 10_240 * 2); + // a Q2_0 key: 64-element blocks of 18 bytes -> 40 blocks per row + assert_eq!(native_head_row_bytes(42, 2560).unwrap(), 40 * 18); +} diff --git a/crates/cuda-driver/src/original_verify_window_moe.rs b/crates/cuda-driver/src/original_verify_window_moe.rs index 86406da8..8bca983e 100644 --- a/crates/cuda-driver/src/original_verify_window_moe.rs +++ b/crates/cuda-driver/src/original_verify_window_moe.rs @@ -945,723 +945,5 @@ pub(crate) fn plan_combine( } #[cfg(test)] -mod tests { - use super::super::kernels::{LayoutMap, test_geometry}; - use super::*; - - const BASE: u64 = 0x2000_0000; - - #[test] - fn the_alternative_pcie_staging_copy_kernels_are_sealed() { - PCIE_FAST.assert_sealed_and_fail_closed(); - assert!(PCIE_FAST.sealed().is_ok()); - } - - fn map() -> LayoutMap { - LayoutMap::new(BASE, test_geometry()) - } - fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { - m.span(name, offset, 4).unwrap() - } - fn rows(begin: usize, end: usize, group: usize) -> Rows { - Rows { begin, end, group } - } - fn weights() -> MoeLayerAddrs { - MoeLayerAddrs { - router: 0x9000_0000, - gate_inp_shexp: 0x9100_0000, - gate_shexp: NativeWeight { ty: 8, data: 0x9200_0000 }, - up_shexp: NativeWeight { ty: 8, data: 0x9300_0000 }, - down_shexp: NativeWeight { ty: 8, data: 0x9400_0000 }, - } - } - fn formats() -> OriginalVerifyExpertFormats { - OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 640).unwrap() - } - fn entries(l: &[Launch]) -> Vec<&'static str> { - l.iter().map(|x| x.entry).collect() - } - - // ---- assets ------------------------------------------------------------------------------ - - fn entry_declared(ptx: &str, e: &str) -> bool { - ptx.contains(&format!(".entry {e}(")) - } - - /// `.param` type tokens of an entry's parameter list (the first token after `.param`). - fn param_types(ptx: &str, entry: &str) -> Vec { - let head = format!(".entry {entry}("); - let start = ptx.find(&head).unwrap_or_else(|| panic!("{entry} missing")) + head.len(); - let rest = &ptx[start..]; - let end = rest.find("\n)").expect("parameter list end"); - rest[..end] - .lines() - .filter(|l| l.contains(".param")) - .map(|l| l.split_whitespace().nth(1).unwrap().to_string()) - .collect() - } - fn expected_type(a: &A) -> &'static str { - match a { - A::P(_) | A::I64(_) | A::U64(_) => ".u64", - A::I32(_) => ".u32", - A::F32(_) => ".f32", - A::Words(_) => ".align", - } - } - - #[test] - fn sealed_assets_are_pinned_and_export_every_named_entry() { - for spec in [&ELEMENT, &ROUTER, &ROUTER_LEGACY, &SHARED, &HEAD_IQ_EXPERT, &S2_HITS, &COMBINE] { - spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); - let text = String::from_utf8_lossy(spec.ptx); - for e in spec.entries { - assert!(entry_declared(&text, e), "{} lacks {e}", spec.name); - } - } - // the window's HEAD_IQ_EXPERT is the same file and pin as proj::HEAD_IQ - assert_eq!(HEAD_IQ_EXPERT.sha, proj::HEAD_IQ.sha); - assert!(HEAD_IQ_EXPERT.ptx == proj::HEAD_IQ.ptx); - } - - #[test] - fn expert_asset_is_sealed_and_a_corrupted_copy_still_refuses_to_load() { - // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim). - EXPERTS.assert_sealed_and_fail_closed(); - assert_eq!(EXPERTS.entries.len(), 16); - assert!(EXPERTS.unsealed.contains("original_verify_window_moe_experts.ptx")); - } - - #[test] - fn expert_entries_match_the_cu_source_and_the_original_format_lists() { - let cu = include_str!("original_verify_window_moe_experts.cu"); - assert!(cu.contains("window_moe_gu_##T") && cu.contains("window_moe_down_##T")); - assert!(cu.contains("STRATA_GU_FMTS(STRATA_WINDOW_GU)") && cu.contains("STRATA_D_FMTS(STRATA_WINDOW_DOWN)")); - let iq = include_str!("mtp_original_full_head_iq.cu"); - let parse = |macro_name: &str| -> Vec { - let line = iq.lines().find(|l| l.starts_with(&format!("#define {macro_name}(X)"))).expect(macro_name); - line.split("X(").skip(1).map(|s| s.split(')').next().unwrap().parse().unwrap()).collect() - }; - let gu: Vec = GU_ENTRIES.iter().map(|e| e.0).collect(); - let d: Vec = DOWN_ENTRIES.iter().map(|e| e.0).collect(); - assert_eq!(gu, parse("STRATA_GU_FMTS")); - assert_eq!(d, parse("STRATA_D_FMTS")); - for (t, name) in GU_ENTRIES { - assert_eq!(*name, format!("window_moe_gu_{t}")); - assert!(EXPERTS.has_entry(name) && gu_qk(*t) > 0); - } - for (t, name) in DOWN_ENTRIES { - assert_eq!(*name, format!("window_moe_down_{t}")); - assert!(EXPERTS.has_entry(name) && d_qk(*t) > 0); - } - assert_eq!(EXPERTS.entries.len(), GU_ENTRIES.len() + DOWN_ENTRIES.len()); - // the Original's per-type values-per-block (Fmt::qk) used by native_expert_supported - for (t, _) in GU_ENTRIES { - let want = format!("template<> struct Fmt<{t}> {{ static constexpr int qk = {},", gu_qk(*t)); - assert!(iq.contains(&want), "{want}"); - } - for (t, _) in DOWN_ENTRIES { - let want = format!("template<> struct Fmt<{t}> {{ static constexpr int qk = {},", d_qk(*t)); - assert!(iq.contains(&want), "{want}"); - } - assert_eq!((gu_qk(20), gu_qk(7), d_qk(16), d_qk(12), d_qk(0)), (0, 0, 0, 0, 0)); - } - - #[test] - fn asset_list_names_every_module_once() { - let a = assets(); - let mut names: Vec<&str> = a.iter().map(|s| s.name).collect(); - names.sort_unstable(); - let len = names.len(); - names.dedup(); - assert_eq!(names.len(), len, "duplicate asset names"); - assert!(a.iter().any(|s| std::ptr::eq(*s, &EXPERTS))); - assert!(shared_attributes(&MoeKnobs::mode17()).is_empty()); - } - - /// The ABI check: every launch of a SEALED asset names an entry whose `.param` list has exactly the - /// recorded argument count and widths. - fn assert_abi(launches: &[Launch]) { - for l in launches { - let text = String::from_utf8_lossy(l.asset.ptx); - let types = param_types(&text, l.entry); - let want: Vec<&str> = l.args.iter().map(expected_type).collect(); - assert_eq!(types, want, "{}", l.label()); - } - } - - // ---- router ------------------------------------------------------------------------------ - - #[test] - fn batched_router_is_one_gemv_and_one_top10_over_the_groups_rows() { - let m = map(); - let g = test_geometry(); - let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(3, 8, 1), true).unwrap(); - assert_eq!(l.len(), 2); - // bf16_gemv_fp32_mmvf_multi(mixed + 3*N, N, w, logits + 3*NE, NE, N, NE, 5): block 256, 5 rows -> 8-col kernel - assert!(l[0].entry.contains("ILi256ELi8EE")); - assert_eq!((l[0].grid, l[0].block), ([512, 1, 1], [256, 1, 1])); - assert_eq!( - l[0].args, - vec![ - A::P(at(&m, "mixed", 3 * 2560 * 4)), - A::I64(2560), - A::P(0x9000_0000), - A::P(at(&m, "logits", 3 * 512 * 4)), - A::I64(512), - A::I32(2560), - A::I32(5) - ] - ); - // native_router_top10_multi: route<<<5, (32, 8)>>>(logits + 3*NE, ids + 3*K, w + 3*K) - assert_eq!((l[1].entry, l[1].grid, l[1].block, l[1].shared), ("mtp_full_route", [5, 1, 1], [32, 8, 1], 0)); - assert_eq!( - l[1].args, - vec![A::P(at(&m, "logits", 3 * 512 * 4)), A::P(at(&m, "ids", 3 * 10 * 4)), A::P(at(&m, "w", 3 * 10 * 4))] - ); - assert_abi(&l); - } - - #[test] - fn batched_router_uses_the_four_column_kernel_up_to_four_rows() { - let m = map(); - let g = test_geometry(); - for n in 2..=4usize { - let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(0, n, 0), true).unwrap(); - assert!(l[0].entry.contains("ILi256ELi4EE"), "{n}"); - assert_eq!(l[1].grid, [n as u32, 1, 1]); - } - } - - #[test] - fn per_row_router_follows_moe_route_for_every_row() { - let m = map(); - let g = test_geometry(); - let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(1, 3, 0), false).unwrap(); - // row 1: bf16_gemv_fp32_mmvf(mixed + N, w, logits + NE, N, NE) + native_router_top10; then row 2 - assert_eq!(entries(&l), ["mtp_full_mmvf256", "mtp_full_route", "mtp_full_mmvf256", "mtp_full_route"]); - assert_eq!(l[0].grid, [512, 1, 1]); - assert_eq!( - l[0].args, - vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(0x9000_0000), A::P(at(&m, "logits", 512 * 4)), A::I32(2560)] - ); - assert_eq!((l[1].grid, l[1].block), ([1, 1, 1], [32, 8, 1])); - assert_eq!( - l[3].args, - vec![A::P(at(&m, "logits", 2 * 512 * 4)), A::P(at(&m, "ids", 2 * 10 * 4)), A::P(at(&m, "w", 2 * 10 * 4))] - ); - assert_abi(&l); - } - - #[test] - fn generic_router_is_the_original_router_top10_launch() { - let m = map(); - let g = test_geometry(); - let mut knobs = MoeKnobs::mode17(); - knobs.native_router = false; - let l = plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 1, 0), false).unwrap(); - assert_eq!(l.len(), 2); - // threads = 512, smem = 512 (taken) + 512*8 (doubles) + 512*4 (floats) = 6656 - assert_eq!((l[1].grid, l[1].block, l[1].shared), ([1, 1, 1], [512, 1, 1], 6656)); - assert_eq!( - l[1].args, - vec![ - A::P(at(&m, "logits", 0)), - A::I32(1), - A::I32(512), - A::I32(10), - A::P(at(&m, "ids", 0)), - A::P(at(&m, "w", 0)) - ] - ); - assert_abi(&l); - // the batched launch needs the native router - assert_eq!( - plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 2, 0), true).unwrap_err(), - Error::InvalidQwenShape - ); - } - - #[test] - fn router_fails_closed_precisely_without_native_bf16_and_on_bad_shapes() { - let m = map(); - let g = test_geometry(); - let mut knobs = MoeKnobs::mode17(); - knobs.native_bf16 = false; - let e = plan_router(&m, &g, &knobs, 1, rows(0, 1, 0), false).unwrap_err(); - match e { - Error::InvalidDriverValue(s) => { - assert!(s.starts_with("Original verifier producer unavailable: router: "), "{s}") - } - other => panic!("{other:?}"), - } - // the batched path never needs the bf16 conversion - assert!(plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 2, 0), true).is_ok()); - // batched with one row, empty rows, rows past the window, group C - let mode = MoeKnobs::mode17(); - assert!(plan_router(&m, &g, &mode, 1, rows(0, 1, 0), true).is_err()); - assert!(plan_router(&m, &g, &mode, 1, rows(2, 2, 0), false).is_err()); - assert!(plan_router(&m, &g, &mode, 1, rows(0, 9, 0), false).is_err()); - assert!(plan_router(&m, &g, &mode, 1, rows(0, 1, 2), false).is_err()); - } - - // ---- shared expert ----------------------------------------------------------------------- - - #[test] - fn batched_shared_expert_runs_the_shared_expert_multi_sequence_in_order() { - let m = map(); - let g = test_geometry(); - let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(2, 6, 1), true).unwrap(); - // f32_to_bf16_bulk(4 rows), quantize x, MMVQ gate, MMVQ up, swiglu, quantize h, MMVQ down, - // gate GEMV (multi), sigmoid (multi), scale rows - assert_eq!(l.len(), 10); - assert!(l[0].entry.ends_with("to_bf16_kernelEPKfPtl")); - assert_eq!((l[0].grid, l[0].block), ([40, 1, 1], [256, 1, 1])); // 4*2560 = 10240 elements - assert_eq!( - l[0].args, - vec![A::P(at(&m, "mixed", 2 * 2560 * 4)), A::P(at(&m, "sh_bf16", 2 * 2560 * 2)), A::I64(10240)] - ); - let xq = at(&m, "xq", 0); - let xm = at(&m, "mixed", 2 * 2560 * 4); - let gate = at(&m, "sh_gate", 2 * 640 * 4); - let up = at(&m, "sh_up", 2 * 640 * 4); - let shared = at(&m, "shared", 2 * 2560 * 4); - let gs = at(&m, "sh_g", 2 * 4); - assert_eq!(l[1].entry, "head_quant"); - assert_eq!(l[1].args, vec![A::P(xm), A::P(xq), A::I32(4 * 2560)]); - // gate/up: Q8_0, 4 columns: head_n8_t4_large, y rows n_ff floats apart - assert_eq!(l[2].entry, "head_n8_t4_large"); - assert_eq!(l[2].args, vec![A::P(0x9200_0000), A::P(xq), A::P(gate), A::I32(2560), A::I32(640)]); - assert_eq!(l[3].entry, "head_n8_t4_large"); - assert_eq!(l[3].args, vec![A::P(0x9300_0000), A::P(xq), A::P(up), A::I32(2560), A::I32(640)]); - // native_swiglu_kernel<<>>(gate, up, gate, 2560) - assert!(l[4].entry.ends_with("native_swiglu_kernelEPKfS3_Pfi")); - assert_eq!((l[4].grid, l[4].block), ([20, 1, 1], [128, 1, 1])); - assert_eq!(l[4].args, vec![A::P(gate), A::P(up), A::P(gate), A::I32(2560)]); - // quantize the activated gate (640 elements per row) in place into xq, then the down projection - assert_eq!(l[5].args, vec![A::P(gate), A::P(xq), A::I32(4 * 640)]); - // down: n_in = 640 values is "small" for Q8_0 (640/32 < 32 blocks per iteration) - assert_eq!(l[6].entry, "head_n8_t4_small"); - assert_eq!(l[6].args, vec![A::P(0x9400_0000), A::P(xq), A::P(shared), A::I32(640), A::I32(2560)]); - // the scalar gate: one GEMV (4 rows, ldy 1, n_out 1) and one sigmoid with thread t = token t - assert!(l[7].entry.contains("ILi256ELi4EE")); - assert_eq!(l[7].grid, [1, 1, 1]); - assert_eq!( - l[7].args, - vec![A::P(xm), A::I64(2560), A::P(0x9100_0000), A::P(gs), A::I64(1), A::I32(2560), A::I32(4)] - ); - assert!(l[8].entry.ends_with("native_scalar_sigmoid_multi_kernelEPf")); - assert_eq!((l[8].grid, l[8].block, l[8].args.clone()), ([1, 1, 1], [4, 1, 1], vec![A::P(gs)])); - // scale_rows_kernel<<<(20, 4), 128>>>(shared, g, 2560) - assert!(l[9].entry.ends_with("scale_rows_kernelEPfPKfi")); - assert_eq!((l[9].grid, l[9].block), ([20, 4, 1], [128, 1, 1])); - assert_eq!(l[9].args, vec![A::P(shared), A::P(gs), A::I32(2560)]); - assert_abi(&l); - } - - #[test] - fn single_row_shared_expert_uses_the_per_token_gate_and_single_row_projections() { - let m = map(); - let g = test_geometry(); - let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(0, 1, 0), true).unwrap(); - // bulk, quantize, gate, up, swiglu, quantize, down, [mmvf + sigmoid], scale - assert_eq!(l.len(), 10); - assert_eq!((l[2].entry, l[6].entry), ("head_n8_s0", "head_n8_s1")); - assert_eq!(l[7].entry, "mtp_full_mmvf256"); - assert_eq!(l[7].args, vec![A::P(at(&m, "mixed", 0)), A::P(0x9100_0000), A::P(at(&m, "sh_g", 0)), A::I32(2560)]); - assert!(l[8].entry.ends_with("native_scalar_sigmoid_kernelEPf")); - assert_eq!(l[8].block, [1, 1, 1]); - assert_eq!(l[9].grid, [20, 1, 1]); - assert_abi(&l); - } - - #[test] - fn shared_expert_without_dec_batch_converts_and_gates_one_row_at_a_time() { - let m = map(); - let g = test_geometry(); - let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(1, 3, 0), false).unwrap(); - // 2 conversions, the six projection / activation launches, 2 x (mmvf + sigmoid), scale - assert_eq!(l.len(), 2 + 6 + 4 + 1); - assert_eq!((l[0].grid, l[0].args.clone()), ([10, 1, 1], vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(at(&m, "sh_bf16", 2560 * 2)), A::I64(2560)])); - assert_eq!(l[1].args[1], A::P(at(&m, "sh_bf16", 2 * 2560 * 2))); - // the projections are still two-row launches, but the gate is per token - assert_eq!(l[3].entry, "head_n8_t2_large"); - assert_eq!( - l[8].args, - vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(0x9100_0000), A::P(at(&m, "sh_g", 4)), A::I32(2560)] - ); - assert_eq!(l[10].args[2], A::P(at(&m, "sh_g", 2 * 4))); - assert_eq!(l[12].grid, [20, 2, 1]); - assert_abi(&l); - } - - #[test] - fn shared_gate_without_native_bf16_extra_reads_the_bf16_activation() { - let m = map(); - let g = test_geometry(); - let mut knobs = MoeKnobs::mode17(); - knobs.native_bf16_extra = false; - let l = plan_shared_expert(&m, &g, &knobs, &weights(), rows(0, 2, 0), true).unwrap(); - // one scalar_gate_kernel<<<1, 256>>>(x_bf16 + t*N, w, g + t, N) per token, no GEMV / sigmoid - let gates: Vec<&Launch> = l.iter().filter(|x| x.entry.ends_with("scalar_gate_kernelEPKtS3_Pfi")).collect(); - assert_eq!(gates.len(), 2); - assert_eq!((gates[0].grid, gates[0].block), ([1, 1, 1], [256, 1, 1])); - assert_eq!( - gates[1].args, - vec![A::P(at(&m, "sh_bf16", 2560 * 2)), A::P(0x9100_0000), A::P(at(&m, "sh_g", 4)), A::I32(2560)] - ); - assert!(!l.iter().any(|x| x.entry.contains("sigmoid"))); - assert_abi(&l); - } - - #[test] - fn shared_expert_covers_every_window_size() { - let m = map(); - let g = test_geometry(); - for n in 1..=8usize { - let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(0, n, 0), true).unwrap(); - assert_eq!(l.last().unwrap().grid, [20, n as u32, 1]); - assert_eq!(l[4].grid, [(640 * n).div_ceil(128) as u32, 1, 1]); - assert_abi(&l); - } - } - - // ---- expert input, groups ---------------------------------------------------------------- - - #[test] - fn expert_input_is_the_q8_1_row_quantizer_into_nat_xq() { - let m = map(); - let g = test_geometry(); - let l = plan_quantize_expert_input(&m, &g, &MoeKnobs::mode17(), rows(4, 8, 1)).unwrap(); - assert_eq!(l.len(), 1); - assert!(l[0].entry.ends_with("quantize_q8_1_kernelEPKfP10block_q8_1x")); - assert_eq!((l[0].grid, l[0].block), ([40, 1, 1], [256, 1, 1])); - assert_eq!( - l[0].args, - vec![A::P(at(&m, "mixed", 4 * 2560 * 4)), A::P(at(&m, "nat_xq", 4 * 2880)), A::I64(4 * 2560)] - ); - assert_abi(&l); - let mut s2 = MoeKnobs::mode17(); - s2.native_experts = false; - assert!(matches!( - plan_quantize_expert_input(&m, &g, &s2, rows(0, 1, 0)), - Err(Error::InvalidDriverValue(s)) if s.contains("quantize_expert_input") - )); - } - - #[test] - fn expert_blob_layout_matches_native_expert_layout() { - // IQ2_XXS gate/up (66 B per 256), IQ4_NL down (18 B per 32): n_embd 2560, n_ff 640 - let b = expert_blob(16, 20, 2560, 640).unwrap(); - assert_eq!((b.gu_row, b.d_row), (10 * 66, 20 * 18)); - assert_eq!((b.up_off, b.down_off), (640 * 660, 2 * 640 * 660)); - assert_eq!(b.bytes, 844_800 + 2560 * 360); - assert_eq!(b.bytes % 16, 0); - assert_eq!( - b.words(), - vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400] - ); - // Q4_K gate/up (144 B per 256) and Q8_0 down (34 B per 32) - let q = expert_blob(12, 8, 2560, 640).unwrap(); - assert_eq!((q.gu_row, q.d_row, q.bytes), (1440, 680, 2 * 640 * 1440 + 2560 * 680)); - // Q2_0 (64 values, 18 B) on both sides - let z = expert_blob(42, 42, 2560, 640).unwrap(); - assert_eq!((z.gu_row, z.d_row), (40 * 18, 10 * 18)); - // IQ4_XS down needs n_ff % 256 == 0: 640 is not; IQ4_NL gate/up and unknown types are refused - assert_eq!(expert_blob(16, 23, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); - assert_eq!(expert_blob(20, 20, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); - assert_eq!(expert_blob(16, 99, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); - assert_eq!(expert_blob(16, 20, 2560, 650).unwrap_err(), Error::UnsupportedQwenOperation); - } - - #[test] - fn expert_formats_validate_all_layers_and_report_blob_bytes() { - let f = formats(); - assert_eq!(f.blob_bytes(0), Ok(1_766_400)); - assert_eq!(f.blob_bytes(47), Ok(1_766_400)); - assert!(f.blob_bytes(48).is_err()); - let mut mixed = [(16, 20); WINDOW_LAYERS]; - mixed[10] = (12, 8); - let f = OriginalVerifyExpertFormats::new(mixed, 2560, 640).unwrap(); - assert_eq!(f.blob_bytes(10), Ok(2 * 640 * 1440 + 2560 * 680)); - assert_eq!(f.blob_bytes(11), Ok(1_766_400)); - mixed[30] = (20, 20); - assert_eq!(OriginalVerifyExpertFormats::new(mixed, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); - } - - #[test] - fn expert_scratch_follows_native_expert_scratch_bytes() { - // gate | up | h each cap*n_ff floats rounded to 256, then cap*(n_ff/32) q8_1 blocks rounded to 256 - assert_eq!(expert_scratch(10, 640), (25_600, 3 * 25_600 + 7_424)); // 10*20*36 = 7200 -> 7424 - assert_eq!(expert_scratch(80, 640), (204_800, 3 * 204_800 + 80 * 20 * 36)); - // rounding path (never reached by n_ff = 640 where cap * n_ff * 4 is a multiple of 256) - assert_eq!(expert_scratch(1, 100), (512, 3 * 512 + 256)); - } - - #[test] - fn vram_tier_reads_the_first_plan_arrays() { - let m = map(); - let g = test_geometry(); - let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 5, rows(0, 3, 0), ExpertTier::Vram); - // the plan itself is pure data - let l = l.unwrap(); - assert_eq!(entries(&l).len(), 4); - // PlanLayout(capx = 80): start 4, dst 85, tok 165, ptr 246, ptr2 406, start2 566; device stride 664 words - let plan = |word: usize| at(&m, "plan", word * 4); - let scratch = at(&m, "hit_scratch", 0); - let xq = at(&m, "nat_xq", 0); - let fa = 3 * 10 * 640 * 4; - // gate/up: grid ((2*640+7)/8 = 160, cap = 30), 256 threads - assert_eq!((l[0].entry, l[0].grid, l[0].block, l[0].shared), ("window_moe_gu_16", [160, 30, 1], [256, 1, 1], 0)); - assert_eq!( - l[0].args, - vec![ - A::P(plan(246)), - A::P(plan(4)), - A::P(plan(0)), - A::P(plan(165)), - A::P(xq), - A::Words(vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400]), - A::P(scratch), - A::P(scratch + fa as u64) - ] - ); - // swiglu_entries and quantize over cap * n_ff = 19200 values - assert!(l[1].entry.ends_with("swiglu_entries_kernelEPKfS3_Pfx")); - assert_eq!((l[1].grid, l[1].block), ([75, 1, 1], [256, 1, 1])); - assert_eq!( - l[1].args, - vec![A::P(scratch), A::P(scratch + fa as u64), A::P(scratch + 2 * fa as u64), A::I64(19_200)] - ); - assert!(l[2].entry.ends_with("quantize_q8_1_kernelEPKfP10block_q8_1x")); - assert_eq!(l[2].args, vec![A::P(scratch + 2 * fa as u64), A::P(scratch + 3 * fa as u64), A::I64(19_200)]); - // down: grid ((2560+7)/8 = 320, 30) - assert_eq!((l[3].entry, l[3].grid), ("window_moe_down_20", [320, 30, 1])); - assert_eq!( - l[3].args, - vec![ - A::P(plan(246)), - A::P(plan(4)), - A::P(plan(0)), - A::P(plan(85)), - A::P(scratch + 3 * fa as u64), - A::Words(vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400]), - A::P(at(&m, "hit_out", 0)) - ] - ); - assert_abi(&l[1..3]); - } - - #[test] - fn pcie_tier_uses_the_second_pointer_start_and_count_of_the_group() { - let m = map(); - let g = test_geometry(); - // group B of a 5-row window: rows 3..5, plan block of group 1 (664 words further) - let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 0, rows(3, 5, 1), ExpertTier::Pcie).unwrap(); - let plan = |word: usize| at(&m, "plan", (664 + word) * 4); - assert_eq!( - l[0].args[..5], - [A::P(plan(406)), A::P(plan(566)), A::P(plan(2)), A::P(plan(165)), A::P(at(&m, "nat_xq", 3 * 2880))] - ); - assert_eq!(l[0].grid, [160, 20, 1]); - assert_eq!( - l[3].args[..4], - [A::P(plan(406)), A::P(plan(566)), A::P(plan(2)), A::P(plan(85))] - ); - // output rows of the group start at tb*K*N - assert_eq!(l[3].args[6], A::P(at(&m, "hit_out", 3 * 10 * 2560 * 4))); - assert_eq!(l[3].grid, [320, 20, 1]); - } - - #[test] - fn expert_groups_pick_the_kernels_of_the_layers_formats() { - let m = map(); - let g = test_geometry(); - let mut fmts = [(16, 20); WINDOW_LAYERS]; - fmts[7] = (12, 8); - fmts[8] = (42, 42); - fmts[9] = (13, 7); - let f = OriginalVerifyExpertFormats::new(fmts, 2560, 640).unwrap(); - let pick = |layer: usize| { - let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, layer, rows(0, 1, 0), ExpertTier::Vram).unwrap(); - (l[0].entry, l[3].entry) - }; - assert_eq!(pick(0), ("window_moe_gu_16", "window_moe_down_20")); - assert_eq!(pick(7), ("window_moe_gu_12", "window_moe_down_8")); - assert_eq!(pick(8), ("window_moe_gu_42", "window_moe_down_42")); - assert_eq!(pick(9), ("window_moe_gu_13", "window_moe_down_7")); - // every launch names an entry of its asset - for t in 0..8usize { - let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, 7, rows(0, t + 1, 0), ExpertTier::Pcie).unwrap(); - assert_eq!(l[0].grid[1], ((t + 1) * 10) as u32); - assert_eq!(l[3].grid[1], ((t + 1) * 10) as u32); - } - } - - #[test] - fn gu_swiglu_replaces_gate_up_swiglu_and_quantize_by_one_launch_and_keeps_the_down_kernel() { - let m = map(); - let g = test_geometry(); - let mut fmts = [(16, 20); WINDOW_LAYERS]; - fmts[7] = (12, 8); - fmts[8] = (22, 20); - let f = OriginalVerifyExpertFormats::new(fmts, 2560, 640).unwrap(); - let mut on = MoeKnobs::mode17(); - on.gu_swiglu = true; - let off = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap(); - let fused = plan_expert_groups(&m, &g, &on, &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap(); - assert_eq!(entries(&fused), ["sm120_moe_gu_swiglu_16", "window_moe_down_20"]); - assert_eq!((fused[0].grid, fused[0].block, fused[0].shared), ([20, 30, 1], [512, 1, 1], 0)); - // the arguments: the same group tables, activations and q8_1 output as the three kernels, upstream's 88-byte layout - let gu = &off[0].args; - let scratch_hq = match &off[2].args[1] { A::P(p) => *p, _ => unreachable!() }; - assert_eq!(fused[0].args[..5], gu[..5]); - assert_eq!(fused[0].args[6], A::P(scratch_hq)); - match (&fused[0].args[5], &gu[5]) { - (A::Words(n), A::Words(o)) => { - assert_eq!((n.len(), o.len()), (11, 8)); - assert_eq!(n[..8], o[..]); - assert_eq!(n[8..], [0, 0, 0]); - } - _ => panic!("layout words"), - } - // the down kernel is untouched (same arguments, reading the same hq) - assert_eq!(fused[1].args, off[3].args); - assert_eq!(fused[1].entry, off[3].entry); - // layers whose gate/up format has no fused kernel keep the three-kernel plan; so does a knobs set without the switch - assert_eq!(entries(&plan_expert_groups(&m, &g, &on, &f, 7, rows(0, 3, 0), ExpertTier::Vram).unwrap())[0], "window_moe_gu_12"); - assert_eq!(entries(&plan_expert_groups(&m, &g, &on, &f, 8, rows(0, 3, 0), ExpertTier::Pcie).unwrap())[0], "sm120_moe_gu_swiglu_22"); - assert_eq!(entries(&off).len(), 4); - } - - #[test] - fn expert_groups_refuse_s2_and_a_mismatched_geometry() { - let m = map(); - let g = test_geometry(); - let mut s2 = MoeKnobs::mode17(); - s2.native_experts = false; - assert!(matches!( - plan_expert_groups(&m, &g, &s2, &formats(), 0, rows(0, 1, 0), ExpertTier::Vram), - Err(Error::InvalidDriverValue(s)) if s.contains("expert_groups") - )); - let other = OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 1280).unwrap(); - assert_eq!( - plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &other, 0, rows(0, 1, 0), ExpertTier::Vram).unwrap_err(), - Error::InvalidQwenShape - ); - assert!(plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 48, rows(0, 1, 0), ExpertTier::Vram).is_err()); - } - - #[test] - fn expert_launches_load_when_sealed_and_are_refused_on_a_corrupted_pin() { - let m = map(); - let g = test_geometry(); - let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 0, rows(0, 1, 0), ExpertTier::Vram).unwrap(); - assert!(std::ptr::eq(l[0].asset, &EXPERTS)); - assert!(l[0].asset.sealed().is_ok()); - assert!(l[1].asset.sealed().is_ok()); - // The same launch against a one-byte-corrupted copy of the asset (synthetic; the real PTX is untouched) - // is refused with the asset's refusal text, exactly as the unsealed placeholder was. - let bad = EXPERTS.derived(crate::sealed_ptx::test_support::one_byte_corrupted(EXPERTS.ptx), EXPERTS.sha); - let launch = Launch::new(bad, l[0].entry, l[0].grid, l[0].block, l[0].shared, l[0].args.clone()).unwrap(); - assert_eq!(launch.asset.sealed().unwrap_err(), Error::InvalidDriverValue(EXPERTS.unsealed)); - assert!(launch.command().is_ok(), "the plan itself is pure data and unaffected"); - } - - // ---- hit add, combine ---------------------------------------------------------------------- - - #[test] - fn hit_add_scans_the_cpu_and_gpu_hits_of_the_group() { - let m = map(); - let g = test_geometry(); - let l = plan_hit_add(&m, &g, rows(3, 5, 1)).unwrap(); - assert_eq!(l.len(), 1); - assert!(l[0].entry.ends_with("add_hits_kernelEPfPKfPKiS6_i")); - // grid (min(ceil(2560/256), 8) = 8, cap = 20), 256 threads - assert_eq!((l[0].grid, l[0].block), ([8, 20, 1], [256, 1, 1])); - let plan = |word: usize| at(&m, "plan", (664 + word) * 4); - assert_eq!( - l[0].args, - vec![ - A::P(at(&m, "parts", 3 * 10 * 2560 * 4)), - A::P(at(&m, "hit_out", 3 * 10 * 2560 * 4)), - A::P(plan(85)), - A::P(plan(1)), - A::I32(2560) - ] - ); - assert_abi(&l); - assert_eq!(plan_hit_add(&m, &g, rows(0, 1, 0)).unwrap()[0].grid, [8, 10, 1]); - } - - #[test] - fn batched_combine_is_one_launch_with_the_token_on_grid_y() { - let m = map(); - let g = test_geometry(); - let l = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(0, 8, 0), true).unwrap(); - assert_eq!(l.len(), 1); - assert_eq!((l[0].entry, l[0].grid, l[0].block), ("mtp_full_combine", [10, 8, 1], [256, 1, 1])); - assert_eq!( - l[0].args, - vec![ - A::P(at(&m, "parts", 0)), - A::P(at(&m, "w", 0)), - A::P(at(&m, "shared", 0)), - A::P(at(&m, "bo", 0)), - A::I64(2560), - A::I32(10) - ] - ); - assert_abi(&l); - let b = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(4, 7, 1), true).unwrap(); - assert_eq!(b[0].grid, [10, 3, 1]); - assert_eq!(b[0].args[0], A::P(at(&m, "parts", 4 * 10 * 2560 * 4))); - assert_eq!(b[0].args[1], A::P(at(&m, "w", 4 * 10 * 4))); - assert_eq!(b[0].args[2], A::P(at(&m, "shared", 4 * 2560 * 4))); - assert_eq!(b[0].args[3], A::P(at(&m, "bo", 4 * 2560 * 4))); - } - - #[test] - fn per_row_combine_is_native_combine_per_token_or_the_legacy_kernel() { - let m = map(); - let g = test_geometry(); - let l = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(1, 3, 0), false).unwrap(); - assert_eq!(l.len(), 2); - assert_eq!((l[1].grid, l[1].block), ([10, 1, 1], [256, 1, 1])); - assert_eq!( - l[1].args, - vec![ - A::P(at(&m, "parts", 2 * 10 * 2560 * 4)), - A::P(at(&m, "w", 2 * 10 * 4)), - A::P(at(&m, "shared", 2 * 2560 * 4)), - A::P(at(&m, "bo", 2 * 2560 * 4)), - A::I64(2560), - A::I32(10) - ] - ); - assert_abi(&l); - // a single-row window is never batched, even with native combine on - let one = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(0, 1, 0), false).unwrap(); - assert_eq!((one[0].entry, one[0].grid), ("mtp_full_combine", [10, 1, 1])); - // moe_combine<<>>(parts, w, shared, y, N, K, has_shared = 1) - let mut legacy = MoeKnobs::mode17(); - legacy.native_combine = false; - let l = plan_combine(&m, &g, &legacy, rows(0, 2, 0), false).unwrap(); - assert_eq!(l.len(), 2); - assert!(l[0].entry.ends_with("moe_combine_kernelEPKfS3_S3_Pfiii")); - assert_eq!((l[0].grid, l[0].block), ([20, 1, 1], [128, 1, 1])); - assert_eq!(l[1].args[4..], [A::I32(2560), A::I32(10), A::I32(1)]); - assert_abi(&l); - assert_eq!(plan_combine(&m, &g, &legacy, rows(0, 2, 0), true).unwrap_err(), Error::InvalidQwenShape); - assert_eq!(plan_combine(&m, &g, &MoeKnobs::mode17(), rows(0, 1, 0), true).unwrap_err(), Error::InvalidQwenShape); - } - - #[test] - fn plan_word_stays_inside_the_plan_span_and_the_two_groups() { - let m = map(); - let g = test_geometry(); - assert_eq!(plan_word(&m, &g, 0, 0).unwrap(), at(&m, "plan", 0)); - assert_eq!(plan_word(&m, &g, 1, 647).unwrap(), at(&m, "plan", (664 + 647) * 4)); - assert!(plan_word(&m, &g, 0, 648).is_err()); - assert!(plan_word(&m, &g, 2, 0).is_err()); - } -} +#[path = "original_verify_window_moe/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_verify_window_moe/tests.rs b/crates/cuda-driver/src/original_verify_window_moe/tests.rs new file mode 100644 index 00000000..08d3cf95 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_moe/tests.rs @@ -0,0 +1,720 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::super::kernels::{LayoutMap, test_geometry}; +use super::*; + +const BASE: u64 = 0x2000_0000; + +#[test] +fn the_alternative_pcie_staging_copy_kernels_are_sealed() { + PCIE_FAST.assert_sealed_and_fail_closed(); + assert!(PCIE_FAST.sealed().is_ok()); +} + +fn map() -> LayoutMap { + LayoutMap::new(BASE, test_geometry()) +} +fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { + m.span(name, offset, 4).unwrap() +} +fn rows(begin: usize, end: usize, group: usize) -> Rows { + Rows { begin, end, group } +} +fn weights() -> MoeLayerAddrs { + MoeLayerAddrs { + router: 0x9000_0000, + gate_inp_shexp: 0x9100_0000, + gate_shexp: NativeWeight { ty: 8, data: 0x9200_0000 }, + up_shexp: NativeWeight { ty: 8, data: 0x9300_0000 }, + down_shexp: NativeWeight { ty: 8, data: 0x9400_0000 }, + } +} +fn formats() -> OriginalVerifyExpertFormats { + OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 640).unwrap() +} +fn entries(l: &[Launch]) -> Vec<&'static str> { + l.iter().map(|x| x.entry).collect() +} + +// ---- assets ------------------------------------------------------------------------------ + +fn entry_declared(ptx: &str, e: &str) -> bool { + ptx.contains(&format!(".entry {e}(")) +} + +/// `.param` type tokens of an entry's parameter list (the first token after `.param`). +fn param_types(ptx: &str, entry: &str) -> Vec { + let head = format!(".entry {entry}("); + let start = ptx.find(&head).unwrap_or_else(|| panic!("{entry} missing")) + head.len(); + let rest = &ptx[start..]; + let end = rest.find("\n)").expect("parameter list end"); + rest[..end] + .lines() + .filter(|l| l.contains(".param")) + .map(|l| l.split_whitespace().nth(1).unwrap().to_string()) + .collect() +} +fn expected_type(a: &A) -> &'static str { + match a { + A::P(_) | A::I64(_) | A::U64(_) => ".u64", + A::I32(_) => ".u32", + A::F32(_) => ".f32", + A::Words(_) => ".align", + } +} + +#[test] +fn sealed_assets_are_pinned_and_export_every_named_entry() { + for spec in [&ELEMENT, &ROUTER, &ROUTER_LEGACY, &SHARED, &HEAD_IQ_EXPERT, &S2_HITS, &COMBINE] { + spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); + let text = String::from_utf8_lossy(spec.ptx); + for e in spec.entries { + assert!(entry_declared(&text, e), "{} lacks {e}", spec.name); + } + } + // the window's HEAD_IQ_EXPERT is the same file and pin as proj::HEAD_IQ + assert_eq!(HEAD_IQ_EXPERT.sha, proj::HEAD_IQ.sha); + assert!(HEAD_IQ_EXPERT.ptx == proj::HEAD_IQ.ptx); +} + +#[test] +fn expert_asset_is_sealed_and_a_corrupted_copy_still_refuses_to_load() { + // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim). + EXPERTS.assert_sealed_and_fail_closed(); + assert_eq!(EXPERTS.entries.len(), 16); + assert!(EXPERTS.unsealed.contains("original_verify_window_moe_experts.ptx")); +} + +#[test] +fn expert_entries_match_the_cu_source_and_the_original_format_lists() { + let cu = include_str!("../original_verify_window_moe_experts.cu"); + assert!(cu.contains("window_moe_gu_##T") && cu.contains("window_moe_down_##T")); + assert!(cu.contains("STRATA_GU_FMTS(STRATA_WINDOW_GU)") && cu.contains("STRATA_D_FMTS(STRATA_WINDOW_DOWN)")); + let iq = include_str!("../mtp_original_full_head_iq.cu"); + let parse = |macro_name: &str| -> Vec { + let line = iq.lines().find(|l| l.starts_with(&format!("#define {macro_name}(X)"))).expect(macro_name); + line.split("X(").skip(1).map(|s| s.split(')').next().unwrap().parse().unwrap()).collect() + }; + let gu: Vec = GU_ENTRIES.iter().map(|e| e.0).collect(); + let d: Vec = DOWN_ENTRIES.iter().map(|e| e.0).collect(); + assert_eq!(gu, parse("STRATA_GU_FMTS")); + assert_eq!(d, parse("STRATA_D_FMTS")); + for (t, name) in GU_ENTRIES { + assert_eq!(*name, format!("window_moe_gu_{t}")); + assert!(EXPERTS.has_entry(name) && gu_qk(*t) > 0); + } + for (t, name) in DOWN_ENTRIES { + assert_eq!(*name, format!("window_moe_down_{t}")); + assert!(EXPERTS.has_entry(name) && d_qk(*t) > 0); + } + assert_eq!(EXPERTS.entries.len(), GU_ENTRIES.len() + DOWN_ENTRIES.len()); + // the Original's per-type values-per-block (Fmt::qk) used by native_expert_supported + for (t, _) in GU_ENTRIES { + let want = format!("template<> struct Fmt<{t}> {{ static constexpr int qk = {},", gu_qk(*t)); + assert!(iq.contains(&want), "{want}"); + } + for (t, _) in DOWN_ENTRIES { + let want = format!("template<> struct Fmt<{t}> {{ static constexpr int qk = {},", d_qk(*t)); + assert!(iq.contains(&want), "{want}"); + } + assert_eq!((gu_qk(20), gu_qk(7), d_qk(16), d_qk(12), d_qk(0)), (0, 0, 0, 0, 0)); +} + +#[test] +fn asset_list_names_every_module_once() { + let a = assets(); + let mut names: Vec<&str> = a.iter().map(|s| s.name).collect(); + names.sort_unstable(); + let len = names.len(); + names.dedup(); + assert_eq!(names.len(), len, "duplicate asset names"); + assert!(a.iter().any(|s| std::ptr::eq(*s, &EXPERTS))); + assert!(shared_attributes(&MoeKnobs::mode17()).is_empty()); +} + +/// The ABI check: every launch of a SEALED asset names an entry whose `.param` list has exactly the +/// recorded argument count and widths. +fn assert_abi(launches: &[Launch]) { + for l in launches { + let text = String::from_utf8_lossy(l.asset.ptx); + let types = param_types(&text, l.entry); + let want: Vec<&str> = l.args.iter().map(expected_type).collect(); + assert_eq!(types, want, "{}", l.label()); + } +} + +// ---- router ------------------------------------------------------------------------------ + +#[test] +fn batched_router_is_one_gemv_and_one_top10_over_the_groups_rows() { + let m = map(); + let g = test_geometry(); + let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(3, 8, 1), true).unwrap(); + assert_eq!(l.len(), 2); + // bf16_gemv_fp32_mmvf_multi(mixed + 3*N, N, w, logits + 3*NE, NE, N, NE, 5): block 256, 5 rows -> 8-col kernel + assert!(l[0].entry.contains("ILi256ELi8EE")); + assert_eq!((l[0].grid, l[0].block), ([512, 1, 1], [256, 1, 1])); + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "mixed", 3 * 2560 * 4)), + A::I64(2560), + A::P(0x9000_0000), + A::P(at(&m, "logits", 3 * 512 * 4)), + A::I64(512), + A::I32(2560), + A::I32(5) + ] + ); + // native_router_top10_multi: route<<<5, (32, 8)>>>(logits + 3*NE, ids + 3*K, w + 3*K) + assert_eq!((l[1].entry, l[1].grid, l[1].block, l[1].shared), ("mtp_full_route", [5, 1, 1], [32, 8, 1], 0)); + assert_eq!( + l[1].args, + vec![A::P(at(&m, "logits", 3 * 512 * 4)), A::P(at(&m, "ids", 3 * 10 * 4)), A::P(at(&m, "w", 3 * 10 * 4))] + ); + assert_abi(&l); +} + +#[test] +fn batched_router_uses_the_four_column_kernel_up_to_four_rows() { + let m = map(); + let g = test_geometry(); + for n in 2..=4usize { + let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(0, n, 0), true).unwrap(); + assert!(l[0].entry.contains("ILi256ELi4EE"), "{n}"); + assert_eq!(l[1].grid, [n as u32, 1, 1]); + } +} + +#[test] +fn per_row_router_follows_moe_route_for_every_row() { + let m = map(); + let g = test_geometry(); + let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(1, 3, 0), false).unwrap(); + // row 1: bf16_gemv_fp32_mmvf(mixed + N, w, logits + NE, N, NE) + native_router_top10; then row 2 + assert_eq!(entries(&l), ["mtp_full_mmvf256", "mtp_full_route", "mtp_full_mmvf256", "mtp_full_route"]); + assert_eq!(l[0].grid, [512, 1, 1]); + assert_eq!( + l[0].args, + vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(0x9000_0000), A::P(at(&m, "logits", 512 * 4)), A::I32(2560)] + ); + assert_eq!((l[1].grid, l[1].block), ([1, 1, 1], [32, 8, 1])); + assert_eq!( + l[3].args, + vec![A::P(at(&m, "logits", 2 * 512 * 4)), A::P(at(&m, "ids", 2 * 10 * 4)), A::P(at(&m, "w", 2 * 10 * 4))] + ); + assert_abi(&l); +} + +#[test] +fn generic_router_is_the_original_router_top10_launch() { + let m = map(); + let g = test_geometry(); + let mut knobs = MoeKnobs::mode17(); + knobs.native_router = false; + let l = plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 1, 0), false).unwrap(); + assert_eq!(l.len(), 2); + // threads = 512, smem = 512 (taken) + 512*8 (doubles) + 512*4 (floats) = 6656 + assert_eq!((l[1].grid, l[1].block, l[1].shared), ([1, 1, 1], [512, 1, 1], 6656)); + assert_eq!( + l[1].args, + vec![ + A::P(at(&m, "logits", 0)), + A::I32(1), + A::I32(512), + A::I32(10), + A::P(at(&m, "ids", 0)), + A::P(at(&m, "w", 0)) + ] + ); + assert_abi(&l); + // the batched launch needs the native router + assert_eq!( + plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 2, 0), true).unwrap_err(), + Error::InvalidQwenShape + ); +} + +#[test] +fn router_fails_closed_precisely_without_native_bf16_and_on_bad_shapes() { + let m = map(); + let g = test_geometry(); + let mut knobs = MoeKnobs::mode17(); + knobs.native_bf16 = false; + let e = plan_router(&m, &g, &knobs, 1, rows(0, 1, 0), false).unwrap_err(); + match e { + Error::InvalidDriverValue(s) => { + assert!(s.starts_with("Original verifier producer unavailable: router: "), "{s}") + } + other => panic!("{other:?}"), + } + // the batched path never needs the bf16 conversion + assert!(plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 2, 0), true).is_ok()); + // batched with one row, empty rows, rows past the window, group C + let mode = MoeKnobs::mode17(); + assert!(plan_router(&m, &g, &mode, 1, rows(0, 1, 0), true).is_err()); + assert!(plan_router(&m, &g, &mode, 1, rows(2, 2, 0), false).is_err()); + assert!(plan_router(&m, &g, &mode, 1, rows(0, 9, 0), false).is_err()); + assert!(plan_router(&m, &g, &mode, 1, rows(0, 1, 2), false).is_err()); +} + +// ---- shared expert ----------------------------------------------------------------------- + +#[test] +fn batched_shared_expert_runs_the_shared_expert_multi_sequence_in_order() { + let m = map(); + let g = test_geometry(); + let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(2, 6, 1), true).unwrap(); + // f32_to_bf16_bulk(4 rows), quantize x, MMVQ gate, MMVQ up, swiglu, quantize h, MMVQ down, + // gate GEMV (multi), sigmoid (multi), scale rows + assert_eq!(l.len(), 10); + assert!(l[0].entry.ends_with("to_bf16_kernelEPKfPtl")); + assert_eq!((l[0].grid, l[0].block), ([40, 1, 1], [256, 1, 1])); // 4*2560 = 10240 elements + assert_eq!( + l[0].args, + vec![A::P(at(&m, "mixed", 2 * 2560 * 4)), A::P(at(&m, "sh_bf16", 2 * 2560 * 2)), A::I64(10240)] + ); + let xq = at(&m, "xq", 0); + let xm = at(&m, "mixed", 2 * 2560 * 4); + let gate = at(&m, "sh_gate", 2 * 640 * 4); + let up = at(&m, "sh_up", 2 * 640 * 4); + let shared = at(&m, "shared", 2 * 2560 * 4); + let gs = at(&m, "sh_g", 2 * 4); + assert_eq!(l[1].entry, "head_quant"); + assert_eq!(l[1].args, vec![A::P(xm), A::P(xq), A::I32(4 * 2560)]); + // gate/up: Q8_0, 4 columns: head_n8_t4_large, y rows n_ff floats apart + assert_eq!(l[2].entry, "head_n8_t4_large"); + assert_eq!(l[2].args, vec![A::P(0x9200_0000), A::P(xq), A::P(gate), A::I32(2560), A::I32(640)]); + assert_eq!(l[3].entry, "head_n8_t4_large"); + assert_eq!(l[3].args, vec![A::P(0x9300_0000), A::P(xq), A::P(up), A::I32(2560), A::I32(640)]); + // native_swiglu_kernel<<>>(gate, up, gate, 2560) + assert!(l[4].entry.ends_with("native_swiglu_kernelEPKfS3_Pfi")); + assert_eq!((l[4].grid, l[4].block), ([20, 1, 1], [128, 1, 1])); + assert_eq!(l[4].args, vec![A::P(gate), A::P(up), A::P(gate), A::I32(2560)]); + // quantize the activated gate (640 elements per row) in place into xq, then the down projection + assert_eq!(l[5].args, vec![A::P(gate), A::P(xq), A::I32(4 * 640)]); + // down: n_in = 640 values is "small" for Q8_0 (640/32 < 32 blocks per iteration) + assert_eq!(l[6].entry, "head_n8_t4_small"); + assert_eq!(l[6].args, vec![A::P(0x9400_0000), A::P(xq), A::P(shared), A::I32(640), A::I32(2560)]); + // the scalar gate: one GEMV (4 rows, ldy 1, n_out 1) and one sigmoid with thread t = token t + assert!(l[7].entry.contains("ILi256ELi4EE")); + assert_eq!(l[7].grid, [1, 1, 1]); + assert_eq!( + l[7].args, + vec![A::P(xm), A::I64(2560), A::P(0x9100_0000), A::P(gs), A::I64(1), A::I32(2560), A::I32(4)] + ); + assert!(l[8].entry.ends_with("native_scalar_sigmoid_multi_kernelEPf")); + assert_eq!((l[8].grid, l[8].block, l[8].args.clone()), ([1, 1, 1], [4, 1, 1], vec![A::P(gs)])); + // scale_rows_kernel<<<(20, 4), 128>>>(shared, g, 2560) + assert!(l[9].entry.ends_with("scale_rows_kernelEPfPKfi")); + assert_eq!((l[9].grid, l[9].block), ([20, 4, 1], [128, 1, 1])); + assert_eq!(l[9].args, vec![A::P(shared), A::P(gs), A::I32(2560)]); + assert_abi(&l); +} + +#[test] +fn single_row_shared_expert_uses_the_per_token_gate_and_single_row_projections() { + let m = map(); + let g = test_geometry(); + let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(0, 1, 0), true).unwrap(); + // bulk, quantize, gate, up, swiglu, quantize, down, [mmvf + sigmoid], scale + assert_eq!(l.len(), 10); + assert_eq!((l[2].entry, l[6].entry), ("head_n8_s0", "head_n8_s1")); + assert_eq!(l[7].entry, "mtp_full_mmvf256"); + assert_eq!(l[7].args, vec![A::P(at(&m, "mixed", 0)), A::P(0x9100_0000), A::P(at(&m, "sh_g", 0)), A::I32(2560)]); + assert!(l[8].entry.ends_with("native_scalar_sigmoid_kernelEPf")); + assert_eq!(l[8].block, [1, 1, 1]); + assert_eq!(l[9].grid, [20, 1, 1]); + assert_abi(&l); +} + +#[test] +fn shared_expert_without_dec_batch_converts_and_gates_one_row_at_a_time() { + let m = map(); + let g = test_geometry(); + let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(1, 3, 0), false).unwrap(); + // 2 conversions, the six projection / activation launches, 2 x (mmvf + sigmoid), scale + assert_eq!(l.len(), 2 + 6 + 4 + 1); + assert_eq!((l[0].grid, l[0].args.clone()), ([10, 1, 1], vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(at(&m, "sh_bf16", 2560 * 2)), A::I64(2560)])); + assert_eq!(l[1].args[1], A::P(at(&m, "sh_bf16", 2 * 2560 * 2))); + // the projections are still two-row launches, but the gate is per token + assert_eq!(l[3].entry, "head_n8_t2_large"); + assert_eq!( + l[8].args, + vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(0x9100_0000), A::P(at(&m, "sh_g", 4)), A::I32(2560)] + ); + assert_eq!(l[10].args[2], A::P(at(&m, "sh_g", 2 * 4))); + assert_eq!(l[12].grid, [20, 2, 1]); + assert_abi(&l); +} + +#[test] +fn shared_gate_without_native_bf16_extra_reads_the_bf16_activation() { + let m = map(); + let g = test_geometry(); + let mut knobs = MoeKnobs::mode17(); + knobs.native_bf16_extra = false; + let l = plan_shared_expert(&m, &g, &knobs, &weights(), rows(0, 2, 0), true).unwrap(); + // one scalar_gate_kernel<<<1, 256>>>(x_bf16 + t*N, w, g + t, N) per token, no GEMV / sigmoid + let gates: Vec<&Launch> = l.iter().filter(|x| x.entry.ends_with("scalar_gate_kernelEPKtS3_Pfi")).collect(); + assert_eq!(gates.len(), 2); + assert_eq!((gates[0].grid, gates[0].block), ([1, 1, 1], [256, 1, 1])); + assert_eq!( + gates[1].args, + vec![A::P(at(&m, "sh_bf16", 2560 * 2)), A::P(0x9100_0000), A::P(at(&m, "sh_g", 4)), A::I32(2560)] + ); + assert!(!l.iter().any(|x| x.entry.contains("sigmoid"))); + assert_abi(&l); +} + +#[test] +fn shared_expert_covers_every_window_size() { + let m = map(); + let g = test_geometry(); + for n in 1..=8usize { + let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(0, n, 0), true).unwrap(); + assert_eq!(l.last().unwrap().grid, [20, n as u32, 1]); + assert_eq!(l[4].grid, [(640 * n).div_ceil(128) as u32, 1, 1]); + assert_abi(&l); + } +} + +// ---- expert input, groups ---------------------------------------------------------------- + +#[test] +fn expert_input_is_the_q8_1_row_quantizer_into_nat_xq() { + let m = map(); + let g = test_geometry(); + let l = plan_quantize_expert_input(&m, &g, &MoeKnobs::mode17(), rows(4, 8, 1)).unwrap(); + assert_eq!(l.len(), 1); + assert!(l[0].entry.ends_with("quantize_q8_1_kernelEPKfP10block_q8_1x")); + assert_eq!((l[0].grid, l[0].block), ([40, 1, 1], [256, 1, 1])); + assert_eq!( + l[0].args, + vec![A::P(at(&m, "mixed", 4 * 2560 * 4)), A::P(at(&m, "nat_xq", 4 * 2880)), A::I64(4 * 2560)] + ); + assert_abi(&l); + let mut s2 = MoeKnobs::mode17(); + s2.native_experts = false; + assert!(matches!( + plan_quantize_expert_input(&m, &g, &s2, rows(0, 1, 0)), + Err(Error::InvalidDriverValue(s)) if s.contains("quantize_expert_input") + )); +} + +#[test] +fn expert_blob_layout_matches_native_expert_layout() { + // IQ2_XXS gate/up (66 B per 256), IQ4_NL down (18 B per 32): n_embd 2560, n_ff 640 + let b = expert_blob(16, 20, 2560, 640).unwrap(); + assert_eq!((b.gu_row, b.d_row), (10 * 66, 20 * 18)); + assert_eq!((b.up_off, b.down_off), (640 * 660, 2 * 640 * 660)); + assert_eq!(b.bytes, 844_800 + 2560 * 360); + assert_eq!(b.bytes % 16, 0); + assert_eq!( + b.words(), + vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400] + ); + // Q4_K gate/up (144 B per 256) and Q8_0 down (34 B per 32) + let q = expert_blob(12, 8, 2560, 640).unwrap(); + assert_eq!((q.gu_row, q.d_row, q.bytes), (1440, 680, 2 * 640 * 1440 + 2560 * 680)); + // Q2_0 (64 values, 18 B) on both sides + let z = expert_blob(42, 42, 2560, 640).unwrap(); + assert_eq!((z.gu_row, z.d_row), (40 * 18, 10 * 18)); + // IQ4_XS down needs n_ff % 256 == 0: 640 is not; IQ4_NL gate/up and unknown types are refused + assert_eq!(expert_blob(16, 23, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); + assert_eq!(expert_blob(20, 20, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); + assert_eq!(expert_blob(16, 99, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); + assert_eq!(expert_blob(16, 20, 2560, 650).unwrap_err(), Error::UnsupportedQwenOperation); +} + +#[test] +fn expert_formats_validate_all_layers_and_report_blob_bytes() { + let f = formats(); + assert_eq!(f.blob_bytes(0), Ok(1_766_400)); + assert_eq!(f.blob_bytes(47), Ok(1_766_400)); + assert!(f.blob_bytes(48).is_err()); + let mut mixed = [(16, 20); WINDOW_LAYERS]; + mixed[10] = (12, 8); + let f = OriginalVerifyExpertFormats::new(mixed, 2560, 640).unwrap(); + assert_eq!(f.blob_bytes(10), Ok(2 * 640 * 1440 + 2560 * 680)); + assert_eq!(f.blob_bytes(11), Ok(1_766_400)); + mixed[30] = (20, 20); + assert_eq!(OriginalVerifyExpertFormats::new(mixed, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); +} + +#[test] +fn expert_scratch_follows_native_expert_scratch_bytes() { + // gate | up | h each cap*n_ff floats rounded to 256, then cap*(n_ff/32) q8_1 blocks rounded to 256 + assert_eq!(expert_scratch(10, 640), (25_600, 3 * 25_600 + 7_424)); // 10*20*36 = 7200 -> 7424 + assert_eq!(expert_scratch(80, 640), (204_800, 3 * 204_800 + 80 * 20 * 36)); + // rounding path (never reached by n_ff = 640 where cap * n_ff * 4 is a multiple of 256) + assert_eq!(expert_scratch(1, 100), (512, 3 * 512 + 256)); +} + +#[test] +fn vram_tier_reads_the_first_plan_arrays() { + let m = map(); + let g = test_geometry(); + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 5, rows(0, 3, 0), ExpertTier::Vram); + // the plan itself is pure data + let l = l.unwrap(); + assert_eq!(entries(&l).len(), 4); + // PlanLayout(capx = 80): start 4, dst 85, tok 165, ptr 246, ptr2 406, start2 566; device stride 664 words + let plan = |word: usize| at(&m, "plan", word * 4); + let scratch = at(&m, "hit_scratch", 0); + let xq = at(&m, "nat_xq", 0); + let fa = 3 * 10 * 640 * 4; + // gate/up: grid ((2*640+7)/8 = 160, cap = 30), 256 threads + assert_eq!((l[0].entry, l[0].grid, l[0].block, l[0].shared), ("window_moe_gu_16", [160, 30, 1], [256, 1, 1], 0)); + assert_eq!( + l[0].args, + vec![ + A::P(plan(246)), + A::P(plan(4)), + A::P(plan(0)), + A::P(plan(165)), + A::P(xq), + A::Words(vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400]), + A::P(scratch), + A::P(scratch + fa as u64) + ] + ); + // swiglu_entries and quantize over cap * n_ff = 19200 values + assert!(l[1].entry.ends_with("swiglu_entries_kernelEPKfS3_Pfx")); + assert_eq!((l[1].grid, l[1].block), ([75, 1, 1], [256, 1, 1])); + assert_eq!( + l[1].args, + vec![A::P(scratch), A::P(scratch + fa as u64), A::P(scratch + 2 * fa as u64), A::I64(19_200)] + ); + assert!(l[2].entry.ends_with("quantize_q8_1_kernelEPKfP10block_q8_1x")); + assert_eq!(l[2].args, vec![A::P(scratch + 2 * fa as u64), A::P(scratch + 3 * fa as u64), A::I64(19_200)]); + // down: grid ((2560+7)/8 = 320, 30) + assert_eq!((l[3].entry, l[3].grid), ("window_moe_down_20", [320, 30, 1])); + assert_eq!( + l[3].args, + vec![ + A::P(plan(246)), + A::P(plan(4)), + A::P(plan(0)), + A::P(plan(85)), + A::P(scratch + 3 * fa as u64), + A::Words(vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400]), + A::P(at(&m, "hit_out", 0)) + ] + ); + assert_abi(&l[1..3]); +} + +#[test] +fn pcie_tier_uses_the_second_pointer_start_and_count_of_the_group() { + let m = map(); + let g = test_geometry(); + // group B of a 5-row window: rows 3..5, plan block of group 1 (664 words further) + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 0, rows(3, 5, 1), ExpertTier::Pcie).unwrap(); + let plan = |word: usize| at(&m, "plan", (664 + word) * 4); + assert_eq!( + l[0].args[..5], + [A::P(plan(406)), A::P(plan(566)), A::P(plan(2)), A::P(plan(165)), A::P(at(&m, "nat_xq", 3 * 2880))] + ); + assert_eq!(l[0].grid, [160, 20, 1]); + assert_eq!( + l[3].args[..4], + [A::P(plan(406)), A::P(plan(566)), A::P(plan(2)), A::P(plan(85))] + ); + // output rows of the group start at tb*K*N + assert_eq!(l[3].args[6], A::P(at(&m, "hit_out", 3 * 10 * 2560 * 4))); + assert_eq!(l[3].grid, [320, 20, 1]); +} + +#[test] +fn expert_groups_pick_the_kernels_of_the_layers_formats() { + let m = map(); + let g = test_geometry(); + let mut fmts = [(16, 20); WINDOW_LAYERS]; + fmts[7] = (12, 8); + fmts[8] = (42, 42); + fmts[9] = (13, 7); + let f = OriginalVerifyExpertFormats::new(fmts, 2560, 640).unwrap(); + let pick = |layer: usize| { + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, layer, rows(0, 1, 0), ExpertTier::Vram).unwrap(); + (l[0].entry, l[3].entry) + }; + assert_eq!(pick(0), ("window_moe_gu_16", "window_moe_down_20")); + assert_eq!(pick(7), ("window_moe_gu_12", "window_moe_down_8")); + assert_eq!(pick(8), ("window_moe_gu_42", "window_moe_down_42")); + assert_eq!(pick(9), ("window_moe_gu_13", "window_moe_down_7")); + // every launch names an entry of its asset + for t in 0..8usize { + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, 7, rows(0, t + 1, 0), ExpertTier::Pcie).unwrap(); + assert_eq!(l[0].grid[1], ((t + 1) * 10) as u32); + assert_eq!(l[3].grid[1], ((t + 1) * 10) as u32); + } +} + +#[test] +fn gu_swiglu_replaces_gate_up_swiglu_and_quantize_by_one_launch_and_keeps_the_down_kernel() { + let m = map(); + let g = test_geometry(); + let mut fmts = [(16, 20); WINDOW_LAYERS]; + fmts[7] = (12, 8); + fmts[8] = (22, 20); + let f = OriginalVerifyExpertFormats::new(fmts, 2560, 640).unwrap(); + let mut on = MoeKnobs::mode17(); + on.gu_swiglu = true; + let off = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap(); + let fused = plan_expert_groups(&m, &g, &on, &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap(); + assert_eq!(entries(&fused), ["sm120_moe_gu_swiglu_16", "window_moe_down_20"]); + assert_eq!((fused[0].grid, fused[0].block, fused[0].shared), ([20, 30, 1], [512, 1, 1], 0)); + // the arguments: the same group tables, activations and q8_1 output as the three kernels, upstream's 88-byte layout + let gu = &off[0].args; + let scratch_hq = match &off[2].args[1] { A::P(p) => *p, _ => unreachable!() }; + assert_eq!(fused[0].args[..5], gu[..5]); + assert_eq!(fused[0].args[6], A::P(scratch_hq)); + match (&fused[0].args[5], &gu[5]) { + (A::Words(n), A::Words(o)) => { + assert_eq!((n.len(), o.len()), (11, 8)); + assert_eq!(n[..8], o[..]); + assert_eq!(n[8..], [0, 0, 0]); + } + _ => panic!("layout words"), + } + // the down kernel is untouched (same arguments, reading the same hq) + assert_eq!(fused[1].args, off[3].args); + assert_eq!(fused[1].entry, off[3].entry); + // layers whose gate/up format has no fused kernel keep the three-kernel plan; so does a knobs set without the switch + assert_eq!(entries(&plan_expert_groups(&m, &g, &on, &f, 7, rows(0, 3, 0), ExpertTier::Vram).unwrap())[0], "window_moe_gu_12"); + assert_eq!(entries(&plan_expert_groups(&m, &g, &on, &f, 8, rows(0, 3, 0), ExpertTier::Pcie).unwrap())[0], "sm120_moe_gu_swiglu_22"); + assert_eq!(entries(&off).len(), 4); +} + +#[test] +fn expert_groups_refuse_s2_and_a_mismatched_geometry() { + let m = map(); + let g = test_geometry(); + let mut s2 = MoeKnobs::mode17(); + s2.native_experts = false; + assert!(matches!( + plan_expert_groups(&m, &g, &s2, &formats(), 0, rows(0, 1, 0), ExpertTier::Vram), + Err(Error::InvalidDriverValue(s)) if s.contains("expert_groups") + )); + let other = OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 1280).unwrap(); + assert_eq!( + plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &other, 0, rows(0, 1, 0), ExpertTier::Vram).unwrap_err(), + Error::InvalidQwenShape + ); + assert!(plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 48, rows(0, 1, 0), ExpertTier::Vram).is_err()); +} + +#[test] +fn expert_launches_load_when_sealed_and_are_refused_on_a_corrupted_pin() { + let m = map(); + let g = test_geometry(); + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 0, rows(0, 1, 0), ExpertTier::Vram).unwrap(); + assert!(std::ptr::eq(l[0].asset, &EXPERTS)); + assert!(l[0].asset.sealed().is_ok()); + assert!(l[1].asset.sealed().is_ok()); + // The same launch against a one-byte-corrupted copy of the asset (synthetic; the real PTX is untouched) + // is refused with the asset's refusal text, exactly as the unsealed placeholder was. + let bad = EXPERTS.derived(crate::sealed_ptx::test_support::one_byte_corrupted(EXPERTS.ptx), EXPERTS.sha); + let launch = Launch::new(bad, l[0].entry, l[0].grid, l[0].block, l[0].shared, l[0].args.clone()).unwrap(); + assert_eq!(launch.asset.sealed().unwrap_err(), Error::InvalidDriverValue(EXPERTS.unsealed)); + assert!(launch.command().is_ok(), "the plan itself is pure data and unaffected"); +} + +// ---- hit add, combine ---------------------------------------------------------------------- + +#[test] +fn hit_add_scans_the_cpu_and_gpu_hits_of_the_group() { + let m = map(); + let g = test_geometry(); + let l = plan_hit_add(&m, &g, rows(3, 5, 1)).unwrap(); + assert_eq!(l.len(), 1); + assert!(l[0].entry.ends_with("add_hits_kernelEPfPKfPKiS6_i")); + // grid (min(ceil(2560/256), 8) = 8, cap = 20), 256 threads + assert_eq!((l[0].grid, l[0].block), ([8, 20, 1], [256, 1, 1])); + let plan = |word: usize| at(&m, "plan", (664 + word) * 4); + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "parts", 3 * 10 * 2560 * 4)), + A::P(at(&m, "hit_out", 3 * 10 * 2560 * 4)), + A::P(plan(85)), + A::P(plan(1)), + A::I32(2560) + ] + ); + assert_abi(&l); + assert_eq!(plan_hit_add(&m, &g, rows(0, 1, 0)).unwrap()[0].grid, [8, 10, 1]); +} + +#[test] +fn batched_combine_is_one_launch_with_the_token_on_grid_y() { + let m = map(); + let g = test_geometry(); + let l = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(0, 8, 0), true).unwrap(); + assert_eq!(l.len(), 1); + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("mtp_full_combine", [10, 8, 1], [256, 1, 1])); + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "parts", 0)), + A::P(at(&m, "w", 0)), + A::P(at(&m, "shared", 0)), + A::P(at(&m, "bo", 0)), + A::I64(2560), + A::I32(10) + ] + ); + assert_abi(&l); + let b = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(4, 7, 1), true).unwrap(); + assert_eq!(b[0].grid, [10, 3, 1]); + assert_eq!(b[0].args[0], A::P(at(&m, "parts", 4 * 10 * 2560 * 4))); + assert_eq!(b[0].args[1], A::P(at(&m, "w", 4 * 10 * 4))); + assert_eq!(b[0].args[2], A::P(at(&m, "shared", 4 * 2560 * 4))); + assert_eq!(b[0].args[3], A::P(at(&m, "bo", 4 * 2560 * 4))); +} + +#[test] +fn per_row_combine_is_native_combine_per_token_or_the_legacy_kernel() { + let m = map(); + let g = test_geometry(); + let l = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(1, 3, 0), false).unwrap(); + assert_eq!(l.len(), 2); + assert_eq!((l[1].grid, l[1].block), ([10, 1, 1], [256, 1, 1])); + assert_eq!( + l[1].args, + vec![ + A::P(at(&m, "parts", 2 * 10 * 2560 * 4)), + A::P(at(&m, "w", 2 * 10 * 4)), + A::P(at(&m, "shared", 2 * 2560 * 4)), + A::P(at(&m, "bo", 2 * 2560 * 4)), + A::I64(2560), + A::I32(10) + ] + ); + assert_abi(&l); + // a single-row window is never batched, even with native combine on + let one = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(0, 1, 0), false).unwrap(); + assert_eq!((one[0].entry, one[0].grid), ("mtp_full_combine", [10, 1, 1])); + // moe_combine<<>>(parts, w, shared, y, N, K, has_shared = 1) + let mut legacy = MoeKnobs::mode17(); + legacy.native_combine = false; + let l = plan_combine(&m, &g, &legacy, rows(0, 2, 0), false).unwrap(); + assert_eq!(l.len(), 2); + assert!(l[0].entry.ends_with("moe_combine_kernelEPKfS3_S3_Pfiii")); + assert_eq!((l[0].grid, l[0].block), ([20, 1, 1], [128, 1, 1])); + assert_eq!(l[1].args[4..], [A::I32(2560), A::I32(10), A::I32(1)]); + assert_abi(&l); + assert_eq!(plan_combine(&m, &g, &legacy, rows(0, 2, 0), true).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(plan_combine(&m, &g, &MoeKnobs::mode17(), rows(0, 1, 0), true).unwrap_err(), Error::InvalidQwenShape); +} + +#[test] +fn plan_word_stays_inside_the_plan_span_and_the_two_groups() { + let m = map(); + let g = test_geometry(); + assert_eq!(plan_word(&m, &g, 0, 0).unwrap(), at(&m, "plan", 0)); + assert_eq!(plan_word(&m, &g, 1, 647).unwrap(), at(&m, "plan", (664 + 647) * 4)); + assert!(plan_word(&m, &g, 0, 648).is_err()); + assert!(plan_word(&m, &g, 2, 0).is_err()); +} diff --git a/crates/cuda-driver/src/original_verify_window_ops.rs b/crates/cuda-driver/src/original_verify_window_ops.rs index afe7b965..0ea466d4 100644 --- a/crates/cuda-driver/src/original_verify_window_ops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops.rs @@ -734,87 +734,5 @@ pub(crate) fn graph_oom_at(error: Error, window: usize) -> Error { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_graph_out_of_memory_is_named_by_the_graph_that_did_not_fit_and_nothing_else_is() { - let oom = Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }; - assert_eq!(graph_oom_at(oom.clone(), 5), Error::GraphOutOfMemory { window: 5 }); - assert_eq!(graph_oom_at(oom.clone(), 0), Error::GraphOutOfMemory { window: 0 }); - // the upload warm-up is not an instantiate, but it shares the code and is treated the same by the capture - assert_eq!( - graph_oom_at(Error::Driver { operation: "cuGraphUpload", code: 2 }, 3), - Error::GraphOutOfMemory { window: 3 } - ); - // another code, another call, and an out-of-memory that carries a cleanup failure all stay fatal as they were - for other in [ - Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 1 }, - Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 700 }, - Error::Driver { operation: "cuStreamEndCapture", code: 2 }, - Error::ContextPoisoned, - Error::InvalidQwenShape, - Error::Multiple { primary: Box::new(oom.clone()), secondary: Box::new(Error::ContextPoisoned) }, - ] { - assert_eq!(graph_oom_at(other.clone(), 4), other); - } - assert!(graph_oom_at(oom, 2).to_string().contains("T=2")); - assert!(Error::GraphOutOfMemory { window: 0 }.to_string().contains("commit")); - } - - #[test] - fn every_window_asset_is_sealed_and_a_corrupted_pin_is_reported_by_name() { - // Sealed with nvcc 13.2.86 on 2026-10-15, so nothing is unsealed and a window may be recorded. - assert_eq!(unsealed_window_assets(), Vec::<&str>::new()); - let all = all_window_assets(); - assert!(!all.is_empty()); - for spec in &all { - spec.assert_sealed_and_fail_closed(); - } - // The two NEW sources (grouped native experts, fast-math QSA gate) are real sealed PTX too. - for new in [&moe::EXPERTS, &qsa::GATE] { - assert!(all.iter().any(|a| std::ptr::eq(*a, new)), "{}", new.name); - } - // Fail-closed reporting is alive: a one-byte-corrupted copy, a wrong digest and a zero pin of a sealed asset - // are each reported by module key (once), and the untouched specs stay out of the list. - let corrupted = moe::EXPERTS.derived(crate::sealed_ptx::test_support::one_byte_corrupted(moe::EXPERTS.ptx), moe::EXPERTS.sha); - let wrong_digest = qsa::GATE.derived(qsa::GATE.ptx, [7; 32]); - let zero_pin = gr::assets()[0].derived(gr::assets()[0].ptx, [0; 32]); - assert_eq!( - unsealed_keys([corrupted, &qsa::GATE, wrong_digest, zero_pin, corrupted]), - [corrupted.key(), wrong_digest.key(), zero_pin.key()] - ); - assert!(unsealed_keys([&moe::EXPERTS, &qsa::GATE]).is_empty()); - } - - #[test] - fn every_window_asset_is_listed_once_and_names_a_distinct_module() { - let all = all_window_assets(); - let mut keys: Vec<&str> = all.iter().map(|a| a.key()).collect(); - let count = keys.len(); - keys.sort_unstable(); - keys.dedup(); - // specs of one PTX file share a key (entries are unioned by the loader); no key hides two different files - assert!(keys.len() <= count); - for key in &keys { - let mut pins = all.iter().filter(|a| a.key() == *key).map(|a| (a.sha, a.ptx.len())); - let first = pins.next().unwrap(); - assert!(pins.all(|p| p == first), "{key}: specs of one module disagree on the file"); - } - assert!(UNBOUND_PRODUCERS.is_empty()); - } - - #[test] - fn expert_layout_requires_whole_16_byte_blobs_within_the_staging_bound() { - assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 4 << 20).is_ok()); - assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 1 << 19).is_err()); - let mut odd = [1 << 20; WINDOW_LAYERS]; - odd[7] = (1 << 20) + 8; - assert!(OriginalVerifyExpertLayout::new(odd, 4 << 20).is_err()); - let mut zero = [1 << 20; WINDOW_LAYERS]; - zero[0] = 0; - assert!(OriginalVerifyExpertLayout::new(zero, 4 << 20).is_err()); - assert_eq!(OriginalVerifyExpertLayout::new([32; WINDOW_LAYERS], 64).unwrap().blob_bytes(47), Ok(32)); - assert!(OriginalVerifyExpertLayout::new([32; WINDOW_LAYERS], 64).unwrap().blob_bytes(48).is_err()); - } -} +#[path = "original_verify_window_ops/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_verify_window_ops/tests.rs b/crates/cuda-driver/src/original_verify_window_ops/tests.rs new file mode 100644 index 00000000..f745de10 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_ops/tests.rs @@ -0,0 +1,84 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn a_graph_out_of_memory_is_named_by_the_graph_that_did_not_fit_and_nothing_else_is() { + let oom = Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }; + assert_eq!(graph_oom_at(oom.clone(), 5), Error::GraphOutOfMemory { window: 5 }); + assert_eq!(graph_oom_at(oom.clone(), 0), Error::GraphOutOfMemory { window: 0 }); + // the upload warm-up is not an instantiate, but it shares the code and is treated the same by the capture + assert_eq!( + graph_oom_at(Error::Driver { operation: "cuGraphUpload", code: 2 }, 3), + Error::GraphOutOfMemory { window: 3 } + ); + // another code, another call, and an out-of-memory that carries a cleanup failure all stay fatal as they were + for other in [ + Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 1 }, + Error::Driver { operation: "cuGraphInstantiateWithFlags", code: 700 }, + Error::Driver { operation: "cuStreamEndCapture", code: 2 }, + Error::ContextPoisoned, + Error::InvalidQwenShape, + Error::Multiple { primary: Box::new(oom.clone()), secondary: Box::new(Error::ContextPoisoned) }, + ] { + assert_eq!(graph_oom_at(other.clone(), 4), other); + } + assert!(graph_oom_at(oom, 2).to_string().contains("T=2")); + assert!(Error::GraphOutOfMemory { window: 0 }.to_string().contains("commit")); +} + +#[test] +fn every_window_asset_is_sealed_and_a_corrupted_pin_is_reported_by_name() { + // Sealed with nvcc 13.2.86 on 2026-10-15, so nothing is unsealed and a window may be recorded. + assert_eq!(unsealed_window_assets(), Vec::<&str>::new()); + let all = all_window_assets(); + assert!(!all.is_empty()); + for spec in &all { + spec.assert_sealed_and_fail_closed(); + } + // The two NEW sources (grouped native experts, fast-math QSA gate) are real sealed PTX too. + for new in [&moe::EXPERTS, &qsa::GATE] { + assert!(all.iter().any(|a| std::ptr::eq(*a, new)), "{}", new.name); + } + // Fail-closed reporting is alive: a one-byte-corrupted copy, a wrong digest and a zero pin of a sealed asset + // are each reported by module key (once), and the untouched specs stay out of the list. + let corrupted = moe::EXPERTS.derived(crate::sealed_ptx::test_support::one_byte_corrupted(moe::EXPERTS.ptx), moe::EXPERTS.sha); + let wrong_digest = qsa::GATE.derived(qsa::GATE.ptx, [7; 32]); + let zero_pin = gr::assets()[0].derived(gr::assets()[0].ptx, [0; 32]); + assert_eq!( + unsealed_keys([corrupted, &qsa::GATE, wrong_digest, zero_pin, corrupted]), + [corrupted.key(), wrong_digest.key(), zero_pin.key()] + ); + assert!(unsealed_keys([&moe::EXPERTS, &qsa::GATE]).is_empty()); +} + +#[test] +fn every_window_asset_is_listed_once_and_names_a_distinct_module() { + let all = all_window_assets(); + let mut keys: Vec<&str> = all.iter().map(|a| a.key()).collect(); + let count = keys.len(); + keys.sort_unstable(); + keys.dedup(); + // specs of one PTX file share a key (entries are unioned by the loader); no key hides two different files + assert!(keys.len() <= count); + for key in &keys { + let mut pins = all.iter().filter(|a| a.key() == *key).map(|a| (a.sha, a.ptx.len())); + let first = pins.next().unwrap(); + assert!(pins.all(|p| p == first), "{key}: specs of one module disagree on the file"); + } + assert!(UNBOUND_PRODUCERS.is_empty()); +} + +#[test] +fn expert_layout_requires_whole_16_byte_blobs_within_the_staging_bound() { + assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 4 << 20).is_ok()); + assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 1 << 19).is_err()); + let mut odd = [1 << 20; WINDOW_LAYERS]; + odd[7] = (1 << 20) + 8; + assert!(OriginalVerifyExpertLayout::new(odd, 4 << 20).is_err()); + let mut zero = [1 << 20; WINDOW_LAYERS]; + zero[0] = 0; + assert!(OriginalVerifyExpertLayout::new(zero, 4 << 20).is_err()); + assert_eq!(OriginalVerifyExpertLayout::new([32; WINDOW_LAYERS], 64).unwrap().blob_bytes(47), Ok(32)); + assert!(OriginalVerifyExpertLayout::new([32; WINDOW_LAYERS], 64).unwrap().blob_bytes(48).is_err()); +} diff --git a/crates/cuda-driver/src/original_verify_window_planner.rs b/crates/cuda-driver/src/original_verify_window_planner.rs index b4a95341..6d305af9 100644 --- a/crates/cuda-driver/src/original_verify_window_planner.rs +++ b/crates/cuda-driver/src/original_verify_window_planner.rs @@ -164,414 +164,5 @@ impl<'p> Planner<'p> { } #[cfg(test)] -mod tests { - use super::super::kernels::{LayoutMap, test_geometry}; - use super::super::moe::MoeLayerAddrs; - use super::super::proj::NativeWeight; - use super::super::qsa::{OriginalVerifyQsaKvBinding, QsaWeightAddrs}; - use super::super::window_plan::WINDOW_LAYERS; - use super::super::window_record::{WindowOps, record_window}; - use super::*; - - const BASE: u64 = 0x7000_0000_0000; - - /// Synthetic weights: every layer's operands get distinct, 256-aligned addresses. - struct Fake { - formats: OriginalVerifyExpertFormats, - ple: bool, - } - fn w(a: u64) -> NativeWeight { - NativeWeight { ty: 14, data: a } - } - impl WindowWeights for Fake { - fn gdn_projections(&self, g: usize) -> Result { - let b = 0x10_0000_0000u64 + g as u64 * 0x1000_0000; - Ok(GdnProjectionAddrs { qkv: w(b), gate: NativeWeight { ty: 8, data: b + 0x100_0000 }, out: NativeWeight { ty: 12, data: b + 0x200_0000 } }) - } - fn qsa_projections(&self, q: usize) -> Result { - let b = 0x20_0000_0000u64 + q as u64 * 0x1000_0000; - Ok(QsaProjectionAddrs { - k: NativeWeight { ty: 12, data: b }, - v: NativeWeight { ty: 12, data: b + 0x100_0000 }, - q: w(b + 0x200_0000), - out: w(b + 0x300_0000), - }) - } - fn hc(&self, layer: usize, half: HcHalf) -> Result { - let b = 0x30_0000_0000u64 + layer as u64 * 0x1_0000_0000 + if half == HcHalf::Ffn { 0x8000_0000 } else { 0 }; - Ok(HcAddrs { norm: b, down: b + 0x100_0000, up: b + 0x200_0000, inject: b + 0x300_0000 }) - } - fn head(&self) -> Result { - Ok(HeadAddrs { norm: 0x3f_0000_0000, down: 0x3f_0100_0000, up: 0x3f_0200_0000 }) - } - fn ple(&self) -> Result> { - Ok(self.ple.then_some(PleAddrs { - key: gr::PleKey::Bf16(0x40_0000_0000), - value: 0x40_1000_0000, - norm_key: 0x40_2000_0000, - norm_query: 0x40_2100_0000, - norm_conv: 0x40_2200_0000, - conv1d: 0x40_2300_0000, - scratch: 0x40_3000_0000, - history: 0x40_4000_0000, - })) - } - fn qsa(&self, q: usize) -> Result { - let b = 0x50_0000_0000u64 + q as u64 * 0x1_0000_0000; - Ok(QsaLayerAddrs { - weights: QsaWeightAddrs { q_norm: b, k_norm: b + 0x1_0000, index_q_norm: b + 0x2_0000, index_k_proj: b + 0x100_0000, index_q_proj: b + 0x200_0000 }, - kv: OriginalVerifyQsaKvBinding { - resident: [b + 0x1000_0000, b + 0x1100_0000, b + 0x1200_0000, b + 0x1210_0000], - table: b + 0x1300_0000, - host: [b + 0x2000_0000, b + 0x2100_0000, b + 0x2200_0000, b + 0x2210_0000], - resolver: [b + 0x1300_0000, b + 0x1310_0000, b + 0x1320_0000, b + 0x1330_0000, b + 0x1340_0000, b + 0x1350_0000, b + 0x1360_0000], - slots: 8192, - pooled: b + 0x1400_0000, - pooled_bytes: 1026 * 512, - dead: b + 0x1410_0000, - dead_bytes: 512, - }, - }) - } - fn rope(&self) -> Result { - QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0) - } - fn moe(&self, layer: usize) -> Result { - let b = 0x60_0000_0000u64 + layer as u64 * 0x1_0000_0000; - Ok(MoeLayerAddrs { - router: b, - gate_inp_shexp: b + 0x100_0000, - gate_shexp: NativeWeight { ty: 8, data: b + 0x200_0000 }, - up_shexp: NativeWeight { ty: 8, data: b + 0x300_0000 }, - down_shexp: NativeWeight { ty: 8, data: b + 0x400_0000 }, - }) - } - fn expert_formats(&self) -> Result<&OriginalVerifyExpertFormats> { - Ok(&self.formats) - } - } - - /// Readable name of a launched kernel: the entry, or for a mangled Original kernel its base name. - fn kernel(l: &Launch) -> String { - const BASES: [&str; 14] = [ - "mmvf_multi_kernel", "mmvf_kernel", "to_bf16_kernel", "native_swiglu_kernel", "scalar_gate_kernel", - "native_scalar_sigmoid_multi_kernel", "native_scalar_sigmoid_kernel", "scale_rows_kernel", "moe_combine_kernel", - "swiglu_entries_kernel", "quantize_q8_1_kernel", "add_hits_kernel", "router_top10_kernel", "block_scores_kernel", - ]; - if !l.entry.starts_with("_ZN") { - return l.entry.to_string(); - } - BASES.iter().find(|b| l.entry.contains(*b)).map(|b| b.to_string()).unwrap_or_else(|| l.entry.to_string()) - } - - /// The recorder driven through the planners with no driver: every producer logs the kernels it would - /// launch (journal-owned producers log a marker). `fail` makes the named producer error. - struct PlanOps<'p> { - planner: Planner<'p>, - log: Vec, - t: usize, - } - impl PlanOps<'_> { - fn plan(&mut self, name: &str, r: Result>) -> Result<()> { - let launches = r?; - self.log.push(format!("<{name}")); - for l in &launches { - self.log.push(kernel(l)); - } - self.log.push(format!("{name}>")); - Ok(()) - } - fn mark(&mut self, s: String) -> Result<()> { - self.log.push(s); - Ok(()) - } - } - impl WindowOps for PlanOps<'_> { - fn embed(&mut self) -> Result<()> { self.mark("embed".into()) } - fn stamp(&mut self, l: usize, s: usize) -> Result<()> { self.mark(format!("stamp {l}.{s}")) } - fn ple_layer1(&mut self, rows: Rows) -> Result<()> { - let per = self.planner.ple_layer1(rows)?; - for (row, launches) in per { - self.log.push(format!(" Result<()> { - let x = self.planner.hc_read(l, h, a, r); - self.plan(&format!("hc {h:?} apply={a}"), x) - } - fn quantize_q8_1(&mut self, _: usize, s: QuantSource, r: Rows) -> Result<()> { - let x = self.planner.quantize_q8_1(s, r); - self.plan(&format!("quant {s:?}"), x) - } - fn mmvq(&mut self, l: usize, p: Projection, r: Rows) -> Result<()> { - let x = self.planner.mmvq(l, p, r); - self.plan(&format!("mmvq {p:?}"), x) - } - fn gdn_conv(&mut self, g: usize, r: Rows) -> Result<()> { self.mark(format!("gdn_conv g{g} {}..{}", r.begin, r.end)) } - fn gdn_alpha_beta(&mut self, g: usize, _: Rows) -> Result<()> { self.mark(format!("gdn_ab g{g}")) } - fn gdn_recurrence(&mut self, g: usize, _: Rows) -> Result<()> { self.mark(format!("gdn_rec g{g}")) } - fn qsa_index_k(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { - let x = self.planner.qsa_index_k(q, r, b); - self.plan("index_k", x) - } - fn qsa_k_norm_rope(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { - let x = self.planner.qsa_k_norm_rope(q, r, b); - self.plan("k_norm_rope", x) - } - fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { self.mark(format!("tail q{q}")) } - fn qsa_kv_append(&mut self, q: usize, r: Rows) -> Result<()> { - let x = self.planner.qsa_kv_append(q, r); - self.plan("kv_append", x) - } - fn qsa_indexer_append(&mut self, q: usize, _: Rows) -> Result<()> { self.mark(format!("indexer_append q{q}")) } - fn qsa_q_path(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { - let x = self.planner.qsa_q_path(q, r, b); - self.plan("q_path", x) - } - fn qsa_index_q_path(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { - let x = self.planner.qsa_index_q_path(q, r, b); - self.plan("index_q_path", x) - } - fn qsa_block_scores_topk(&mut self, q: usize, r: Rows) -> Result<()> { - let x = self.planner.qsa_block_scores_topk(q, r); - self.plan("scores_topk", x) - } - fn qsa_kv_resolve(&mut self, q: usize, r: Rows) -> Result<()> { - let x = self.planner.qsa_kv_resolve(q, r); - self.plan("kv_resolve", x) - } - fn qsa_decode_attention(&mut self, q: usize, r: Rows) -> Result<()> { - let x = self.planner.qsa_decode_attention(q, r); - self.plan("attention", x) - } - fn qsa_gate(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { - let x = self.planner.qsa_gate(q, r, b); - self.plan("gate", x) - } - fn router(&mut self, l: usize, r: Rows, b: bool) -> Result<()> { - let x = self.planner.router(l, r, b); - self.plan("router", x) - } - fn doorbell(&mut self, _: Rows) -> Result<()> { self.mark("doorbell".into()) } - fn shared_expert(&mut self, l: usize, r: Rows, b: bool) -> Result<()> { - let x = self.planner.shared_expert(l, r, b); - self.plan("shared", x) - } - fn quantize_expert_input(&mut self, _: usize, r: Rows) -> Result<()> { - let x = self.planner.quantize_expert_input(r); - self.plan("xq", x) - } - fn wait_plan(&mut self, ring: u32, _: Rows) -> Result<()> { self.mark(format!("waitA {ring}")) } - fn expert_groups(&mut self, l: usize, r: Rows, t: ExpertTier) -> Result<()> { - let x = self.planner.expert_groups(l, r, t); - self.plan(&format!("experts {t:?}"), x) - } - fn wait_copies(&mut self, ring: u32) -> Result<()> { self.mark(format!("waitB {ring}")) } - fn pcie_stage(&mut self, _: usize, _: Rows) -> Result<()> { self.mark("pcie_stage".into()) } - fn wait_cpu(&mut self, ring: u32) -> Result<()> { self.mark(format!("waitM {ring}")) } - fn copy_cpu_rows(&mut self, _: Rows, _: bool) -> Result<()> { self.mark("cpu_rows".into()) } - fn hit_add(&mut self, r: Rows) -> Result<()> { - let x = self.planner.hit_add(r); - self.plan("hit_add", x) - } - fn combine(&mut self, _: usize, r: Rows, b: bool) -> Result<()> { - let x = self.planner.combine(r, b); - self.plan("combine", x) - } - fn final_write(&mut self, r: Rows) -> Result<()> { - let x = self.planner.final_write(r); - self.plan("final_write", x) - } - fn head(&mut self, rows: usize) -> Result<()> { - assert_eq!(rows, self.t); - let x = self.planner.head_mix(0x7f_0000_0000, rows); - self.plan("head_mix", x)?; - self.mark("head_tail".into()) - } - } - - fn geometry_and_fake(ple: bool) -> (LayoutMap, Fake) { - let m = LayoutMap::new(BASE, test_geometry()); - let formats = OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 640).unwrap(); - (m, Fake { formats, ple }) - } - fn sm120() -> GrConfig { - GrConfig::from_device(gr::GrVariant::Staged, true, 12, 0, 99 * 1024, 48 * 1024) - } - fn record(t: usize, groups: usize, ple: bool) -> Vec { - let (m, fake) = geometry_and_fake(ple); - let planner = Planner::new(&m, test_geometry(), WindowPolicy::mode17(), sm120(), &fake); - let mut ops = PlanOps { planner, log: Vec::new(), t }; - record_window(&mut ops, &WindowPolicy::mode17(), t, groups, ple).unwrap(); - ops.log - } - fn section<'a>(log: &'a [String], from: &str, to: &str) -> &'a [String] { - let a = log.iter().position(|s| s == from).unwrap_or_else(|| panic!("{from} missing")); - let b = a + log[a..].iter().position(|s| s == to).unwrap_or_else(|| panic!("{to} missing")); - &log[a..=b] - } - fn names(log: &[String]) -> Vec<&str> { - log.iter().map(String::as_str).collect() - } - - #[test] - fn every_window_size_and_group_split_plans_without_error() { - for groups in [1usize, 2] { - for t in 1..=8usize { - if groups == 2 && t < 2 { - continue; - } - for ple in [false, true] { - // the 8-row xq/qfull/kcur ... spans and every arena bound hold for the whole 48-layer window - let log = record(t, groups, ple); - assert_eq!(log.iter().filter(|s| *s == "doorbell").count(), 48 * groups); - assert_eq!(log.iter().filter(|s| s.as_str() == "head_tail").count(), 1); - assert_eq!(log.iter().filter(|s| s.starts_with("") < pos(""); - assert_eq!(names(router).iter().filter(|s| s.contains("mmvf_multi_kernel") || **s == "mtp_full_route").count(), 2); - // the projections are the native MMVQ of the bound weight types at three rows - assert!(k.contains(&"head_n14_t3_large") && k.contains(&"head_n8_t3_large") && k.contains(&"head_n12_t3_large")); - // layer 1's attention read folds the pending write (apply=true), layer 0's did not - assert!(log.iter().any(|s| s == " = order.iter().map(|n| pos(n)).collect(); - assert!(at.windows(2).all(|w| w[0] < w[1]), "{order:?} -> {at:?}"); - // four rows are batched: one index-k multi gemv, one mmvq per projection at four columns - assert!(k.iter().any(|s| s.contains("mmvf_multi_kernel"))); - assert!(k.contains(&"head_n12_t4_large") && k.contains(&"head_n14_t4_large")); - assert!(k.contains(&"verify_window_qsa_gate")); - assert!(k.contains(&"leleka_qsa_decode_chunk") && k.contains(&"leleka_qsa_decode_merge")); - // the single-row window keeps the per-token (unbatched) kernels - let one = record(1, 1, false); - let one_k = names(section(&one, "stamp 3.0", "stamp 3.16")); - assert!(one_k.iter().any(|s| s.contains("mtp_full_mmvf"))); - assert!(!one_k.iter().any(|s| s.contains("mmvf_multi_kernel"))); - } - - #[test] - fn post_records_vram_then_pcie_experts_hit_add_and_combine() { - let log = record(2, 1, false); - let post = section(&log, "waitA 1", "stamp 0.24"); - let k = names(post); - let order = ["waitA 1", " = order.iter().map(|n| k.iter().position(|s| s == n).unwrap_or_else(|| panic!("{n} missing"))).collect(); - assert!(at.windows(2).all(|w| w[0] < w[1]), "{at:?}"); - // each tier is gate/up, swiglu, quantize, down - let vram = names(section(&log, "")); - assert_eq!(&vram[1..vram.len() - 1], ["window_moe_gu_16", "swiglu_entries_kernel", "quantize_q8_1_kernel", "window_moe_down_20"]); - // the last layer writes the residual once per row - let last = section(&log, "stamp 47.24", "stamp 48.0"); - assert_eq!(names(last).iter().filter(|s| **s == "mtp_full_native_write").count(), 2); - } - - #[test] - fn split_windows_interleave_groups_but_keep_each_group_in_order() { - let log = record(5, 2, false); - // pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) ...: group B's first read follows A's FFN prep, then A's experts - let hcs: Vec = log.iter().enumerate().filter(|(_, s)| s.starts_with(">(); - assert_eq!(strip(&on), strip(&off)); - assert_eq!(off.iter().filter(|s| *s == "leleka_qsa_decode_chunk").count(), 12); - } - - #[test] - fn chain_switches_swap_in_the_hoisted_kernels_and_the_default_keeps_the_originals() { - use super::super::chain::{self, ChainFlags}; - let base = record(4, 1, false); - assert!(base.iter().any(|s| s == "mtp_scalar_gr_split") && base.iter().any(|s| s == "mtp_scalar_gr_up")); - assert!(!base.iter().any(|s| s.starts_with("chain_"))); - let on = chain::with_flags(ChainFlags { glue: true, ab: true, gr: true, qsa: true, tiny: true, head: true, mtp: true }, || record(4, 1, false)); - // every hc read: split norm -> (unchanged staged down) -> up; 96 reads per window - assert_eq!(on.iter().filter(|s| *s == "chain_gr_split").count(), 96 + 0); - assert_eq!(on.iter().filter(|s| *s == "chain_gr_up8").count(), 96); - assert_eq!(on.iter().filter(|s| s.starts_with("chain_gr_down_t2w8_nb") || s.starts_with("chain_gr_down_w8_nb")).count(), 96, "the down projection is the 8-warp register-row kernel"); - assert!(!on.iter().any(|s| s == "mtp_scalar_gr_staged")); - assert!(!on.iter().any(|s| s == "mtp_scalar_gr_split" || s == "mtp_scalar_gr_up")); - assert_eq!(on.iter().filter(|s| *s == "chain_qsa_decode_chunk").count(), 12); - assert!(!on.iter().any(|s| s == "leleka_qsa_decode_chunk")); - assert!(on.iter().any(|s| s == "leleka_qsa_decode_merge"), "merge is unchanged"); - // the groups are independent - let only_gr = chain::with_flags(ChainFlags { gr: true, ..ChainFlags::default() }, || record(4, 1, false)); - assert!(only_gr.iter().any(|s| s == "chain_gr_split") && only_gr.iter().any(|s| s == "leleka_qsa_decode_chunk")); - } - - #[test] - fn the_head_mixes_every_row_then_the_head_owner_finishes() { - let log = record(3, 1, false); - let tail = section(&log, "stamp 48.0", "stamp 48.1"); - let k = names(tail); - assert_eq!(k.iter().filter(|s| **s == "mtp_full_gr_norm").count(), 3); - assert_eq!(k.iter().filter(|s| **s == "mtp_full_pre_final").count(), 3); - assert_eq!(k[k.len() - 2], "head_tail"); - } - - #[test] - fn ple_runs_once_at_layer_one_row_by_row_with_each_rows_snapshot() { - let log = record(2, 1, true); - let l1 = section(&log, "stamp 1.0", "stamp 1.1"); - let k = names(l1); - assert_eq!(k.iter().filter(|s| s.starts_with(" NativeWeight { + NativeWeight { ty: 14, data: a } +} +impl WindowWeights for Fake { + fn gdn_projections(&self, g: usize) -> Result { + let b = 0x10_0000_0000u64 + g as u64 * 0x1000_0000; + Ok(GdnProjectionAddrs { qkv: w(b), gate: NativeWeight { ty: 8, data: b + 0x100_0000 }, out: NativeWeight { ty: 12, data: b + 0x200_0000 } }) + } + fn qsa_projections(&self, q: usize) -> Result { + let b = 0x20_0000_0000u64 + q as u64 * 0x1000_0000; + Ok(QsaProjectionAddrs { + k: NativeWeight { ty: 12, data: b }, + v: NativeWeight { ty: 12, data: b + 0x100_0000 }, + q: w(b + 0x200_0000), + out: w(b + 0x300_0000), + }) + } + fn hc(&self, layer: usize, half: HcHalf) -> Result { + let b = 0x30_0000_0000u64 + layer as u64 * 0x1_0000_0000 + if half == HcHalf::Ffn { 0x8000_0000 } else { 0 }; + Ok(HcAddrs { norm: b, down: b + 0x100_0000, up: b + 0x200_0000, inject: b + 0x300_0000 }) + } + fn head(&self) -> Result { + Ok(HeadAddrs { norm: 0x3f_0000_0000, down: 0x3f_0100_0000, up: 0x3f_0200_0000 }) + } + fn ple(&self) -> Result> { + Ok(self.ple.then_some(PleAddrs { + key: gr::PleKey::Bf16(0x40_0000_0000), + value: 0x40_1000_0000, + norm_key: 0x40_2000_0000, + norm_query: 0x40_2100_0000, + norm_conv: 0x40_2200_0000, + conv1d: 0x40_2300_0000, + scratch: 0x40_3000_0000, + history: 0x40_4000_0000, + })) + } + fn qsa(&self, q: usize) -> Result { + let b = 0x50_0000_0000u64 + q as u64 * 0x1_0000_0000; + Ok(QsaLayerAddrs { + weights: QsaWeightAddrs { q_norm: b, k_norm: b + 0x1_0000, index_q_norm: b + 0x2_0000, index_k_proj: b + 0x100_0000, index_q_proj: b + 0x200_0000 }, + kv: OriginalVerifyQsaKvBinding { + resident: [b + 0x1000_0000, b + 0x1100_0000, b + 0x1200_0000, b + 0x1210_0000], + table: b + 0x1300_0000, + host: [b + 0x2000_0000, b + 0x2100_0000, b + 0x2200_0000, b + 0x2210_0000], + resolver: [b + 0x1300_0000, b + 0x1310_0000, b + 0x1320_0000, b + 0x1330_0000, b + 0x1340_0000, b + 0x1350_0000, b + 0x1360_0000], + slots: 8192, + pooled: b + 0x1400_0000, + pooled_bytes: 1026 * 512, + dead: b + 0x1410_0000, + dead_bytes: 512, + }, + }) + } + fn rope(&self) -> Result { + QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0) + } + fn moe(&self, layer: usize) -> Result { + let b = 0x60_0000_0000u64 + layer as u64 * 0x1_0000_0000; + Ok(MoeLayerAddrs { + router: b, + gate_inp_shexp: b + 0x100_0000, + gate_shexp: NativeWeight { ty: 8, data: b + 0x200_0000 }, + up_shexp: NativeWeight { ty: 8, data: b + 0x300_0000 }, + down_shexp: NativeWeight { ty: 8, data: b + 0x400_0000 }, + }) + } + fn expert_formats(&self) -> Result<&OriginalVerifyExpertFormats> { + Ok(&self.formats) + } +} + +/// Readable name of a launched kernel: the entry, or for a mangled Original kernel its base name. +fn kernel(l: &Launch) -> String { + const BASES: [&str; 14] = [ + "mmvf_multi_kernel", "mmvf_kernel", "to_bf16_kernel", "native_swiglu_kernel", "scalar_gate_kernel", + "native_scalar_sigmoid_multi_kernel", "native_scalar_sigmoid_kernel", "scale_rows_kernel", "moe_combine_kernel", + "swiglu_entries_kernel", "quantize_q8_1_kernel", "add_hits_kernel", "router_top10_kernel", "block_scores_kernel", + ]; + if !l.entry.starts_with("_ZN") { + return l.entry.to_string(); + } + BASES.iter().find(|b| l.entry.contains(*b)).map(|b| b.to_string()).unwrap_or_else(|| l.entry.to_string()) +} + +/// The recorder driven through the planners with no driver: every producer logs the kernels it would +/// launch (journal-owned producers log a marker). `fail` makes the named producer error. +struct PlanOps<'p> { + planner: Planner<'p>, + log: Vec, + t: usize, +} +impl PlanOps<'_> { + fn plan(&mut self, name: &str, r: Result>) -> Result<()> { + let launches = r?; + self.log.push(format!("<{name}")); + for l in &launches { + self.log.push(kernel(l)); + } + self.log.push(format!("{name}>")); + Ok(()) + } + fn mark(&mut self, s: String) -> Result<()> { + self.log.push(s); + Ok(()) + } +} +impl WindowOps for PlanOps<'_> { + fn embed(&mut self) -> Result<()> { self.mark("embed".into()) } + fn stamp(&mut self, l: usize, s: usize) -> Result<()> { self.mark(format!("stamp {l}.{s}")) } + fn ple_layer1(&mut self, rows: Rows) -> Result<()> { + let per = self.planner.ple_layer1(rows)?; + for (row, launches) in per { + self.log.push(format!(" Result<()> { + let x = self.planner.hc_read(l, h, a, r); + self.plan(&format!("hc {h:?} apply={a}"), x) + } + fn quantize_q8_1(&mut self, _: usize, s: QuantSource, r: Rows) -> Result<()> { + let x = self.planner.quantize_q8_1(s, r); + self.plan(&format!("quant {s:?}"), x) + } + fn mmvq(&mut self, l: usize, p: Projection, r: Rows) -> Result<()> { + let x = self.planner.mmvq(l, p, r); + self.plan(&format!("mmvq {p:?}"), x) + } + fn gdn_conv(&mut self, g: usize, r: Rows) -> Result<()> { self.mark(format!("gdn_conv g{g} {}..{}", r.begin, r.end)) } + fn gdn_alpha_beta(&mut self, g: usize, _: Rows) -> Result<()> { self.mark(format!("gdn_ab g{g}")) } + fn gdn_recurrence(&mut self, g: usize, _: Rows) -> Result<()> { self.mark(format!("gdn_rec g{g}")) } + fn qsa_index_k(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_index_k(q, r, b); + self.plan("index_k", x) + } + fn qsa_k_norm_rope(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_k_norm_rope(q, r, b); + self.plan("k_norm_rope", x) + } + fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { self.mark(format!("tail q{q}")) } + fn qsa_kv_append(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_kv_append(q, r); + self.plan("kv_append", x) + } + fn qsa_indexer_append(&mut self, q: usize, _: Rows) -> Result<()> { self.mark(format!("indexer_append q{q}")) } + fn qsa_q_path(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_q_path(q, r, b); + self.plan("q_path", x) + } + fn qsa_index_q_path(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_index_q_path(q, r, b); + self.plan("index_q_path", x) + } + fn qsa_block_scores_topk(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_block_scores_topk(q, r); + self.plan("scores_topk", x) + } + fn qsa_kv_resolve(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_kv_resolve(q, r); + self.plan("kv_resolve", x) + } + fn qsa_decode_attention(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_decode_attention(q, r); + self.plan("attention", x) + } + fn qsa_gate(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_gate(q, r, b); + self.plan("gate", x) + } + fn router(&mut self, l: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.router(l, r, b); + self.plan("router", x) + } + fn doorbell(&mut self, _: Rows) -> Result<()> { self.mark("doorbell".into()) } + fn shared_expert(&mut self, l: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.shared_expert(l, r, b); + self.plan("shared", x) + } + fn quantize_expert_input(&mut self, _: usize, r: Rows) -> Result<()> { + let x = self.planner.quantize_expert_input(r); + self.plan("xq", x) + } + fn wait_plan(&mut self, ring: u32, _: Rows) -> Result<()> { self.mark(format!("waitA {ring}")) } + fn expert_groups(&mut self, l: usize, r: Rows, t: ExpertTier) -> Result<()> { + let x = self.planner.expert_groups(l, r, t); + self.plan(&format!("experts {t:?}"), x) + } + fn wait_copies(&mut self, ring: u32) -> Result<()> { self.mark(format!("waitB {ring}")) } + fn pcie_stage(&mut self, _: usize, _: Rows) -> Result<()> { self.mark("pcie_stage".into()) } + fn wait_cpu(&mut self, ring: u32) -> Result<()> { self.mark(format!("waitM {ring}")) } + fn copy_cpu_rows(&mut self, _: Rows, _: bool) -> Result<()> { self.mark("cpu_rows".into()) } + fn hit_add(&mut self, r: Rows) -> Result<()> { + let x = self.planner.hit_add(r); + self.plan("hit_add", x) + } + fn combine(&mut self, _: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.combine(r, b); + self.plan("combine", x) + } + fn final_write(&mut self, r: Rows) -> Result<()> { + let x = self.planner.final_write(r); + self.plan("final_write", x) + } + fn head(&mut self, rows: usize) -> Result<()> { + assert_eq!(rows, self.t); + let x = self.planner.head_mix(0x7f_0000_0000, rows); + self.plan("head_mix", x)?; + self.mark("head_tail".into()) + } +} + +fn geometry_and_fake(ple: bool) -> (LayoutMap, Fake) { + let m = LayoutMap::new(BASE, test_geometry()); + let formats = OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 640).unwrap(); + (m, Fake { formats, ple }) +} +fn sm120() -> GrConfig { + GrConfig::from_device(gr::GrVariant::Staged, true, 12, 0, 99 * 1024, 48 * 1024) +} +fn record(t: usize, groups: usize, ple: bool) -> Vec { + let (m, fake) = geometry_and_fake(ple); + let planner = Planner::new(&m, test_geometry(), WindowPolicy::mode17(), sm120(), &fake); + let mut ops = PlanOps { planner, log: Vec::new(), t }; + record_window(&mut ops, &WindowPolicy::mode17(), t, groups, ple).unwrap(); + ops.log +} +fn section<'a>(log: &'a [String], from: &str, to: &str) -> &'a [String] { + let a = log.iter().position(|s| s == from).unwrap_or_else(|| panic!("{from} missing")); + let b = a + log[a..].iter().position(|s| s == to).unwrap_or_else(|| panic!("{to} missing")); + &log[a..=b] +} +fn names(log: &[String]) -> Vec<&str> { + log.iter().map(String::as_str).collect() +} + +#[test] +fn every_window_size_and_group_split_plans_without_error() { + for groups in [1usize, 2] { + for t in 1..=8usize { + if groups == 2 && t < 2 { + continue; + } + for ple in [false, true] { + // the 8-row xq/qfull/kcur ... spans and every arena bound hold for the whole 48-layer window + let log = record(t, groups, ple); + assert_eq!(log.iter().filter(|s| *s == "doorbell").count(), 48 * groups); + assert_eq!(log.iter().filter(|s| s.as_str() == "head_tail").count(), 1); + assert_eq!(log.iter().filter(|s| s.starts_with("") < pos(""); + assert_eq!(names(router).iter().filter(|s| s.contains("mmvf_multi_kernel") || **s == "mtp_full_route").count(), 2); + // the projections are the native MMVQ of the bound weight types at three rows + assert!(k.contains(&"head_n14_t3_large") && k.contains(&"head_n8_t3_large") && k.contains(&"head_n12_t3_large")); + // layer 1's attention read folds the pending write (apply=true), layer 0's did not + assert!(log.iter().any(|s| s == " = order.iter().map(|n| pos(n)).collect(); + assert!(at.windows(2).all(|w| w[0] < w[1]), "{order:?} -> {at:?}"); + // four rows are batched: one index-k multi gemv, one mmvq per projection at four columns + assert!(k.iter().any(|s| s.contains("mmvf_multi_kernel"))); + assert!(k.contains(&"head_n12_t4_large") && k.contains(&"head_n14_t4_large")); + assert!(k.contains(&"verify_window_qsa_gate")); + assert!(k.contains(&"leleka_qsa_decode_chunk") && k.contains(&"leleka_qsa_decode_merge")); + // the single-row window keeps the per-token (unbatched) kernels + let one = record(1, 1, false); + let one_k = names(section(&one, "stamp 3.0", "stamp 3.16")); + assert!(one_k.iter().any(|s| s.contains("mtp_full_mmvf"))); + assert!(!one_k.iter().any(|s| s.contains("mmvf_multi_kernel"))); +} + +#[test] +fn post_records_vram_then_pcie_experts_hit_add_and_combine() { + let log = record(2, 1, false); + let post = section(&log, "waitA 1", "stamp 0.24"); + let k = names(post); + let order = ["waitA 1", " = order.iter().map(|n| k.iter().position(|s| s == n).unwrap_or_else(|| panic!("{n} missing"))).collect(); + assert!(at.windows(2).all(|w| w[0] < w[1]), "{at:?}"); + // each tier is gate/up, swiglu, quantize, down + let vram = names(section(&log, "")); + assert_eq!(&vram[1..vram.len() - 1], ["window_moe_gu_16", "swiglu_entries_kernel", "quantize_q8_1_kernel", "window_moe_down_20"]); + // the last layer writes the residual once per row + let last = section(&log, "stamp 47.24", "stamp 48.0"); + assert_eq!(names(last).iter().filter(|s| **s == "mtp_full_native_write").count(), 2); +} + +#[test] +fn split_windows_interleave_groups_but_keep_each_group_in_order() { + let log = record(5, 2, false); + // pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) ...: group B's first read follows A's FFN prep, then A's experts + let hcs: Vec = log.iter().enumerate().filter(|(_, s)| s.starts_with(">(); + assert_eq!(strip(&on), strip(&off)); + assert_eq!(off.iter().filter(|s| *s == "leleka_qsa_decode_chunk").count(), 12); +} + +#[test] +fn chain_switches_swap_in_the_hoisted_kernels_and_the_default_keeps_the_originals() { + use super::super::chain::{self, ChainFlags}; + let base = record(4, 1, false); + assert!(base.iter().any(|s| s == "mtp_scalar_gr_split") && base.iter().any(|s| s == "mtp_scalar_gr_up")); + assert!(!base.iter().any(|s| s.starts_with("chain_"))); + let on = chain::with_flags(ChainFlags { glue: true, ab: true, gr: true, qsa: true, tiny: true, head: true, mtp: true }, || record(4, 1, false)); + // every hc read: split norm -> (unchanged staged down) -> up; 96 reads per window + assert_eq!(on.iter().filter(|s| *s == "chain_gr_split").count(), 96 + 0); + assert_eq!(on.iter().filter(|s| *s == "chain_gr_up8").count(), 96); + assert_eq!(on.iter().filter(|s| s.starts_with("chain_gr_down_t2w8_nb") || s.starts_with("chain_gr_down_w8_nb")).count(), 96, "the down projection is the 8-warp register-row kernel"); + assert!(!on.iter().any(|s| s == "mtp_scalar_gr_staged")); + assert!(!on.iter().any(|s| s == "mtp_scalar_gr_split" || s == "mtp_scalar_gr_up")); + assert_eq!(on.iter().filter(|s| *s == "chain_qsa_decode_chunk").count(), 12); + assert!(!on.iter().any(|s| s == "leleka_qsa_decode_chunk")); + assert!(on.iter().any(|s| s == "leleka_qsa_decode_merge"), "merge is unchanged"); + // the groups are independent + let only_gr = chain::with_flags(ChainFlags { gr: true, ..ChainFlags::default() }, || record(4, 1, false)); + assert!(only_gr.iter().any(|s| s == "chain_gr_split") && only_gr.iter().any(|s| s == "leleka_qsa_decode_chunk")); +} + +#[test] +fn the_head_mixes_every_row_then_the_head_owner_finishes() { + let log = record(3, 1, false); + let tail = section(&log, "stamp 48.0", "stamp 48.1"); + let k = names(tail); + assert_eq!(k.iter().filter(|s| **s == "mtp_full_gr_norm").count(), 3); + assert_eq!(k.iter().filter(|s| **s == "mtp_full_pre_final").count(), 3); + assert_eq!(k[k.len() - 2], "head_tail"); +} + +#[test] +fn ple_runs_once_at_layer_one_row_by_row_with_each_rows_snapshot() { + let log = record(2, 1, true); + let l1 = section(&log, "stamp 1.0", "stamp 1.1"); + let k = names(l1); + assert_eq!(k.iter().filter(|s| s.starts_with(" OriginalVerifyProjBinding<'a, 'ctx> { } #[cfg(test)] -mod tests { - use super::*; - - fn entry_declared(ptx: &str, e: &str) -> bool { - ptx.contains(&format!(".entry {e}(")) - } - - #[test] - fn assets_are_pinned_and_export_every_named_entry() { - for spec in [&HEAD_NATIVE, &HEAD_IQ, &BF16] { - spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); - let text = String::from_utf8_lossy(spec.ptx); - for e in spec.entries { - assert!(entry_declared(&text, e), "{} lacks {e}", spec.name); - } - } - } - - #[test] - fn quantize_is_one_launch_over_all_rows() { - let l = plan_quantize_q8_1(0x100, 0x200, 2560, 8).unwrap(); - assert_eq!(l.entry, "head_quant"); - assert_eq!(l.grid, [80, 1, 1]); - assert_eq!(l.args, vec![A::P(0x100), A::P(0x200), A::I32(20480)]); - assert_eq!(plan_quantize_q8_1(0, 0, 2560, 9).unwrap_err(), Error::InvalidQwenShape); - assert_eq!(plan_quantize_q8_1(0, 0, 2570, 1).unwrap_err(), Error::InvalidQwenShape); - assert_eq!(q8_1_row_bytes(2560), 2880); - } - - #[test] - fn mmvq_follows_the_native_head_dispatch() { - let d = NativeHeadDispatch::default(); - let q8 = NativeWeight { ty: 8, data: 0x1000 }; - let one = plan_mmvq(&q8, 0x2000, 0x3000, 2560, 12288, 1, d).unwrap(); - assert_eq!((one.entry, one.grid, one.block), ("head_n8_s0", [12288, 1, 1], [32, 4, 1])); - assert_eq!(one.args, vec![A::P(0x1000), A::P(0x2000), A::P(0x3000), A::I32(2560), A::I32(12288)]); - let four = plan_mmvq(&q8, 0x2000, 0x3000, 2560, 12288, 4, d).unwrap(); - assert_eq!((four.entry, four.grid), ("head_n8_t4_large", [12288, 1, 1])); - // 256-wide K quants, 3 rows - let q6 = NativeWeight { ty: 14, data: 0x1000 }; - assert_eq!(plan_mmvq(&q6, 1, 2, 6144, 2560, 3, d).unwrap().entry, "head_n14_t3_large"); - // not exact: the upstream layout - let up = NativeHeadDispatch { multi_exact: false, old_iq: false }; - assert_eq!(plan_mmvq(&q8, 1, 2, 2560, 640, 3, up).unwrap().entry, "head_n8_t3_upstream"); - assert_eq!(plan_mmvq(&NativeWeight { ty: 99, data: 0 }, 1, 2, 2560, 64, 1, d).unwrap_err(), Error::UnsupportedQwenOperation); - assert_eq!(plan_mmvq(&q8, 1, 2, 2560, 0, 1, d).unwrap_err(), Error::InvalidQwenShape); - } - - #[test] - fn iq_kinds_use_the_iq_asset_with_row_bytes_and_columns() { - assert!(is_iq_kind(16) && !is_iq_kind(8) && !is_iq_kind(23)); - let w = NativeWeight { ty: 16, data: 0x10 }; - let l = plan_mmvq(&w, 0x20, 0x30, 2560, 1280, 3, NativeHeadDispatch::default()).unwrap(); - assert!(std::ptr::eq(l.asset, &HEAD_IQ)); - assert_eq!(l.entry, "head_i16_c4"); - assert_eq!(l.args[1], A::U64(2560 / 256 * 66)); - assert_eq!(l.args.last(), Some(&A::I32(3))); - assert_eq!(l.grid, [320, 1, 1]); - } - - #[test] - fn mmvf_block_matches_the_original_search() { - assert_eq!(mmvf_block_size(2560), 256); - // 64: 3 iterations, 96: 2, 128: 2 (no gain), 160: 1 -> 160 (later candidates cannot beat one iteration) - assert_eq!(mmvf_block_size(320), 160); - assert_eq!(mmvf_block_size(192), 96); - assert_eq!(mmvf_block_size(10240), 256); - assert_eq!(mmvf_block_size(64), 32); - assert_eq!(mmvf_block_size(128), 64); - } - - #[test] - fn bf16_gemv_is_single_for_one_row_and_multi_otherwise() { - let s = plan_bf16_gemv(0x1000, 2560, 0x2000, 0x3000, 128, 2560, 128, 1).unwrap(); - assert_eq!((s.entry, s.grid, s.block), ("mtp_full_mmvf256", [128, 1, 1], [256, 1, 1])); - assert_eq!(s.args, vec![A::P(0x1000), A::P(0x2000), A::P(0x3000), A::I32(2560)]); - let m = plan_bf16_gemv(0x1000, 2560, 0x2000, 0x3000, 512, 2560, 512, 4).unwrap(); - assert!(m.entry.contains("ILi256ELi4EE")); - assert_eq!(m.args[1], A::I64(2560)); - assert_eq!(m.args[4], A::I64(512)); - assert_eq!(m.args[6], A::I32(4)); - assert!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2560, 512, 5).unwrap().entry.contains("ILi256ELi8EE")); - // one row whose output stride is narrower than the row goes through the multi kernel - assert!(plan_bf16_gemv(0x1000, 2560, 2, 3, 64, 2560, 512, 1).unwrap().entry.contains("ILi256ELi4EE")); - assert_eq!(plan_bf16_gemv(0x1004, 2560, 2, 3, 512, 2560, 512, 2).unwrap_err(), Error::InvalidQwenShape); - assert_eq!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2561, 512, 2).unwrap_err(), Error::InvalidQwenShape); - assert_eq!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2560, 512, 9).unwrap_err(), Error::InvalidQwenShape); - } - - use super::super::kernels::{LayoutMap, test_geometry}; - - fn rows(begin: usize, end: usize) -> Rows { - Rows { begin, end, group: 0 } - } - - #[test] - fn window_quantize_reads_the_groups_rows_and_writes_the_start_of_xq() { - let geo = test_geometry(); - let m = LayoutMap::new(0x4000_0000, geo); - let off = |name: &str| m.layout.span(name).unwrap().offset as u64; - let l = plan_window_quantize(&m, &geo, QuantSource::Mixed, rows(2, 5)).unwrap(); - assert_eq!(l.entry, "head_quant"); - assert_eq!(l.grid, [(3 * 2560usize).div_ceil(256) as u32, 1, 1]); - assert_eq!(l.args, vec![A::P(0x4000_0000 + off("mixed") + 2 * 2560 * 4), A::P(0x4000_0000 + off("xq")), A::I32(7680)]); - // GDN y rows are 48 heads x 128, QSA attn32 rows 24 x 256: both 6144 wide - let y = plan_window_quantize(&m, &geo, QuantSource::GdnY, rows(0, 8)).unwrap(); - assert_eq!(y.args, vec![A::P(0x4000_0000 + off("y")), A::P(0x4000_0000 + off("xq")), A::I32(8 * 6144)]); - assert_eq!(y.grid, [192, 1, 1]); - let a = plan_window_quantize(&m, &geo, QuantSource::Attention, rows(4, 8)).unwrap(); - assert_eq!(a.args[0], A::P(0x4000_0000 + off("attn32") + 4 * 6144 * 4)); - // the 8-row 6144-wide image fills xq exactly (the arena carves xq for max_in = 6144) - assert_eq!(m.layout.span("xq").unwrap().bytes, 8 * q8_1_row_bytes(6144)); - assert!(plan_window_quantize(&m, &geo, QuantSource::Mixed, rows(3, 3)).is_err()); - assert!(plan_window_quantize(&m, &geo, QuantSource::Mixed, rows(6, 9)).is_err()); - } - - #[test] - fn window_mmvq_addresses_follow_the_original_output_banks() { - let geo = test_geometry(); - let m = LayoutMap::new(0x4000_0000, geo); - let off = |name: &str| m.layout.span(name).unwrap().offset as u64; - let w = NativeWeight { ty: 8, data: 0xAA00 }; - let d = NativeHeadDispatch::default(); - // GDN layer 4 is the fourth GDN layer (index 3); the retained qkv bank has max_t rows per GDN layer - let qkv = plan_window_mmvq(&m, &geo, 4, Projection::GdnQkv, &w, rows(3, 5), d).unwrap(); - assert_eq!((qkv.entry, qkv.grid, qkv.block), ("head_n8_t2_large", [10240, 1, 1], [32, 4, 1])); - assert_eq!( - qkv.args, - vec![A::P(0xAA00), A::P(0x4000_0000 + off("xq")), A::P(0x4000_0000 + off("qkv_L") + (3 * 8 + 3) as u64 * 10240 * 4), A::I32(2560), A::I32(10240)] - ); - let gate = plan_window_mmvq(&m, &geo, 0, Projection::GdnGate, &w, rows(0, 1), d).unwrap(); - assert_eq!((gate.entry, gate.grid), ("head_n8_s0", [6144, 1, 1])); - assert_eq!(gate.args[2], A::P(0x4000_0000 + off("z"))); - let out = plan_window_mmvq(&m, &geo, 0, Projection::GdnOut, &w, rows(0, 8), d).unwrap(); - assert_eq!(out.args[3..], [A::I32(6144), A::I32(2560)]); - assert_eq!(out.args[2], A::P(0x4000_0000 + off("bo"))); - // QSA layer 3 (index 0) - let q = plan_window_mmvq(&m, &geo, 3, Projection::QsaQ, &w, rows(1, 3), d).unwrap(); - assert_eq!(q.args[2], A::P(0x4000_0000 + off("qfull") + 12288 * 4)); - assert_eq!(q.args[4], A::I32(12288)); - let k = plan_window_mmvq(&m, &geo, 3, Projection::QsaK, &w, rows(0, 8), d).unwrap(); - assert_eq!(k.args[4], A::I32(512)); - assert_eq!(k.args[2], A::P(0x4000_0000 + off("kcur"))); - let o = plan_window_mmvq(&m, &geo, 7, Projection::QsaOut, &w, rows(0, 2), d).unwrap(); - assert_eq!(o.args[3..], [A::I32(6144), A::I32(2560)]); - // a projection of the other layer kind is refused - assert!(plan_window_mmvq(&m, &geo, 3, Projection::GdnQkv, &w, rows(0, 1), d).is_err()); - assert!(plan_window_mmvq(&m, &geo, 4, Projection::QsaK, &w, rows(0, 1), d).is_err()); - assert!(plan_window_mmvq(&m, &geo, 4, Projection::GdnQkv, &w, rows(0, 9), d).is_err()); - } - - #[test] - fn native_matrix_sizes_are_row_bytes_times_rows() { - assert_eq!(native_matrix_bytes(8, 2560, 10240).unwrap(), 2560 / 32 * 34 * 10240); - assert_eq!(native_matrix_bytes(14, 6144, 2560).unwrap(), 6144 / 256 * 210 * 2560); - assert!(native_matrix_bytes(8, 2570, 4).is_err()); - assert!(native_matrix_bytes(99, 2560, 4).is_err()); - } -} +#[path = "original_verify_window_proj/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_verify_window_proj/tests.rs b/crates/cuda-driver/src/original_verify_window_proj/tests.rs new file mode 100644 index 00000000..8f67846c --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_proj/tests.rs @@ -0,0 +1,159 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn entry_declared(ptx: &str, e: &str) -> bool { + ptx.contains(&format!(".entry {e}(")) +} + +#[test] +fn assets_are_pinned_and_export_every_named_entry() { + for spec in [&HEAD_NATIVE, &HEAD_IQ, &BF16] { + spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); + let text = String::from_utf8_lossy(spec.ptx); + for e in spec.entries { + assert!(entry_declared(&text, e), "{} lacks {e}", spec.name); + } + } +} + +#[test] +fn quantize_is_one_launch_over_all_rows() { + let l = plan_quantize_q8_1(0x100, 0x200, 2560, 8).unwrap(); + assert_eq!(l.entry, "head_quant"); + assert_eq!(l.grid, [80, 1, 1]); + assert_eq!(l.args, vec![A::P(0x100), A::P(0x200), A::I32(20480)]); + assert_eq!(plan_quantize_q8_1(0, 0, 2560, 9).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(plan_quantize_q8_1(0, 0, 2570, 1).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(q8_1_row_bytes(2560), 2880); +} + +#[test] +fn mmvq_follows_the_native_head_dispatch() { + let d = NativeHeadDispatch::default(); + let q8 = NativeWeight { ty: 8, data: 0x1000 }; + let one = plan_mmvq(&q8, 0x2000, 0x3000, 2560, 12288, 1, d).unwrap(); + assert_eq!((one.entry, one.grid, one.block), ("head_n8_s0", [12288, 1, 1], [32, 4, 1])); + assert_eq!(one.args, vec![A::P(0x1000), A::P(0x2000), A::P(0x3000), A::I32(2560), A::I32(12288)]); + let four = plan_mmvq(&q8, 0x2000, 0x3000, 2560, 12288, 4, d).unwrap(); + assert_eq!((four.entry, four.grid), ("head_n8_t4_large", [12288, 1, 1])); + // 256-wide K quants, 3 rows + let q6 = NativeWeight { ty: 14, data: 0x1000 }; + assert_eq!(plan_mmvq(&q6, 1, 2, 6144, 2560, 3, d).unwrap().entry, "head_n14_t3_large"); + // not exact: the upstream layout + let up = NativeHeadDispatch { multi_exact: false, old_iq: false }; + assert_eq!(plan_mmvq(&q8, 1, 2, 2560, 640, 3, up).unwrap().entry, "head_n8_t3_upstream"); + assert_eq!(plan_mmvq(&NativeWeight { ty: 99, data: 0 }, 1, 2, 2560, 64, 1, d).unwrap_err(), Error::UnsupportedQwenOperation); + assert_eq!(plan_mmvq(&q8, 1, 2, 2560, 0, 1, d).unwrap_err(), Error::InvalidQwenShape); +} + +#[test] +fn iq_kinds_use_the_iq_asset_with_row_bytes_and_columns() { + assert!(is_iq_kind(16) && !is_iq_kind(8) && !is_iq_kind(23)); + let w = NativeWeight { ty: 16, data: 0x10 }; + let l = plan_mmvq(&w, 0x20, 0x30, 2560, 1280, 3, NativeHeadDispatch::default()).unwrap(); + assert!(std::ptr::eq(l.asset, &HEAD_IQ)); + assert_eq!(l.entry, "head_i16_c4"); + assert_eq!(l.args[1], A::U64(2560 / 256 * 66)); + assert_eq!(l.args.last(), Some(&A::I32(3))); + assert_eq!(l.grid, [320, 1, 1]); +} + +#[test] +fn mmvf_block_matches_the_original_search() { + assert_eq!(mmvf_block_size(2560), 256); + // 64: 3 iterations, 96: 2, 128: 2 (no gain), 160: 1 -> 160 (later candidates cannot beat one iteration) + assert_eq!(mmvf_block_size(320), 160); + assert_eq!(mmvf_block_size(192), 96); + assert_eq!(mmvf_block_size(10240), 256); + assert_eq!(mmvf_block_size(64), 32); + assert_eq!(mmvf_block_size(128), 64); +} + +#[test] +fn bf16_gemv_is_single_for_one_row_and_multi_otherwise() { + let s = plan_bf16_gemv(0x1000, 2560, 0x2000, 0x3000, 128, 2560, 128, 1).unwrap(); + assert_eq!((s.entry, s.grid, s.block), ("mtp_full_mmvf256", [128, 1, 1], [256, 1, 1])); + assert_eq!(s.args, vec![A::P(0x1000), A::P(0x2000), A::P(0x3000), A::I32(2560)]); + let m = plan_bf16_gemv(0x1000, 2560, 0x2000, 0x3000, 512, 2560, 512, 4).unwrap(); + assert!(m.entry.contains("ILi256ELi4EE")); + assert_eq!(m.args[1], A::I64(2560)); + assert_eq!(m.args[4], A::I64(512)); + assert_eq!(m.args[6], A::I32(4)); + assert!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2560, 512, 5).unwrap().entry.contains("ILi256ELi8EE")); + // one row whose output stride is narrower than the row goes through the multi kernel + assert!(plan_bf16_gemv(0x1000, 2560, 2, 3, 64, 2560, 512, 1).unwrap().entry.contains("ILi256ELi4EE")); + assert_eq!(plan_bf16_gemv(0x1004, 2560, 2, 3, 512, 2560, 512, 2).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2561, 512, 2).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2560, 512, 9).unwrap_err(), Error::InvalidQwenShape); +} + +use super::super::kernels::{LayoutMap, test_geometry}; + +fn rows(begin: usize, end: usize) -> Rows { + Rows { begin, end, group: 0 } +} + +#[test] +fn window_quantize_reads_the_groups_rows_and_writes_the_start_of_xq() { + let geo = test_geometry(); + let m = LayoutMap::new(0x4000_0000, geo); + let off = |name: &str| m.layout.span(name).unwrap().offset as u64; + let l = plan_window_quantize(&m, &geo, QuantSource::Mixed, rows(2, 5)).unwrap(); + assert_eq!(l.entry, "head_quant"); + assert_eq!(l.grid, [(3 * 2560usize).div_ceil(256) as u32, 1, 1]); + assert_eq!(l.args, vec![A::P(0x4000_0000 + off("mixed") + 2 * 2560 * 4), A::P(0x4000_0000 + off("xq")), A::I32(7680)]); + // GDN y rows are 48 heads x 128, QSA attn32 rows 24 x 256: both 6144 wide + let y = plan_window_quantize(&m, &geo, QuantSource::GdnY, rows(0, 8)).unwrap(); + assert_eq!(y.args, vec![A::P(0x4000_0000 + off("y")), A::P(0x4000_0000 + off("xq")), A::I32(8 * 6144)]); + assert_eq!(y.grid, [192, 1, 1]); + let a = plan_window_quantize(&m, &geo, QuantSource::Attention, rows(4, 8)).unwrap(); + assert_eq!(a.args[0], A::P(0x4000_0000 + off("attn32") + 4 * 6144 * 4)); + // the 8-row 6144-wide image fills xq exactly (the arena carves xq for max_in = 6144) + assert_eq!(m.layout.span("xq").unwrap().bytes, 8 * q8_1_row_bytes(6144)); + assert!(plan_window_quantize(&m, &geo, QuantSource::Mixed, rows(3, 3)).is_err()); + assert!(plan_window_quantize(&m, &geo, QuantSource::Mixed, rows(6, 9)).is_err()); +} + +#[test] +fn window_mmvq_addresses_follow_the_original_output_banks() { + let geo = test_geometry(); + let m = LayoutMap::new(0x4000_0000, geo); + let off = |name: &str| m.layout.span(name).unwrap().offset as u64; + let w = NativeWeight { ty: 8, data: 0xAA00 }; + let d = NativeHeadDispatch::default(); + // GDN layer 4 is the fourth GDN layer (index 3); the retained qkv bank has max_t rows per GDN layer + let qkv = plan_window_mmvq(&m, &geo, 4, Projection::GdnQkv, &w, rows(3, 5), d).unwrap(); + assert_eq!((qkv.entry, qkv.grid, qkv.block), ("head_n8_t2_large", [10240, 1, 1], [32, 4, 1])); + assert_eq!( + qkv.args, + vec![A::P(0xAA00), A::P(0x4000_0000 + off("xq")), A::P(0x4000_0000 + off("qkv_L") + (3 * 8 + 3) as u64 * 10240 * 4), A::I32(2560), A::I32(10240)] + ); + let gate = plan_window_mmvq(&m, &geo, 0, Projection::GdnGate, &w, rows(0, 1), d).unwrap(); + assert_eq!((gate.entry, gate.grid), ("head_n8_s0", [6144, 1, 1])); + assert_eq!(gate.args[2], A::P(0x4000_0000 + off("z"))); + let out = plan_window_mmvq(&m, &geo, 0, Projection::GdnOut, &w, rows(0, 8), d).unwrap(); + assert_eq!(out.args[3..], [A::I32(6144), A::I32(2560)]); + assert_eq!(out.args[2], A::P(0x4000_0000 + off("bo"))); + // QSA layer 3 (index 0) + let q = plan_window_mmvq(&m, &geo, 3, Projection::QsaQ, &w, rows(1, 3), d).unwrap(); + assert_eq!(q.args[2], A::P(0x4000_0000 + off("qfull") + 12288 * 4)); + assert_eq!(q.args[4], A::I32(12288)); + let k = plan_window_mmvq(&m, &geo, 3, Projection::QsaK, &w, rows(0, 8), d).unwrap(); + assert_eq!(k.args[4], A::I32(512)); + assert_eq!(k.args[2], A::P(0x4000_0000 + off("kcur"))); + let o = plan_window_mmvq(&m, &geo, 7, Projection::QsaOut, &w, rows(0, 2), d).unwrap(); + assert_eq!(o.args[3..], [A::I32(6144), A::I32(2560)]); + // a projection of the other layer kind is refused + assert!(plan_window_mmvq(&m, &geo, 3, Projection::GdnQkv, &w, rows(0, 1), d).is_err()); + assert!(plan_window_mmvq(&m, &geo, 4, Projection::QsaK, &w, rows(0, 1), d).is_err()); + assert!(plan_window_mmvq(&m, &geo, 4, Projection::GdnQkv, &w, rows(0, 9), d).is_err()); +} + +#[test] +fn native_matrix_sizes_are_row_bytes_times_rows() { + assert_eq!(native_matrix_bytes(8, 2560, 10240).unwrap(), 2560 / 32 * 34 * 10240); + assert_eq!(native_matrix_bytes(14, 6144, 2560).unwrap(), 6144 / 256 * 210 * 2560); + assert!(native_matrix_bytes(8, 2570, 4).is_err()); + assert!(native_matrix_bytes(99, 2560, 4).is_err()); +} diff --git a/crates/cuda-driver/src/original_verify_window_qsa.rs b/crates/cuda-driver/src/original_verify_window_qsa.rs index daf2b2c4..aa54b1e9 100644 --- a/crates/cuda-driver/src/original_verify_window_qsa.rs +++ b/crates/cuda-driver/src/original_verify_window_qsa.rs @@ -838,655 +838,5 @@ impl<'a> QsaWindow<'a> { } #[cfg(test)] -mod tests { - use super::super::kernels::{LayoutMap, test_geometry}; - use super::*; - - const BASE: u64 = 0x7000_0000_0000; - const KV: OriginalVerifyQsaKvBinding = OriginalVerifyQsaKvBinding { - resident: [0x1_0000_0000, 0x1_1000_0000, 0x1_2000_0000, 0x1_2100_0000], - table: 0x1_3000_0000, - host: [0x2_0000_0000, 0x2_1000_0000, 0x2_2000_0000, 0x2_2100_0000], - resolver: [0x1_3000_0000, 0x1_3100_0000, 0x1_3200_0000, 0x1_3300_0000, 0x1_3400_0000, 0x1_3500_0000, 0x1_3600_0000], - slots: 8192, - pooled: 0x1_4000_0000, - pooled_bytes: 1026 * 512, - dead: 0x1_4100_0000, - dead_bytes: 512, - }; - const W: QsaWeightAddrs = QsaWeightAddrs { - q_norm: 0x3_0000_0000, - k_norm: 0x3_0001_0000, - index_q_norm: 0x3_0002_0000, - index_k_proj: 0x3_1000_0000, - index_q_proj: 0x3_2000_0000, - }; - fn layer() -> QsaLayerAddrs { - QsaLayerAddrs { weights: W, kv: KV } - } - fn identity() -> QsaRope { - QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0).unwrap() - } - fn rows(begin: usize, end: usize) -> Rows { - Rows { begin, end, group: if begin == 0 { 0 } else { 1 } } - } - fn setup() -> (LayoutMap, OriginalVerifyGeometry) { - let g = test_geometry(); - (LayoutMap::new(BASE, g), g) - } - fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { - BASE + m.layout.span(name).unwrap().offset as u64 + offset as u64 - } - fn window(m: &LayoutMap, g: OriginalVerifyGeometry) -> QsaWindow<'_> { - QsaWindow::new(m, g, OriginalVerifyQsaPolicy::mode17(), identity()).unwrap() - } - - /// `.param` count the PTX declares for `entry`. - fn declared_params(ptx: &[u8], entry: &str) -> usize { - let text = String::from_utf8_lossy(ptx); - let head = format!(".entry {entry}("); - let at = text.find(&head).unwrap_or_else(|| panic!("{entry} not declared")); - let rest = &text[at..]; - let end = rest.find("\n)\n").expect("entry parameter list end"); - rest[..end].matches(".param").count() - } - fn assert_abi(l: &Launch) { - assert_eq!(declared_params(l.asset.ptx, l.entry), l.args.len(), "{}", l.label()); - } - - #[test] - fn sealed_assets_are_pinned_and_export_every_named_entry() { - for spec in assets() { - spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); - let text = String::from_utf8_lossy(spec.ptx); - for e in spec.entries { - assert!(text.contains(&format!(".entry {e}(")), "{} lacks {e}", spec.name); - } - } - } - - #[test] - fn the_new_gate_asset_is_sealed_with_a_matching_source() { - // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim). - GATE.assert_sealed_and_fail_closed(); - assert_eq!(GATE.ptx.iter().filter(|&&b| b == 0).count(), 1); - let source = include_str!("original_verify_window_qsa_gate.cu"); - for e in GATE.entries { - assert!(source.contains(&format!("extern \"C\" __global__ void {e}(")), "{e}"); - } - // the body is the Original `gate`: second half of each [head][2][head_dim] row - assert!(source.contains("q_full[head * 2 * head_dim + head_dim + channel]")); - assert!(source.contains("1.0f / (1.0f + expf(-raw))")); - assert!(include_str!("../../../docs/cuda-seal-plan-additions-window.json").contains("--use_fast_math")); - } - - #[test] - fn asset_set_has_distinct_names_and_the_bf16_projection_module() { - let a = assets(); - let mut names: Vec<&str> = a.iter().map(|s| s.name).collect(); - names.sort_unstable(); - names.dedup(); - assert_eq!(names.len(), a.len()); - assert!(a.iter().any(|s| std::ptr::eq(*s, &proj::BF16))); - let g = test_geometry(); - assert!(shared_attributes(&OriginalVerifyQsaPolicy::mode17(), &g).is_empty()); - assert!(cluster_assets(&OriginalVerifyQsaPolicy::mode17()).is_empty()); - // the cluster top-k: its module is loaded only on request and opts into the dynamic shared memory of its keys - let p = OriginalVerifyQsaPolicy { cluster_topk: true, ..OriginalVerifyQsaPolicy::mode17() }; - assert!(cluster_assets(&p).iter().any(|s| std::ptr::eq(*s, &CLUSTER))); - assert!(!a.iter().any(|s| std::ptr::eq(*s, &CLUSTER)), "the cluster module is not in the always-loaded list"); - let attributes = shared_attributes(&p, &g); - assert_eq!(attributes.len(), 1); - assert!(std::ptr::eq(attributes[0].0, &CLUSTER)); - assert_eq!((attributes[0].1, attributes[0].2), ("leleka_qsa_topk_cluster", max_blocks(&g).div_ceil(8) * 4)); - CLUSTER.assert_sealed_and_fail_closed(); - } - - #[test] - fn the_cluster_policy_replaces_only_the_topk_launch_and_keeps_its_arguments() { - let (m, g) = setup(); - let reference = window(&m, g).block_scores_topk(0, &layer(), rows(0, 3)).unwrap(); - let p = OriginalVerifyQsaPolicy { cluster_topk: true, ..OriginalVerifyQsaPolicy::mode17() }; - let w = QsaWindow::new(&m, g, p, identity()).unwrap(); - let l = w.block_scores_topk(0, &layer(), rows(0, 3)).unwrap(); - assert_eq!(l.len(), 2); - assert_eq!(l[0], reference[0], "the scores launch is untouched"); - assert_eq!(l[1].entry, "leleka_qsa_topk_cluster"); - assert_eq!((l[1].grid, l[1].block, l[1].cluster), ([8, 3, 1], [1024, 1, 1], 8)); - assert_eq!(l[1].shared as usize, max_blocks(&g).div_ceil(8) * 4); - assert_eq!(l[1].args, reference[1].args, "scores, steps, max_blocks, cap, ids as qsa_topk_ref"); - assert_eq!(reference[1].cluster, 0); - assert_abi(&l[1]); - } - - #[test] - fn policy_refuses_every_variant_without_a_sealed_owner() { - assert!(OriginalVerifyQsaPolicy::mode17().validate().is_ok()); - let base = OriginalVerifyQsaPolicy::mode17(); - let variants: [fn(&mut OriginalVerifyQsaPolicy); 8] = [ - |p| p.native_qsa = false, - |p| p.native_rope = false, - |p| p.kv_q4 = true, - |p| p.kv_hybrid = true, - |p| p.kv_rot = true, - |p| p.without_key = true, - |p| p.trace = true, - |p| p.kv_streamed = false, - ]; - let mut seen = std::collections::BTreeSet::new(); - for f in variants { - let mut p = base; - f(&mut p); - match p.validate().unwrap_err() { - Error::InvalidDriverValue(m) => { - assert!(m.starts_with("Original verifier producer unavailable: qsa: "), "{m}"); - seen.insert(m); - } - e => panic!("{e:?}"), - } - } - assert!(seen.len() >= 6, "reasons are specific: {seen:?}"); - let mut fp16 = base; - fp16.kv_int8 = false; - assert!(fp16.validate().is_err()); - } - - #[test] - fn rope_constants_refuse_tables_and_non_finite_values() { - assert!(QsaRope::new(f32::NAN, 1.0, 0.0, 0.0, 0.0, 1.0).is_err()); - assert!(QsaRope::new(0.7, 0.0, 0.0, 0.0, 0.0, 1.0).is_err()); - assert!(QsaRope::new(0.7, 1.0, 0.0, 0.0, -1.0, 1.0).is_err()); - assert!(identity().is_identity()); - assert!(!QsaRope::new(0.7, 0.5, 0.0, 0.0, 1.0, 1.1).unwrap().is_identity()); - } - - #[test] - fn index_k_is_one_multi_gemv_when_batched_and_a_single_gemv_per_token_otherwise() { - let (m, g) = setup(); - let w = window(&m, g); - for n in 2..=8usize { - let l = w.index_k(2, &layer(), rows(0, n), true).unwrap(); - assert_eq!(l.len(), 1); - let nt = if n <= 4 { "ELi4EE" } else { "ELi8EE" }; - assert!(l[0].entry.contains("ILi256") && l[0].entry.contains(nt), "{}", l[0].entry); - assert_eq!((l[0].grid, l[0].block), ([128, 1, 1], [256, 1, 1])); - // x = mixed, ldx = 2560, w, y = idx_raw layer 2 row 0, ldy = 128, n_in = 2560, n_tok - assert_eq!( - l[0].args, - vec![ - A::P(at(&m, "mixed", 0)), - A::I64(2560), - A::P(W.index_k_proj), - A::P(at(&m, "idx_raw_L", 2 * 8 * 128 * 4)), - A::I64(128), - A::I32(2560), - A::I32(n as i32) - ] - ); - assert_abi(&l[0]); - } - // second group rows 3..5 of an 8 row bank: x at row 3, y at (layer 11 * 8 + 3) * 128 floats - let l = w.index_k(11, &layer(), rows(3, 5), true).unwrap(); - assert_eq!(l[0].args[0], A::P(at(&m, "mixed", 3 * 2560 * 4))); - assert_eq!(l[0].args[3], A::P(at(&m, "idx_raw_L", (11 * 8 + 3) * 128 * 4))); - // per token - let l = w.index_k(0, &layer(), rows(0, 3), false).unwrap(); - assert_eq!(l.len(), 3); - for (t, launch) in l.iter().enumerate() { - assert_eq!(launch.entry, "mtp_full_mmvf256"); - assert_eq!( - launch.args, - vec![A::P(at(&m, "mixed", t * 2560 * 4)), A::P(W.index_k_proj), A::P(at(&m, "idx_raw_L", t * 128 * 4)), A::I32(2560)] - ); - assert_abi(launch); - } - // a lone row is never batched; layer and row bounds - assert_eq!(w.index_k(0, &layer(), rows(0, 1), true).unwrap_err(), Error::InvalidQwenShape); - assert_eq!(w.index_k(12, &layer(), rows(0, 2), true).unwrap_err(), Error::InvalidQwenShape); - assert_eq!(w.index_k(0, &layer(), rows(0, 9), false).unwrap_err(), Error::InvalidQwenShape); - } - - fn rope_param_count() -> usize { - match rope_abi().unwrap() { - RopeAbi::Frozen => 6, - RopeAbi::Extended => 11, - } - } - - #[test] - fn k_norm_rope_batched_is_one_norm_and_one_rope_over_n_times_two_head_rows() { - let (m, g) = setup(); - let w = window(&m, g); - for n in 2..=8usize { - let l = w.k_norm_rope(1, &layer(), rows(0, n), true).unwrap(); - assert_eq!(l.len(), 2); - let data = at(&m, "kcur", 0); - assert_eq!((l[0].entry, l[0].grid, l[0].block), ("qsa_decode_rms", [2 * n as u32, 1, 1], [256, 1, 1])); - assert_eq!(l[0].args, vec![A::P(data), A::P(W.k_norm), A::P(data), A::I32(256), A::F32(1e-6)]); - assert_eq!((l[1].entry, l[1].grid, l[1].block), ("qsa_decode_rope", [1, 2 * n as u32, 1], [128, 1, 1])); - // pos_k = pos + MT * NH = 8 * 24 ints - assert_eq!(l[1].args[5], A::P(at(&m, "pos", 8 * 24 * 4))); - assert_eq!(l[1].args[..5], [A::P(data), A::P(data), A::I32(2 * n as i32), A::I32(256), A::F32(0.7498942)]); - assert_eq!(l[1].args.len(), rope_param_count()); - l.iter().for_each(assert_abi); - } - // second group: rows 5..8 start at token 5, 2 K rows per token - let l = w.k_norm_rope(0, &layer(), rows(5, 8), true).unwrap(); - assert_eq!(l[0].args[0], A::P(at(&m, "kcur", 5 * 2 * 256 * 4))); - assert_eq!(l[1].args[5], A::P(at(&m, "pos", (8 * 24 + 5 * 2) * 4))); - assert_eq!(l[0].grid, [6, 1, 1]); - } - - #[test] - fn k_norm_rope_per_token_uses_the_pos_rows_of_the_query_layout() { - let (m, g) = setup(); - let w = window(&m, g); - let l = w.k_norm_rope(0, &layer(), rows(2, 4), false).unwrap(); - assert_eq!(l.len(), 4); - // token 2 then 3: NKV rows each, positions pos_ + t * NH - assert_eq!(l[0].args[0], A::P(at(&m, "kcur", 2 * 512 * 4))); - assert_eq!(l[0].grid, [2, 1, 1]); - assert_eq!(l[1].args[5], A::P(at(&m, "pos", 2 * 24 * 4))); - assert_eq!(l[3].args[5], A::P(at(&m, "pos", 3 * 24 * 4))); - assert_eq!(l[3].grid, [1, 2, 1]); - } - - #[test] - fn the_rope_entry_follows_the_declared_abi_and_refuses_scaling_on_frozen_ptx() { - let (m, g) = setup(); - let scaled = QsaRope::new(0.7498942, 0.5, 1.0, 20.0, 1.0, 1.1).unwrap(); - let w = QsaWindow::new(&m, g, OriginalVerifyQsaPolicy::mode17(), scaled).unwrap(); - let frozen = w.rope_with(RopeAbi::Frozen, 0x1000, 4, 256, 0x2000).unwrap_err(); - assert!(matches!(frozen, Error::InvalidDriverValue(msg) if msg.contains("ROPE-ARGS ABI 1"))); - let ext = w.rope_with(RopeAbi::Extended, 0x1000, 4, 256, 0x2000).unwrap(); - assert_eq!(ext.args.len(), 11); - assert_eq!(ext.args[6..], [A::F32(0.5), A::F32(1.0), A::F32(20.0), A::F32(1.0), A::F32(1.1)]); - let id = window(&m, g); - let fro = id.rope_with(RopeAbi::Frozen, 0x1000, 128, 128, 0x2000).unwrap(); - assert_eq!(fro.args.len(), 6); - assert_eq!(fro.grid, [1, 128, 1]); - assert_eq!(id.rope_with(RopeAbi::Extended, 0x1000, 4, 256, 0x2000).unwrap().args.len(), 11); - // positions are 4-byte aligned, widths 128/256 only - assert!(id.rope_with(RopeAbi::Frozen, 0x1000, 4, 256, 0x2002).is_err()); - assert!(id.rope_with(RopeAbi::Frozen, 0x1000, 4, 64, 0x2000).is_err()); - } - - #[test] - fn kv_append_is_one_step_driven_launch_per_row_with_the_host_mirror() { - let (m, g) = setup(); - let w = window(&m, g); - let l = w.kv_append(4, &layer(), rows(1, 4)).unwrap(); - assert_eq!(l.len(), 3); - for (i, launch) in l.iter().enumerate() { - let t = 1 + i; - assert_eq!((launch.entry, launch.grid, launch.block, launch.shared), ("mtp_original_append", [2, 4, 2], [64, 1, 1], 0)); - assert_eq!( - launch.args, - vec![ - A::P(KV.resident[0]), - A::P(KV.resident[1]), - A::P(KV.resident[2]), - A::P(KV.resident[3]), - A::P(KV.table), - A::P(at(&m, "step", t * 16)), - A::P(at(&m, "kcur", t * 512 * 4)), - A::P(at(&m, "vcur", t * 512 * 4)), - A::I32(2), - A::I32(256), - A::I32(4), - A::P(KV.host[0]), - A::P(KV.host[1]), - A::P(KV.host[2]), - A::P(KV.host[3]), - ] - ); - assert_abi(launch); - } - // the binding is validated at capture: aliased owners and short index keys refuse - let mut bad = layer(); - bad.kv.host[1] = bad.kv.resident[0]; - assert_eq!(w.kv_append(0, &bad, rows(0, 1)).unwrap_err(), Error::OutputAliasesInput); - let mut short = layer(); - short.kv.pooled_bytes = 512; - assert!(w.kv_append(0, &short, rows(0, 1)).is_err()); - // the serving image is exactly (max_cells / index_block + 1) rows: it must be admitted - let mut serving = layer(); - serving.kv.pooled_bytes = (4096 / 4 + 1) * 512; - assert!(w.kv_append(0, &serving, rows(0, 1)).is_ok()); - serving.kv.pooled_bytes -= 1; - assert!(w.kv_append(0, &serving, rows(0, 1)).is_err()); - let mut unaligned = layer(); - unaligned.kv.table += 4; - assert!(w.kv_append(0, &unaligned, rows(0, 1)).is_err()); - } - - #[test] - fn q_path_batched_is_split_norm_rope_over_n_times_24_head_rows() { - let (m, g) = setup(); - let w = window(&m, g); - for n in 2..=8usize { - let l = w.q_path(0, &layer(), rows(0, n), true).unwrap(); - assert_eq!(l.len(), 3); - // cudaMemcpy2DAsync width HD*4 x n*NH rows, src pitch HD*2*4: T=n tokens of 24 heads - assert_eq!((l[0].entry, l[0].grid, l[0].block), ("qsa_split_q", [24 * n as u32, 1, 1], [256, 1, 1])); - assert_eq!(l[0].args, vec![A::P(at(&m, "qfull", 0)), A::P(at(&m, "qcur", 0)), A::I64(n as i64)]); - assert_eq!(l[1].grid, [24 * n as u32, 1, 1]); - assert_eq!(l[1].args[1], A::P(W.q_norm)); - assert_eq!(l[2].grid, [1, 24 * n as u32, 1]); - // positions pos_ + tb * NH - assert_eq!(l[2].args[5], A::P(at(&m, "pos", 0))); - l.iter().for_each(assert_abi); - } - let l = w.q_path(0, &layer(), rows(4, 8), true).unwrap(); - assert_eq!(l[0].args[0], A::P(at(&m, "qfull", 4 * 24 * 512 * 4))); - assert_eq!(l[0].args[1], A::P(at(&m, "qcur", 4 * 24 * 256 * 4))); - assert_eq!(l[2].args[5], A::P(at(&m, "pos", 4 * 24 * 4))); - } - - #[test] - fn q_path_per_token_splits_and_rotates_each_token_in_order() { - let (m, g) = setup(); - let w = window(&m, g); - let l = w.q_path(7, &layer(), rows(0, 2), false).unwrap(); - assert_eq!(l.len(), 6); - let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); - assert_eq!(names, ["qsa_split_q", "qsa_decode_rms", "qsa_decode_rope", "qsa_split_q", "qsa_decode_rms", "qsa_decode_rope"]); - assert_eq!(l[0].grid, [24, 1, 1]); - assert_eq!(l[3].args, vec![A::P(at(&m, "qfull", 24 * 512 * 4)), A::P(at(&m, "qcur", 24 * 256 * 4)), A::I64(1)]); - assert_eq!(l[5].args[5], A::P(at(&m, "pos", 24 * 4))); - assert_eq!(l[4].grid, [24, 1, 1]); - } - - #[test] - fn index_q_path_projects_512_outputs_then_norms_and_rotates_index_rows() { - let (m, g) = setup(); - let w = window(&m, g); - for n in 2..=8usize { - let l = w.index_q_path(3, &layer(), rows(0, n), true).unwrap(); - assert_eq!(l.len(), 3); - assert_eq!( - l[0].args, - vec![ - A::P(at(&m, "mixed", 0)), - A::I64(2560), - A::P(W.index_q_proj), - A::P(at(&m, "qidx", 0)), - A::I64(512), - A::I32(2560), - A::I32(n as i32) - ] - ); - assert_eq!(l[0].grid, [512, 1, 1]); - assert_eq!((l[1].grid, l[1].args[1].clone(), l[1].args[3].clone()), ([4 * n as u32, 1, 1], A::P(W.index_q_norm), A::I32(128))); - assert_eq!(l[2].grid, [1, 4 * n as u32, 1]); - assert_eq!(l[2].args[3], A::I32(128)); - // pos_i = pos + MT * (NH + NKV) - assert_eq!(l[2].args[5], A::P(at(&m, "pos", 8 * 26 * 4))); - l.iter().for_each(assert_abi); - } - let l = w.index_q_path(0, &layer(), rows(6, 8), true).unwrap(); - assert_eq!(l[2].args[5], A::P(at(&m, "pos", (8 * 26 + 6 * 4) * 4))); - // per token: single gemv (ldy == n_out), rows IQ, positions pos_ + t * NH - let l = w.index_q_path(0, &layer(), rows(1, 3), false).unwrap(); - assert_eq!(l.len(), 6); - assert_eq!(l[0].entry, "mtp_full_mmvf256"); - assert_eq!(l[0].args[2], A::P(at(&m, "qidx", 512 * 4))); - assert_eq!(l[2].args[5], A::P(at(&m, "pos", 24 * 4))); - assert_eq!(l[2].grid, [1, 4, 1]); - assert_eq!(l[5].args[5], A::P(at(&m, "pos", 2 * 24 * 4))); - } - - #[test] - fn scores_use_the_multi_query_kernel_then_the_radix_topk() { - let (m, g) = setup(); - let w = window(&m, g); - // max_blocks = 4096 / 4 + 2 = 1026, cap = 2051 - for n in 1..=8usize { - let l = w.block_scores_topk(5, &layer(), rows(0, n)).unwrap(); - assert_eq!(l.len(), 2); - assert_eq!((l[0].entry, l[0].grid, l[0].block), ("qsa_decode_scores", [256, 1, 1], [256, 1, 1])); - assert_eq!( - l[0].args, - vec![ - A::P(KV.pooled), - A::P(KV.dead), - A::P(at(&m, "qidx", 0)), - A::P(at(&m, "step", 0)), - A::I32(n as i32), - A::I64(1026), - A::P(at(&m, "scores", 0)) - ] - ); - assert_eq!((l[1].entry, l[1].grid, l[1].block), ("qsa_topk_ref", [n as u32, 1, 1], [256, 1, 1])); - assert_eq!( - l[1].args, - vec![A::P(at(&m, "scores", 0)), A::P(at(&m, "step", 0)), A::I64(1026), A::I64(2051), A::P(at(&m, "sel", 0))] - ); - l.iter().for_each(assert_abi); - } - // group B rows 4..7: q rows, steps (16 B), scores rows (1026 floats) and ids rows (2051 ints) offset by tb - let l = w.block_scores_topk(5, &layer(), rows(4, 7)).unwrap(); - assert_eq!(l[0].args[2], A::P(at(&m, "qidx", 4 * 512 * 4))); - assert_eq!(l[0].args[3], A::P(at(&m, "step", 4 * 16))); - assert_eq!(l[0].args[6], A::P(at(&m, "scores", 4 * 1026 * 4))); - assert_eq!(l[1].args[4], A::P(at(&m, "sel", 4 * 2051 * 4))); - assert_eq!(l[1].grid, [3, 1, 1]); - } - - #[test] - fn the_single_query_score_kernel_is_used_without_the_multi_policy() { - let (m, g) = setup(); - let mut p = OriginalVerifyQsaPolicy::mode17(); - p.scores_multi = false; - let w = QsaWindow::new(&m, g, p, identity()).unwrap(); - let l = w.block_scores_topk(0, &layer(), rows(0, 3)).unwrap(); - assert_eq!(l[0].entry, SCORE_SINGLE); - // grid (ceil(1026 / 8), nq) - assert_eq!((l[0].grid, l[0].block), ([129, 3, 1], [256, 1, 1])); - assert_eq!(l[0].args.len(), 6); - assert_eq!(l[0].args[4], A::I64(1026)); - assert_abi(&l[0]); - } - - #[test] - fn production_context_geometry_scales_the_block_arrays() { - let mut g = test_geometry(); - g.max_cells = 262144; - let m = LayoutMap::new(BASE, g); - let w = QsaWindow::new(&m, g, OriginalVerifyQsaPolicy::mode17(), identity()).unwrap(); - let mut kv = KV; - kv.pooled_bytes = 65538 * 512; - let l = QsaLayerAddrs { weights: W, kv }; - let launches = w.block_scores_topk(0, &l, rows(2, 4)).unwrap(); - assert_eq!(launches[0].args[5], A::I64(65538)); - assert_eq!(launches[0].args[6], A::P(at(&m, "scores", 2 * 65538 * 4))); - assert_eq!(launches[1].args[2], A::I64(65538)); - } - - #[test] - fn resolve_is_the_clock_kernel_then_the_96_block_miss_copy() { - let (m, g) = setup(); - let w = window(&m, g); - for n in 1..=8usize { - let l = w.kv_resolve(9, &layer(), rows(0, n)).unwrap(); - assert_eq!(l.len(), 2); - assert_eq!((l[0].entry, l[0].grid, l[0].block), ("leleka_qsa_resolve", [1, 1, 1], [1024, 1, 1])); - let mut want: Vec = KV.resolver.iter().map(|&a| A::P(a)).collect(); - want.extend([A::P(at(&m, "sel", 0)), A::P(at(&m, "step", 0)), A::I32(n as i32), A::I64(8192)]); - assert_eq!(l[0].args, want); - assert_eq!((l[1].entry, l[1].grid, l[1].block), ("leleka_qsa_miss_copy", [96, 1, 1], [128, 1, 1])); - let mut copy = vec![A::P(KV.resolver[4]), A::P(KV.resolver[5]), A::P(KV.resolver[6])]; - copy.extend(KV.host.iter().chain(&KV.resident).map(|&a| A::P(a))); - assert_eq!(l[1].args, copy); - l.iter().for_each(assert_abi); - } - let l = w.kv_resolve(0, &layer(), rows(3, 6)).unwrap(); - assert_eq!(l[0].args[7], A::P(at(&m, "sel", 3 * 2051 * 4))); - assert_eq!(l[0].args[8], A::P(at(&m, "step", 3 * 16))); - assert_eq!(l[0].args[9], A::I32(3)); - assert_eq!(l[0].args[10], A::I64(8192)); - } - - #[test] - fn resolve_launches_with_the_owners_resident_window_and_refuses_one_too_small() { - let (m, g) = setup(); - let w = window(&m, g); - // --kv-resident 20480: 5120 slots hold the selections of a whole 8-row window - let mut l = layer(); - l.kv.slots = 5120; - let launches = w.kv_resolve(0, &l, rows(0, 8)).unwrap(); - assert_eq!(launches[0].args[10], A::I64(5120)); - launches.iter().for_each(assert_abi); - // fewer slots than the resolve block, or than one call can miss, is refused before any launch - l.kv.slots = 1023; - assert!(w.kv_resolve(0, &l, rows(0, 1)).is_err()); - l.kv.slots = 1024; - assert!(w.kv_resolve(0, &l, rows(0, 1)).is_ok()); - assert!(w.kv_resolve(0, &l, rows(0, 2)).is_err()); - } - - #[test] - fn attention_chunk_and_merge_grids_cover_33_chunks_per_query() { - let (m, g) = setup(); - let w = window(&m, g); - // ceil(2051 / 64) = 33 chunks; scratch floats = 33 * 24 * 258 + 64 = 204400 - let stride = 33 * 24 * 258 + 64; - assert_eq!(stride, 204_400); - for n in 1..=8usize { - let l = w.decode_attention(2, &layer(), rows(0, n)).unwrap(); - assert_eq!(l.len(), 2); - assert_eq!((l[0].entry, l[0].grid, l[0].block, l[0].shared), ("leleka_qsa_decode_chunk", [33, 2, n as u32], [256, 1, 1], 0)); - let acc = at(&m, "attn_scratch", 0); - assert_eq!( - l[0].args, - vec![ - A::P(at(&m, "qcur", 0)), - A::P(KV.resident[0]), - A::P(KV.resident[1]), - A::P(KV.resident[2]), - A::P(KV.resident[3]), - A::P(KV.table), - A::P(at(&m, "sel", 0)), - A::P(at(&m, "step", 0)), - A::I32(2), - A::I32(4), - A::F32(0.0625), - A::P(acc), - // part_m after n_chunks * n_head * HD floats, part_l after n_chunks * n_head more - A::P(acc + 33 * 24 * 256 * 4), - A::P(acc + (33 * 24 * 256 + 33 * 24) * 4), - A::I32(33), - A::I32(2051), - A::I64(stride as i64) - ] - ); - assert_eq!((l[1].entry, l[1].grid, l[1].block), ("leleka_qsa_decode_merge", [24, n as u32, 1], [256, 1, 1])); - assert_eq!( - l[1].args, - vec![ - A::P(acc), - A::P(acc + 33 * 24 * 256 * 4), - A::P(acc + (33 * 24 * 256 + 33 * 24) * 4), - A::I32(33), - A::P(at(&m, "attn", 0)), - A::I64(stride as i64) - ] - ); - l.iter().for_each(assert_abi); - } - let l = w.decode_attention(2, &layer(), rows(5, 8)).unwrap(); - assert_eq!(l[0].args[0], A::P(at(&m, "qcur", 5 * 24 * 256 * 4))); - assert_eq!(l[0].args[11], A::P(at(&m, "attn_scratch", 5 * stride * 4))); - assert_eq!(l[0].args[6], A::P(at(&m, "sel", 5 * 2051 * 4))); - assert_eq!(l[1].args[4], A::P(at(&m, "attn", 5 * 24 * 256 * 4))); - // the per-query scratch region holds acc + m + l - assert!(((33 * 24 * 258) as usize) < stride); - } - - #[test] - fn gate_is_one_launch_over_n_times_24_heads_when_batched() { - let (m, g) = setup(); - let w = window(&m, g); - for n in 2..=8usize { - let l = w.gate(1, rows(0, n), true).unwrap(); - assert_eq!(l.len(), 1); - // ceil(n * 24 * 256 / 256) blocks of 256 threads - assert_eq!((l[0].entry, l[0].grid, l[0].block), ("verify_window_qsa_gate", [24 * n as u32, 1, 1], [256, 1, 1])); - assert_eq!( - l[0].args, - vec![A::P(at(&m, "attn", 0)), A::P(at(&m, "qfull", 0)), A::P(at(&m, "attn32", 0)), A::I32(24 * n as i32), A::I32(256)] - ); - } - let l = w.gate(1, rows(2, 5), false).unwrap(); - assert_eq!(l.len(), 3); - assert_eq!(l[1].args[0], A::P(at(&m, "attn", 3 * 6144 * 4))); - assert_eq!(l[1].args[1], A::P(at(&m, "qfull", 3 * 12288 * 4))); - assert_eq!(l[1].args[2], A::P(at(&m, "attn32", 3 * 6144 * 4))); - assert_eq!(l[1].args[3], A::I32(24)); - assert_eq!(l[1].grid, [24, 1, 1]); - } - - #[test] - fn a_corrupted_gate_pin_fails_closed_by_name_but_other_plans_are_unaffected() { - assert!(GATE.sealed().is_ok()); - // loading goes through `AssetSpec::sealed`, which names the refused asset; exercised on synthetic copies - // (a one-byte-corrupted body and a wrong digest) of the real gate PTX - let bytes = GATE.derived(crate::sealed_ptx::test_support::one_byte_corrupted(GATE.ptx), GATE.sha); - let digest = GATE.derived(GATE.ptx, [3; 32]); - for bad in [bytes, digest] { - let err = bad.sealed().unwrap_err(); - assert!(matches!(err, Error::InvalidDriverValue(m) if m.contains("original_verify_window_qsa_gate.ptx"))); - assert!(!bad.entries.is_empty() && bad.has_entry("verify_window_qsa_gate")); - } - let (m, g) = setup(); - let w = window(&m, g); - assert!(w.kv_resolve(0, &layer(), rows(0, 2)).is_ok()); - assert!(w.gate(0, rows(0, 2), true).is_ok()); - } - - #[test] - fn the_whole_layer_sequence_follows_verify_cpp_for_one_group() { - // order of the producers' first launch across a batched QSA layer (projections excluded) - let (m, g) = setup(); - let w = window(&m, g); - let r = rows(0, 4); - let a = layer(); - let mut seq: Vec<&str> = Vec::new(); - for l in [ - w.index_k(0, &a, r, true).unwrap(), - w.k_norm_rope(0, &a, r, true).unwrap(), - w.kv_append(0, &a, r).unwrap(), - w.q_path(0, &a, r, true).unwrap(), - w.index_q_path(0, &a, r, true).unwrap(), - w.block_scores_topk(0, &a, r).unwrap(), - w.kv_resolve(0, &a, r).unwrap(), - w.decode_attention(0, &a, r).unwrap(), - w.gate(0, r, true).unwrap(), - ] { - seq.extend(l.iter().map(|x| x.entry)); - } - assert_eq!(seq.len(), 1 + 2 + 4 + 3 + 3 + 2 + 2 + 2 + 1); - assert_eq!(seq[1], "qsa_decode_rms"); - assert_eq!(seq[seq.len() - 1], "verify_window_qsa_gate"); - } - - #[test] - fn weight_sizes_are_the_original_tensor_shapes() { - let g = test_geometry(); - assert_eq!(OriginalVerifyQsaBinding::sizes(&g), [1024, 1024, 512, 128 * 2560 * 2, 512 * 2560 * 2]); - assert_eq!(max_blocks(&g), 1026); - assert_eq!(scratch_floats(&g), 204_400); - assert!(KV.validate(&g).is_ok()); - } - - #[test] - fn construction_refuses_unsupported_geometry_and_policy() { - let (m, g) = setup(); - let mut bad = g; - bad.selection = 2048; - assert!(QsaWindow::new(&m, bad, OriginalVerifyQsaPolicy::mode17(), identity()).is_err()); - let mut p = OriginalVerifyQsaPolicy::mode17(); - p.kv_q4 = true; - assert!(QsaWindow::new(&m, g, p, identity()).is_err()); - } -} +#[path = "original_verify_window_qsa/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_verify_window_qsa/tests.rs b/crates/cuda-driver/src/original_verify_window_qsa/tests.rs new file mode 100644 index 00000000..003e9456 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_qsa/tests.rs @@ -0,0 +1,652 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::super::kernels::{LayoutMap, test_geometry}; +use super::*; + +const BASE: u64 = 0x7000_0000_0000; +const KV: OriginalVerifyQsaKvBinding = OriginalVerifyQsaKvBinding { + resident: [0x1_0000_0000, 0x1_1000_0000, 0x1_2000_0000, 0x1_2100_0000], + table: 0x1_3000_0000, + host: [0x2_0000_0000, 0x2_1000_0000, 0x2_2000_0000, 0x2_2100_0000], + resolver: [0x1_3000_0000, 0x1_3100_0000, 0x1_3200_0000, 0x1_3300_0000, 0x1_3400_0000, 0x1_3500_0000, 0x1_3600_0000], + slots: 8192, + pooled: 0x1_4000_0000, + pooled_bytes: 1026 * 512, + dead: 0x1_4100_0000, + dead_bytes: 512, +}; +const W: QsaWeightAddrs = QsaWeightAddrs { + q_norm: 0x3_0000_0000, + k_norm: 0x3_0001_0000, + index_q_norm: 0x3_0002_0000, + index_k_proj: 0x3_1000_0000, + index_q_proj: 0x3_2000_0000, +}; +fn layer() -> QsaLayerAddrs { + QsaLayerAddrs { weights: W, kv: KV } +} +fn identity() -> QsaRope { + QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0).unwrap() +} +fn rows(begin: usize, end: usize) -> Rows { + Rows { begin, end, group: if begin == 0 { 0 } else { 1 } } +} +fn setup() -> (LayoutMap, OriginalVerifyGeometry) { + let g = test_geometry(); + (LayoutMap::new(BASE, g), g) +} +fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { + BASE + m.layout.span(name).unwrap().offset as u64 + offset as u64 +} +fn window(m: &LayoutMap, g: OriginalVerifyGeometry) -> QsaWindow<'_> { + QsaWindow::new(m, g, OriginalVerifyQsaPolicy::mode17(), identity()).unwrap() +} + +/// `.param` count the PTX declares for `entry`. +fn declared_params(ptx: &[u8], entry: &str) -> usize { + let text = String::from_utf8_lossy(ptx); + let head = format!(".entry {entry}("); + let at = text.find(&head).unwrap_or_else(|| panic!("{entry} not declared")); + let rest = &text[at..]; + let end = rest.find("\n)\n").expect("entry parameter list end"); + rest[..end].matches(".param").count() +} +fn assert_abi(l: &Launch) { + assert_eq!(declared_params(l.asset.ptx, l.entry), l.args.len(), "{}", l.label()); +} + +#[test] +fn sealed_assets_are_pinned_and_export_every_named_entry() { + for spec in assets() { + spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); + let text = String::from_utf8_lossy(spec.ptx); + for e in spec.entries { + assert!(text.contains(&format!(".entry {e}(")), "{} lacks {e}", spec.name); + } + } +} + +#[test] +fn the_new_gate_asset_is_sealed_with_a_matching_source() { + // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim). + GATE.assert_sealed_and_fail_closed(); + assert_eq!(GATE.ptx.iter().filter(|&&b| b == 0).count(), 1); + let source = include_str!("../original_verify_window_qsa_gate.cu"); + for e in GATE.entries { + assert!(source.contains(&format!("extern \"C\" __global__ void {e}(")), "{e}"); + } + // the body is the Original `gate`: second half of each [head][2][head_dim] row + assert!(source.contains("q_full[head * 2 * head_dim + head_dim + channel]")); + assert!(source.contains("1.0f / (1.0f + expf(-raw))")); + assert!(include_str!("../../../../docs/cuda-seal-plan-additions-window.json").contains("--use_fast_math")); +} + +#[test] +fn asset_set_has_distinct_names_and_the_bf16_projection_module() { + let a = assets(); + let mut names: Vec<&str> = a.iter().map(|s| s.name).collect(); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), a.len()); + assert!(a.iter().any(|s| std::ptr::eq(*s, &proj::BF16))); + let g = test_geometry(); + assert!(shared_attributes(&OriginalVerifyQsaPolicy::mode17(), &g).is_empty()); + assert!(cluster_assets(&OriginalVerifyQsaPolicy::mode17()).is_empty()); + // the cluster top-k: its module is loaded only on request and opts into the dynamic shared memory of its keys + let p = OriginalVerifyQsaPolicy { cluster_topk: true, ..OriginalVerifyQsaPolicy::mode17() }; + assert!(cluster_assets(&p).iter().any(|s| std::ptr::eq(*s, &CLUSTER))); + assert!(!a.iter().any(|s| std::ptr::eq(*s, &CLUSTER)), "the cluster module is not in the always-loaded list"); + let attributes = shared_attributes(&p, &g); + assert_eq!(attributes.len(), 1); + assert!(std::ptr::eq(attributes[0].0, &CLUSTER)); + assert_eq!((attributes[0].1, attributes[0].2), ("leleka_qsa_topk_cluster", max_blocks(&g).div_ceil(8) * 4)); + CLUSTER.assert_sealed_and_fail_closed(); +} + +#[test] +fn the_cluster_policy_replaces_only_the_topk_launch_and_keeps_its_arguments() { + let (m, g) = setup(); + let reference = window(&m, g).block_scores_topk(0, &layer(), rows(0, 3)).unwrap(); + let p = OriginalVerifyQsaPolicy { cluster_topk: true, ..OriginalVerifyQsaPolicy::mode17() }; + let w = QsaWindow::new(&m, g, p, identity()).unwrap(); + let l = w.block_scores_topk(0, &layer(), rows(0, 3)).unwrap(); + assert_eq!(l.len(), 2); + assert_eq!(l[0], reference[0], "the scores launch is untouched"); + assert_eq!(l[1].entry, "leleka_qsa_topk_cluster"); + assert_eq!((l[1].grid, l[1].block, l[1].cluster), ([8, 3, 1], [1024, 1, 1], 8)); + assert_eq!(l[1].shared as usize, max_blocks(&g).div_ceil(8) * 4); + assert_eq!(l[1].args, reference[1].args, "scores, steps, max_blocks, cap, ids as qsa_topk_ref"); + assert_eq!(reference[1].cluster, 0); + assert_abi(&l[1]); +} + +#[test] +fn policy_refuses_every_variant_without_a_sealed_owner() { + assert!(OriginalVerifyQsaPolicy::mode17().validate().is_ok()); + let base = OriginalVerifyQsaPolicy::mode17(); + let variants: [fn(&mut OriginalVerifyQsaPolicy); 8] = [ + |p| p.native_qsa = false, + |p| p.native_rope = false, + |p| p.kv_q4 = true, + |p| p.kv_hybrid = true, + |p| p.kv_rot = true, + |p| p.without_key = true, + |p| p.trace = true, + |p| p.kv_streamed = false, + ]; + let mut seen = std::collections::BTreeSet::new(); + for f in variants { + let mut p = base; + f(&mut p); + match p.validate().unwrap_err() { + Error::InvalidDriverValue(m) => { + assert!(m.starts_with("Original verifier producer unavailable: qsa: "), "{m}"); + seen.insert(m); + } + e => panic!("{e:?}"), + } + } + assert!(seen.len() >= 6, "reasons are specific: {seen:?}"); + let mut fp16 = base; + fp16.kv_int8 = false; + assert!(fp16.validate().is_err()); +} + +#[test] +fn rope_constants_refuse_tables_and_non_finite_values() { + assert!(QsaRope::new(f32::NAN, 1.0, 0.0, 0.0, 0.0, 1.0).is_err()); + assert!(QsaRope::new(0.7, 0.0, 0.0, 0.0, 0.0, 1.0).is_err()); + assert!(QsaRope::new(0.7, 1.0, 0.0, 0.0, -1.0, 1.0).is_err()); + assert!(identity().is_identity()); + assert!(!QsaRope::new(0.7, 0.5, 0.0, 0.0, 1.0, 1.1).unwrap().is_identity()); +} + +#[test] +fn index_k_is_one_multi_gemv_when_batched_and_a_single_gemv_per_token_otherwise() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 2..=8usize { + let l = w.index_k(2, &layer(), rows(0, n), true).unwrap(); + assert_eq!(l.len(), 1); + let nt = if n <= 4 { "ELi4EE" } else { "ELi8EE" }; + assert!(l[0].entry.contains("ILi256") && l[0].entry.contains(nt), "{}", l[0].entry); + assert_eq!((l[0].grid, l[0].block), ([128, 1, 1], [256, 1, 1])); + // x = mixed, ldx = 2560, w, y = idx_raw layer 2 row 0, ldy = 128, n_in = 2560, n_tok + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "mixed", 0)), + A::I64(2560), + A::P(W.index_k_proj), + A::P(at(&m, "idx_raw_L", 2 * 8 * 128 * 4)), + A::I64(128), + A::I32(2560), + A::I32(n as i32) + ] + ); + assert_abi(&l[0]); + } + // second group rows 3..5 of an 8 row bank: x at row 3, y at (layer 11 * 8 + 3) * 128 floats + let l = w.index_k(11, &layer(), rows(3, 5), true).unwrap(); + assert_eq!(l[0].args[0], A::P(at(&m, "mixed", 3 * 2560 * 4))); + assert_eq!(l[0].args[3], A::P(at(&m, "idx_raw_L", (11 * 8 + 3) * 128 * 4))); + // per token + let l = w.index_k(0, &layer(), rows(0, 3), false).unwrap(); + assert_eq!(l.len(), 3); + for (t, launch) in l.iter().enumerate() { + assert_eq!(launch.entry, "mtp_full_mmvf256"); + assert_eq!( + launch.args, + vec![A::P(at(&m, "mixed", t * 2560 * 4)), A::P(W.index_k_proj), A::P(at(&m, "idx_raw_L", t * 128 * 4)), A::I32(2560)] + ); + assert_abi(launch); + } + // a lone row is never batched; layer and row bounds + assert_eq!(w.index_k(0, &layer(), rows(0, 1), true).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(w.index_k(12, &layer(), rows(0, 2), true).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(w.index_k(0, &layer(), rows(0, 9), false).unwrap_err(), Error::InvalidQwenShape); +} + +fn rope_param_count() -> usize { + match rope_abi().unwrap() { + RopeAbi::Frozen => 6, + RopeAbi::Extended => 11, + } +} + +#[test] +fn k_norm_rope_batched_is_one_norm_and_one_rope_over_n_times_two_head_rows() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 2..=8usize { + let l = w.k_norm_rope(1, &layer(), rows(0, n), true).unwrap(); + assert_eq!(l.len(), 2); + let data = at(&m, "kcur", 0); + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("qsa_decode_rms", [2 * n as u32, 1, 1], [256, 1, 1])); + assert_eq!(l[0].args, vec![A::P(data), A::P(W.k_norm), A::P(data), A::I32(256), A::F32(1e-6)]); + assert_eq!((l[1].entry, l[1].grid, l[1].block), ("qsa_decode_rope", [1, 2 * n as u32, 1], [128, 1, 1])); + // pos_k = pos + MT * NH = 8 * 24 ints + assert_eq!(l[1].args[5], A::P(at(&m, "pos", 8 * 24 * 4))); + assert_eq!(l[1].args[..5], [A::P(data), A::P(data), A::I32(2 * n as i32), A::I32(256), A::F32(0.7498942)]); + assert_eq!(l[1].args.len(), rope_param_count()); + l.iter().for_each(assert_abi); + } + // second group: rows 5..8 start at token 5, 2 K rows per token + let l = w.k_norm_rope(0, &layer(), rows(5, 8), true).unwrap(); + assert_eq!(l[0].args[0], A::P(at(&m, "kcur", 5 * 2 * 256 * 4))); + assert_eq!(l[1].args[5], A::P(at(&m, "pos", (8 * 24 + 5 * 2) * 4))); + assert_eq!(l[0].grid, [6, 1, 1]); +} + +#[test] +fn k_norm_rope_per_token_uses_the_pos_rows_of_the_query_layout() { + let (m, g) = setup(); + let w = window(&m, g); + let l = w.k_norm_rope(0, &layer(), rows(2, 4), false).unwrap(); + assert_eq!(l.len(), 4); + // token 2 then 3: NKV rows each, positions pos_ + t * NH + assert_eq!(l[0].args[0], A::P(at(&m, "kcur", 2 * 512 * 4))); + assert_eq!(l[0].grid, [2, 1, 1]); + assert_eq!(l[1].args[5], A::P(at(&m, "pos", 2 * 24 * 4))); + assert_eq!(l[3].args[5], A::P(at(&m, "pos", 3 * 24 * 4))); + assert_eq!(l[3].grid, [1, 2, 1]); +} + +#[test] +fn the_rope_entry_follows_the_declared_abi_and_refuses_scaling_on_frozen_ptx() { + let (m, g) = setup(); + let scaled = QsaRope::new(0.7498942, 0.5, 1.0, 20.0, 1.0, 1.1).unwrap(); + let w = QsaWindow::new(&m, g, OriginalVerifyQsaPolicy::mode17(), scaled).unwrap(); + let frozen = w.rope_with(RopeAbi::Frozen, 0x1000, 4, 256, 0x2000).unwrap_err(); + assert!(matches!(frozen, Error::InvalidDriverValue(msg) if msg.contains("ROPE-ARGS ABI 1"))); + let ext = w.rope_with(RopeAbi::Extended, 0x1000, 4, 256, 0x2000).unwrap(); + assert_eq!(ext.args.len(), 11); + assert_eq!(ext.args[6..], [A::F32(0.5), A::F32(1.0), A::F32(20.0), A::F32(1.0), A::F32(1.1)]); + let id = window(&m, g); + let fro = id.rope_with(RopeAbi::Frozen, 0x1000, 128, 128, 0x2000).unwrap(); + assert_eq!(fro.args.len(), 6); + assert_eq!(fro.grid, [1, 128, 1]); + assert_eq!(id.rope_with(RopeAbi::Extended, 0x1000, 4, 256, 0x2000).unwrap().args.len(), 11); + // positions are 4-byte aligned, widths 128/256 only + assert!(id.rope_with(RopeAbi::Frozen, 0x1000, 4, 256, 0x2002).is_err()); + assert!(id.rope_with(RopeAbi::Frozen, 0x1000, 4, 64, 0x2000).is_err()); +} + +#[test] +fn kv_append_is_one_step_driven_launch_per_row_with_the_host_mirror() { + let (m, g) = setup(); + let w = window(&m, g); + let l = w.kv_append(4, &layer(), rows(1, 4)).unwrap(); + assert_eq!(l.len(), 3); + for (i, launch) in l.iter().enumerate() { + let t = 1 + i; + assert_eq!((launch.entry, launch.grid, launch.block, launch.shared), ("mtp_original_append", [2, 4, 2], [64, 1, 1], 0)); + assert_eq!( + launch.args, + vec![ + A::P(KV.resident[0]), + A::P(KV.resident[1]), + A::P(KV.resident[2]), + A::P(KV.resident[3]), + A::P(KV.table), + A::P(at(&m, "step", t * 16)), + A::P(at(&m, "kcur", t * 512 * 4)), + A::P(at(&m, "vcur", t * 512 * 4)), + A::I32(2), + A::I32(256), + A::I32(4), + A::P(KV.host[0]), + A::P(KV.host[1]), + A::P(KV.host[2]), + A::P(KV.host[3]), + ] + ); + assert_abi(launch); + } + // the binding is validated at capture: aliased owners and short index keys refuse + let mut bad = layer(); + bad.kv.host[1] = bad.kv.resident[0]; + assert_eq!(w.kv_append(0, &bad, rows(0, 1)).unwrap_err(), Error::OutputAliasesInput); + let mut short = layer(); + short.kv.pooled_bytes = 512; + assert!(w.kv_append(0, &short, rows(0, 1)).is_err()); + // the serving image is exactly (max_cells / index_block + 1) rows: it must be admitted + let mut serving = layer(); + serving.kv.pooled_bytes = (4096 / 4 + 1) * 512; + assert!(w.kv_append(0, &serving, rows(0, 1)).is_ok()); + serving.kv.pooled_bytes -= 1; + assert!(w.kv_append(0, &serving, rows(0, 1)).is_err()); + let mut unaligned = layer(); + unaligned.kv.table += 4; + assert!(w.kv_append(0, &unaligned, rows(0, 1)).is_err()); +} + +#[test] +fn q_path_batched_is_split_norm_rope_over_n_times_24_head_rows() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 2..=8usize { + let l = w.q_path(0, &layer(), rows(0, n), true).unwrap(); + assert_eq!(l.len(), 3); + // cudaMemcpy2DAsync width HD*4 x n*NH rows, src pitch HD*2*4: T=n tokens of 24 heads + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("qsa_split_q", [24 * n as u32, 1, 1], [256, 1, 1])); + assert_eq!(l[0].args, vec![A::P(at(&m, "qfull", 0)), A::P(at(&m, "qcur", 0)), A::I64(n as i64)]); + assert_eq!(l[1].grid, [24 * n as u32, 1, 1]); + assert_eq!(l[1].args[1], A::P(W.q_norm)); + assert_eq!(l[2].grid, [1, 24 * n as u32, 1]); + // positions pos_ + tb * NH + assert_eq!(l[2].args[5], A::P(at(&m, "pos", 0))); + l.iter().for_each(assert_abi); + } + let l = w.q_path(0, &layer(), rows(4, 8), true).unwrap(); + assert_eq!(l[0].args[0], A::P(at(&m, "qfull", 4 * 24 * 512 * 4))); + assert_eq!(l[0].args[1], A::P(at(&m, "qcur", 4 * 24 * 256 * 4))); + assert_eq!(l[2].args[5], A::P(at(&m, "pos", 4 * 24 * 4))); +} + +#[test] +fn q_path_per_token_splits_and_rotates_each_token_in_order() { + let (m, g) = setup(); + let w = window(&m, g); + let l = w.q_path(7, &layer(), rows(0, 2), false).unwrap(); + assert_eq!(l.len(), 6); + let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); + assert_eq!(names, ["qsa_split_q", "qsa_decode_rms", "qsa_decode_rope", "qsa_split_q", "qsa_decode_rms", "qsa_decode_rope"]); + assert_eq!(l[0].grid, [24, 1, 1]); + assert_eq!(l[3].args, vec![A::P(at(&m, "qfull", 24 * 512 * 4)), A::P(at(&m, "qcur", 24 * 256 * 4)), A::I64(1)]); + assert_eq!(l[5].args[5], A::P(at(&m, "pos", 24 * 4))); + assert_eq!(l[4].grid, [24, 1, 1]); +} + +#[test] +fn index_q_path_projects_512_outputs_then_norms_and_rotates_index_rows() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 2..=8usize { + let l = w.index_q_path(3, &layer(), rows(0, n), true).unwrap(); + assert_eq!(l.len(), 3); + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "mixed", 0)), + A::I64(2560), + A::P(W.index_q_proj), + A::P(at(&m, "qidx", 0)), + A::I64(512), + A::I32(2560), + A::I32(n as i32) + ] + ); + assert_eq!(l[0].grid, [512, 1, 1]); + assert_eq!((l[1].grid, l[1].args[1].clone(), l[1].args[3].clone()), ([4 * n as u32, 1, 1], A::P(W.index_q_norm), A::I32(128))); + assert_eq!(l[2].grid, [1, 4 * n as u32, 1]); + assert_eq!(l[2].args[3], A::I32(128)); + // pos_i = pos + MT * (NH + NKV) + assert_eq!(l[2].args[5], A::P(at(&m, "pos", 8 * 26 * 4))); + l.iter().for_each(assert_abi); + } + let l = w.index_q_path(0, &layer(), rows(6, 8), true).unwrap(); + assert_eq!(l[2].args[5], A::P(at(&m, "pos", (8 * 26 + 6 * 4) * 4))); + // per token: single gemv (ldy == n_out), rows IQ, positions pos_ + t * NH + let l = w.index_q_path(0, &layer(), rows(1, 3), false).unwrap(); + assert_eq!(l.len(), 6); + assert_eq!(l[0].entry, "mtp_full_mmvf256"); + assert_eq!(l[0].args[2], A::P(at(&m, "qidx", 512 * 4))); + assert_eq!(l[2].args[5], A::P(at(&m, "pos", 24 * 4))); + assert_eq!(l[2].grid, [1, 4, 1]); + assert_eq!(l[5].args[5], A::P(at(&m, "pos", 2 * 24 * 4))); +} + +#[test] +fn scores_use_the_multi_query_kernel_then_the_radix_topk() { + let (m, g) = setup(); + let w = window(&m, g); + // max_blocks = 4096 / 4 + 2 = 1026, cap = 2051 + for n in 1..=8usize { + let l = w.block_scores_topk(5, &layer(), rows(0, n)).unwrap(); + assert_eq!(l.len(), 2); + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("qsa_decode_scores", [256, 1, 1], [256, 1, 1])); + assert_eq!( + l[0].args, + vec![ + A::P(KV.pooled), + A::P(KV.dead), + A::P(at(&m, "qidx", 0)), + A::P(at(&m, "step", 0)), + A::I32(n as i32), + A::I64(1026), + A::P(at(&m, "scores", 0)) + ] + ); + assert_eq!((l[1].entry, l[1].grid, l[1].block), ("qsa_topk_ref", [n as u32, 1, 1], [256, 1, 1])); + assert_eq!( + l[1].args, + vec![A::P(at(&m, "scores", 0)), A::P(at(&m, "step", 0)), A::I64(1026), A::I64(2051), A::P(at(&m, "sel", 0))] + ); + l.iter().for_each(assert_abi); + } + // group B rows 4..7: q rows, steps (16 B), scores rows (1026 floats) and ids rows (2051 ints) offset by tb + let l = w.block_scores_topk(5, &layer(), rows(4, 7)).unwrap(); + assert_eq!(l[0].args[2], A::P(at(&m, "qidx", 4 * 512 * 4))); + assert_eq!(l[0].args[3], A::P(at(&m, "step", 4 * 16))); + assert_eq!(l[0].args[6], A::P(at(&m, "scores", 4 * 1026 * 4))); + assert_eq!(l[1].args[4], A::P(at(&m, "sel", 4 * 2051 * 4))); + assert_eq!(l[1].grid, [3, 1, 1]); +} + +#[test] +fn the_single_query_score_kernel_is_used_without_the_multi_policy() { + let (m, g) = setup(); + let mut p = OriginalVerifyQsaPolicy::mode17(); + p.scores_multi = false; + let w = QsaWindow::new(&m, g, p, identity()).unwrap(); + let l = w.block_scores_topk(0, &layer(), rows(0, 3)).unwrap(); + assert_eq!(l[0].entry, SCORE_SINGLE); + // grid (ceil(1026 / 8), nq) + assert_eq!((l[0].grid, l[0].block), ([129, 3, 1], [256, 1, 1])); + assert_eq!(l[0].args.len(), 6); + assert_eq!(l[0].args[4], A::I64(1026)); + assert_abi(&l[0]); +} + +#[test] +fn production_context_geometry_scales_the_block_arrays() { + let mut g = test_geometry(); + g.max_cells = 262144; + let m = LayoutMap::new(BASE, g); + let w = QsaWindow::new(&m, g, OriginalVerifyQsaPolicy::mode17(), identity()).unwrap(); + let mut kv = KV; + kv.pooled_bytes = 65538 * 512; + let l = QsaLayerAddrs { weights: W, kv }; + let launches = w.block_scores_topk(0, &l, rows(2, 4)).unwrap(); + assert_eq!(launches[0].args[5], A::I64(65538)); + assert_eq!(launches[0].args[6], A::P(at(&m, "scores", 2 * 65538 * 4))); + assert_eq!(launches[1].args[2], A::I64(65538)); +} + +#[test] +fn resolve_is_the_clock_kernel_then_the_96_block_miss_copy() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 1..=8usize { + let l = w.kv_resolve(9, &layer(), rows(0, n)).unwrap(); + assert_eq!(l.len(), 2); + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("leleka_qsa_resolve", [1, 1, 1], [1024, 1, 1])); + let mut want: Vec = KV.resolver.iter().map(|&a| A::P(a)).collect(); + want.extend([A::P(at(&m, "sel", 0)), A::P(at(&m, "step", 0)), A::I32(n as i32), A::I64(8192)]); + assert_eq!(l[0].args, want); + assert_eq!((l[1].entry, l[1].grid, l[1].block), ("leleka_qsa_miss_copy", [96, 1, 1], [128, 1, 1])); + let mut copy = vec![A::P(KV.resolver[4]), A::P(KV.resolver[5]), A::P(KV.resolver[6])]; + copy.extend(KV.host.iter().chain(&KV.resident).map(|&a| A::P(a))); + assert_eq!(l[1].args, copy); + l.iter().for_each(assert_abi); + } + let l = w.kv_resolve(0, &layer(), rows(3, 6)).unwrap(); + assert_eq!(l[0].args[7], A::P(at(&m, "sel", 3 * 2051 * 4))); + assert_eq!(l[0].args[8], A::P(at(&m, "step", 3 * 16))); + assert_eq!(l[0].args[9], A::I32(3)); + assert_eq!(l[0].args[10], A::I64(8192)); +} + +#[test] +fn resolve_launches_with_the_owners_resident_window_and_refuses_one_too_small() { + let (m, g) = setup(); + let w = window(&m, g); + // --kv-resident 20480: 5120 slots hold the selections of a whole 8-row window + let mut l = layer(); + l.kv.slots = 5120; + let launches = w.kv_resolve(0, &l, rows(0, 8)).unwrap(); + assert_eq!(launches[0].args[10], A::I64(5120)); + launches.iter().for_each(assert_abi); + // fewer slots than the resolve block, or than one call can miss, is refused before any launch + l.kv.slots = 1023; + assert!(w.kv_resolve(0, &l, rows(0, 1)).is_err()); + l.kv.slots = 1024; + assert!(w.kv_resolve(0, &l, rows(0, 1)).is_ok()); + assert!(w.kv_resolve(0, &l, rows(0, 2)).is_err()); +} + +#[test] +fn attention_chunk_and_merge_grids_cover_33_chunks_per_query() { + let (m, g) = setup(); + let w = window(&m, g); + // ceil(2051 / 64) = 33 chunks; scratch floats = 33 * 24 * 258 + 64 = 204400 + let stride = 33 * 24 * 258 + 64; + assert_eq!(stride, 204_400); + for n in 1..=8usize { + let l = w.decode_attention(2, &layer(), rows(0, n)).unwrap(); + assert_eq!(l.len(), 2); + assert_eq!((l[0].entry, l[0].grid, l[0].block, l[0].shared), ("leleka_qsa_decode_chunk", [33, 2, n as u32], [256, 1, 1], 0)); + let acc = at(&m, "attn_scratch", 0); + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "qcur", 0)), + A::P(KV.resident[0]), + A::P(KV.resident[1]), + A::P(KV.resident[2]), + A::P(KV.resident[3]), + A::P(KV.table), + A::P(at(&m, "sel", 0)), + A::P(at(&m, "step", 0)), + A::I32(2), + A::I32(4), + A::F32(0.0625), + A::P(acc), + // part_m after n_chunks * n_head * HD floats, part_l after n_chunks * n_head more + A::P(acc + 33 * 24 * 256 * 4), + A::P(acc + (33 * 24 * 256 + 33 * 24) * 4), + A::I32(33), + A::I32(2051), + A::I64(stride as i64) + ] + ); + assert_eq!((l[1].entry, l[1].grid, l[1].block), ("leleka_qsa_decode_merge", [24, n as u32, 1], [256, 1, 1])); + assert_eq!( + l[1].args, + vec![ + A::P(acc), + A::P(acc + 33 * 24 * 256 * 4), + A::P(acc + (33 * 24 * 256 + 33 * 24) * 4), + A::I32(33), + A::P(at(&m, "attn", 0)), + A::I64(stride as i64) + ] + ); + l.iter().for_each(assert_abi); + } + let l = w.decode_attention(2, &layer(), rows(5, 8)).unwrap(); + assert_eq!(l[0].args[0], A::P(at(&m, "qcur", 5 * 24 * 256 * 4))); + assert_eq!(l[0].args[11], A::P(at(&m, "attn_scratch", 5 * stride * 4))); + assert_eq!(l[0].args[6], A::P(at(&m, "sel", 5 * 2051 * 4))); + assert_eq!(l[1].args[4], A::P(at(&m, "attn", 5 * 24 * 256 * 4))); + // the per-query scratch region holds acc + m + l + assert!(((33 * 24 * 258) as usize) < stride); +} + +#[test] +fn gate_is_one_launch_over_n_times_24_heads_when_batched() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 2..=8usize { + let l = w.gate(1, rows(0, n), true).unwrap(); + assert_eq!(l.len(), 1); + // ceil(n * 24 * 256 / 256) blocks of 256 threads + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("verify_window_qsa_gate", [24 * n as u32, 1, 1], [256, 1, 1])); + assert_eq!( + l[0].args, + vec![A::P(at(&m, "attn", 0)), A::P(at(&m, "qfull", 0)), A::P(at(&m, "attn32", 0)), A::I32(24 * n as i32), A::I32(256)] + ); + } + let l = w.gate(1, rows(2, 5), false).unwrap(); + assert_eq!(l.len(), 3); + assert_eq!(l[1].args[0], A::P(at(&m, "attn", 3 * 6144 * 4))); + assert_eq!(l[1].args[1], A::P(at(&m, "qfull", 3 * 12288 * 4))); + assert_eq!(l[1].args[2], A::P(at(&m, "attn32", 3 * 6144 * 4))); + assert_eq!(l[1].args[3], A::I32(24)); + assert_eq!(l[1].grid, [24, 1, 1]); +} + +#[test] +fn a_corrupted_gate_pin_fails_closed_by_name_but_other_plans_are_unaffected() { + assert!(GATE.sealed().is_ok()); + // loading goes through `AssetSpec::sealed`, which names the refused asset; exercised on synthetic copies + // (a one-byte-corrupted body and a wrong digest) of the real gate PTX + let bytes = GATE.derived(crate::sealed_ptx::test_support::one_byte_corrupted(GATE.ptx), GATE.sha); + let digest = GATE.derived(GATE.ptx, [3; 32]); + for bad in [bytes, digest] { + let err = bad.sealed().unwrap_err(); + assert!(matches!(err, Error::InvalidDriverValue(m) if m.contains("original_verify_window_qsa_gate.ptx"))); + assert!(!bad.entries.is_empty() && bad.has_entry("verify_window_qsa_gate")); + } + let (m, g) = setup(); + let w = window(&m, g); + assert!(w.kv_resolve(0, &layer(), rows(0, 2)).is_ok()); + assert!(w.gate(0, rows(0, 2), true).is_ok()); +} + +#[test] +fn the_whole_layer_sequence_follows_verify_cpp_for_one_group() { + // order of the producers' first launch across a batched QSA layer (projections excluded) + let (m, g) = setup(); + let w = window(&m, g); + let r = rows(0, 4); + let a = layer(); + let mut seq: Vec<&str> = Vec::new(); + for l in [ + w.index_k(0, &a, r, true).unwrap(), + w.k_norm_rope(0, &a, r, true).unwrap(), + w.kv_append(0, &a, r).unwrap(), + w.q_path(0, &a, r, true).unwrap(), + w.index_q_path(0, &a, r, true).unwrap(), + w.block_scores_topk(0, &a, r).unwrap(), + w.kv_resolve(0, &a, r).unwrap(), + w.decode_attention(0, &a, r).unwrap(), + w.gate(0, r, true).unwrap(), + ] { + seq.extend(l.iter().map(|x| x.entry)); + } + assert_eq!(seq.len(), 1 + 2 + 4 + 3 + 3 + 2 + 2 + 2 + 1); + assert_eq!(seq[1], "qsa_decode_rms"); + assert_eq!(seq[seq.len() - 1], "verify_window_qsa_gate"); +} + +#[test] +fn weight_sizes_are_the_original_tensor_shapes() { + let g = test_geometry(); + assert_eq!(OriginalVerifyQsaBinding::sizes(&g), [1024, 1024, 512, 128 * 2560 * 2, 512 * 2560 * 2]); + assert_eq!(max_blocks(&g), 1026); + assert_eq!(scratch_floats(&g), 204_400); + assert!(KV.validate(&g).is_ok()); +} + +#[test] +fn construction_refuses_unsupported_geometry_and_policy() { + let (m, g) = setup(); + let mut bad = g; + bad.selection = 2048; + assert!(QsaWindow::new(&m, bad, OriginalVerifyQsaPolicy::mode17(), identity()).is_err()); + let mut p = OriginalVerifyQsaPolicy::mode17(); + p.kv_q4 = true; + assert!(QsaWindow::new(&m, g, p, identity()).is_err()); +} diff --git a/crates/cuda-driver/src/original_verify_window_record.rs b/crates/cuda-driver/src/original_verify_window_record.rs index 1b2eb8c0..45bc2135 100644 --- a/crates/cuda-driver/src/original_verify_window_record.rs +++ b/crates/cuda-driver/src/original_verify_window_record.rs @@ -321,320 +321,5 @@ fn post(ops: &mut O, policy: &WindowPolicy, groups: usize, l: usiz } #[cfg(test)] -mod tests { - use super::*; - - #[derive(Default)] - struct Trace { - log: Vec, - fail_at: Option, - } - impl Trace { - fn note(&mut self, s: String) -> Result<()> { - let fail = self.fail_at.as_deref().is_some_and(|f| s.split_whitespace().next() == Some(f)); - self.log.push(s); - if fail { Err(Error::InvalidDriverValue("trace")) } else { Ok(()) } - } - } - fn r(rows: Rows) -> String { - format!("{}..{}g{}", rows.begin, rows.end, rows.group) - } - impl WindowOps for Trace { - fn embed(&mut self) -> Result<()> { self.note("embed".into()) } - fn stamp(&mut self, l: usize, s: usize) -> Result<()> { self.note(format!("stamp {l}.{s}")) } - fn ple_layer1(&mut self, x: Rows) -> Result<()> { self.note(format!("ple {}", r(x))) } - fn hc_read(&mut self, l: usize, h: HcHalf, a: bool, x: Rows) -> Result<()> { - self.note(format!("hc {l} {:?} apply={a} {}", h, r(x))) - } - fn quantize_q8_1(&mut self, l: usize, s: QuantSource, x: Rows) -> Result<()> { self.note(format!("quant {l} {s:?} {}", r(x))) } - fn mmvq(&mut self, l: usize, p: Projection, x: Rows) -> Result<()> { self.note(format!("mmvq {l} {p:?} {}", r(x))) } - fn gdn_conv(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("conv g{g} {}", r(x))) } - fn gdn_alpha_beta(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("ab g{g} {}", r(x))) } - fn gdn_recurrence(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("rec g{g} {}", r(x))) } - fn qsa_index_k(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("idxk q{q} {} b={b}", r(x))) } - fn qsa_k_norm_rope(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("knr q{q} {} b={b}", r(x))) } - fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { self.note(format!("tail q{q}")) } - fn qsa_kv_append(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("kv q{q} {}", r(x))) } - fn qsa_indexer_append(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("iapp q{q} {}", r(x))) } - fn qsa_q_path(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("qpath q{q} {} b={b}", r(x))) } - fn qsa_index_q_path(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("iqpath q{q} {} b={b}", r(x))) } - fn qsa_block_scores_topk(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("scores q{q} {}", r(x))) } - fn qsa_kv_resolve(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("resolve q{q} {}", r(x))) } - fn qsa_decode_attention(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("attn q{q} {}", r(x))) } - fn qsa_gate(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("gate q{q} {} b={b}", r(x))) } - fn router(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("router {l} {} b={b}", r(x))) } - fn doorbell(&mut self, x: Rows) -> Result<()> { self.note(format!("doorbell {}", r(x))) } - fn shared_expert(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("shared {l} {} b={b}", r(x))) } - fn quantize_expert_input(&mut self, l: usize, x: Rows) -> Result<()> { self.note(format!("xq {l} {}", r(x))) } - fn wait_plan(&mut self, ring: u32, x: Rows) -> Result<()> { self.note(format!("waitA {ring} {}", r(x))) } - fn expert_groups(&mut self, l: usize, x: Rows, t: ExpertTier) -> Result<()> { self.note(format!("experts {l} {t:?} {}", r(x))) } - fn wait_copies(&mut self, ring: u32) -> Result<()> { self.note(format!("waitB {ring}")) } - fn pcie_stage(&mut self, l: usize, x: Rows) -> Result<()> { self.note(format!("stage {l} {}", r(x))) } - fn wait_cpu(&mut self, ring: u32) -> Result<()> { self.note(format!("waitM {ring}")) } - fn copy_cpu_rows(&mut self, x: Rows, only: bool) -> Result<()> { self.note(format!("cpurows {} only={only}", r(x))) } - fn hit_add(&mut self, x: Rows) -> Result<()> { self.note(format!("hitadd {}", r(x))) } - fn combine(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("combine {l} {} b={b}", r(x))) } - fn final_write(&mut self, x: Rows) -> Result<()> { self.note(format!("final {}", r(x))) } - fn head(&mut self, t: usize) -> Result<()> { self.note(format!("head {t}")) } - } - - fn record(t: usize, groups: usize, ple: bool) -> Vec { - let mut o = Trace::default(); - record_window(&mut o, &WindowPolicy::mode17(), t, groups, ple).unwrap(); - o.log - } - fn index_of(log: &[String], prefix: &str) -> usize { - log.iter().position(|s| s.starts_with(prefix)).unwrap_or_else(|| panic!("{prefix} missing")) - } - - #[test] - fn policy_refuses_what_it_cannot_reproduce_literally() { - let mut p = WindowPolicy::mode17(); - assert!(p.validate_selected().is_ok()); - for f in [ - |p: &mut WindowPolicy| p.device_plan = true, - |p: &mut WindowPolicy| p.cvec = true, - |p: &mut WindowPolicy| p.non_int8_kv = true, - |p: &mut WindowPolicy| p.variant = true, - ] { - let mut q = p; - f(&mut q); - assert_eq!(q.validate_selected(), Err(Error::UnsupportedQwenOperation)); - } - p.pcie_mode = 3; - assert_eq!(p.validate_selected(), Err(Error::InvalidQwenShape)); - } - - #[test] - fn rejects_invalid_window_shapes() { - let mut o = Trace::default(); - let p = WindowPolicy::mode17(); - assert!(record_window(&mut o, &p, 0, 1, false).is_err()); - assert!(record_window(&mut o, &p, 9, 1, false).is_err()); - assert!(record_window(&mut o, &p, 1, 2, false).is_err()); - assert!(record_window(&mut o, &p, 4, 3, false).is_err()); - assert!(o.log.is_empty(), "nothing is recorded before the shape is admitted"); - } - - #[test] - fn gdn_layer_runs_the_literal_pre_sequence() { - let log = record(3, 1, false); - // layer 0 (GDN): stamps 0..6 interleaved with the producers, no pending write, then out-projection - let first: Vec<&str> = log.iter().map(String::as_str).skip(1).take(17).collect(); - assert_eq!( - first, - [ - "stamp 0.0", - "hc 0 Attention apply=false 0..3g0", - "stamp 0.1", - "quant 0 Mixed 0..3g0", - "mmvq 0 GdnQkv 0..3g0", - "stamp 0.2", - "conv g0 0..3g0", - "stamp 0.3", - "ab g0 0..3g0", - "stamp 0.4", - "mmvq 0 GdnGate 0..3g0", - "stamp 0.5", - "rec g0 0..3g0", - "stamp 0.6", - "quant 0 GdnY 0..3g0", - "mmvq 0 GdnOut 0..3g0", - "stamp 0.16" - ] - ); - assert_eq!(log[0], "embed"); - } - - #[test] - fn qsa_layer_runs_the_literal_pre_sequence_with_batched_rows() { - let log = record(4, 1, false); - let start = index_of(&log, "stamp 3.0"); - let end = index_of(&log, "stamp 3.16") + 1; - let seq: Vec<&str> = log[start..end].iter().map(String::as_str).collect(); - assert_eq!( - seq, - [ - "stamp 3.0", - "hc 3 Attention apply=true 0..4g0", - "stamp 3.1", - "quant 3 Mixed 0..4g0", - "idxk q0 0..4g0 b=true", - "stamp 3.7", - "mmvq 3 QsaK 0..4g0", - "mmvq 3 QsaV 0..4g0", - "knr q0 0..4g0 b=true", - "stamp 3.8", - "tail q0", - "kv q0 0..4g0", - "iapp q0 0..4g0", - "stamp 3.9", - "mmvq 3 QsaQ 0..4g0", - "qpath q0 0..4g0 b=true", - "iqpath q0 0..4g0 b=true", - "stamp 3.10", - "scores q0 0..4g0", - "stamp 3.11", - "resolve q0 0..4g0", - "stamp 3.12", - "attn q0 0..4g0", - "stamp 3.13", - "gate q0 0..4g0 b=true", - "stamp 3.14", - "quant 3 Attention 0..4g0", - "mmvq 3 QsaOut 0..4g0", - "stamp 3.16" - ] - ); - } - - #[test] - fn single_row_windows_are_never_batched() { - let log = record(1, 1, false); - assert!(log.iter().any(|s| s == "idxk q0 0..1g0 b=false")); - assert!(log.iter().any(|s| s == "router 0 0..1g0 b=false")); - assert!(log.iter().any(|s| s == "combine 0 0..1g0 b=false")); - assert!(!log.iter().any(|s| s.contains("b=true") && !s.starts_with("shared"))); - // shared expert follows dec_batch, not the row count - assert!(log.iter().any(|s| s == "shared 0 0..1g0 b=true")); - } - - #[test] - fn ffn_half_router_doorbell_shared_and_expert_input_precede_the_ring_wait() { - let log = record(2, 1, false); - let seq: Vec<&str> = - log[index_of(&log, "stamp 0.16")..index_of(&log, "stamp 0.18") + 1].iter().map(String::as_str).collect(); - assert_eq!( - seq, - [ - "stamp 0.16", - "hc 0 Ffn apply=true 0..2g0", - "router 0 0..2g0 b=true", - "doorbell 0..2g0", - "stamp 0.17", - "shared 0 0..2g0 b=true", - "xq 0 0..2g0", - "stamp 0.18" - ] - ); - } - - #[test] - fn post_sequence_waits_the_three_flags_in_order_with_the_layers_ring() { - let log = record(2, 1, false); - let from = index_of(&log, "waitA 1"); - let to = index_of(&log, "stamp 0.24") + 1; - let seq: Vec<&str> = log[from..to].iter().map(String::as_str).collect(); - assert_eq!( - seq, - [ - "waitA 1 0..2g0", - "stamp 0.19", - "experts 0 Vram 0..2g0", - "stamp 0.20", - "waitB 1", - "stamp 0.21", - "experts 0 Pcie 0..2g0", - "stamp 0.22", - "waitM 1", - "stamp 0.23", - "cpurows 0..2g0 only=true", - "hitadd 0..2g0", - "combine 0 0..2g0 b=true", - "stamp 0.24" - ] - ); - } - - #[test] - fn pcie_mode_two_stages_blobs_with_a_copy_kernel_between_wait_b_and_the_pcie_group() { - let mut o = Trace::default(); - let mut p = WindowPolicy::mode17(); - p.pcie_mode = 2; - record_window(&mut o, &p, 3, 1, false).unwrap(); - let b = index_of(&o.log, "waitB 1"); - assert!(o.log[b + 1].starts_with("stage 0")); - let none = record(3, 1, false); - assert!(!none.iter().any(|s| s.starts_with("stage"))); - } - - #[test] - fn layer_one_pending_write_is_replaced_by_the_ple_block_only_when_ple_is_on() { - let with = record(2, 1, true); - let l1 = index_of(&with, "stamp 1.0"); - assert_eq!(with[l1 + 1], "ple 0..2g0"); - assert_eq!(with[l1 + 2], "hc 1 Attention apply=false 0..2g0"); - let without = record(2, 1, false); - let l1 = index_of(&without, "stamp 1.0"); - assert_eq!(without[l1 + 1], "hc 1 Attention apply=true 0..2g0"); - assert_eq!(without.iter().filter(|s| s.starts_with("ple")).count(), 0); - assert_eq!(with.iter().filter(|s| s.starts_with("ple")).count(), 1, "PLE runs once, at layer 1"); - } - - #[test] - fn last_layer_writes_the_residual_and_the_window_ends_with_the_head() { - let log = record(3, 1, false); - let n = log.len(); - assert_eq!(&log[n - 5..], ["stamp 47.24", "final 0..3g0", "stamp 48.0", "head 3", "stamp 48.1"]); - assert_eq!(log.iter().filter(|s| s.starts_with("final")).count(), 1); - } - - #[test] - fn split_window_stamps_group_zero_only_and_interleaves_cpu_with_gpu_work() { - let log = record(5, 2, false); - // pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) pre(1,B) - let order = [ - "hc 0 Attention apply=false 0..3g0", - "hc 0 Attention apply=false 3..5g1", - "waitA 1 0..3g0", - "hc 1 Attention apply=true 0..3g0", - "waitA 2 3..5g1", - "hc 1 Attention apply=true 3..5g1", - ]; - let mut at = 0; - for want in order { - let found = log[at..].iter().position(|s| s == want).unwrap_or_else(|| panic!("{want} not after {at}")); - at += found + 1; - } - // profile stamps come from group 0 only - let stamps0 = log.iter().filter(|s| s.starts_with("stamp 5.")).count(); - let g1_lines: Vec<&String> = log.iter().filter(|s| s.ends_with("g1")).collect(); - assert!(stamps0 > 0 && !g1_lines.iter().any(|s| s.starts_with("stamp"))); - // the doorbell of each group is its own rows - assert!(log.contains(&"doorbell 0..3g0".to_string()) && log.contains(&"doorbell 3..5g1".to_string())); - // only group 0 snapshots the index tail (before the first group's append) - let tails = log.iter().filter(|s| s.starts_with("tail q0")).count(); - assert_eq!(tails, 1); - let tail = index_of(&log, "tail q0"); - assert!(tail < index_of(&log, "kv q0 3..5g1"), "the snapshot precedes B's append"); - // rings of group B are even - assert!(log.contains(&"waitA 2 3..5g1".to_string()) && log.contains(&"waitM 96".to_string())); - // group B of a 2-row window is one row and is not batched - let two = record(2, 2, false); - assert!(two.iter().any(|s| s == "router 0 1..2g1 b=false")); - } - - #[test] - fn every_ring_is_waited_exactly_three_times_and_in_run_order() { - for groups in [1usize, 2] { - let log = record(4, groups, true); - let a: Vec = log.iter().filter_map(|s| s.strip_prefix("waitA ")?.split(' ').next()?.parse().ok()).collect(); - assert_eq!(a, (1..=(48 * groups) as u32).collect::>()); - for flag in ["waitB ", "waitM "] { - let v: Vec = log.iter().filter_map(|s| s.strip_prefix(flag)?.parse().ok()).collect(); - assert_eq!(v, a); - } - // exactly one doorbell per (layer, group): the host loop expects the same count - assert_eq!(log.iter().filter(|s| s.starts_with("doorbell")).count(), 48 * groups); - } - } - - #[test] - fn a_producer_failure_stops_the_recording_at_that_call() { - let mut o = Trace { fail_at: Some("router".into()), ..Default::default() }; - let err = record_window(&mut o, &WindowPolicy::mode17(), 2, 1, false).unwrap_err(); - assert_eq!(err, Error::InvalidDriverValue("trace")); - assert!(o.log.last().unwrap().starts_with("router 0")); - assert!(!o.log.iter().any(|s| s.starts_with("doorbell"))); - } -} +#[path = "original_verify_window_record/tests.rs"] +mod tests; diff --git a/crates/cuda-driver/src/original_verify_window_record/tests.rs b/crates/cuda-driver/src/original_verify_window_record/tests.rs new file mode 100644 index 00000000..49ad881a --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_record/tests.rs @@ -0,0 +1,317 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[derive(Default)] +struct Trace { + log: Vec, + fail_at: Option, +} +impl Trace { + fn note(&mut self, s: String) -> Result<()> { + let fail = self.fail_at.as_deref().is_some_and(|f| s.split_whitespace().next() == Some(f)); + self.log.push(s); + if fail { Err(Error::InvalidDriverValue("trace")) } else { Ok(()) } + } +} +fn r(rows: Rows) -> String { + format!("{}..{}g{}", rows.begin, rows.end, rows.group) +} +impl WindowOps for Trace { + fn embed(&mut self) -> Result<()> { self.note("embed".into()) } + fn stamp(&mut self, l: usize, s: usize) -> Result<()> { self.note(format!("stamp {l}.{s}")) } + fn ple_layer1(&mut self, x: Rows) -> Result<()> { self.note(format!("ple {}", r(x))) } + fn hc_read(&mut self, l: usize, h: HcHalf, a: bool, x: Rows) -> Result<()> { + self.note(format!("hc {l} {:?} apply={a} {}", h, r(x))) + } + fn quantize_q8_1(&mut self, l: usize, s: QuantSource, x: Rows) -> Result<()> { self.note(format!("quant {l} {s:?} {}", r(x))) } + fn mmvq(&mut self, l: usize, p: Projection, x: Rows) -> Result<()> { self.note(format!("mmvq {l} {p:?} {}", r(x))) } + fn gdn_conv(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("conv g{g} {}", r(x))) } + fn gdn_alpha_beta(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("ab g{g} {}", r(x))) } + fn gdn_recurrence(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("rec g{g} {}", r(x))) } + fn qsa_index_k(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("idxk q{q} {} b={b}", r(x))) } + fn qsa_k_norm_rope(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("knr q{q} {} b={b}", r(x))) } + fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { self.note(format!("tail q{q}")) } + fn qsa_kv_append(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("kv q{q} {}", r(x))) } + fn qsa_indexer_append(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("iapp q{q} {}", r(x))) } + fn qsa_q_path(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("qpath q{q} {} b={b}", r(x))) } + fn qsa_index_q_path(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("iqpath q{q} {} b={b}", r(x))) } + fn qsa_block_scores_topk(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("scores q{q} {}", r(x))) } + fn qsa_kv_resolve(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("resolve q{q} {}", r(x))) } + fn qsa_decode_attention(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("attn q{q} {}", r(x))) } + fn qsa_gate(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("gate q{q} {} b={b}", r(x))) } + fn router(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("router {l} {} b={b}", r(x))) } + fn doorbell(&mut self, x: Rows) -> Result<()> { self.note(format!("doorbell {}", r(x))) } + fn shared_expert(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("shared {l} {} b={b}", r(x))) } + fn quantize_expert_input(&mut self, l: usize, x: Rows) -> Result<()> { self.note(format!("xq {l} {}", r(x))) } + fn wait_plan(&mut self, ring: u32, x: Rows) -> Result<()> { self.note(format!("waitA {ring} {}", r(x))) } + fn expert_groups(&mut self, l: usize, x: Rows, t: ExpertTier) -> Result<()> { self.note(format!("experts {l} {t:?} {}", r(x))) } + fn wait_copies(&mut self, ring: u32) -> Result<()> { self.note(format!("waitB {ring}")) } + fn pcie_stage(&mut self, l: usize, x: Rows) -> Result<()> { self.note(format!("stage {l} {}", r(x))) } + fn wait_cpu(&mut self, ring: u32) -> Result<()> { self.note(format!("waitM {ring}")) } + fn copy_cpu_rows(&mut self, x: Rows, only: bool) -> Result<()> { self.note(format!("cpurows {} only={only}", r(x))) } + fn hit_add(&mut self, x: Rows) -> Result<()> { self.note(format!("hitadd {}", r(x))) } + fn combine(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("combine {l} {} b={b}", r(x))) } + fn final_write(&mut self, x: Rows) -> Result<()> { self.note(format!("final {}", r(x))) } + fn head(&mut self, t: usize) -> Result<()> { self.note(format!("head {t}")) } +} + +fn record(t: usize, groups: usize, ple: bool) -> Vec { + let mut o = Trace::default(); + record_window(&mut o, &WindowPolicy::mode17(), t, groups, ple).unwrap(); + o.log +} +fn index_of(log: &[String], prefix: &str) -> usize { + log.iter().position(|s| s.starts_with(prefix)).unwrap_or_else(|| panic!("{prefix} missing")) +} + +#[test] +fn policy_refuses_what_it_cannot_reproduce_literally() { + let mut p = WindowPolicy::mode17(); + assert!(p.validate_selected().is_ok()); + for f in [ + |p: &mut WindowPolicy| p.device_plan = true, + |p: &mut WindowPolicy| p.cvec = true, + |p: &mut WindowPolicy| p.non_int8_kv = true, + |p: &mut WindowPolicy| p.variant = true, + ] { + let mut q = p; + f(&mut q); + assert_eq!(q.validate_selected(), Err(Error::UnsupportedQwenOperation)); + } + p.pcie_mode = 3; + assert_eq!(p.validate_selected(), Err(Error::InvalidQwenShape)); +} + +#[test] +fn rejects_invalid_window_shapes() { + let mut o = Trace::default(); + let p = WindowPolicy::mode17(); + assert!(record_window(&mut o, &p, 0, 1, false).is_err()); + assert!(record_window(&mut o, &p, 9, 1, false).is_err()); + assert!(record_window(&mut o, &p, 1, 2, false).is_err()); + assert!(record_window(&mut o, &p, 4, 3, false).is_err()); + assert!(o.log.is_empty(), "nothing is recorded before the shape is admitted"); +} + +#[test] +fn gdn_layer_runs_the_literal_pre_sequence() { + let log = record(3, 1, false); + // layer 0 (GDN): stamps 0..6 interleaved with the producers, no pending write, then out-projection + let first: Vec<&str> = log.iter().map(String::as_str).skip(1).take(17).collect(); + assert_eq!( + first, + [ + "stamp 0.0", + "hc 0 Attention apply=false 0..3g0", + "stamp 0.1", + "quant 0 Mixed 0..3g0", + "mmvq 0 GdnQkv 0..3g0", + "stamp 0.2", + "conv g0 0..3g0", + "stamp 0.3", + "ab g0 0..3g0", + "stamp 0.4", + "mmvq 0 GdnGate 0..3g0", + "stamp 0.5", + "rec g0 0..3g0", + "stamp 0.6", + "quant 0 GdnY 0..3g0", + "mmvq 0 GdnOut 0..3g0", + "stamp 0.16" + ] + ); + assert_eq!(log[0], "embed"); +} + +#[test] +fn qsa_layer_runs_the_literal_pre_sequence_with_batched_rows() { + let log = record(4, 1, false); + let start = index_of(&log, "stamp 3.0"); + let end = index_of(&log, "stamp 3.16") + 1; + let seq: Vec<&str> = log[start..end].iter().map(String::as_str).collect(); + assert_eq!( + seq, + [ + "stamp 3.0", + "hc 3 Attention apply=true 0..4g0", + "stamp 3.1", + "quant 3 Mixed 0..4g0", + "idxk q0 0..4g0 b=true", + "stamp 3.7", + "mmvq 3 QsaK 0..4g0", + "mmvq 3 QsaV 0..4g0", + "knr q0 0..4g0 b=true", + "stamp 3.8", + "tail q0", + "kv q0 0..4g0", + "iapp q0 0..4g0", + "stamp 3.9", + "mmvq 3 QsaQ 0..4g0", + "qpath q0 0..4g0 b=true", + "iqpath q0 0..4g0 b=true", + "stamp 3.10", + "scores q0 0..4g0", + "stamp 3.11", + "resolve q0 0..4g0", + "stamp 3.12", + "attn q0 0..4g0", + "stamp 3.13", + "gate q0 0..4g0 b=true", + "stamp 3.14", + "quant 3 Attention 0..4g0", + "mmvq 3 QsaOut 0..4g0", + "stamp 3.16" + ] + ); +} + +#[test] +fn single_row_windows_are_never_batched() { + let log = record(1, 1, false); + assert!(log.iter().any(|s| s == "idxk q0 0..1g0 b=false")); + assert!(log.iter().any(|s| s == "router 0 0..1g0 b=false")); + assert!(log.iter().any(|s| s == "combine 0 0..1g0 b=false")); + assert!(!log.iter().any(|s| s.contains("b=true") && !s.starts_with("shared"))); + // shared expert follows dec_batch, not the row count + assert!(log.iter().any(|s| s == "shared 0 0..1g0 b=true")); +} + +#[test] +fn ffn_half_router_doorbell_shared_and_expert_input_precede_the_ring_wait() { + let log = record(2, 1, false); + let seq: Vec<&str> = + log[index_of(&log, "stamp 0.16")..index_of(&log, "stamp 0.18") + 1].iter().map(String::as_str).collect(); + assert_eq!( + seq, + [ + "stamp 0.16", + "hc 0 Ffn apply=true 0..2g0", + "router 0 0..2g0 b=true", + "doorbell 0..2g0", + "stamp 0.17", + "shared 0 0..2g0 b=true", + "xq 0 0..2g0", + "stamp 0.18" + ] + ); +} + +#[test] +fn post_sequence_waits_the_three_flags_in_order_with_the_layers_ring() { + let log = record(2, 1, false); + let from = index_of(&log, "waitA 1"); + let to = index_of(&log, "stamp 0.24") + 1; + let seq: Vec<&str> = log[from..to].iter().map(String::as_str).collect(); + assert_eq!( + seq, + [ + "waitA 1 0..2g0", + "stamp 0.19", + "experts 0 Vram 0..2g0", + "stamp 0.20", + "waitB 1", + "stamp 0.21", + "experts 0 Pcie 0..2g0", + "stamp 0.22", + "waitM 1", + "stamp 0.23", + "cpurows 0..2g0 only=true", + "hitadd 0..2g0", + "combine 0 0..2g0 b=true", + "stamp 0.24" + ] + ); +} + +#[test] +fn pcie_mode_two_stages_blobs_with_a_copy_kernel_between_wait_b_and_the_pcie_group() { + let mut o = Trace::default(); + let mut p = WindowPolicy::mode17(); + p.pcie_mode = 2; + record_window(&mut o, &p, 3, 1, false).unwrap(); + let b = index_of(&o.log, "waitB 1"); + assert!(o.log[b + 1].starts_with("stage 0")); + let none = record(3, 1, false); + assert!(!none.iter().any(|s| s.starts_with("stage"))); +} + +#[test] +fn layer_one_pending_write_is_replaced_by_the_ple_block_only_when_ple_is_on() { + let with = record(2, 1, true); + let l1 = index_of(&with, "stamp 1.0"); + assert_eq!(with[l1 + 1], "ple 0..2g0"); + assert_eq!(with[l1 + 2], "hc 1 Attention apply=false 0..2g0"); + let without = record(2, 1, false); + let l1 = index_of(&without, "stamp 1.0"); + assert_eq!(without[l1 + 1], "hc 1 Attention apply=true 0..2g0"); + assert_eq!(without.iter().filter(|s| s.starts_with("ple")).count(), 0); + assert_eq!(with.iter().filter(|s| s.starts_with("ple")).count(), 1, "PLE runs once, at layer 1"); +} + +#[test] +fn last_layer_writes_the_residual_and_the_window_ends_with_the_head() { + let log = record(3, 1, false); + let n = log.len(); + assert_eq!(&log[n - 5..], ["stamp 47.24", "final 0..3g0", "stamp 48.0", "head 3", "stamp 48.1"]); + assert_eq!(log.iter().filter(|s| s.starts_with("final")).count(), 1); +} + +#[test] +fn split_window_stamps_group_zero_only_and_interleaves_cpu_with_gpu_work() { + let log = record(5, 2, false); + // pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) pre(1,B) + let order = [ + "hc 0 Attention apply=false 0..3g0", + "hc 0 Attention apply=false 3..5g1", + "waitA 1 0..3g0", + "hc 1 Attention apply=true 0..3g0", + "waitA 2 3..5g1", + "hc 1 Attention apply=true 3..5g1", + ]; + let mut at = 0; + for want in order { + let found = log[at..].iter().position(|s| s == want).unwrap_or_else(|| panic!("{want} not after {at}")); + at += found + 1; + } + // profile stamps come from group 0 only + let stamps0 = log.iter().filter(|s| s.starts_with("stamp 5.")).count(); + let g1_lines: Vec<&String> = log.iter().filter(|s| s.ends_with("g1")).collect(); + assert!(stamps0 > 0 && !g1_lines.iter().any(|s| s.starts_with("stamp"))); + // the doorbell of each group is its own rows + assert!(log.contains(&"doorbell 0..3g0".to_string()) && log.contains(&"doorbell 3..5g1".to_string())); + // only group 0 snapshots the index tail (before the first group's append) + let tails = log.iter().filter(|s| s.starts_with("tail q0")).count(); + assert_eq!(tails, 1); + let tail = index_of(&log, "tail q0"); + assert!(tail < index_of(&log, "kv q0 3..5g1"), "the snapshot precedes B's append"); + // rings of group B are even + assert!(log.contains(&"waitA 2 3..5g1".to_string()) && log.contains(&"waitM 96".to_string())); + // group B of a 2-row window is one row and is not batched + let two = record(2, 2, false); + assert!(two.iter().any(|s| s == "router 0 1..2g1 b=false")); +} + +#[test] +fn every_ring_is_waited_exactly_three_times_and_in_run_order() { + for groups in [1usize, 2] { + let log = record(4, groups, true); + let a: Vec = log.iter().filter_map(|s| s.strip_prefix("waitA ")?.split(' ').next()?.parse().ok()).collect(); + assert_eq!(a, (1..=(48 * groups) as u32).collect::>()); + for flag in ["waitB ", "waitM "] { + let v: Vec = log.iter().filter_map(|s| s.strip_prefix(flag)?.parse().ok()).collect(); + assert_eq!(v, a); + } + // exactly one doorbell per (layer, group): the host loop expects the same count + assert_eq!(log.iter().filter(|s| s.starts_with("doorbell")).count(), 48 * groups); + } +} + +#[test] +fn a_producer_failure_stops_the_recording_at_that_call() { + let mut o = Trace { fail_at: Some("router".into()), ..Default::default() }; + let err = record_window(&mut o, &WindowPolicy::mode17(), 2, 1, false).unwrap_err(); + assert_eq!(err, Error::InvalidDriverValue("trace")); + assert!(o.log.last().unwrap().starts_with("router 0")); + assert!(!o.log.iter().any(|s| s.starts_with("doorbell"))); +} diff --git a/crates/cuda-driver/src/qsa_prompt_attention_select.rs b/crates/cuda-driver/src/qsa_prompt_attention_select.rs index 4f94966f..7f6c7e7e 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_select.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_select.rs @@ -446,182 +446,4 @@ pub fn f16_to_f32(h: u16) -> f32 { } #[cfg(test)] -mod tests { - use super::*; - - const AMPERE: DeviceCaps = DeviceCaps { cc_major: 8, cc_minor: 6, max_shared_optin: 101_376 }; - const BLACKWELL: DeviceCaps = DeviceCaps { cc_major: 12, cc_minor: 0, max_shared_optin: 101_376 }; - const TURING: DeviceCaps = DeviceCaps { cc_major: 7, cc_minor: 5, max_shared_optin: 65_536 }; - const VOLTA: DeviceCaps = DeviceCaps { cc_major: 7, cc_minor: 0, max_shared_optin: 98_304 }; - const NONE: SelectSwitches = SelectSwitches { qsa_warp_arm: false, prompt_attn_v1: false }; - - fn pick(p: PoolPresence, d: DeviceCaps, s: SelectSwitches) -> Option { - select(p, Shapes::QWEN, 2051, true, d, s) - } - - #[test] - fn smem_sizes_match_the_compiled_structs() { - // sizeof(Smem<0>), sizeof(Smem<1>), sizeof(Smem<3>) from clang on qsa_prompt_attention_variants.cu - assert_eq!(smem_bytes(0), 54_288); - assert_eq!(smem_bytes(1), 37_904); - assert_eq!(smem_bytes(3), 46_096); - // the sibling module's hard-coded dynamic size for the v2 kernel - assert_eq!(smem2_bytes(), 45_584); - assert_eq!(PromptAttnKernel::Int8V2.smem_bytes(), 45_584); - // only the FP16 kernel needs the >48 KiB opt-in - assert!(PromptAttnKernel::Fp16.smem_bytes() > DEFAULT_SHARED_LIMIT); - assert!(PromptAttnKernel::Int8V1.smem_bytes() < DEFAULT_SHARED_LIMIT); - } - - #[test] - fn selection_follows_the_original_decision_tree() { - use PromptAttnKernel::*; - assert_eq!(pick(PoolPresence::int8(), BLACKWELL, NONE), Some(Int8V2)); - assert_eq!(pick(PoolPresence::int8(), AMPERE, NONE), Some(Int8V2)); - // Turing has no cp.async: the v1 kernel - assert_eq!(pick(PoolPresence::int8(), TURING, NONE), Some(Int8V1)); - // STRATA_PROMPT_ATTN_V1 (debug) on any card - let v1 = SelectSwitches { prompt_attn_v1: true, ..NONE }; - assert_eq!(pick(PoolPresence::int8(), BLACKWELL, v1), Some(Int8V1)); - // STRATA_QSA_WARP=1 forces cc 75 (the "RTX 20" arm) - let warp = SelectSwitches { qsa_warp_arm: true, ..NONE }; - assert_eq!(pick(PoolPresence::int8(), BLACKWELL, warp), Some(Int8V1)); - // sm_70 has no m16n8k8: refused - assert_eq!(pick(PoolPresence::int8(), VOLTA, NONE), None); - assert_eq!(pick(PoolPresence::fp16(), BLACKWELL, NONE), Some(Fp16)); - assert_eq!(pick(PoolPresence::hybrid_k8v4(), BLACKWELL, NONE), Some(HybridK8V4)); - assert_eq!(pick(PoolPresence::hybrid_k8v4(), TURING, NONE), Some(HybridK8V4)); - // Q4_0 K and pools missing a member - assert_eq!(pick(PoolPresence::q4(), BLACKWELL, NONE), None); - for broken in [ - PoolPresence { v_q: false, ..PoolPresence::int8() }, - PoolPresence { k_scale: false, ..PoolPresence::int8() }, - PoolPresence { v_scale: false, ..PoolPresence::int8() }, - PoolPresence { k_pool: false, ..PoolPresence::fp16() }, - PoolPresence { v_pool: false, ..PoolPresence::fp16() }, - PoolPresence { k_scale: false, ..PoolPresence::hybrid_k8v4() }, - PoolPresence { page_table: false, ..PoolPresence::int8() }, - ] { - assert_eq!(pick(broken, BLACKWELL, NONE), None, "{broken:?}"); - } - // geometry and selection arrays - let bad = Shapes { n_head: 24, n_head_kv: 4, head_dim: 256 }; - assert_eq!(select(PoolPresence::int8(), bad, 2051, true, BLACKWELL, NONE), None); - let bad = Shapes { head_dim: 128, ..Shapes::QWEN }; - assert_eq!(select(PoolPresence::int8(), bad, 2051, true, BLACKWELL, NONE), None); - assert_eq!(select(PoolPresence::int8(), Shapes::QWEN, 0, true, BLACKWELL, NONE), None); - assert_eq!(select(PoolPresence::int8(), Shapes::QWEN, 2051, false, BLACKWELL, NONE), None); - // the dynamic shared memory opt-in must cover the FP16 kernel's 54288 bytes - let small = DeviceCaps { max_shared_optin: 49_152, ..BLACKWELL }; - assert_eq!(pick(PoolPresence::fp16(), small, NONE), None); - assert_eq!(pick(PoolPresence::int8(), small, NONE), Some(Int8V2)); - // the AMD arm does not exist on CUDA - assert!(!hip_wmma_usable()); - } - - #[test] - fn switches_read_the_original_environment_forms() { - assert_eq!(SelectSwitches::from_values(Some("1"), None), SelectSwitches { qsa_warp_arm: true, prompt_attn_v1: false }); - assert!(SelectSwitches::from_values(Some("attn"), None).qsa_warp_arm); - assert!(!SelectSwitches::from_values(Some("0"), None).qsa_warp_arm); - assert!(!SelectSwitches::from_values(Some(""), None).qsa_warp_arm); - // getenv != nullptr: even an empty value selects v1 - assert!(SelectSwitches::from_values(None, Some("")).prompt_attn_v1); - assert!(!SelectSwitches::from_values(None, None).prompt_attn_v1); - } - - #[test] - fn launch_slicing_covers_every_query_once() { - let s = launch_slices(PromptAttnKernel::Fp16, 65535 * 2 + 7, 2); - assert_eq!(s.iter().map(|x| x.blocks_x as usize).collect::>(), vec![65535, 65535, 7]); - assert_eq!(s.iter().map(|x| x.q0).collect::>(), vec![0, 65535, 131070]); - assert!(s.iter().all(|x| x.blocks_y == 2 && x.threads == 128 && x.dynamic_shared == 54_288)); - assert_eq!(launch_slices(PromptAttnKernel::Int8V2, 1, 2).len(), 1); - assert!(launch_slices(PromptAttnKernel::Int8V2, 0, 2).is_empty()); - assert_eq!(slice_offsets(65535, 24, 2051), (65535 * 24 * 256, 65535 * 2051, 65535 * 4, 65535 * 24 * 256)); - assert_eq!(scale_log2(), 1.442_695_0_f32 / 16.0); - } - - #[test] - fn pool_rows_follow_the_page_table() { - let table = [3, 1, -1]; - assert_eq!(pool_row(&table, 0, 4, 2, 0), Some((3 * 2) * 4)); - assert_eq!(pool_row(&table, 5, 4, 2, 1), Some(((1 * 2 + 1) * 4 + 1) as i64)); - assert_eq!(pool_row(&table, 9, 4, 2, 0), None); - assert_eq!(pool_row(&table, 100, 4, 2, 0), None); - } - - #[test] - fn entry_table_matches_the_cuda_source() { - let source = include_str!("qsa_prompt_attention_variants.cu"); - for kernel in [PromptAttnKernel::Int8V1, PromptAttnKernel::Fp16, PromptAttnKernel::HybridK8V4] { - let name = kernel.entry().to_str().unwrap(); - assert!(source.contains(&format!("{name}(")), "{name}"); - assert_eq!(VARIANT_ENTRIES[kernel.variant_index().unwrap()], kernel.entry()); - } - for needed in ["leleka_qsa_prompt_guard", "leleka_qsa_prompt_output_guard"] { - assert!(source.contains(needed)); - } - // constants shared with the source - assert!(source.contains("constexpr int HD = 256;")); - assert!(source.contains("constexpr int G = 12;")); - assert!(source.contains("constexpr int THREADS = 128;")); - assert!(source.contains("#define D1_CH 32")); - assert!(source.contains("constexpr int QS = HD + 8;")); - // the v2 module's entry is the sibling file - assert!(include_str!("qsa_prompt_attention.cu").contains("leleka_qsa_prompt_attn(")); - assert_eq!(PromptAttnKernel::Int8V2.entry(), ENTRY_V2_INT8); - } - - #[test] - fn f16_helpers_round_like_the_hardware() { - for (x, hi) in [(1.0f32, 1.0f32), (0.1, 0.099975586), (65504.0, 65504.0), (65520.0, f32::INFINITY), (1e-8, 0.0)] { - assert_eq!(f16_round(x), hi, "{x}"); - } - // exact halfway case rounds to even: 1 + 2^-11 is halfway between 1 and 1 + 2^-10 - assert_eq!(f16_round(1.0 + 2f32.powi(-11)), 1.0); - assert_eq!(f16_round(1.0 + 3.0 * 2f32.powi(-11)), 1.0 + 2f32.powi(-9)); - // subnormals - assert_eq!(f16_round(2f32.powi(-24)), 2f32.powi(-24)); - assert_eq!(f16_round(2f32.powi(-25)), 0.0); - let (hi, lo) = f16_hi_lo(0.1234567); - assert!((hi + lo - 0.1234567).abs() < 2f32.powi(-22), "{}", hi + lo); - // 22-bit claim of qsa_prompt_attn.hpp: hi + lo keeps ~22 bits of any scaled value in [2^-14, 2^14] - for i in 1..2000 { - let x = (i as f32) * 7.31 + 0.000123 * (i as f32); - let (hi, lo) = f16_hi_lo(x); - assert!(((hi + lo) - x).abs() <= x.abs() * 2f32.powi(-21), "{x}"); - } - } - - #[test] - fn q_prescale_matches_frexpf_ldexpf() { - let sl = scale_log2(); - let (qe, qup, qdown) = q_prescale(0.0, sl); - assert_eq!((qe, qup, qdown), (0, 16384.0, sl / 16384.0)); - // qm in [2^(qe-1), 2^qe): qup * qm lies in [2^13, 2^14) - for qm in [0.3f32, 1.0, 1.5, 3.99, 100.0, 12345.6, 1e-30] { - let (qe, qup, _) = q_prescale(qm, sl); - let scaled = qm * qup; - assert!((8192.0..16384.0).contains(&scaled), "{qm} {qe} {scaled}"); - } - } - - #[test] - fn reference_attention_has_the_softmax_properties() { - // one cell: output == v; two equal cells: mean of v - let q = vec![0.5f32; G * HD]; - let k0 = vec![0.25f32; HD]; - let v0: Vec = (0..HD).map(|d| d as f32).collect(); - let one = reference_attention_f64(&q, &[k0.clone()], &[v0.clone()], 1.0 / 16.0); - for h in 0..G { - assert_eq!(&one[h * HD..(h + 1) * HD], &v0[..]); - } - let v1: Vec = (0..HD).map(|d| 2.0 * d as f32 + 1.0).collect(); - let two = reference_attention_f64(&q, &[k0.clone(), k0], &[v0.clone(), v1.clone()], 1.0 / 16.0); - for d in 0..HD { - assert!((two[d] - 0.5 * (v0[d] + v1[d])).abs() < 1e-4); - } - assert!(reference_attention_f64(&q, &[], &[], 1.0).iter().all(|x| *x == 0.0)); - } -} +mod tests; diff --git a/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs b/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs new file mode 100644 index 00000000..df0a5a0c --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs @@ -0,0 +1,179 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +const AMPERE: DeviceCaps = DeviceCaps { cc_major: 8, cc_minor: 6, max_shared_optin: 101_376 }; +const BLACKWELL: DeviceCaps = DeviceCaps { cc_major: 12, cc_minor: 0, max_shared_optin: 101_376 }; +const TURING: DeviceCaps = DeviceCaps { cc_major: 7, cc_minor: 5, max_shared_optin: 65_536 }; +const VOLTA: DeviceCaps = DeviceCaps { cc_major: 7, cc_minor: 0, max_shared_optin: 98_304 }; +const NONE: SelectSwitches = SelectSwitches { qsa_warp_arm: false, prompt_attn_v1: false }; + +fn pick(p: PoolPresence, d: DeviceCaps, s: SelectSwitches) -> Option { + select(p, Shapes::QWEN, 2051, true, d, s) +} + +#[test] +fn smem_sizes_match_the_compiled_structs() { + // sizeof(Smem<0>), sizeof(Smem<1>), sizeof(Smem<3>) from clang on qsa_prompt_attention_variants.cu + assert_eq!(smem_bytes(0), 54_288); + assert_eq!(smem_bytes(1), 37_904); + assert_eq!(smem_bytes(3), 46_096); + // the sibling module's hard-coded dynamic size for the v2 kernel + assert_eq!(smem2_bytes(), 45_584); + assert_eq!(PromptAttnKernel::Int8V2.smem_bytes(), 45_584); + // only the FP16 kernel needs the >48 KiB opt-in + assert!(PromptAttnKernel::Fp16.smem_bytes() > DEFAULT_SHARED_LIMIT); + assert!(PromptAttnKernel::Int8V1.smem_bytes() < DEFAULT_SHARED_LIMIT); +} + +#[test] +fn selection_follows_the_original_decision_tree() { + use PromptAttnKernel::*; + assert_eq!(pick(PoolPresence::int8(), BLACKWELL, NONE), Some(Int8V2)); + assert_eq!(pick(PoolPresence::int8(), AMPERE, NONE), Some(Int8V2)); + // Turing has no cp.async: the v1 kernel + assert_eq!(pick(PoolPresence::int8(), TURING, NONE), Some(Int8V1)); + // STRATA_PROMPT_ATTN_V1 (debug) on any card + let v1 = SelectSwitches { prompt_attn_v1: true, ..NONE }; + assert_eq!(pick(PoolPresence::int8(), BLACKWELL, v1), Some(Int8V1)); + // STRATA_QSA_WARP=1 forces cc 75 (the "RTX 20" arm) + let warp = SelectSwitches { qsa_warp_arm: true, ..NONE }; + assert_eq!(pick(PoolPresence::int8(), BLACKWELL, warp), Some(Int8V1)); + // sm_70 has no m16n8k8: refused + assert_eq!(pick(PoolPresence::int8(), VOLTA, NONE), None); + assert_eq!(pick(PoolPresence::fp16(), BLACKWELL, NONE), Some(Fp16)); + assert_eq!(pick(PoolPresence::hybrid_k8v4(), BLACKWELL, NONE), Some(HybridK8V4)); + assert_eq!(pick(PoolPresence::hybrid_k8v4(), TURING, NONE), Some(HybridK8V4)); + // Q4_0 K and pools missing a member + assert_eq!(pick(PoolPresence::q4(), BLACKWELL, NONE), None); + for broken in [ + PoolPresence { v_q: false, ..PoolPresence::int8() }, + PoolPresence { k_scale: false, ..PoolPresence::int8() }, + PoolPresence { v_scale: false, ..PoolPresence::int8() }, + PoolPresence { k_pool: false, ..PoolPresence::fp16() }, + PoolPresence { v_pool: false, ..PoolPresence::fp16() }, + PoolPresence { k_scale: false, ..PoolPresence::hybrid_k8v4() }, + PoolPresence { page_table: false, ..PoolPresence::int8() }, + ] { + assert_eq!(pick(broken, BLACKWELL, NONE), None, "{broken:?}"); + } + // geometry and selection arrays + let bad = Shapes { n_head: 24, n_head_kv: 4, head_dim: 256 }; + assert_eq!(select(PoolPresence::int8(), bad, 2051, true, BLACKWELL, NONE), None); + let bad = Shapes { head_dim: 128, ..Shapes::QWEN }; + assert_eq!(select(PoolPresence::int8(), bad, 2051, true, BLACKWELL, NONE), None); + assert_eq!(select(PoolPresence::int8(), Shapes::QWEN, 0, true, BLACKWELL, NONE), None); + assert_eq!(select(PoolPresence::int8(), Shapes::QWEN, 2051, false, BLACKWELL, NONE), None); + // the dynamic shared memory opt-in must cover the FP16 kernel's 54288 bytes + let small = DeviceCaps { max_shared_optin: 49_152, ..BLACKWELL }; + assert_eq!(pick(PoolPresence::fp16(), small, NONE), None); + assert_eq!(pick(PoolPresence::int8(), small, NONE), Some(Int8V2)); + // the AMD arm does not exist on CUDA + assert!(!hip_wmma_usable()); +} + +#[test] +fn switches_read_the_original_environment_forms() { + assert_eq!(SelectSwitches::from_values(Some("1"), None), SelectSwitches { qsa_warp_arm: true, prompt_attn_v1: false }); + assert!(SelectSwitches::from_values(Some("attn"), None).qsa_warp_arm); + assert!(!SelectSwitches::from_values(Some("0"), None).qsa_warp_arm); + assert!(!SelectSwitches::from_values(Some(""), None).qsa_warp_arm); + // getenv != nullptr: even an empty value selects v1 + assert!(SelectSwitches::from_values(None, Some("")).prompt_attn_v1); + assert!(!SelectSwitches::from_values(None, None).prompt_attn_v1); +} + +#[test] +fn launch_slicing_covers_every_query_once() { + let s = launch_slices(PromptAttnKernel::Fp16, 65535 * 2 + 7, 2); + assert_eq!(s.iter().map(|x| x.blocks_x as usize).collect::>(), vec![65535, 65535, 7]); + assert_eq!(s.iter().map(|x| x.q0).collect::>(), vec![0, 65535, 131070]); + assert!(s.iter().all(|x| x.blocks_y == 2 && x.threads == 128 && x.dynamic_shared == 54_288)); + assert_eq!(launch_slices(PromptAttnKernel::Int8V2, 1, 2).len(), 1); + assert!(launch_slices(PromptAttnKernel::Int8V2, 0, 2).is_empty()); + assert_eq!(slice_offsets(65535, 24, 2051), (65535 * 24 * 256, 65535 * 2051, 65535 * 4, 65535 * 24 * 256)); + assert_eq!(scale_log2(), 1.442_695_0_f32 / 16.0); +} + +#[test] +fn pool_rows_follow_the_page_table() { + let table = [3, 1, -1]; + assert_eq!(pool_row(&table, 0, 4, 2, 0), Some((3 * 2) * 4)); + assert_eq!(pool_row(&table, 5, 4, 2, 1), Some(((1 * 2 + 1) * 4 + 1) as i64)); + assert_eq!(pool_row(&table, 9, 4, 2, 0), None); + assert_eq!(pool_row(&table, 100, 4, 2, 0), None); +} + +#[test] +fn entry_table_matches_the_cuda_source() { + let source = include_str!("../qsa_prompt_attention_variants.cu"); + for kernel in [PromptAttnKernel::Int8V1, PromptAttnKernel::Fp16, PromptAttnKernel::HybridK8V4] { + let name = kernel.entry().to_str().unwrap(); + assert!(source.contains(&format!("{name}(")), "{name}"); + assert_eq!(VARIANT_ENTRIES[kernel.variant_index().unwrap()], kernel.entry()); + } + for needed in ["leleka_qsa_prompt_guard", "leleka_qsa_prompt_output_guard"] { + assert!(source.contains(needed)); + } + // constants shared with the source + assert!(source.contains("constexpr int HD = 256;")); + assert!(source.contains("constexpr int G = 12;")); + assert!(source.contains("constexpr int THREADS = 128;")); + assert!(source.contains("#define D1_CH 32")); + assert!(source.contains("constexpr int QS = HD + 8;")); + // the v2 module's entry is the sibling file + assert!(include_str!("../qsa_prompt_attention.cu").contains("leleka_qsa_prompt_attn(")); + assert_eq!(PromptAttnKernel::Int8V2.entry(), ENTRY_V2_INT8); +} + +#[test] +fn f16_helpers_round_like_the_hardware() { + for (x, hi) in [(1.0f32, 1.0f32), (0.1, 0.099975586), (65504.0, 65504.0), (65520.0, f32::INFINITY), (1e-8, 0.0)] { + assert_eq!(f16_round(x), hi, "{x}"); + } + // exact halfway case rounds to even: 1 + 2^-11 is halfway between 1 and 1 + 2^-10 + assert_eq!(f16_round(1.0 + 2f32.powi(-11)), 1.0); + assert_eq!(f16_round(1.0 + 3.0 * 2f32.powi(-11)), 1.0 + 2f32.powi(-9)); + // subnormals + assert_eq!(f16_round(2f32.powi(-24)), 2f32.powi(-24)); + assert_eq!(f16_round(2f32.powi(-25)), 0.0); + let (hi, lo) = f16_hi_lo(0.1234567); + assert!((hi + lo - 0.1234567).abs() < 2f32.powi(-22), "{}", hi + lo); + // 22-bit claim of qsa_prompt_attn.hpp: hi + lo keeps ~22 bits of any scaled value in [2^-14, 2^14] + for i in 1..2000 { + let x = (i as f32) * 7.31 + 0.000123 * (i as f32); + let (hi, lo) = f16_hi_lo(x); + assert!(((hi + lo) - x).abs() <= x.abs() * 2f32.powi(-21), "{x}"); + } +} + +#[test] +fn q_prescale_matches_frexpf_ldexpf() { + let sl = scale_log2(); + let (qe, qup, qdown) = q_prescale(0.0, sl); + assert_eq!((qe, qup, qdown), (0, 16384.0, sl / 16384.0)); + // qm in [2^(qe-1), 2^qe): qup * qm lies in [2^13, 2^14) + for qm in [0.3f32, 1.0, 1.5, 3.99, 100.0, 12345.6, 1e-30] { + let (qe, qup, _) = q_prescale(qm, sl); + let scaled = qm * qup; + assert!((8192.0..16384.0).contains(&scaled), "{qm} {qe} {scaled}"); + } +} + +#[test] +fn reference_attention_has_the_softmax_properties() { + // one cell: output == v; two equal cells: mean of v + let q = vec![0.5f32; G * HD]; + let k0 = vec![0.25f32; HD]; + let v0: Vec = (0..HD).map(|d| d as f32).collect(); + let one = reference_attention_f64(&q, &[k0.clone()], &[v0.clone()], 1.0 / 16.0); + for h in 0..G { + assert_eq!(&one[h * HD..(h + 1) * HD], &v0[..]); + } + let v1: Vec = (0..HD).map(|d| 2.0 * d as f32 + 1.0).collect(); + let two = reference_attention_f64(&q, &[k0.clone(), k0], &[v0.clone(), v1.clone()], 1.0 / 16.0); + for d in 0..HD { + assert!((two[d] - 0.5 * (v0[d] + v1[d])).abs() < 1e-4); + } + assert!(reference_attention_f64(&q, &[], &[], 1.0).iter().all(|x| *x == 0.0)); +} diff --git a/crates/cuda-driver/src/s_gemv_legacy.rs b/crates/cuda-driver/src/s_gemv_legacy.rs index 1486a300..f4f574a5 100644 --- a/crates/cuda-driver/src/s_gemv_legacy.rs +++ b/crates/cuda-driver/src/s_gemv_legacy.rs @@ -565,224 +565,4 @@ pub fn q8_split_f32(w: &Weights, act: &[f32]) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::Value; - - fn golden() -> Value { - serde_json::from_str(include_str!("../oracle/fixtures/s_gemv_legacy_golden.json")).unwrap() - } - fn u8s(v: &Value) -> Vec { - v.as_array().unwrap().iter().map(|x| x.as_u64().unwrap() as u8).collect() - } - fn f32s(v: &Value) -> Vec { - v.as_array().unwrap().iter().map(|x| x.as_f64().unwrap() as f32).collect() - } - fn form(c: &Value) -> SForm { - SForm { - code_bits: c["bits"].as_i64().unwrap() as i32, - code_bias: c["bias"].as_i64().unwrap() as i32, - group_elems: c["group"].as_i64().unwrap() as i32, - codebook: if c["codebook"].as_i64().unwrap() == 1 { Codebook::Iq4Nl } else { Codebook::Affine }, - has_offset: c["has_offset"].as_i64().unwrap() == 1, - act_kind: 0, - } - } - fn bits_eq(a: &[f32], b: &[f32], what: &str) { - assert_eq!(a.len(), b.len(), "{what}"); - for (i, (x, y)) in a.iter().zip(b).enumerate() { - assert_eq!(x.to_bits(), y.to_bits(), "{what}[{i}]: model {x} vs shim-kernel {y}"); - } - } - - #[test] - fn golden_cases_match_the_shim_executed_kernels_bit_for_bit() { - let g = golden(); - let mut checked = 0; - for c in g["cases"].as_array().unwrap() { - let name = c["name"].as_str().unwrap(); - let f = form(c); - let (n_in, n_out) = (c["n_in"].as_u64().unwrap() as usize, c["n_out"].as_u64().unwrap() as usize); - let codes = u8s(&c["codes"]); - let scales = f32s(&c["scales"]); - let offset = if f.has_offset { Some(f32s(&c["offset"])) } else { None }; - let w = Weights { codes: &codes, scales: &scales, offset: offset.as_deref(), form: f, n_in, n_out }; - let exact = c["exact"].as_i64().unwrap() == 1; - // fp16 activations - let x: Vec = c["x"].as_array().unwrap().iter().map(|v| f16_to_f32(v.as_u64().unwrap() as u16)).collect(); - let y = f32s(&c["y_fp16"]); - bits_eq(&split_f32(&w, &x, 64), &y, &format!("{name} split64")); - if exact { - // every order is exact: the naive kernel, the FP64 spec and the split kernel coincide - bits_eq(&naive_f32(&w, &x), &y, &format!("{name} naive")); - let r: Vec = reference_f64(&w, &x).iter().map(|&v| v as f32).collect(); - bits_eq(&r, &y, &format!("{name} f64")); - } - // Q8_K activations (4- and 8-bit forms with n_in % 256 == 0) - let q8k = u8s(&c["q8k"]); - if f.code_bits != 2 && !q8k.is_empty() { - let a = q8k_dequant(&q8k, n_in); - bits_eq(&q8_split_f32(&w, &a), &f32s(&c["y_q8k"]), &format!("{name} q8k split")); - } - // Q8_0 activations (the S2 entry is s2_gemv_q8, whose tree is the quad kernel's) - let q80 = u8s(&c["q80"]); - if !q80.is_empty() { - let a = q8_0_dequant(&q80, n_in); - let y80 = f32s(&c["y_q80"]); - if f.code_bits != 2 { - bits_eq(&q8_split_f32(&w, &a), &y80, &format!("{name} q8_0 split")); - } else { - assert!(exact); - let r: Vec = reference_f64(&w, &a).iter().map(|&v| v as f32).collect(); - bits_eq(&r, &y80, &format!("{name} s2_gemv_q8")); - } - } - checked += 1; - } - assert_eq!(checked, 8); - } - - #[test] - fn pack_unpack_roundtrip_all_widths() { - for bits in [2u32, 4, 8] { - let raw: Vec = (0..64u32).map(|i| ((i * 37 + 5) & ((1 << bits) - 1)) as u8).collect(); - let packed = pack_codes(&raw, bits); - assert_eq!(packed.len(), 64 * bits as usize / 8); - for (e, &r) in raw.iter().enumerate() { - assert_eq!(code_at(&packed, bits, e), r as u32); - } - } - } - - #[test] - fn f16_conversion_covers_normal_subnormal_and_special() { - assert_eq!(f16_to_f32(0x3c00), 1.0); - assert_eq!(f16_to_f32(0xc000), -2.0); - assert_eq!(f16_to_f32(0x0001), 2f32.powi(-24)); - assert_eq!(f16_to_f32(0x7bff), 65504.0); - assert!(f16_to_f32(0x7c00).is_infinite()); - assert!(f16_to_f32(0x7e00).is_nan()); - } - - #[test] - fn cuda_source_carries_the_codebook_and_every_entry() { - let src = include_str!("s_gemv_legacy.cu"); - let table = IQ4NL.iter().map(|v| v.to_string()).collect::>().join(", "); - let squashed: String = src.split_whitespace().collect::>().join(" "); - assert!(squashed.contains(&format!("kIq4Nl[16] = {{{table}}};")), "codebook drifted from s_gemv.cu"); - for b in [2, 4, 8] { - assert!(src.contains(&format!("LELEKA_S_GEMV({b})")) && src.contains(&format!("LELEKA_S_GEMV_SPLIT({b})"))); - } - for b in [4, 8] { - assert!(src.contains(&format!("LELEKA_S_GEMV_Q8K({b})"))); - } - for e in Kernel::ALL_ENTRIES { - // macro-expanded entries are checked above through their invocations; the explicit ones by name - let direct = src.contains(&format!("void {e}(")); - let via_macro = e.starts_with("leleka_s_gemv_") && !e.contains("q8k_split") && !e.contains("q8_0_split"); - let split = (e.contains("q8k_split") || e.contains("q8_0_split")) && src.contains(&format!("LELEKA_S_GEMV_Q8_SPLIT({e},")); - assert!(direct || via_macro || split, "entry {e} not found in s_gemv_legacy.cu"); - } - // the s2_gemv_fast code table was generated: row b is [(b>>2k & 3) - 1 for k in 0..4] - assert!(src.contains("{-1.0f, -1.0f, -1.0f, -1.0f},")); - assert!(src.contains("{2.0f, 2.0f, 2.0f, 2.0f}\n};")); - assert!(src.contains("{0.0f, -1.0f, -1.0f, -1.0f},")); - } - - #[test] - fn entry_names_are_distinct_and_match_kernel_enum() { - let mut all: Vec<&str> = Kernel::ALL_ENTRIES.to_vec(); - all.sort(); - all.dedup(); - assert_eq!(all.len(), 17); - assert_eq!(Kernel::SGemv(8).entry(), "leleka_s_gemv_8"); - assert_eq!(Kernel::SGemvQ80Split(4).entry(), "leleka_s_gemv_q8_0_split_4"); - assert_eq!(Kernel::S2GemvFastUnstaged.entry(), "leleka_s2_gemv_fast_unstaged"); - } - - fn s4() -> SForm { - SForm { code_bits: 4, code_bias: -8, group_elems: 32, codebook: Codebook::Affine, has_offset: false, act_kind: 0 } - } - - #[test] - fn plan_s_gemv_geometry_and_refusals() { - let p = plan_s_gemv(2560, 10240, &s4(), false).unwrap().unwrap(); - assert_eq!(p.kernel, Kernel::SGemv(4)); - assert_eq!(p.launch, Launch { grid: [80, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }); - assert_eq!(plan_s_gemv(0, 5, &s4(), false), Ok(None)); - assert_eq!(plan_s_gemv(2560, 0, &s4(), false), Ok(None)); - assert_eq!(plan_s_gemv(100, 8, &s4(), false), Err(Error::NInNotGroupMultiple { who: "s_gemv", n_in: 100, group: 32 })); - let mut f = s4(); - f.has_offset = true; - assert_eq!(plan_s_gemv(64, 8, &f, false), Err(Error::OffsetMissing { who: "s_gemv" })); - assert!(plan_s_gemv(64, 8, &f, true).is_ok()); - f.code_bits = 3; - assert_eq!(plan_s_gemv(64, 8, &f, true), Err(Error::UnsupportedCodeBits { who: "s_gemv", bits: 3 })); - assert_eq!(Error::NInNotGroupMultiple { who: "s_gemv", n_in: 100, group: 32 }.message(), "s_gemv: n_in 100 is not a multiple of group_elems 32"); - } - - #[test] - fn plan_split_uses_a_row_per_block_and_shift_group() { - let f = SForm { code_bits: 2, code_bias: -1, group_elems: 64, ..SForm::default() }; - let p = plan_s_gemv_split(2560, 640, &f, 64, false).unwrap().unwrap(); - assert_eq!(p.kernel, Kernel::SGemvSplit(2)); - assert_eq!(p.group_shift, 6); - assert_eq!(p.launch, Launch { grid: [640, 1, 1], block: [64, 1, 1], dynamic_shared: 256 }); - for t in [0, 3, 2048, -1] { - assert_eq!(plan_s_gemv_split(2560, 640, &f, t, false), Err(Error::ThreadsPerRow { who: "s_gemv_split", threads: t })); - } - let odd = SForm { group_elems: 48, ..f }; - assert_eq!(plan_s_gemv_split(2560, 8, &odd, 32, false), Err(Error::GroupNotPowerOfTwo { who: "s_gemv_split", group: 48 })); - let two = SForm { group_elems: 2, ..f }; - assert_eq!(plan_s_gemv_split(64, 8, &two, 32, false), Err(Error::GroupNotMultiple { who: "s_gemv_split", group: 2, multiple: 4 })); - // stricter than the Original: n_in must be a group multiple - assert!(plan_s_gemv_split(2562, 8, &f, 32, false).is_err()); - } - - #[test] - fn plan_q8_kernels_enforce_the_activation_contract() { - let f = SForm { code_bits: 4, code_bias: 0, group_elems: 32, codebook: Codebook::Iq4Nl, has_offset: false, act_kind: 1 }; - let p = plan_s_gemv_q8k_split(2560, 10240, &f).unwrap().unwrap(); - assert_eq!(p.launch, Launch { grid: [1280, 1, 1], block: [256, 1, 1], dynamic_shared: 0 }); - assert_eq!(p.group_shift, 5); - assert_eq!(plan_s_gemv_q8k(2560, 10240, &f).unwrap().unwrap().launch.grid, [80, 1, 1]); - // 640 is a multiple of 32 but not of 256: only the Q8_0 kernel serves ffn_down_shexp - assert_eq!(plan_s_gemv_q8k_split(640, 2560, &f), Err(Error::NInNotBlockMultiple { who: "s_gemv_q8k_split", n_in: 640, block: 256 })); - let p0 = plan_s_gemv_q8_0_split(640, 2560, &f).unwrap().unwrap(); - assert_eq!(p0.kernel, Kernel::SGemvQ80Split(4)); - assert_eq!(p0.launch.grid, [320, 1, 1]); - assert_eq!(plan_s_gemv_q8_0_split(100, 8, &f), Err(Error::NInNotBlockMultiple { who: "s_gemv_q8_0_split", n_in: 100, block: 32 })); - let g8 = SForm { group_elems: 8, ..f }; - assert_eq!(plan_s_gemv_q8_0_split(640, 8, &g8), Err(Error::GroupNotMultiple { who: "s_gemv_q8_0_split", group: 8, multiple: 16 })); - let s2 = SForm { code_bits: 2, ..f }; - assert!(matches!(plan_s_gemv_q8k(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. }))); - assert!(matches!(plan_s_gemv_q8k_split(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. }))); - assert!(matches!(plan_s_gemv_q8_0_split(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. }))); - } - - #[test] - fn plan_s2_kernels() { - assert_eq!(plan_s2_gemv(2560, 300).unwrap().unwrap().launch, Launch { grid: [3, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }); - assert!(plan_s2_gemv(100, 8).is_err()); - let q = plan_s2_gemv_quads(2560, 640, 32).unwrap().unwrap(); - assert_eq!(q.launch, Launch { grid: [640, 1, 1], block: [32, 1, 1], dynamic_shared: 128 }); - assert_eq!(plan_s2_gemv_quads(6, 8, 32), Err(Error::NInNotBlockMultiple { who: "s2_gemv_quads", n_in: 6, block: 4 })); - assert!(plan_s2_gemv_quads(64, 8, 24).is_err()); - assert_eq!(plan_s2_gemv_q8(640, 8, 64).unwrap().unwrap().launch.dynamic_shared, 256); - assert!(plan_s2_gemv_q8(96, 8, 64).is_err()); - let st = plan_s2_gemv_fast(2560, 640, 64, true).unwrap().unwrap(); - assert_eq!(st.kernel, Kernel::S2GemvFastStaged); - assert_eq!(st.launch.dynamic_shared, 8192 + 256); - let un = plan_s2_gemv_fast(2560, 640, 64, false).unwrap().unwrap(); - assert_eq!((un.kernel, un.launch.dynamic_shared), (Kernel::S2GemvFastUnstaged, 256)); - assert_eq!(plan_s2_gemv_fast(8192, 8, 64, true), Err(Error::StagingLimit { n_in: 8192 })); - assert!(plan_s2_gemv_fast(8192, 8, 64, false).is_ok()); - } - - #[test] - fn grid_overflow_is_refused_not_truncated() { - let f = SForm { code_bits: 2, ..SForm::default() }; - let big = (u32::MAX as i64) + 1; - assert!(matches!(plan_s_gemv_split(64, big, &f, 32, false), Err(Error::GridTooLarge { .. }))); - } -} +mod tests; diff --git a/crates/cuda-driver/src/s_gemv_legacy/tests.rs b/crates/cuda-driver/src/s_gemv_legacy/tests.rs new file mode 100644 index 00000000..863e061c --- /dev/null +++ b/crates/cuda-driver/src/s_gemv_legacy/tests.rs @@ -0,0 +1,221 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use serde_json::Value; + +fn golden() -> Value { + serde_json::from_str(include_str!("../../oracle/fixtures/s_gemv_legacy_golden.json")).unwrap() +} +fn u8s(v: &Value) -> Vec { + v.as_array().unwrap().iter().map(|x| x.as_u64().unwrap() as u8).collect() +} +fn f32s(v: &Value) -> Vec { + v.as_array().unwrap().iter().map(|x| x.as_f64().unwrap() as f32).collect() +} +fn form(c: &Value) -> SForm { + SForm { + code_bits: c["bits"].as_i64().unwrap() as i32, + code_bias: c["bias"].as_i64().unwrap() as i32, + group_elems: c["group"].as_i64().unwrap() as i32, + codebook: if c["codebook"].as_i64().unwrap() == 1 { Codebook::Iq4Nl } else { Codebook::Affine }, + has_offset: c["has_offset"].as_i64().unwrap() == 1, + act_kind: 0, + } +} +fn bits_eq(a: &[f32], b: &[f32], what: &str) { + assert_eq!(a.len(), b.len(), "{what}"); + for (i, (x, y)) in a.iter().zip(b).enumerate() { + assert_eq!(x.to_bits(), y.to_bits(), "{what}[{i}]: model {x} vs shim-kernel {y}"); + } +} + +#[test] +fn golden_cases_match_the_shim_executed_kernels_bit_for_bit() { + let g = golden(); + let mut checked = 0; + for c in g["cases"].as_array().unwrap() { + let name = c["name"].as_str().unwrap(); + let f = form(c); + let (n_in, n_out) = (c["n_in"].as_u64().unwrap() as usize, c["n_out"].as_u64().unwrap() as usize); + let codes = u8s(&c["codes"]); + let scales = f32s(&c["scales"]); + let offset = if f.has_offset { Some(f32s(&c["offset"])) } else { None }; + let w = Weights { codes: &codes, scales: &scales, offset: offset.as_deref(), form: f, n_in, n_out }; + let exact = c["exact"].as_i64().unwrap() == 1; + // fp16 activations + let x: Vec = c["x"].as_array().unwrap().iter().map(|v| f16_to_f32(v.as_u64().unwrap() as u16)).collect(); + let y = f32s(&c["y_fp16"]); + bits_eq(&split_f32(&w, &x, 64), &y, &format!("{name} split64")); + if exact { + // every order is exact: the naive kernel, the FP64 spec and the split kernel coincide + bits_eq(&naive_f32(&w, &x), &y, &format!("{name} naive")); + let r: Vec = reference_f64(&w, &x).iter().map(|&v| v as f32).collect(); + bits_eq(&r, &y, &format!("{name} f64")); + } + // Q8_K activations (4- and 8-bit forms with n_in % 256 == 0) + let q8k = u8s(&c["q8k"]); + if f.code_bits != 2 && !q8k.is_empty() { + let a = q8k_dequant(&q8k, n_in); + bits_eq(&q8_split_f32(&w, &a), &f32s(&c["y_q8k"]), &format!("{name} q8k split")); + } + // Q8_0 activations (the S2 entry is s2_gemv_q8, whose tree is the quad kernel's) + let q80 = u8s(&c["q80"]); + if !q80.is_empty() { + let a = q8_0_dequant(&q80, n_in); + let y80 = f32s(&c["y_q80"]); + if f.code_bits != 2 { + bits_eq(&q8_split_f32(&w, &a), &y80, &format!("{name} q8_0 split")); + } else { + assert!(exact); + let r: Vec = reference_f64(&w, &a).iter().map(|&v| v as f32).collect(); + bits_eq(&r, &y80, &format!("{name} s2_gemv_q8")); + } + } + checked += 1; + } + assert_eq!(checked, 8); +} + +#[test] +fn pack_unpack_roundtrip_all_widths() { + for bits in [2u32, 4, 8] { + let raw: Vec = (0..64u32).map(|i| ((i * 37 + 5) & ((1 << bits) - 1)) as u8).collect(); + let packed = pack_codes(&raw, bits); + assert_eq!(packed.len(), 64 * bits as usize / 8); + for (e, &r) in raw.iter().enumerate() { + assert_eq!(code_at(&packed, bits, e), r as u32); + } + } +} + +#[test] +fn f16_conversion_covers_normal_subnormal_and_special() { + assert_eq!(f16_to_f32(0x3c00), 1.0); + assert_eq!(f16_to_f32(0xc000), -2.0); + assert_eq!(f16_to_f32(0x0001), 2f32.powi(-24)); + assert_eq!(f16_to_f32(0x7bff), 65504.0); + assert!(f16_to_f32(0x7c00).is_infinite()); + assert!(f16_to_f32(0x7e00).is_nan()); +} + +#[test] +fn cuda_source_carries_the_codebook_and_every_entry() { + let src = include_str!("../s_gemv_legacy.cu"); + let table = IQ4NL.iter().map(|v| v.to_string()).collect::>().join(", "); + let squashed: String = src.split_whitespace().collect::>().join(" "); + assert!(squashed.contains(&format!("kIq4Nl[16] = {{{table}}};")), "codebook drifted from s_gemv.cu"); + for b in [2, 4, 8] { + assert!(src.contains(&format!("LELEKA_S_GEMV({b})")) && src.contains(&format!("LELEKA_S_GEMV_SPLIT({b})"))); + } + for b in [4, 8] { + assert!(src.contains(&format!("LELEKA_S_GEMV_Q8K({b})"))); + } + for e in Kernel::ALL_ENTRIES { + // macro-expanded entries are checked above through their invocations; the explicit ones by name + let direct = src.contains(&format!("void {e}(")); + let via_macro = e.starts_with("leleka_s_gemv_") && !e.contains("q8k_split") && !e.contains("q8_0_split"); + let split = (e.contains("q8k_split") || e.contains("q8_0_split")) && src.contains(&format!("LELEKA_S_GEMV_Q8_SPLIT({e},")); + assert!(direct || via_macro || split, "entry {e} not found in s_gemv_legacy.cu"); + } + // the s2_gemv_fast code table was generated: row b is [(b>>2k & 3) - 1 for k in 0..4] + assert!(src.contains("{-1.0f, -1.0f, -1.0f, -1.0f},")); + assert!(src.contains("{2.0f, 2.0f, 2.0f, 2.0f}\n};")); + assert!(src.contains("{0.0f, -1.0f, -1.0f, -1.0f},")); +} + +#[test] +fn entry_names_are_distinct_and_match_kernel_enum() { + let mut all: Vec<&str> = Kernel::ALL_ENTRIES.to_vec(); + all.sort(); + all.dedup(); + assert_eq!(all.len(), 17); + assert_eq!(Kernel::SGemv(8).entry(), "leleka_s_gemv_8"); + assert_eq!(Kernel::SGemvQ80Split(4).entry(), "leleka_s_gemv_q8_0_split_4"); + assert_eq!(Kernel::S2GemvFastUnstaged.entry(), "leleka_s2_gemv_fast_unstaged"); +} + +fn s4() -> SForm { + SForm { code_bits: 4, code_bias: -8, group_elems: 32, codebook: Codebook::Affine, has_offset: false, act_kind: 0 } +} + +#[test] +fn plan_s_gemv_geometry_and_refusals() { + let p = plan_s_gemv(2560, 10240, &s4(), false).unwrap().unwrap(); + assert_eq!(p.kernel, Kernel::SGemv(4)); + assert_eq!(p.launch, Launch { grid: [80, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }); + assert_eq!(plan_s_gemv(0, 5, &s4(), false), Ok(None)); + assert_eq!(plan_s_gemv(2560, 0, &s4(), false), Ok(None)); + assert_eq!(plan_s_gemv(100, 8, &s4(), false), Err(Error::NInNotGroupMultiple { who: "s_gemv", n_in: 100, group: 32 })); + let mut f = s4(); + f.has_offset = true; + assert_eq!(plan_s_gemv(64, 8, &f, false), Err(Error::OffsetMissing { who: "s_gemv" })); + assert!(plan_s_gemv(64, 8, &f, true).is_ok()); + f.code_bits = 3; + assert_eq!(plan_s_gemv(64, 8, &f, true), Err(Error::UnsupportedCodeBits { who: "s_gemv", bits: 3 })); + assert_eq!(Error::NInNotGroupMultiple { who: "s_gemv", n_in: 100, group: 32 }.message(), "s_gemv: n_in 100 is not a multiple of group_elems 32"); +} + +#[test] +fn plan_split_uses_a_row_per_block_and_shift_group() { + let f = SForm { code_bits: 2, code_bias: -1, group_elems: 64, ..SForm::default() }; + let p = plan_s_gemv_split(2560, 640, &f, 64, false).unwrap().unwrap(); + assert_eq!(p.kernel, Kernel::SGemvSplit(2)); + assert_eq!(p.group_shift, 6); + assert_eq!(p.launch, Launch { grid: [640, 1, 1], block: [64, 1, 1], dynamic_shared: 256 }); + for t in [0, 3, 2048, -1] { + assert_eq!(plan_s_gemv_split(2560, 640, &f, t, false), Err(Error::ThreadsPerRow { who: "s_gemv_split", threads: t })); + } + let odd = SForm { group_elems: 48, ..f }; + assert_eq!(plan_s_gemv_split(2560, 8, &odd, 32, false), Err(Error::GroupNotPowerOfTwo { who: "s_gemv_split", group: 48 })); + let two = SForm { group_elems: 2, ..f }; + assert_eq!(plan_s_gemv_split(64, 8, &two, 32, false), Err(Error::GroupNotMultiple { who: "s_gemv_split", group: 2, multiple: 4 })); + // stricter than the Original: n_in must be a group multiple + assert!(plan_s_gemv_split(2562, 8, &f, 32, false).is_err()); +} + +#[test] +fn plan_q8_kernels_enforce_the_activation_contract() { + let f = SForm { code_bits: 4, code_bias: 0, group_elems: 32, codebook: Codebook::Iq4Nl, has_offset: false, act_kind: 1 }; + let p = plan_s_gemv_q8k_split(2560, 10240, &f).unwrap().unwrap(); + assert_eq!(p.launch, Launch { grid: [1280, 1, 1], block: [256, 1, 1], dynamic_shared: 0 }); + assert_eq!(p.group_shift, 5); + assert_eq!(plan_s_gemv_q8k(2560, 10240, &f).unwrap().unwrap().launch.grid, [80, 1, 1]); + // 640 is a multiple of 32 but not of 256: only the Q8_0 kernel serves ffn_down_shexp + assert_eq!(plan_s_gemv_q8k_split(640, 2560, &f), Err(Error::NInNotBlockMultiple { who: "s_gemv_q8k_split", n_in: 640, block: 256 })); + let p0 = plan_s_gemv_q8_0_split(640, 2560, &f).unwrap().unwrap(); + assert_eq!(p0.kernel, Kernel::SGemvQ80Split(4)); + assert_eq!(p0.launch.grid, [320, 1, 1]); + assert_eq!(plan_s_gemv_q8_0_split(100, 8, &f), Err(Error::NInNotBlockMultiple { who: "s_gemv_q8_0_split", n_in: 100, block: 32 })); + let g8 = SForm { group_elems: 8, ..f }; + assert_eq!(plan_s_gemv_q8_0_split(640, 8, &g8), Err(Error::GroupNotMultiple { who: "s_gemv_q8_0_split", group: 8, multiple: 16 })); + let s2 = SForm { code_bits: 2, ..f }; + assert!(matches!(plan_s_gemv_q8k(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. }))); + assert!(matches!(plan_s_gemv_q8k_split(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. }))); + assert!(matches!(plan_s_gemv_q8_0_split(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. }))); +} + +#[test] +fn plan_s2_kernels() { + assert_eq!(plan_s2_gemv(2560, 300).unwrap().unwrap().launch, Launch { grid: [3, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }); + assert!(plan_s2_gemv(100, 8).is_err()); + let q = plan_s2_gemv_quads(2560, 640, 32).unwrap().unwrap(); + assert_eq!(q.launch, Launch { grid: [640, 1, 1], block: [32, 1, 1], dynamic_shared: 128 }); + assert_eq!(plan_s2_gemv_quads(6, 8, 32), Err(Error::NInNotBlockMultiple { who: "s2_gemv_quads", n_in: 6, block: 4 })); + assert!(plan_s2_gemv_quads(64, 8, 24).is_err()); + assert_eq!(plan_s2_gemv_q8(640, 8, 64).unwrap().unwrap().launch.dynamic_shared, 256); + assert!(plan_s2_gemv_q8(96, 8, 64).is_err()); + let st = plan_s2_gemv_fast(2560, 640, 64, true).unwrap().unwrap(); + assert_eq!(st.kernel, Kernel::S2GemvFastStaged); + assert_eq!(st.launch.dynamic_shared, 8192 + 256); + let un = plan_s2_gemv_fast(2560, 640, 64, false).unwrap().unwrap(); + assert_eq!((un.kernel, un.launch.dynamic_shared), (Kernel::S2GemvFastUnstaged, 256)); + assert_eq!(plan_s2_gemv_fast(8192, 8, 64, true), Err(Error::StagingLimit { n_in: 8192 })); + assert!(plan_s2_gemv_fast(8192, 8, 64, false).is_ok()); +} + +#[test] +fn grid_overflow_is_refused_not_truncated() { + let f = SForm { code_bits: 2, ..SForm::default() }; + let big = (u32::MAX as i64) + 1; + assert!(matches!(plan_s_gemv_split(64, big, &f, 32, false), Err(Error::GridTooLarge { .. }))); +} diff --git a/crates/deploy/src/cli.rs b/crates/deploy/src/cli.rs index 68b8c07f..c48f0aa9 100644 --- a/crates/deploy/src/cli.rs +++ b/crates/deploy/src/cli.rs @@ -758,413 +758,4 @@ pub fn parse(args: &[String], env: &Environment) -> Result { } #[cfg(test)] -mod tests { - use super::*; - - fn strings(items: &[&str]) -> Vec { - items.iter().map(|s| s.to_string()).collect() - } - - fn parse_as(root: bool, args: &[&str]) -> Result { - let var = |_: &str| None; - parse( - &strings(args), - &Environment { - root, - home: Some("/home/para".into()), - var: &var, - }, - ) - } - - #[test] - fn logs_and_report_take_their_own_flags_and_the_locating_ones() { - let state = if cfg!(windows) { - "C:\\x\\state" - } else { - "/var/lib/x" - }; - let Ok(Command::Logs(options, logs)) = parse_as( - false, - &[ - "logs", - "--tail", - "20", - "--since=15m", - "--level", - "warn", - "--request", - "0b1c2d3e", - "--state-dir", - state, - ], - ) else { - panic!() - }; - assert_eq!( - ( - logs.tail, - logs.since.as_deref(), - logs.level.as_deref(), - logs.request.as_deref() - ), - (Some(20), Some("15m"), Some("warn"), Some("0b1c2d3e")) - ); - assert_eq!(options.dirs.state, PathBuf::from(state)); - assert!( - matches!(parse_as(false, &["logs", "-f", "--source", "api"]), Ok(Command::Logs(_, l)) if l.follow && l.source.as_deref() == Some("api")) - ); - assert!(parse_as(false, &["logs", "--tail", "0"]).is_err()); - assert!(parse_as(false, &["logs", "--tail", "x"]).is_err()); - assert!(parse_as(false, &["logs", "-f", "--request", "abcdef"]).is_err()); - assert!(parse_as(false, &["logs", "--bogus"]).is_err()); - let Ok(Command::Report(_, report)) = parse_as(false, &["report"]) else { - panic!() - }; - assert!( - !report.yes && report.last == 50 && report.out.is_none(), - "the opt-in is explicit" - ); - let Ok(Command::Report(_, report)) = - parse_as(false, &["report", "--yes", "--last", "200", "--out", "-"]) - else { - panic!() - }; - assert!(report.yes && report.last == 200 && report.out.as_deref() == Some("-")); - assert!(parse_as(false, &["report", "--last", "9999"]).is_err()); - assert!( - USAGE.contains("leleka logs") - && USAGE.contains("leleka report") - && USAGE.contains("--yes") - ); - } - - #[cfg(unix)] - #[test] - fn up_defaults_for_a_user() { - let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { - panic!() - }; - assert_eq!( - options.dirs.assets, - PathBuf::from("/home/para/.local/share/leleka/assets") - ); - assert_eq!(options.ports.api, "127.0.0.1:8081"); - assert!(options.fetch && options.install_cublas && !options.dry_run); - assert_eq!(options.mode, ModeChoice::Auto); - assert_eq!(options.timeout_s, 3600); - } - - #[test] - fn the_expert_profile_flags_parse_and_exclude_each_other() { - let Command::Up(options) = parse_as( - false, - &["up", "--expert-profile-file", "/mnt/usb/expert-profile.bin"], - ) - .unwrap() else { - panic!() - }; - assert_eq!( - options.expert_profile_file, - Some(PathBuf::from("/mnt/usb/expert-profile.bin")) - ); - assert!(!options.no_expert_tier); - let Command::Up(options) = parse_as(false, &["up", "--no-expert-tier"]).unwrap() else { - panic!() - }; - assert!(options.no_expert_tier && options.expert_profile_file.is_none()); - let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { - panic!() - }; - assert!(!options.no_expert_tier && options.expert_profile_file.is_none()); - let error = parse_as( - false, - &["up", "--no-expert-tier", "--expert-profile-file", "/x"], - ) - .unwrap_err(); - assert!(error.contains("contradict"), "{error}"); - assert!(parse_as(false, &["up", "--no-expert-tier=1"]).is_err()); - } - - #[test] - fn flags_accept_both_forms_and_reject_mistakes() { - let Command::Up(options) = parse_as( - false, - &[ - "up", - "--assets=/data/l", - "--gpu", - "1", - "--foreground", - "--dry-run", - "--json", - "--no-fetch", - "--api-port=9000", - ], - ) - .unwrap() else { - panic!() - }; - assert_eq!(options.dirs.assets, PathBuf::from("/data/l")); - assert_eq!( - ( - options.gpu, - options.mode, - options.dry_run, - options.json, - options.fetch - ), - (1, ModeChoice::Foreground, true, true, false) - ); - assert_eq!(options.ports.api, "127.0.0.1:9000"); - for bad in [ - &["up", "--nope"][..], - &["up", "--gpu"], - &["up", "--dry-run", "--dry-run"], - &["up", "--dry-run=1"], - &["up", "--assets", "relative/dir"], - &["up", "--api-port", "80"], - &["up", "--api-port", "9000", "--engine-port", "9000"], - &["up", "--mode", "weird"], - &["up", "--foreground", "--mode", "user"], - &["up", "--gpu-budget-gib", "0"], - &["up", "--context-tokens", "999999"], - &["up", "--timeout-s", "0"], - ] { - assert!(parse_as(false, bad).is_err(), "{bad:?} should fail"); - } - } - - #[test] - fn the_resource_preset_comes_from_the_flag_then_the_environment() { - use crate::resources::Preset; - let preset = |args: &[&str]| match parse_as(false, args) { - Ok(Command::Up(options)) => Ok(options.preset), - Ok(_) => unreachable!(), - Err(message) => Err(message), - }; - assert_eq!(preset(&["up"]), Ok(Preset::Dedicated)); - assert_eq!( - preset(&["up", "--preset", "workstation"]), - Ok(Preset::Workstation) - ); - assert!( - preset(&["up", "--preset", "shared"]) - .unwrap_err() - .contains("unknown preset") - ); - } - - #[test] - fn reconfigure_collects_the_settings_and_locates_the_service_with_the_up_flags() { - let Ok(Command::Reconfigure(options, args)) = parse_as( - false, - &[ - "reconfigure", - "--context-tokens", - "65536", - "--prefix-cache-tail=reply", - "--prefix-cache-mib", - "20480", - "--spec-min-p", - "0.5", - "--state-dir", - "/var/lib/leleka/state", - ], - ) else { - panic!("reconfigure did not parse"); - }; - assert_eq!( - options.dirs.state, - std::path::PathBuf::from("/var/lib/leleka/state") - ); - assert!(!args.needs_restart() && !args.persist); - let value = serde_json::Value::Object(args.settings); - assert_eq!(value["context_tokens"], 65536); - assert_eq!(value["prefix_cache_tail"], "reply"); - assert_eq!(value["prefix_cache_mib"], "20480"); - assert_eq!(value["spec_min_p"], 0.5); - assert!( - parse_as(false, &["reconfigure"]) - .unwrap_err() - .contains("at least one setting") - ); - assert!( - parse_as(false, &["reconfigure", "--cpu-workers", "many"]) - .unwrap_err() - .contains("whole number") - ); - assert!( - parse_as( - false, - &["reconfigure", "--cpu-workers", "4", "--cpu-workers", "5"] - ) - .unwrap_err() - .contains("twice") - ); - } - - #[test] - fn reconfigure_takes_the_budget_the_preset_and_persist_out_of_the_up_flags() { - let Ok(Command::Reconfigure(options, args)) = parse_as( - false, - &[ - "reconfigure", - "--gpu-budget-gib", - "24", - "--preset=workstation", - "--persist", - "--context-tokens", - "65536", - "--state-dir", - "/s", - ], - ) else { - panic!("reconfigure did not parse"); - }; - assert!(args.needs_restart() && args.persist); - assert_eq!(args.gpu_budget_gib, Some(24)); - assert_eq!(args.preset, Some(crate::resources::Preset::Workstation)); - assert_eq!(args.settings["context_tokens"], 65536); - // they are the restart request, not `up` options: the service is located by the remaining flags only - assert_eq!(options.dirs.state, std::path::PathBuf::from("/s")); - assert_eq!(options.gpu_budget_gib, None); - assert_eq!(options.preset, crate::resources::Preset::Dedicated); - // the budget or the preset alone is a request; nothing at all is not - assert!(matches!( - parse_as(false, &["reconfigure", "--preset", "dedicated"]), - Ok(Command::Reconfigure(..)) - )); - assert!(matches!( - parse_as(false, &["reconfigure", "--gpu-budget-gib", "20"]), - Ok(Command::Reconfigure(..)) - )); - assert!( - parse_as(false, &["reconfigure", "--persist"]) - .unwrap_err() - .contains("at least one setting") - ); - assert!( - parse_as(false, &["reconfigure", "--gpu-budget-gib", "0"]) - .unwrap_err() - .contains("1..1024") - ); - assert!( - parse_as(false, &["reconfigure", "--gpu-budget-gib", "many"]) - .unwrap_err() - .contains("whole number") - ); - assert!( - parse_as(false, &["reconfigure", "--preset", "shared"]) - .unwrap_err() - .contains("unknown preset") - ); - assert!( - parse_as( - false, - &["reconfigure", "--persist=yes", "--cpu-workers", "2"] - ) - .unwrap_err() - .contains("no value") - ); - assert!( - parse_as( - false, - &[ - "reconfigure", - "--gpu-budget-gib", - "20", - "--gpu-budget-gib", - "21" - ] - ) - .unwrap_err() - .contains("twice") - ); - } - - #[test] - fn api_bind_is_explicit_and_only_for_the_api() { - let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap() - else { - panic!() - }; - assert_eq!(options.ports.api, "0.0.0.0:8081"); - assert_eq!(options.ports.engine, "127.0.0.1:18766"); - assert!(parse_as(false, &["up", "--api-bind", "localhost"]).is_err()); - assert!(parse_as(false, &["up", "--api-bind", "::"]).is_err()); - } - - #[cfg(windows)] - #[test] - fn windows_has_no_systemd_modes_and_defaults_to_the_profile() { - assert!( - parse_as(false, &["up", "--mode", "system"]) - .unwrap_err() - .contains("--foreground") - ); - assert!(parse_as(false, &["up", "--mode=user"]).is_err()); - let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { - panic!() - }; - assert!( - options.dirs.state.ends_with("leleka/state"), - "{:?}", - options.dirs - ); - assert_eq!(options.mode, ModeChoice::Auto); - assert!(parse_as(false, &["up", "--assets", "D:\\models"]).is_ok()); - assert!(parse_as(false, &["up", "--assets", "models"]).is_err()); - } - - #[cfg(unix)] - #[test] - fn system_mode_needs_root() { - assert!( - parse_as(false, &["up", "--mode", "system"]) - .unwrap_err() - .contains("root") - ); - assert!(parse_as(true, &["up", "--mode", "system"]).is_ok()); - let Command::Up(options) = parse_as(true, &["up"]).unwrap() else { - panic!() - }; - assert_eq!(options.dirs.prefix, PathBuf::from("/opt/leleka")); - } - - #[test] - fn other_commands() { - assert!(matches!(parse_as(false, &[]).unwrap(), Command::Help)); - assert!(matches!( - parse_as(false, &["profiles"]).unwrap(), - Command::Profiles(None) - )); - assert!(matches!( - parse_as(false, &["profiles", "show", "rtx5090-32g"]).unwrap(), - Command::Profiles(Some(_)) - )); - let Command::Run { config, kar_fd } = parse_as( - false, - &["run", "--config", "/s/leleka.json", "--kar-fd", "3"], - ) - .unwrap() else { - panic!() - }; - assert_eq!((config, kar_fd), (PathBuf::from("/s/leleka.json"), Some(3))); - assert!(parse_as(false, &["run"]).is_err()); - assert!(parse_as(false, &["frobnicate"]).is_err()); - assert!(matches!( - parse_as(false, &["exec-inherit", "--", "x"]).unwrap(), - Command::ExecInherit(_) - )); - assert!(matches!( - parse_as(false, &["seal-exec", "--file", "f", "--", "x"]).unwrap(), - Command::SealExec(_) - )); - assert!(matches!( - parse_as(false, &["seal-probe", "/x/y"]).unwrap(), - Command::SealProbe(_) - )); - assert!(parse_as(false, &["seal-probe"]).is_err()); - } -} +mod tests; diff --git a/crates/deploy/src/cli/tests.rs b/crates/deploy/src/cli/tests.rs new file mode 100644 index 00000000..2847fffa --- /dev/null +++ b/crates/deploy/src/cli/tests.rs @@ -0,0 +1,410 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn strings(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() +} + +fn parse_as(root: bool, args: &[&str]) -> Result { + let var = |_: &str| None; + parse( + &strings(args), + &Environment { + root, + home: Some("/home/para".into()), + var: &var, + }, + ) +} + +#[test] +fn logs_and_report_take_their_own_flags_and_the_locating_ones() { + let state = if cfg!(windows) { + "C:\\x\\state" + } else { + "/var/lib/x" + }; + let Ok(Command::Logs(options, logs)) = parse_as( + false, + &[ + "logs", + "--tail", + "20", + "--since=15m", + "--level", + "warn", + "--request", + "0b1c2d3e", + "--state-dir", + state, + ], + ) else { + panic!() + }; + assert_eq!( + ( + logs.tail, + logs.since.as_deref(), + logs.level.as_deref(), + logs.request.as_deref() + ), + (Some(20), Some("15m"), Some("warn"), Some("0b1c2d3e")) + ); + assert_eq!(options.dirs.state, PathBuf::from(state)); + assert!( + matches!(parse_as(false, &["logs", "-f", "--source", "api"]), Ok(Command::Logs(_, l)) if l.follow && l.source.as_deref() == Some("api")) + ); + assert!(parse_as(false, &["logs", "--tail", "0"]).is_err()); + assert!(parse_as(false, &["logs", "--tail", "x"]).is_err()); + assert!(parse_as(false, &["logs", "-f", "--request", "abcdef"]).is_err()); + assert!(parse_as(false, &["logs", "--bogus"]).is_err()); + let Ok(Command::Report(_, report)) = parse_as(false, &["report"]) else { + panic!() + }; + assert!( + !report.yes && report.last == 50 && report.out.is_none(), + "the opt-in is explicit" + ); + let Ok(Command::Report(_, report)) = + parse_as(false, &["report", "--yes", "--last", "200", "--out", "-"]) + else { + panic!() + }; + assert!(report.yes && report.last == 200 && report.out.as_deref() == Some("-")); + assert!(parse_as(false, &["report", "--last", "9999"]).is_err()); + assert!( + USAGE.contains("leleka logs") + && USAGE.contains("leleka report") + && USAGE.contains("--yes") + ); +} + +#[cfg(unix)] +#[test] +fn up_defaults_for_a_user() { + let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { + panic!() + }; + assert_eq!( + options.dirs.assets, + PathBuf::from("/home/para/.local/share/leleka/assets") + ); + assert_eq!(options.ports.api, "127.0.0.1:8081"); + assert!(options.fetch && options.install_cublas && !options.dry_run); + assert_eq!(options.mode, ModeChoice::Auto); + assert_eq!(options.timeout_s, 3600); +} + +#[test] +fn the_expert_profile_flags_parse_and_exclude_each_other() { + let Command::Up(options) = parse_as( + false, + &["up", "--expert-profile-file", "/mnt/usb/expert-profile.bin"], + ) + .unwrap() else { + panic!() + }; + assert_eq!( + options.expert_profile_file, + Some(PathBuf::from("/mnt/usb/expert-profile.bin")) + ); + assert!(!options.no_expert_tier); + let Command::Up(options) = parse_as(false, &["up", "--no-expert-tier"]).unwrap() else { + panic!() + }; + assert!(options.no_expert_tier && options.expert_profile_file.is_none()); + let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { + panic!() + }; + assert!(!options.no_expert_tier && options.expert_profile_file.is_none()); + let error = parse_as( + false, + &["up", "--no-expert-tier", "--expert-profile-file", "/x"], + ) + .unwrap_err(); + assert!(error.contains("contradict"), "{error}"); + assert!(parse_as(false, &["up", "--no-expert-tier=1"]).is_err()); +} + +#[test] +fn flags_accept_both_forms_and_reject_mistakes() { + let Command::Up(options) = parse_as( + false, + &[ + "up", + "--assets=/data/l", + "--gpu", + "1", + "--foreground", + "--dry-run", + "--json", + "--no-fetch", + "--api-port=9000", + ], + ) + .unwrap() else { + panic!() + }; + assert_eq!(options.dirs.assets, PathBuf::from("/data/l")); + assert_eq!( + ( + options.gpu, + options.mode, + options.dry_run, + options.json, + options.fetch + ), + (1, ModeChoice::Foreground, true, true, false) + ); + assert_eq!(options.ports.api, "127.0.0.1:9000"); + for bad in [ + &["up", "--nope"][..], + &["up", "--gpu"], + &["up", "--dry-run", "--dry-run"], + &["up", "--dry-run=1"], + &["up", "--assets", "relative/dir"], + &["up", "--api-port", "80"], + &["up", "--api-port", "9000", "--engine-port", "9000"], + &["up", "--mode", "weird"], + &["up", "--foreground", "--mode", "user"], + &["up", "--gpu-budget-gib", "0"], + &["up", "--context-tokens", "999999"], + &["up", "--timeout-s", "0"], + ] { + assert!(parse_as(false, bad).is_err(), "{bad:?} should fail"); + } +} + +#[test] +fn the_resource_preset_comes_from_the_flag_then_the_environment() { + use crate::resources::Preset; + let preset = |args: &[&str]| match parse_as(false, args) { + Ok(Command::Up(options)) => Ok(options.preset), + Ok(_) => unreachable!(), + Err(message) => Err(message), + }; + assert_eq!(preset(&["up"]), Ok(Preset::Dedicated)); + assert_eq!( + preset(&["up", "--preset", "workstation"]), + Ok(Preset::Workstation) + ); + assert!( + preset(&["up", "--preset", "shared"]) + .unwrap_err() + .contains("unknown preset") + ); +} + +#[test] +fn reconfigure_collects_the_settings_and_locates_the_service_with_the_up_flags() { + let Ok(Command::Reconfigure(options, args)) = parse_as( + false, + &[ + "reconfigure", + "--context-tokens", + "65536", + "--prefix-cache-tail=reply", + "--prefix-cache-mib", + "20480", + "--spec-min-p", + "0.5", + "--state-dir", + "/var/lib/leleka/state", + ], + ) else { + panic!("reconfigure did not parse"); + }; + assert_eq!( + options.dirs.state, + std::path::PathBuf::from("/var/lib/leleka/state") + ); + assert!(!args.needs_restart() && !args.persist); + let value = serde_json::Value::Object(args.settings); + assert_eq!(value["context_tokens"], 65536); + assert_eq!(value["prefix_cache_tail"], "reply"); + assert_eq!(value["prefix_cache_mib"], "20480"); + assert_eq!(value["spec_min_p"], 0.5); + assert!( + parse_as(false, &["reconfigure"]) + .unwrap_err() + .contains("at least one setting") + ); + assert!( + parse_as(false, &["reconfigure", "--cpu-workers", "many"]) + .unwrap_err() + .contains("whole number") + ); + assert!( + parse_as( + false, + &["reconfigure", "--cpu-workers", "4", "--cpu-workers", "5"] + ) + .unwrap_err() + .contains("twice") + ); +} + +#[test] +fn reconfigure_takes_the_budget_the_preset_and_persist_out_of_the_up_flags() { + let Ok(Command::Reconfigure(options, args)) = parse_as( + false, + &[ + "reconfigure", + "--gpu-budget-gib", + "24", + "--preset=workstation", + "--persist", + "--context-tokens", + "65536", + "--state-dir", + "/s", + ], + ) else { + panic!("reconfigure did not parse"); + }; + assert!(args.needs_restart() && args.persist); + assert_eq!(args.gpu_budget_gib, Some(24)); + assert_eq!(args.preset, Some(crate::resources::Preset::Workstation)); + assert_eq!(args.settings["context_tokens"], 65536); + // they are the restart request, not `up` options: the service is located by the remaining flags only + assert_eq!(options.dirs.state, std::path::PathBuf::from("/s")); + assert_eq!(options.gpu_budget_gib, None); + assert_eq!(options.preset, crate::resources::Preset::Dedicated); + // the budget or the preset alone is a request; nothing at all is not + assert!(matches!( + parse_as(false, &["reconfigure", "--preset", "dedicated"]), + Ok(Command::Reconfigure(..)) + )); + assert!(matches!( + parse_as(false, &["reconfigure", "--gpu-budget-gib", "20"]), + Ok(Command::Reconfigure(..)) + )); + assert!( + parse_as(false, &["reconfigure", "--persist"]) + .unwrap_err() + .contains("at least one setting") + ); + assert!( + parse_as(false, &["reconfigure", "--gpu-budget-gib", "0"]) + .unwrap_err() + .contains("1..1024") + ); + assert!( + parse_as(false, &["reconfigure", "--gpu-budget-gib", "many"]) + .unwrap_err() + .contains("whole number") + ); + assert!( + parse_as(false, &["reconfigure", "--preset", "shared"]) + .unwrap_err() + .contains("unknown preset") + ); + assert!( + parse_as( + false, + &["reconfigure", "--persist=yes", "--cpu-workers", "2"] + ) + .unwrap_err() + .contains("no value") + ); + assert!( + parse_as( + false, + &[ + "reconfigure", + "--gpu-budget-gib", + "20", + "--gpu-budget-gib", + "21" + ] + ) + .unwrap_err() + .contains("twice") + ); +} + +#[test] +fn api_bind_is_explicit_and_only_for_the_api() { + let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap() + else { + panic!() + }; + assert_eq!(options.ports.api, "0.0.0.0:8081"); + assert_eq!(options.ports.engine, "127.0.0.1:18766"); + assert!(parse_as(false, &["up", "--api-bind", "localhost"]).is_err()); + assert!(parse_as(false, &["up", "--api-bind", "::"]).is_err()); +} + +#[cfg(windows)] +#[test] +fn windows_has_no_systemd_modes_and_defaults_to_the_profile() { + assert!( + parse_as(false, &["up", "--mode", "system"]) + .unwrap_err() + .contains("--foreground") + ); + assert!(parse_as(false, &["up", "--mode=user"]).is_err()); + let Command::Up(options) = parse_as(false, &["up"]).unwrap() else { + panic!() + }; + assert!( + options.dirs.state.ends_with("leleka/state"), + "{:?}", + options.dirs + ); + assert_eq!(options.mode, ModeChoice::Auto); + assert!(parse_as(false, &["up", "--assets", "D:\\models"]).is_ok()); + assert!(parse_as(false, &["up", "--assets", "models"]).is_err()); +} + +#[cfg(unix)] +#[test] +fn system_mode_needs_root() { + assert!( + parse_as(false, &["up", "--mode", "system"]) + .unwrap_err() + .contains("root") + ); + assert!(parse_as(true, &["up", "--mode", "system"]).is_ok()); + let Command::Up(options) = parse_as(true, &["up"]).unwrap() else { + panic!() + }; + assert_eq!(options.dirs.prefix, PathBuf::from("/opt/leleka")); +} + +#[test] +fn other_commands() { + assert!(matches!(parse_as(false, &[]).unwrap(), Command::Help)); + assert!(matches!( + parse_as(false, &["profiles"]).unwrap(), + Command::Profiles(None) + )); + assert!(matches!( + parse_as(false, &["profiles", "show", "rtx5090-32g"]).unwrap(), + Command::Profiles(Some(_)) + )); + let Command::Run { config, kar_fd } = parse_as( + false, + &["run", "--config", "/s/leleka.json", "--kar-fd", "3"], + ) + .unwrap() else { + panic!() + }; + assert_eq!((config, kar_fd), (PathBuf::from("/s/leleka.json"), Some(3))); + assert!(parse_as(false, &["run"]).is_err()); + assert!(parse_as(false, &["frobnicate"]).is_err()); + assert!(matches!( + parse_as(false, &["exec-inherit", "--", "x"]).unwrap(), + Command::ExecInherit(_) + )); + assert!(matches!( + parse_as(false, &["seal-exec", "--file", "f", "--", "x"]).unwrap(), + Command::SealExec(_) + )); + assert!(matches!( + parse_as(false, &["seal-probe", "/x/y"]).unwrap(), + Command::SealProbe(_) + )); + assert!(parse_as(false, &["seal-probe"]).is_err()); +} diff --git a/crates/deploy/src/expert_profile.rs b/crates/deploy/src/expert_profile.rs index 7ac7d5be..073f3fef 100644 --- a/crates/deploy/src/expert_profile.rs +++ b/crates/deploy/src/expert_profile.rs @@ -429,491 +429,4 @@ pub fn start_environment( } #[cfg(test)] -mod tests { - use super::*; - use std::cell::RefCell; - - fn temp(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!( - "leleka-expert-profile-{}-{name}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir - } - - /// A small stand-in for the table; the real digest is pinned, tests pin the digest of this fixture instead. - const FIXTURE: &[u8] = b"STRP\x01\x00\x00\x00 a small fixture, not a routing table"; - - fn fixture_digest() -> String { - sha256_hex(FIXTURE) - } - - #[test] - fn the_pinned_numbers_are_consistent() { - assert_eq!(PINNED_SHA256.len(), 64); - assert_eq!(PINNED_BYTES, 24 + 4 * 24_576 + 4 * 48 * 512); - assert!(SOURCES.iter().all(|url| url.starts_with("https://"))); - assert!(SOURCES[0].contains(UPSTREAM_COMMIT) && SOURCES[1].contains(UPSTREAM_COMMIT)); - assert_eq!(short_digest(PINNED_SHA256), "8f59b4aa...388975baf"); - assert_eq!(crate::plan::EXPERT_PROFILE_SHA256, PINNED_SHA256); - } - - #[test] - fn a_file_is_absent_valid_or_wrong() { - let dir = temp("state"); - let path = dir.join("p.bin"); - assert_eq!(file_state(&path, &fixture_digest()), FileState::Absent); - std::fs::write(&path, FIXTURE).unwrap(); - assert_eq!(file_state(&path, &fixture_digest()), FileState::Valid); - assert!( - matches!(file_state(&path, PINNED_SHA256), FileState::WrongDigest { actual } if actual == fixture_digest()) - ); - std::fs::write(&path, vec![0u8; (MAX_BYTES + 5) as usize]).unwrap(); - assert!(matches!( - file_state(&path, PINNED_SHA256), - FileState::WrongDigest { .. } - )); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn the_embedded_table_is_the_pinned_upstream_file() { - assert_eq!(EMBEDDED.len() as u64, PINNED_BYTES); - assert_eq!(sha256_hex(EMBEDDED), PINNED_SHA256); - assert_eq!(&EMBEDDED[..4], b"STRP"); - assert!(embedded_for(PINNED_SHA256).is_some()); - assert!(embedded_for(&fixture_digest()).is_none()); - } - - #[test] - fn the_embedded_table_is_installed_offline_before_any_download() { - let dir = temp("embedded"); - let dest = dir.join("data").join("expert-profile.bin"); - let mut never = |_: &str, _: &Path| -> Result<(), String> { - panic!("offline: the embedded table must be used before any download") - }; - let request = Request { - dest: &dest, - expected: PINNED_SHA256, - local: None, - embedded: embedded_for(PINNED_SHA256), - sources: &SOURCES, - }; - assert_eq!( - provision(&request, &mut never).unwrap(), - Outcome::Installed { - origin: EMBEDDED_ORIGIN.into(), - moved_aside: None - } - ); - assert_eq!(file_state(&dest, PINNED_SHA256), FileState::Valid); - assert!(!with_suffix(&dest, ".part").exists()); - assert_eq!( - provision(&request, &mut never).unwrap(), - Outcome::AlreadyPresent - ); - // an explicit file wins over the embedded table - let other = dir.join("other.bin"); - std::fs::write(&other, EMBEDDED).unwrap(); - let second = dir.join("second").join("p.bin"); - let outcome = provision( - &Request { - dest: &second, - local: Some(&other), - ..request - }, - &mut never, - ) - .unwrap(); - assert!( - matches!(outcome, Outcome::Installed { origin, .. } if origin.ends_with("other.bin")) - ); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn an_embedded_table_that_fails_its_digest_falls_back_to_the_download() { - let dir = temp("embedded-bad"); - let dest = dir.join("expert-profile.bin"); - let digest = fixture_digest(); - let mut fetch = - |_: &str, part: &Path| std::fs::write(part, FIXTURE).map_err(|e| e.to_string()); - let request = Request { - dest: &dest, - expected: &digest, - local: None, - embedded: Some(b"corrupted copy"), - sources: &["https://one.test/p.bin"], - }; - assert_eq!( - provision(&request, &mut fetch).unwrap(), - Outcome::Installed { - origin: "https://one.test/p.bin".into(), - moved_aside: None - } - ); - // ... and without a source the failure names the embedded table - let _ = std::fs::remove_file(&dest); - let error = provision( - &Request { - sources: &[], - ..request - }, - &mut fetch, - ) - .unwrap_err(); - assert!( - error.contains("embedded") && error.contains("is not the expected"), - "{error}" - ); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn a_download_is_verified_then_installed_and_a_present_file_is_left_alone() { - let dir = temp("download"); - let dest = dir.join("data").join("expert-profile.bin"); - let calls = RefCell::new(Vec::new()); - let mut fetch = |url: &str, part: &Path| { - calls.borrow_mut().push(url.to_owned()); - std::fs::write(part, FIXTURE).map_err(|e| e.to_string()) - }; - let digest = fixture_digest(); - let request = Request { - dest: &dest, - expected: &digest, - local: None, - embedded: None, - sources: &["https://one.test/p.bin", "https://two.test/p.bin"], - }; - let outcome = provision(&request, &mut fetch).unwrap(); - assert_eq!( - outcome, - Outcome::Installed { - origin: "https://one.test/p.bin".into(), - moved_aside: None - } - ); - assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); - assert!( - !with_suffix(&dest, ".part").exists(), - "the staging file is gone" - ); - // Second run: nothing is fetched. - assert_eq!( - provision(&request, &mut fetch).unwrap(), - Outcome::AlreadyPresent - ); - assert_eq!(calls.borrow().len(), 1); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn a_digest_mismatch_fails_closed_and_installs_nothing() { - let dir = temp("mismatch"); - let dest = dir.join("expert-profile.bin"); - let mut fetch = |_: &str, part: &Path| { - std::fs::write(part, b"an error page, not the table").map_err(|e| e.to_string()) - }; - let digest = fixture_digest(); - let request = Request { - dest: &dest, - expected: &digest, - local: None, - embedded: None, - sources: &["https://one.test/p.bin", "https://two.test/p.bin"], - }; - let error = provision(&request, &mut fetch).unwrap_err(); - assert!( - error.contains("one.test") - && error.contains("two.test") - && error.contains("is not the expected"), - "{error}" - ); - assert!( - error.contains("--expert-profile-file") && error.contains("--no-expert-tier"), - "{error}" - ); - assert!(!dest.exists() && !with_suffix(&dest, ".part").exists()); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn the_next_source_is_tried_when_one_fails() { - let dir = temp("fallback"); - let dest = dir.join("expert-profile.bin"); - let mut fetch = |url: &str, part: &Path| { - if url.contains("down") { - Err("curl exited with 22".to_owned()) - } else { - std::fs::write(part, FIXTURE).map_err(|e| e.to_string()) - } - }; - let digest = fixture_digest(); - let request = Request { - dest: &dest, - expected: &digest, - local: None, - embedded: None, - sources: &["https://down.test/p.bin", "https://up.test/p.bin"], - }; - assert_eq!( - provision(&request, &mut fetch).unwrap(), - Outcome::Installed { - origin: "https://up.test/p.bin".into(), - moved_aside: None - } - ); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn a_local_file_is_installed_offline_and_a_wrong_one_is_refused() { - let dir = temp("local"); - let dest = dir.join("data").join("expert-profile.bin"); - let good = dir.join("good.bin"); - let bad = dir.join("bad.bin"); - std::fs::write(&good, FIXTURE).unwrap(); - std::fs::write(&bad, b"my own learned table").unwrap(); - let digest = fixture_digest(); - let mut never = |_: &str, _: &Path| -> Result<(), String> { - panic!("offline: no download may be attempted") - }; - let refused = provision( - &Request { - dest: &dest, - expected: &digest, - local: Some(&bad), - embedded: None, - sources: &["https://x.test/p"], - }, - &mut never, - ) - .unwrap_err(); - assert!( - refused.contains("only the pinned upstream table"), - "{refused}" - ); - assert!(!dest.exists()); - let outcome = provision( - &Request { - dest: &dest, - expected: &digest, - local: Some(&good), - embedded: None, - sources: &["https://x.test/p"], - }, - &mut never, - ) - .unwrap(); - assert!(matches!( - outcome, - Outcome::Installed { - moved_aside: None, - .. - } - )); - assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); - let missing = provision( - &Request { - dest: &dir.join("other.bin"), - expected: &digest, - local: Some(&dir.join("nope.bin")), - embedded: None, - sources: &[], - }, - &mut never, - ) - .unwrap_err(); - assert!(missing.contains("--expert-profile-file"), "{missing}"); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn a_wrong_file_in_the_way_is_moved_aside_never_deleted() { - let dir = temp("aside"); - let dest = dir.join("expert-profile.bin"); - std::fs::write(&dest, b"learned by hand").unwrap(); - let mut fetch = - |_: &str, part: &Path| std::fs::write(part, FIXTURE).map_err(|e| e.to_string()); - let digest = fixture_digest(); - let outcome = provision( - &Request { - dest: &dest, - expected: &digest, - local: None, - embedded: None, - sources: &["https://one.test/p.bin"], - }, - &mut fetch, - ) - .unwrap(); - let Outcome::Installed { - moved_aside: Some(aside), - .. - } = outcome - else { - panic!("{outcome:?}") - }; - assert_eq!(std::fs::read(&aside).unwrap(), b"learned by hand"); - assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn a_custom_digest_without_sources_asks_for_the_file() { - let dir = temp("custom"); - let mut fetch = |_: &str, _: &Path| -> Result<(), String> { panic!("no sources") }; - let error = provision( - &Request { - dest: &dir.join("p.bin"), - expected: &fixture_digest(), - local: None, - embedded: None, - sources: &[], - }, - &mut fetch, - ) - .unwrap_err(); - assert!(error.contains("no download source"), "{error}"); - let _ = std::fs::remove_dir_all(dir); - } - - fn config(assets: &Path, expert_tier: bool, with_env: bool) -> RunConfig { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile.expert_profile_sha256 = Some(fixture_digest()); - let dirs = crate::layout::Dirs { - prefix: assets.join("p"), - state: assets.join("s"), - assets: assets.to_path_buf(), - }; - let ports = crate::config::Ports { - api: "127.0.0.1:8081".into(), - engine: "127.0.0.1:18766".into(), - daemon: "127.0.0.1:18080".into(), - }; - let mut env = BTreeMap::new(); - if with_env { - env.insert( - PROFILE_ENV.to_owned(), - assets.join("data/expert-profile.bin").display().to_string(), - ); - env.insert(SLOTS_ENV.to_owned(), "auto".to_owned()); - } - let mut config = RunConfig::new(&dirs, ports, 0, profile, env); - config.expert_tier = expert_tier; - config - } - - #[test] - fn the_report_says_on_with_the_digest_or_off_with_the_reason() { - let dir = temp("report"); - let path = dir.join("data").join("expert-profile.bin"); - // missing - let report = tier_report(&config(&dir, true, true), &dir); - assert!( - !report.on && !report.opted_out && report.reason.contains("is missing"), - "{report:?}" - ); - assert!( - report.line().starts_with("WARNING expert tier OFF"), - "{}", - report.line() - ); - // present and valid - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(&path, FIXTURE).unwrap(); - let report = tier_report(&config(&dir, true, true), &dir); - assert!(report.on, "{report:?}"); - assert!( - report.line().starts_with("expert tier ON") - && report.line().contains(&short_digest(&fixture_digest())), - "{}", - report.line() - ); - // valid file but a configuration written without the switches - let report = tier_report(&config(&dir, true, false), &dir); - assert!( - !report.on && report.reason.contains("rerun `leleka up`"), - "{report:?}" - ); - // explicit opt-out - let report = tier_report(&config(&dir, false, false), &dir); - assert!( - !report.on && report.opted_out && report.reason.contains("--no-expert-tier"), - "{report:?}" - ); - // a replaced file - std::fs::write(&path, b"something else").unwrap(); - let report = tier_report(&config(&dir, true, true), &dir); - assert!( - !report.on && report.reason.contains("not the pinned") && report.sha256.is_some(), - "{report:?}" - ); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn a_digest_observed_elsewhere_gives_the_same_report() { - let dir = temp("bridge"); - let cfg = config(&dir, true, true); - let shown = "/home/me/leleka/data/expert-profile.bin"; - let digest = fixture_digest(); - assert!( - tier_report_with(&cfg, shown, || FileState::from_digest( - Some(&digest), - &digest - )) - .on - ); - let missing = tier_report_with(&cfg, shown, || FileState::from_digest(None, &digest)); - assert!(!missing.on && missing.reason.contains(shown), "{missing:?}"); - let wrong = tier_report_with(&cfg, shown, || { - FileState::from_digest(Some("00ff"), &digest) - }); - assert!(!wrong.on && wrong.sha256.as_deref() == Some("00ff")); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn a_profile_without_a_tier_reports_off_and_the_engine_never_gets_a_bad_table() { - let dir = temp("env"); - let mut no_tier = config(&dir, true, true); - no_tier.profile.expert_profile = None; - assert!(!tier_report(&no_tier, &dir).on); - // valid file: the switches pass through - let path = dir.join("data").join("expert-profile.bin"); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(&path, FIXTURE).unwrap(); - let cfg = config(&dir, true, true); - let (env, report) = start_environment(&cfg, &dir); - assert!(env.contains_key(PROFILE_ENV) && report.on); - // the file changed since `up`: the switches are dropped - std::fs::write(&path, b"changed").unwrap(); - let (env, report) = start_environment(&cfg, &dir); - assert!(!report.on && !env.contains_key(PROFILE_ENV) && !env.contains_key(SLOTS_ENV)); - let _ = std::fs::remove_dir_all(dir); - } - - /// Live check of the pinned sources (needs network and curl): `cargo test -p leleka-deploy -- --ignored pinned_sources`. - #[test] - #[ignore = "network"] - fn pinned_sources_serve_the_pinned_table() { - let dir = temp("live"); - for url in SOURCES.iter().take(2) { - let out = dir.join("p.bin"); - let status = std::process::Command::new("curl") - .args(["-fsSL", "--proto", "=https", "--max-time", "60", "-o"]) - .arg(&out) - .arg(url) - .status() - .unwrap(); - assert!(status.success(), "{url}"); - assert_eq!(file_state(&out, PINNED_SHA256), FileState::Valid, "{url}"); - assert_eq!(std::fs::metadata(&out).unwrap().len(), PINNED_BYTES); - } - let _ = std::fs::remove_dir_all(dir); - } -} +mod tests; diff --git a/crates/deploy/src/expert_profile/tests.rs b/crates/deploy/src/expert_profile/tests.rs new file mode 100644 index 00000000..f054d06e --- /dev/null +++ b/crates/deploy/src/expert_profile/tests.rs @@ -0,0 +1,488 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use std::cell::RefCell; + +fn temp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "leleka-expert-profile-{}-{name}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A small stand-in for the table; the real digest is pinned, tests pin the digest of this fixture instead. +const FIXTURE: &[u8] = b"STRP\x01\x00\x00\x00 a small fixture, not a routing table"; + +fn fixture_digest() -> String { + sha256_hex(FIXTURE) +} + +#[test] +fn the_pinned_numbers_are_consistent() { + assert_eq!(PINNED_SHA256.len(), 64); + assert_eq!(PINNED_BYTES, 24 + 4 * 24_576 + 4 * 48 * 512); + assert!(SOURCES.iter().all(|url| url.starts_with("https://"))); + assert!(SOURCES[0].contains(UPSTREAM_COMMIT) && SOURCES[1].contains(UPSTREAM_COMMIT)); + assert_eq!(short_digest(PINNED_SHA256), "8f59b4aa...388975baf"); + assert_eq!(crate::plan::EXPERT_PROFILE_SHA256, PINNED_SHA256); +} + +#[test] +fn a_file_is_absent_valid_or_wrong() { + let dir = temp("state"); + let path = dir.join("p.bin"); + assert_eq!(file_state(&path, &fixture_digest()), FileState::Absent); + std::fs::write(&path, FIXTURE).unwrap(); + assert_eq!(file_state(&path, &fixture_digest()), FileState::Valid); + assert!( + matches!(file_state(&path, PINNED_SHA256), FileState::WrongDigest { actual } if actual == fixture_digest()) + ); + std::fs::write(&path, vec![0u8; (MAX_BYTES + 5) as usize]).unwrap(); + assert!(matches!( + file_state(&path, PINNED_SHA256), + FileState::WrongDigest { .. } + )); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_embedded_table_is_the_pinned_upstream_file() { + assert_eq!(EMBEDDED.len() as u64, PINNED_BYTES); + assert_eq!(sha256_hex(EMBEDDED), PINNED_SHA256); + assert_eq!(&EMBEDDED[..4], b"STRP"); + assert!(embedded_for(PINNED_SHA256).is_some()); + assert!(embedded_for(&fixture_digest()).is_none()); +} + +#[test] +fn the_embedded_table_is_installed_offline_before_any_download() { + let dir = temp("embedded"); + let dest = dir.join("data").join("expert-profile.bin"); + let mut never = |_: &str, _: &Path| -> Result<(), String> { + panic!("offline: the embedded table must be used before any download") + }; + let request = Request { + dest: &dest, + expected: PINNED_SHA256, + local: None, + embedded: embedded_for(PINNED_SHA256), + sources: &SOURCES, + }; + assert_eq!( + provision(&request, &mut never).unwrap(), + Outcome::Installed { + origin: EMBEDDED_ORIGIN.into(), + moved_aside: None + } + ); + assert_eq!(file_state(&dest, PINNED_SHA256), FileState::Valid); + assert!(!with_suffix(&dest, ".part").exists()); + assert_eq!( + provision(&request, &mut never).unwrap(), + Outcome::AlreadyPresent + ); + // an explicit file wins over the embedded table + let other = dir.join("other.bin"); + std::fs::write(&other, EMBEDDED).unwrap(); + let second = dir.join("second").join("p.bin"); + let outcome = provision( + &Request { + dest: &second, + local: Some(&other), + ..request + }, + &mut never, + ) + .unwrap(); + assert!( + matches!(outcome, Outcome::Installed { origin, .. } if origin.ends_with("other.bin")) + ); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_embedded_table_that_fails_its_digest_falls_back_to_the_download() { + let dir = temp("embedded-bad"); + let dest = dir.join("expert-profile.bin"); + let digest = fixture_digest(); + let mut fetch = + |_: &str, part: &Path| std::fs::write(part, FIXTURE).map_err(|e| e.to_string()); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + embedded: Some(b"corrupted copy"), + sources: &["https://one.test/p.bin"], + }; + assert_eq!( + provision(&request, &mut fetch).unwrap(), + Outcome::Installed { + origin: "https://one.test/p.bin".into(), + moved_aside: None + } + ); + // ... and without a source the failure names the embedded table + let _ = std::fs::remove_file(&dest); + let error = provision( + &Request { + sources: &[], + ..request + }, + &mut fetch, + ) + .unwrap_err(); + assert!( + error.contains("embedded") && error.contains("is not the expected"), + "{error}" + ); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_download_is_verified_then_installed_and_a_present_file_is_left_alone() { + let dir = temp("download"); + let dest = dir.join("data").join("expert-profile.bin"); + let calls = RefCell::new(Vec::new()); + let mut fetch = |url: &str, part: &Path| { + calls.borrow_mut().push(url.to_owned()); + std::fs::write(part, FIXTURE).map_err(|e| e.to_string()) + }; + let digest = fixture_digest(); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + embedded: None, + sources: &["https://one.test/p.bin", "https://two.test/p.bin"], + }; + let outcome = provision(&request, &mut fetch).unwrap(); + assert_eq!( + outcome, + Outcome::Installed { + origin: "https://one.test/p.bin".into(), + moved_aside: None + } + ); + assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); + assert!( + !with_suffix(&dest, ".part").exists(), + "the staging file is gone" + ); + // Second run: nothing is fetched. + assert_eq!( + provision(&request, &mut fetch).unwrap(), + Outcome::AlreadyPresent + ); + assert_eq!(calls.borrow().len(), 1); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_digest_mismatch_fails_closed_and_installs_nothing() { + let dir = temp("mismatch"); + let dest = dir.join("expert-profile.bin"); + let mut fetch = |_: &str, part: &Path| { + std::fs::write(part, b"an error page, not the table").map_err(|e| e.to_string()) + }; + let digest = fixture_digest(); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + embedded: None, + sources: &["https://one.test/p.bin", "https://two.test/p.bin"], + }; + let error = provision(&request, &mut fetch).unwrap_err(); + assert!( + error.contains("one.test") + && error.contains("two.test") + && error.contains("is not the expected"), + "{error}" + ); + assert!( + error.contains("--expert-profile-file") && error.contains("--no-expert-tier"), + "{error}" + ); + assert!(!dest.exists() && !with_suffix(&dest, ".part").exists()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_next_source_is_tried_when_one_fails() { + let dir = temp("fallback"); + let dest = dir.join("expert-profile.bin"); + let mut fetch = |url: &str, part: &Path| { + if url.contains("down") { + Err("curl exited with 22".to_owned()) + } else { + std::fs::write(part, FIXTURE).map_err(|e| e.to_string()) + } + }; + let digest = fixture_digest(); + let request = Request { + dest: &dest, + expected: &digest, + local: None, + embedded: None, + sources: &["https://down.test/p.bin", "https://up.test/p.bin"], + }; + assert_eq!( + provision(&request, &mut fetch).unwrap(), + Outcome::Installed { + origin: "https://up.test/p.bin".into(), + moved_aside: None + } + ); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_local_file_is_installed_offline_and_a_wrong_one_is_refused() { + let dir = temp("local"); + let dest = dir.join("data").join("expert-profile.bin"); + let good = dir.join("good.bin"); + let bad = dir.join("bad.bin"); + std::fs::write(&good, FIXTURE).unwrap(); + std::fs::write(&bad, b"my own learned table").unwrap(); + let digest = fixture_digest(); + let mut never = |_: &str, _: &Path| -> Result<(), String> { + panic!("offline: no download may be attempted") + }; + let refused = provision( + &Request { + dest: &dest, + expected: &digest, + local: Some(&bad), + embedded: None, + sources: &["https://x.test/p"], + }, + &mut never, + ) + .unwrap_err(); + assert!( + refused.contains("only the pinned upstream table"), + "{refused}" + ); + assert!(!dest.exists()); + let outcome = provision( + &Request { + dest: &dest, + expected: &digest, + local: Some(&good), + embedded: None, + sources: &["https://x.test/p"], + }, + &mut never, + ) + .unwrap(); + assert!(matches!( + outcome, + Outcome::Installed { + moved_aside: None, + .. + } + )); + assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); + let missing = provision( + &Request { + dest: &dir.join("other.bin"), + expected: &digest, + local: Some(&dir.join("nope.bin")), + embedded: None, + sources: &[], + }, + &mut never, + ) + .unwrap_err(); + assert!(missing.contains("--expert-profile-file"), "{missing}"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_wrong_file_in_the_way_is_moved_aside_never_deleted() { + let dir = temp("aside"); + let dest = dir.join("expert-profile.bin"); + std::fs::write(&dest, b"learned by hand").unwrap(); + let mut fetch = + |_: &str, part: &Path| std::fs::write(part, FIXTURE).map_err(|e| e.to_string()); + let digest = fixture_digest(); + let outcome = provision( + &Request { + dest: &dest, + expected: &digest, + local: None, + embedded: None, + sources: &["https://one.test/p.bin"], + }, + &mut fetch, + ) + .unwrap(); + let Outcome::Installed { + moved_aside: Some(aside), + .. + } = outcome + else { + panic!("{outcome:?}") + }; + assert_eq!(std::fs::read(&aside).unwrap(), b"learned by hand"); + assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_custom_digest_without_sources_asks_for_the_file() { + let dir = temp("custom"); + let mut fetch = |_: &str, _: &Path| -> Result<(), String> { panic!("no sources") }; + let error = provision( + &Request { + dest: &dir.join("p.bin"), + expected: &fixture_digest(), + local: None, + embedded: None, + sources: &[], + }, + &mut fetch, + ) + .unwrap_err(); + assert!(error.contains("no download source"), "{error}"); + let _ = std::fs::remove_dir_all(dir); +} + +fn config(assets: &Path, expert_tier: bool, with_env: bool) -> RunConfig { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.expert_profile_sha256 = Some(fixture_digest()); + let dirs = crate::layout::Dirs { + prefix: assets.join("p"), + state: assets.join("s"), + assets: assets.to_path_buf(), + }; + let ports = crate::config::Ports { + api: "127.0.0.1:8081".into(), + engine: "127.0.0.1:18766".into(), + daemon: "127.0.0.1:18080".into(), + }; + let mut env = BTreeMap::new(); + if with_env { + env.insert( + PROFILE_ENV.to_owned(), + assets.join("data/expert-profile.bin").display().to_string(), + ); + env.insert(SLOTS_ENV.to_owned(), "auto".to_owned()); + } + let mut config = RunConfig::new(&dirs, ports, 0, profile, env); + config.expert_tier = expert_tier; + config +} + +#[test] +fn the_report_says_on_with_the_digest_or_off_with_the_reason() { + let dir = temp("report"); + let path = dir.join("data").join("expert-profile.bin"); + // missing + let report = tier_report(&config(&dir, true, true), &dir); + assert!( + !report.on && !report.opted_out && report.reason.contains("is missing"), + "{report:?}" + ); + assert!( + report.line().starts_with("WARNING expert tier OFF"), + "{}", + report.line() + ); + // present and valid + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, FIXTURE).unwrap(); + let report = tier_report(&config(&dir, true, true), &dir); + assert!(report.on, "{report:?}"); + assert!( + report.line().starts_with("expert tier ON") + && report.line().contains(&short_digest(&fixture_digest())), + "{}", + report.line() + ); + // valid file but a configuration written without the switches + let report = tier_report(&config(&dir, true, false), &dir); + assert!( + !report.on && report.reason.contains("rerun `leleka up`"), + "{report:?}" + ); + // explicit opt-out + let report = tier_report(&config(&dir, false, false), &dir); + assert!( + !report.on && report.opted_out && report.reason.contains("--no-expert-tier"), + "{report:?}" + ); + // a replaced file + std::fs::write(&path, b"something else").unwrap(); + let report = tier_report(&config(&dir, true, true), &dir); + assert!( + !report.on && report.reason.contains("not the pinned") && report.sha256.is_some(), + "{report:?}" + ); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_digest_observed_elsewhere_gives_the_same_report() { + let dir = temp("bridge"); + let cfg = config(&dir, true, true); + let shown = "/home/me/leleka/data/expert-profile.bin"; + let digest = fixture_digest(); + assert!( + tier_report_with(&cfg, shown, || FileState::from_digest( + Some(&digest), + &digest + )) + .on + ); + let missing = tier_report_with(&cfg, shown, || FileState::from_digest(None, &digest)); + assert!(!missing.on && missing.reason.contains(shown), "{missing:?}"); + let wrong = tier_report_with(&cfg, shown, || { + FileState::from_digest(Some("00ff"), &digest) + }); + assert!(!wrong.on && wrong.sha256.as_deref() == Some("00ff")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_profile_without_a_tier_reports_off_and_the_engine_never_gets_a_bad_table() { + let dir = temp("env"); + let mut no_tier = config(&dir, true, true); + no_tier.profile.expert_profile = None; + assert!(!tier_report(&no_tier, &dir).on); + // valid file: the switches pass through + let path = dir.join("data").join("expert-profile.bin"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, FIXTURE).unwrap(); + let cfg = config(&dir, true, true); + let (env, report) = start_environment(&cfg, &dir); + assert!(env.contains_key(PROFILE_ENV) && report.on); + // the file changed since `up`: the switches are dropped + std::fs::write(&path, b"changed").unwrap(); + let (env, report) = start_environment(&cfg, &dir); + assert!(!report.on && !env.contains_key(PROFILE_ENV) && !env.contains_key(SLOTS_ENV)); + let _ = std::fs::remove_dir_all(dir); +} + +/// Live check of the pinned sources (needs network and curl): `cargo test -p leleka-deploy -- --ignored pinned_sources`. +#[test] +#[ignore = "network"] +fn pinned_sources_serve_the_pinned_table() { + let dir = temp("live"); + for url in SOURCES.iter().take(2) { + let out = dir.join("p.bin"); + let status = std::process::Command::new("curl") + .args(["-fsSL", "--proto", "=https", "--max-time", "60", "-o"]) + .arg(&out) + .arg(url) + .status() + .unwrap(); + assert!(status.success(), "{url}"); + assert_eq!(file_state(&out, PINNED_SHA256), FileState::Valid, "{url}"); + assert_eq!(std::fs::metadata(&out).unwrap().len(), PINNED_BYTES); + } + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/deploy/src/facts.rs b/crates/deploy/src/facts.rs index 9ed2edb4..f852c55d 100644 --- a/crates/deploy/src/facts.rs +++ b/crates/deploy/src/facts.rs @@ -603,99 +603,4 @@ fn lab_holder_running() -> bool { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn nvidia_smi_csv_for_server_and_laptop() { - let server = - parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, 12.0\n"); - assert_eq!(server.len(), 1); - assert_eq!(server[0].sm, Some(120)); - assert_eq!(server[0].driver_major(), Some(595)); - assert_eq!(server[0].vram_free_mib, 32105); - let laptop = - parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234, 8.6\n"); - assert_eq!(laptop[0].sm, Some(86)); - assert_eq!(laptop[0].driver_major(), Some(617)); - } - - #[test] - fn missing_compute_capability_falls_back_to_the_name_table() { - let gpus = - parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234\n"); - assert_eq!(gpus[0].sm, Some(86)); - let gpus = parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, [N/A]\n"); - assert_eq!(gpus[0].sm, Some(120)); - let gpus = parse_nvidia_smi("0, Mystery Board, 595.1, 8000, 8000, [N/A]\n"); - assert_eq!(gpus[0].sm, None); - assert!(parse_nvidia_smi("garbage\n\n").is_empty()); - } - - #[test] - fn meminfo_bytes() { - let memory = parse_meminfo( - "MemTotal: 24447308 kB\nMemFree: 1 kB\nMemAvailable: 22000000 kB\nSwapTotal: 2097152 kB\n", - ); - assert_eq!(memory.total, 24_447_308 * 1024); - assert_eq!(memory.available, 22_000_000 * 1024); - assert_eq!(memory.swap_total, 2_097_152 * 1024); - assert_eq!(parse_meminfo("nothing"), Memory::default()); - } - - #[test] - fn wsl_and_cgroup_detection() { - assert!(is_wsl( - "Linux version 5.15.167.4-microsoft-standard-WSL2 (root@x) (gcc)" - )); - assert!(!is_wsl( - "Linux version 7.0.0-38-generic (buildd@lcy02) (gcc)" - )); - assert_eq!(parse_cgroup_max("max\n"), None); - assert_eq!(parse_cgroup_max("68719476736\n"), Some(68_719_476_736)); - } - - #[test] - fn filesystem_type_uses_the_longest_mount_prefix() { - let mounts = - "/dev/sdc / ext4 rw 0 0\nC:\\134 /mnt/c 9p rw 0 0\n/dev/sdd /mnt/c/data ext4 rw 0 0\n"; - assert_eq!( - fs_type_for(mounts, Path::new("/mnt/c/Users/x")).as_deref(), - Some("9p") - ); - assert_eq!( - fs_type_for(mounts, Path::new("/mnt/c/data/models")).as_deref(), - Some("ext4") - ); - assert_eq!( - fs_type_for(mounts, Path::new("/home/x")).as_deref(), - Some("ext4") - ); - assert!(is_slow_foreign_fs("9p") && !is_slow_foreign_fs("ext4")); - } - - #[test] - fn library_lookup_prefers_directories_then_ldconfig() { - let ldconfig = "\tlibcublas.so.12 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libcublas.so.12\n\tlibcublasLt.so.13 (libc6,x86-64) => /usr/lib/libcublasLt.so.13\n"; - assert_eq!( - find_library("libcublas.so.12", &[], ldconfig), - Some(PathBuf::from("/usr/lib/x86_64-linux-gnu/libcublas.so.12")) - ); - assert_eq!(find_library("libcublasLt.so.12", &[], ldconfig), None); - } - - #[test] - fn env_file_parser_handles_comments_and_quotes() { - let env = parse_env_file( - "# c\nA=1\n B = \"two words\" \nbad key=3\nexport X=1\nLD_LIBRARY_PATH=/a:/b\n", - ); - assert_eq!(env.get("A").map(String::as_str), Some("1")); - assert_eq!(env.get("B").map(String::as_str), Some("two words")); - assert_eq!( - env.get("LD_LIBRARY_PATH").map(String::as_str), - Some("/a:/b") - ); - assert!(!env.contains_key("bad key")); - assert!(!env.contains_key("export X")); - } -} +mod tests; diff --git a/crates/deploy/src/facts/tests.rs b/crates/deploy/src/facts/tests.rs new file mode 100644 index 00000000..d9676cd5 --- /dev/null +++ b/crates/deploy/src/facts/tests.rs @@ -0,0 +1,96 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn nvidia_smi_csv_for_server_and_laptop() { + let server = + parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, 12.0\n"); + assert_eq!(server.len(), 1); + assert_eq!(server[0].sm, Some(120)); + assert_eq!(server[0].driver_major(), Some(595)); + assert_eq!(server[0].vram_free_mib, 32105); + let laptop = + parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234, 8.6\n"); + assert_eq!(laptop[0].sm, Some(86)); + assert_eq!(laptop[0].driver_major(), Some(617)); +} + +#[test] +fn missing_compute_capability_falls_back_to_the_name_table() { + let gpus = + parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234\n"); + assert_eq!(gpus[0].sm, Some(86)); + let gpus = parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, [N/A]\n"); + assert_eq!(gpus[0].sm, Some(120)); + let gpus = parse_nvidia_smi("0, Mystery Board, 595.1, 8000, 8000, [N/A]\n"); + assert_eq!(gpus[0].sm, None); + assert!(parse_nvidia_smi("garbage\n\n").is_empty()); +} + +#[test] +fn meminfo_bytes() { + let memory = parse_meminfo( + "MemTotal: 24447308 kB\nMemFree: 1 kB\nMemAvailable: 22000000 kB\nSwapTotal: 2097152 kB\n", + ); + assert_eq!(memory.total, 24_447_308 * 1024); + assert_eq!(memory.available, 22_000_000 * 1024); + assert_eq!(memory.swap_total, 2_097_152 * 1024); + assert_eq!(parse_meminfo("nothing"), Memory::default()); +} + +#[test] +fn wsl_and_cgroup_detection() { + assert!(is_wsl( + "Linux version 5.15.167.4-microsoft-standard-WSL2 (root@x) (gcc)" + )); + assert!(!is_wsl( + "Linux version 7.0.0-38-generic (buildd@lcy02) (gcc)" + )); + assert_eq!(parse_cgroup_max("max\n"), None); + assert_eq!(parse_cgroup_max("68719476736\n"), Some(68_719_476_736)); +} + +#[test] +fn filesystem_type_uses_the_longest_mount_prefix() { + let mounts = + "/dev/sdc / ext4 rw 0 0\nC:\\134 /mnt/c 9p rw 0 0\n/dev/sdd /mnt/c/data ext4 rw 0 0\n"; + assert_eq!( + fs_type_for(mounts, Path::new("/mnt/c/Users/x")).as_deref(), + Some("9p") + ); + assert_eq!( + fs_type_for(mounts, Path::new("/mnt/c/data/models")).as_deref(), + Some("ext4") + ); + assert_eq!( + fs_type_for(mounts, Path::new("/home/x")).as_deref(), + Some("ext4") + ); + assert!(is_slow_foreign_fs("9p") && !is_slow_foreign_fs("ext4")); +} + +#[test] +fn library_lookup_prefers_directories_then_ldconfig() { + let ldconfig = "\tlibcublas.so.12 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libcublas.so.12\n\tlibcublasLt.so.13 (libc6,x86-64) => /usr/lib/libcublasLt.so.13\n"; + assert_eq!( + find_library("libcublas.so.12", &[], ldconfig), + Some(PathBuf::from("/usr/lib/x86_64-linux-gnu/libcublas.so.12")) + ); + assert_eq!(find_library("libcublasLt.so.12", &[], ldconfig), None); +} + +#[test] +fn env_file_parser_handles_comments_and_quotes() { + let env = parse_env_file( + "# c\nA=1\n B = \"two words\" \nbad key=3\nexport X=1\nLD_LIBRARY_PATH=/a:/b\n", + ); + assert_eq!(env.get("A").map(String::as_str), Some("1")); + assert_eq!(env.get("B").map(String::as_str), Some("two words")); + assert_eq!( + env.get("LD_LIBRARY_PATH").map(String::as_str), + Some("/a:/b") + ); + assert!(!env.contains_key("bad key")); + assert!(!env.contains_key("export X")); +} diff --git a/crates/deploy/src/logview.rs b/crates/deploy/src/logview.rs index def92171..a7af9f67 100644 --- a/crates/deploy/src/logview.rs +++ b/crates/deploy/src/logview.rs @@ -983,352 +983,4 @@ fn write_report(path: &Path, text: &str) -> std::io::Result<()> { } #[cfg(test)] -mod tests { - use super::*; - - fn api_line(rid: &str, ts: &str, fin: &str, ttft: u64, tps: f64) -> String { - format!( - "{{\"ts\":\"{ts}\",\"lvl\":\"info\",\"comp\":\"api\",\"ev\":\"request\",\"rid\":\"{rid}\",\"sid\":\"s-1\",\"ep\":\"responses\",\"fin\":\"{fin}\",\"ptok\":1000,\"ctok\":900,\"otok\":50,\"ttft_ms\":{ttft},\"dec_tps\":{tps},\"ms\":5000,\"restart\":false,\"err\":\"none\"}}" - ) - } - - fn scratch(name: &str) -> PathBuf { - let dir = - std::env::temp_dir().join(format!("leleka-logview-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn json_lines_old_supervisor_lines_and_free_text_all_parse() { - let e = parse_line( - &api_line("req-1", "2026-11-02T10:00:00.250Z", "stop", 800, 70.5), - "requests", - ); - assert_eq!( - (e.comp.as_str(), e.ev.as_str(), e.level), - ("api", "request", Level::Info) - ); - assert_eq!(e.fields["rid"], "req-1"); - assert!(e.ts_ms.is_some() && !e.fields.contains_key("ts")); - let old = parse_line( - "2026-11-02T10:00:00Z leleka: engine exited (signal 9); the API reports not-ready", - "leleka", - ); - assert_eq!((old.level, old.ts_ms.is_some()), (Level::Warn, true)); - assert_eq!( - old.fields["msg"], - "engine exited (signal 9); the API reports not-ready" - ); - let text = parse_line("loading 4096 experts", "engine"); - assert_eq!( - (text.ts_ms, text.comp.as_str(), text.level), - (None, "engine", Level::Info) - ); - assert_eq!( - parse_line("thread 'main' panicked at x.rs:1", "engine").level, - Level::Error - ); - } - - #[test] - fn rotated_generations_are_read_oldest_first_and_filters_apply() { - let dir = scratch("gens"); - let name = |s: &str| dir.join(s); - std::fs::write( - name("api.log.2"), - format!( - "{}\n", - api_line("req-a", "2026-11-02T09:00:00.000Z", "stop", 1, 1.0) - ), - ) - .unwrap(); - std::fs::write( - name("api.log.1"), - format!( - "{}\n", - api_line("req-b", "2026-11-02T09:30:00.000Z", "length", 2, 2.0) - ), - ) - .unwrap(); - std::fs::write( - name("api.log"), - format!( - "{}\n{{\"ts\":\"2026-11-02T10:05:00.000Z\",\"lvl\":\"warn\",\"comp\":\"api\",\"ev\":\"engine_lost\",\"reason\":\"gone\"}}\nnot json at all\n", - api_line("req-c", "2026-11-02T10:00:00.000Z", "error", 3, 3.0) - ), - ) - .unwrap(); - let all = collect( - &dir, - &Filter { - tail: 100, - ..Filter::default() - }, - ); - let ids: Vec<_> = all - .iter() - .filter_map(|e| e.fields.get("rid").and_then(Value::as_str)) - .collect(); - assert_eq!(ids, ["req-a", "req-b", "req-c"]); - assert_eq!( - all.len(), - 5, - "the free-text line is kept, next to its neighbours in time" - ); - let warn = collect( - &dir, - &Filter { - min_level: Level::Warn, - tail: 100, - ..Filter::default() - }, - ); - assert!( - warn.iter().all(|e| e.level >= Level::Warn) - && warn.iter().any(|e| e.ev == "engine_lost") - ); - let since = parse_utc_ms("2026-11-02T09:45:00Z").unwrap(); - let recent = collect( - &dir, - &Filter { - since_ms: Some(since), - tail: 100, - ..Filter::default() - }, - ); - assert!( - recent.iter().all(|e| e.ts_ms.unwrap() >= since) && recent.len() == 3, - "{recent:?}" - ); - let tail = collect( - &dir, - &Filter { - tail: 2, - ..Filter::default() - }, - ); - assert_eq!(tail.len(), 2); - let by_id = collect( - &dir, - &Filter { - request: Some("REQ-b".into()), - tail: 100, - ..Filter::default() - }, - ); - assert_eq!(by_id.len(), 1); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn the_api_record_and_the_engine_line_of_a_request_join_by_id() { - let engine = "{\"ts\":\"2026-11-02T10:00:00.100Z\",\"lvl\":\"info\",\"comp\":\"engine\",\"ev\":\"request\",\"rid\":\"req-1\",\"rounds\":10,\"tok_per_round\":3.2,\"tier_vram_pct\":91.5}"; - let entries = vec![ - parse_line( - &api_line("req-1", "2026-11-02T10:00:01.000Z", "stop", 800, 70.0), - "requests", - ), - parse_line(engine, "engine"), - parse_line( - &api_line("req-2", "2026-11-02T10:00:02.000Z", "stop", 900, 71.0), - "requests", - ), - ]; - let joined = join_requests(&entries); - assert_eq!(joined.len(), 2); - assert_eq!(joined[0]["eng_rounds"], 10); - assert_eq!(joined[0]["eng_tok_per_round"], 3.2); - assert!(joined[1].get("eng_rounds").is_none()); - assert_eq!(joined[0]["ts"], "2026-11-02T10:00:01.000Z"); - } - - #[test] - fn the_summary_has_percentiles_outcomes_and_the_cache_ratio() { - let records: Vec = (1..=10) - .map(|i| json!({"fin": if i == 10 { "error" } else { "stop" }, "err": if i == 10 { "stall" } else { "none" }, "ptok": 1000, "ctok": 900, "ttft_ms": i * 100, "dec_tps": 60.0, "restart": i == 10})) - .collect(); - let s = summarize(&records); - assert_eq!(s["count"], 10); - assert_eq!(s["outcomes"]["stop"], 9); - assert_eq!(s["errors"]["stall"], 1); - assert_eq!(s["during_engine_restart"], 1); - assert_eq!(s["cache_hit_ratio"], 0.9); - assert_eq!(s["ttft_ms"]["p50"], 600.0); - assert_eq!(s["ttft_ms"]["max"], 1000.0); - assert_eq!(summarize(&[])["count"], 0); - } - - #[test] - fn the_display_scrubs_a_credential_that_an_older_writer_left_in_a_line() { - leleka_obs::register_secret("tok-display-secret-0123456789abcdef"); - let entry = parse_line( - "{\"ts\":\"2026-11-02T10:00:00.000Z\",\"lvl\":\"warn\",\"comp\":\"engine\",\"ev\":\"msg\",\"msg\":\"reply said tok-display-secret-0123456789abcdef\"}", - "engine", - ); - let shown = redact::scrub(&render_entry(&entry)).into_owned(); - assert!(!shown.contains("tok-display-secret"), "{shown}"); - assert!(shown.contains("WARN") && shown.contains("engine")); - } - - #[test] - fn since_takes_durations_and_times() { - let now = parse_utc_ms("2026-11-02T12:00:00Z").unwrap(); - assert_eq!( - parse_since("30m", now).unwrap(), - parse_utc_ms("2026-11-02T11:30:00Z").unwrap() - ); - assert_eq!( - parse_since("2026-11-02T08:00:00Z", now).unwrap(), - parse_utc_ms("2026-11-02T08:00:00Z").unwrap() - ); - assert!(parse_since("yesterday", now).is_err()); - assert!( - filter_from( - &LogsArgs { - request: Some("abc".into()), - ..Default::default() - }, - now - ) - .is_err() - ); - assert!( - filter_from( - &LogsArgs { - level: Some("loud".into()), - ..Default::default() - }, - now - ) - .is_err() - ); - } - - fn inputs_with_secrets() -> ReportInputs { - let leaked_warning = parse_line( - "{\"ts\":\"2026-11-02T10:05:00.000Z\",\"lvl\":\"warn\",\"comp\":\"api\",\"ev\":\"msg\",\"msg\":\"upstream said Authorization: Bearer abcdef0123456789abcdef0123456789 and the key sk-report-secret-key-0123456789\"}", - "api", - ); - ReportInputs { - now_ms: parse_utc_ms("2026-11-02T10:10:00Z").unwrap(), - version: "leleka 0.1.0\ncommit abc (clean)".into(), - config: Some( - json!({"profile": "workstation", "assets_hint": "/home/para/work/leleka/models", "prompt": "my private prompt text", "api_key": "sk-report-secret-key-0123456789"}), - ), - expert_tier: Some(json!({"on": true, "sha256": "8f59b4aa", "reason": ""})), - host: json!({"os": "linux", "gpus": [{"name": "NVIDIA GeForce RTX 5090"}]}), - service: Some(json!({"phase": "ready", "engine_restarts_total": 2})), - recent: vec![ - json!({"rid": "req-1", "fin": "stop", "ptok": 10, "ttft_ms": 5, "content": "model said hello", "note": "see /home/para/x"}), - ], - warnings: vec![leaked_warning], - log_files: vec![("api.log".into(), 123)], - } - } - - #[test] - fn the_report_holds_no_secret_no_text_and_no_home_directory() { - redact::register_secret("sk-report-secret-key-0123456789"); - let report = build_report(&inputs_with_secrets(), Some("/home/para")); - let text = serde_json::to_string_pretty(&report).unwrap(); - for leaked in [ - "sk-report-secret", - "abcdef0123456789", - "private prompt", - "model said hello", - "/home/para", - ] { - assert!( - !text.contains(leaked), - "{leaked} leaked into the report:\n{text}" - ); - } - for kept in [ - "workstation", - "RTX 5090", - "\"engine_restarts_total\": 2", - "req-1", - "8f59b4aa", - "~/x", - ] { - assert!(text.contains(kept), "{kept} missing:\n{text}"); - } - assert_eq!(report["report_version"], 1); - assert!(text.len() < 8 * 1024, "{} bytes", text.len()); - } - - #[test] - fn the_report_is_written_only_with_the_opt_in_and_never_over_a_network() { - let dir = scratch("report"); - let state = dir.join("state"); - std::fs::create_dir_all(state.join("logs")).unwrap(); - std::fs::write( - state.join("logs").join("requests.log"), - format!( - "{}\n", - api_line("req-9", "2026-11-02T10:00:00.000Z", "stop", 800, 70.0) - ), - ) - .unwrap(); - let dirs = crate::layout::Dirs { - prefix: dir.join("prefix"), - state: state.clone(), - assets: dir.join("assets"), - }; - let opts = crate::cli::tests_options(dirs); - let out = dir.join("out.json"); - let without_opt_in = ReportArgs { - out: Some(out.display().to_string()), - last: 10, - yes: false, - }; - assert_eq!(run_report(&opts, &without_opt_in), 3); - assert!(!out.exists(), "no file without --yes"); - let with_opt_in = ReportArgs { - yes: true, - ..without_opt_in - }; - assert_eq!(run_report(&opts, &with_opt_in), 0); - let written: Value = serde_json::from_str(&std::fs::read_to_string(&out).unwrap()).unwrap(); - assert_eq!(written["requests"]["last"][0]["rid"], "req-9"); - assert_eq!(written["requests"]["summary"]["count"], 1); - assert!(!dir.join("out.json.tmp").exists()); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn the_status_line_summarises_the_last_quarter_hour() { - let dir = scratch("statusline"); - let now = now_ms(); - let line = |i: u64, fin: &str| { - api_line( - &format!("req-{i}"), - &format_utc_ms(now - 60_000 + i), - fin, - 1000 + i, - 80.0, - ) - }; - std::fs::write( - dir.join("requests.log"), - format!( - "{}\n{}\n{}\n", - line(1, "stop"), - line(2, "error"), - line(3, "stop") - ), - ) - .unwrap(); - let text = recent_requests_line(&dir, now).unwrap(); - assert!( - text.contains("3 in the last 15 min (1 failed)") - && text.contains("decode p50 80.0 tok/s") - && text.contains("cache hit 90%"), - "{text}" - ); - assert_eq!(recent_requests_line(&scratch("empty"), now), None); - let _ = std::fs::remove_dir_all(&dir); - } -} +mod tests; diff --git a/crates/deploy/src/logview/tests.rs b/crates/deploy/src/logview/tests.rs new file mode 100644 index 00000000..c7f063ef --- /dev/null +++ b/crates/deploy/src/logview/tests.rs @@ -0,0 +1,349 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn api_line(rid: &str, ts: &str, fin: &str, ttft: u64, tps: f64) -> String { + format!( + "{{\"ts\":\"{ts}\",\"lvl\":\"info\",\"comp\":\"api\",\"ev\":\"request\",\"rid\":\"{rid}\",\"sid\":\"s-1\",\"ep\":\"responses\",\"fin\":\"{fin}\",\"ptok\":1000,\"ctok\":900,\"otok\":50,\"ttft_ms\":{ttft},\"dec_tps\":{tps},\"ms\":5000,\"restart\":false,\"err\":\"none\"}}" + ) +} + +fn scratch(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("leleka-logview-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn json_lines_old_supervisor_lines_and_free_text_all_parse() { + let e = parse_line( + &api_line("req-1", "2026-11-02T10:00:00.250Z", "stop", 800, 70.5), + "requests", + ); + assert_eq!( + (e.comp.as_str(), e.ev.as_str(), e.level), + ("api", "request", Level::Info) + ); + assert_eq!(e.fields["rid"], "req-1"); + assert!(e.ts_ms.is_some() && !e.fields.contains_key("ts")); + let old = parse_line( + "2026-11-02T10:00:00Z leleka: engine exited (signal 9); the API reports not-ready", + "leleka", + ); + assert_eq!((old.level, old.ts_ms.is_some()), (Level::Warn, true)); + assert_eq!( + old.fields["msg"], + "engine exited (signal 9); the API reports not-ready" + ); + let text = parse_line("loading 4096 experts", "engine"); + assert_eq!( + (text.ts_ms, text.comp.as_str(), text.level), + (None, "engine", Level::Info) + ); + assert_eq!( + parse_line("thread 'main' panicked at x.rs:1", "engine").level, + Level::Error + ); +} + +#[test] +fn rotated_generations_are_read_oldest_first_and_filters_apply() { + let dir = scratch("gens"); + let name = |s: &str| dir.join(s); + std::fs::write( + name("api.log.2"), + format!( + "{}\n", + api_line("req-a", "2026-11-02T09:00:00.000Z", "stop", 1, 1.0) + ), + ) + .unwrap(); + std::fs::write( + name("api.log.1"), + format!( + "{}\n", + api_line("req-b", "2026-11-02T09:30:00.000Z", "length", 2, 2.0) + ), + ) + .unwrap(); + std::fs::write( + name("api.log"), + format!( + "{}\n{{\"ts\":\"2026-11-02T10:05:00.000Z\",\"lvl\":\"warn\",\"comp\":\"api\",\"ev\":\"engine_lost\",\"reason\":\"gone\"}}\nnot json at all\n", + api_line("req-c", "2026-11-02T10:00:00.000Z", "error", 3, 3.0) + ), + ) + .unwrap(); + let all = collect( + &dir, + &Filter { + tail: 100, + ..Filter::default() + }, + ); + let ids: Vec<_> = all + .iter() + .filter_map(|e| e.fields.get("rid").and_then(Value::as_str)) + .collect(); + assert_eq!(ids, ["req-a", "req-b", "req-c"]); + assert_eq!( + all.len(), + 5, + "the free-text line is kept, next to its neighbours in time" + ); + let warn = collect( + &dir, + &Filter { + min_level: Level::Warn, + tail: 100, + ..Filter::default() + }, + ); + assert!( + warn.iter().all(|e| e.level >= Level::Warn) + && warn.iter().any(|e| e.ev == "engine_lost") + ); + let since = parse_utc_ms("2026-11-02T09:45:00Z").unwrap(); + let recent = collect( + &dir, + &Filter { + since_ms: Some(since), + tail: 100, + ..Filter::default() + }, + ); + assert!( + recent.iter().all(|e| e.ts_ms.unwrap() >= since) && recent.len() == 3, + "{recent:?}" + ); + let tail = collect( + &dir, + &Filter { + tail: 2, + ..Filter::default() + }, + ); + assert_eq!(tail.len(), 2); + let by_id = collect( + &dir, + &Filter { + request: Some("REQ-b".into()), + tail: 100, + ..Filter::default() + }, + ); + assert_eq!(by_id.len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_api_record_and_the_engine_line_of_a_request_join_by_id() { + let engine = "{\"ts\":\"2026-11-02T10:00:00.100Z\",\"lvl\":\"info\",\"comp\":\"engine\",\"ev\":\"request\",\"rid\":\"req-1\",\"rounds\":10,\"tok_per_round\":3.2,\"tier_vram_pct\":91.5}"; + let entries = vec![ + parse_line( + &api_line("req-1", "2026-11-02T10:00:01.000Z", "stop", 800, 70.0), + "requests", + ), + parse_line(engine, "engine"), + parse_line( + &api_line("req-2", "2026-11-02T10:00:02.000Z", "stop", 900, 71.0), + "requests", + ), + ]; + let joined = join_requests(&entries); + assert_eq!(joined.len(), 2); + assert_eq!(joined[0]["eng_rounds"], 10); + assert_eq!(joined[0]["eng_tok_per_round"], 3.2); + assert!(joined[1].get("eng_rounds").is_none()); + assert_eq!(joined[0]["ts"], "2026-11-02T10:00:01.000Z"); +} + +#[test] +fn the_summary_has_percentiles_outcomes_and_the_cache_ratio() { + let records: Vec = (1..=10) + .map(|i| json!({"fin": if i == 10 { "error" } else { "stop" }, "err": if i == 10 { "stall" } else { "none" }, "ptok": 1000, "ctok": 900, "ttft_ms": i * 100, "dec_tps": 60.0, "restart": i == 10})) + .collect(); + let s = summarize(&records); + assert_eq!(s["count"], 10); + assert_eq!(s["outcomes"]["stop"], 9); + assert_eq!(s["errors"]["stall"], 1); + assert_eq!(s["during_engine_restart"], 1); + assert_eq!(s["cache_hit_ratio"], 0.9); + assert_eq!(s["ttft_ms"]["p50"], 600.0); + assert_eq!(s["ttft_ms"]["max"], 1000.0); + assert_eq!(summarize(&[])["count"], 0); +} + +#[test] +fn the_display_scrubs_a_credential_that_an_older_writer_left_in_a_line() { + leleka_obs::register_secret("tok-display-secret-0123456789abcdef"); + let entry = parse_line( + "{\"ts\":\"2026-11-02T10:00:00.000Z\",\"lvl\":\"warn\",\"comp\":\"engine\",\"ev\":\"msg\",\"msg\":\"reply said tok-display-secret-0123456789abcdef\"}", + "engine", + ); + let shown = redact::scrub(&render_entry(&entry)).into_owned(); + assert!(!shown.contains("tok-display-secret"), "{shown}"); + assert!(shown.contains("WARN") && shown.contains("engine")); +} + +#[test] +fn since_takes_durations_and_times() { + let now = parse_utc_ms("2026-11-02T12:00:00Z").unwrap(); + assert_eq!( + parse_since("30m", now).unwrap(), + parse_utc_ms("2026-11-02T11:30:00Z").unwrap() + ); + assert_eq!( + parse_since("2026-11-02T08:00:00Z", now).unwrap(), + parse_utc_ms("2026-11-02T08:00:00Z").unwrap() + ); + assert!(parse_since("yesterday", now).is_err()); + assert!( + filter_from( + &LogsArgs { + request: Some("abc".into()), + ..Default::default() + }, + now + ) + .is_err() + ); + assert!( + filter_from( + &LogsArgs { + level: Some("loud".into()), + ..Default::default() + }, + now + ) + .is_err() + ); +} + +fn inputs_with_secrets() -> ReportInputs { + let leaked_warning = parse_line( + "{\"ts\":\"2026-11-02T10:05:00.000Z\",\"lvl\":\"warn\",\"comp\":\"api\",\"ev\":\"msg\",\"msg\":\"upstream said Authorization: Bearer abcdef0123456789abcdef0123456789 and the key sk-report-secret-key-0123456789\"}", + "api", + ); + ReportInputs { + now_ms: parse_utc_ms("2026-11-02T10:10:00Z").unwrap(), + version: "leleka 0.1.0\ncommit abc (clean)".into(), + config: Some( + json!({"profile": "workstation", "assets_hint": "/home/para/work/leleka/models", "prompt": "my private prompt text", "api_key": "sk-report-secret-key-0123456789"}), + ), + expert_tier: Some(json!({"on": true, "sha256": "8f59b4aa", "reason": ""})), + host: json!({"os": "linux", "gpus": [{"name": "NVIDIA GeForce RTX 5090"}]}), + service: Some(json!({"phase": "ready", "engine_restarts_total": 2})), + recent: vec![ + json!({"rid": "req-1", "fin": "stop", "ptok": 10, "ttft_ms": 5, "content": "model said hello", "note": "see /home/para/x"}), + ], + warnings: vec![leaked_warning], + log_files: vec![("api.log".into(), 123)], + } +} + +#[test] +fn the_report_holds_no_secret_no_text_and_no_home_directory() { + redact::register_secret("sk-report-secret-key-0123456789"); + let report = build_report(&inputs_with_secrets(), Some("/home/para")); + let text = serde_json::to_string_pretty(&report).unwrap(); + for leaked in [ + "sk-report-secret", + "abcdef0123456789", + "private prompt", + "model said hello", + "/home/para", + ] { + assert!( + !text.contains(leaked), + "{leaked} leaked into the report:\n{text}" + ); + } + for kept in [ + "workstation", + "RTX 5090", + "\"engine_restarts_total\": 2", + "req-1", + "8f59b4aa", + "~/x", + ] { + assert!(text.contains(kept), "{kept} missing:\n{text}"); + } + assert_eq!(report["report_version"], 1); + assert!(text.len() < 8 * 1024, "{} bytes", text.len()); +} + +#[test] +fn the_report_is_written_only_with_the_opt_in_and_never_over_a_network() { + let dir = scratch("report"); + let state = dir.join("state"); + std::fs::create_dir_all(state.join("logs")).unwrap(); + std::fs::write( + state.join("logs").join("requests.log"), + format!( + "{}\n", + api_line("req-9", "2026-11-02T10:00:00.000Z", "stop", 800, 70.0) + ), + ) + .unwrap(); + let dirs = crate::layout::Dirs { + prefix: dir.join("prefix"), + state: state.clone(), + assets: dir.join("assets"), + }; + let opts = crate::cli::tests_options(dirs); + let out = dir.join("out.json"); + let without_opt_in = ReportArgs { + out: Some(out.display().to_string()), + last: 10, + yes: false, + }; + assert_eq!(run_report(&opts, &without_opt_in), 3); + assert!(!out.exists(), "no file without --yes"); + let with_opt_in = ReportArgs { + yes: true, + ..without_opt_in + }; + assert_eq!(run_report(&opts, &with_opt_in), 0); + let written: Value = serde_json::from_str(&std::fs::read_to_string(&out).unwrap()).unwrap(); + assert_eq!(written["requests"]["last"][0]["rid"], "req-9"); + assert_eq!(written["requests"]["summary"]["count"], 1); + assert!(!dir.join("out.json.tmp").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_status_line_summarises_the_last_quarter_hour() { + let dir = scratch("statusline"); + let now = now_ms(); + let line = |i: u64, fin: &str| { + api_line( + &format!("req-{i}"), + &format_utc_ms(now - 60_000 + i), + fin, + 1000 + i, + 80.0, + ) + }; + std::fs::write( + dir.join("requests.log"), + format!( + "{}\n{}\n{}\n", + line(1, "stop"), + line(2, "error"), + line(3, "stop") + ), + ) + .unwrap(); + let text = recent_requests_line(&dir, now).unwrap(); + assert!( + text.contains("3 in the last 15 min (1 failed)") + && text.contains("decode p50 80.0 tok/s") + && text.contains("cache hit 90%"), + "{text}" + ); + assert_eq!(recent_requests_line(&scratch("empty"), now), None); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/deploy/src/preflight.rs b/crates/deploy/src/preflight.rs index b0682185..337535ce 100644 --- a/crates/deploy/src/preflight.rs +++ b/crates/deploy/src/preflight.rs @@ -801,480 +801,4 @@ pub fn evaluate(facts: &Facts, profile: &Profile, needs: &Needs) -> Report { } #[cfg(test)] -mod tests { - use super::*; - use crate::facts::{DirFact, Memory}; - - fn server_facts() -> Facts { - let mut facts = Facts { - os: "linux".into(), - arch: "x86_64".into(), - nvidia_smi_found: true, - gpus: vec![Gpu { - index: 0, - name: "NVIDIA GeForce RTX 5090".into(), - driver: "595.99.02".into(), - vram_total_mib: 32607, - vram_free_mib: 32105, - sm: Some(120), - }], - memory: Memory { - total: 121 * GIB, - available: 118 * GIB, - swap_total: 0, - }, - systemd_system: true, - proc_fd: true, - memfd_ok: true, - ..Facts::default() - }; - facts.libs.insert( - "libcublas.so.12".into(), - Some("/opt/c/libcublas.so.12".into()), - ); - facts.libs.insert( - "libcublasLt.so.12".into(), - Some("/opt/c/libcublasLt.so.12".into()), - ); - facts.libs.insert( - "libcuda.so.1".into(), - Some("/usr/lib/x86_64-linux-gnu/libcuda.so.1".into()), - ); - for tool in ["curl", "tar", "xz", "systemctl"] { - facts.tools.insert(tool.into(), true); - } - for key in ["assets", "state", "prefix"] { - facts.dirs.insert( - key.into(), - DirFact { - path: format!("/data/{key}").into(), - free_bytes: Some(900 * GIB), - fs_type: Some("ext4".into()), - }, - ); - } - facts - } - - fn needs() -> Needs { - Needs { - assets_dir: "/data/assets".into(), - shard_bytes_missing: 83_617_662_656, - kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, - install_binaries: true, - may_install_cublas: true, - cublas_download_bytes: 500 << 20, - wants_systemd: true, - service_ports: vec![("api".into(), 8081), ("engine".into(), 18766)], - ..Needs::default() - } - } - - fn level_of(report: &Report, id: &str) -> Level { - report - .checks - .iter() - .find(|c| c.id == id) - .unwrap_or_else(|| panic!("no check {id}")) - .level - } - - #[test] - fn the_expert_tier_is_always_reported_on_or_off() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let report_for = |state: Option| { - let mut n = needs(); - n.expert_profile = state; - evaluate(&server_facts(), &profile, &n) - }; - let report = report_for(Some(ExpertProfileState::Valid)); - assert_eq!(level_of(&report, "expert-profile"), Level::Pass); - assert!( - report.render().contains("ON:") && report.render().contains("8f59b4aa...388975baf") - ); - for (state, needle) in [ - (ExpertProfileState::Absent, "OFF until installed"), - ( - ExpertProfileState::WrongDigest, - "does not have the pinned sha256", - ), - (ExpertProfileState::OptedOut, "--no-expert-tier was given"), - ] { - let report = report_for(Some(state)); - assert_eq!(level_of(&report, "expert-profile"), Level::Warn); - let text = report.render(); - assert!(text.contains("OFF") && text.contains(needle), "{text}"); - } - // an absent table names the way out - assert!( - report_for(Some(ExpertProfileState::Absent)) - .render() - .contains("--expert-profile-file") - ); - } - - #[test] - fn healthy_server_passes_everything() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let report = evaluate(&server_facts(), &profile, &needs()); - assert!(!report.failed(), "{}", report.render()); - assert_eq!(level_of(&report, "arch"), Level::Pass); - assert_eq!(level_of(&report, "memfd"), Level::Pass); - } - - #[test] - fn old_driver_and_busy_gpu_fail_with_actionable_text() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.gpus[0].driver = "580.65.06".into(); - facts.gpus[0].vram_free_mib = 9000; - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "driver"), Level::Fail); - assert_eq!(level_of(&report, "vram"), Level::Fail); - let text = report.render(); - assert!(text.contains("580.65.06 is older than 595"), "{text}"); - assert!(text.contains("--gpu-budget-gib"), "{text}"); - } - - #[test] - fn a_running_lab_holder_is_named_as_the_reason_the_gpu_is_taken() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.gpus[0].vram_free_mib = 1200; - facts.lab_holder = true; - let text = evaluate(&facts, &profile, &needs()).render(); - assert!( - text.contains("kar_holder") && text.contains("Lab mode"), - "{text}" - ); - facts.lab_holder = false; - let text = evaluate(&facts, &profile, &needs()).render(); - assert!( - !text.contains("kar_holder") && text.contains("--gpu-budget-gib"), - "{text}" - ); - } - - #[test] - fn no_gpu_names_the_wsl_remedy_under_wsl() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.gpus.clear(); - facts.nvidia_smi_found = false; - facts.wsl = true; - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "gpu"), Level::Fail); - assert!(report.render().contains("Windows driver")); - } - - #[test] - fn laptop_under_default_wsl_memory_gets_wslconfig_advice() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.wsl = true; - facts.gpus[0] = Gpu { - index: 0, - name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), - driver: "617.42".into(), - vram_total_mib: 16384, - vram_free_mib: 15234, - sm: Some(86), - }; - facts.memory = Memory { - total: 12 * GIB, - available: 9 * GIB, - swap_total: 0, - }; - let mut n = needs(); - n.binary_has_sm86 = Some(true); - let report = evaluate(&facts, &profile, &n); - assert_eq!(level_of(&report, "ram"), Level::Fail); - let text = report.render(); - assert!( - text.contains(".wslconfig") - && text.contains("memory=32GB") - && text.contains("wsl --shutdown"), - "{text}" - ); - assert_eq!(level_of(&report, "arch"), Level::Pass); - // 24 GB as WSL2 gives by default passes. - facts.memory = Memory { - total: 24_447_308 * 1024, - available: 22 * GIB, - swap_total: 0, - }; - let report = evaluate(&facts, &profile, &n); - assert!(!report.failed(), "{}", report.render()); - } - - #[test] - fn sm86_card_needs_binaries_with_the_companion_feature() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.gpus[0].sm = Some(86); - facts.gpus[0].vram_total_mib = 16384; - facts.gpus[0].vram_free_mib = 15000; - let mut n = needs(); - n.binary_has_sm86 = Some(false); - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "arch"), - Level::Fail - ); - n.binary_has_sm86 = None; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "arch"), - Level::Warn - ); - } - - #[test] - fn model_volume_on_a_windows_mount_is_refused_under_wsl() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = server_facts(); - facts.wsl = true; - facts.dirs.get_mut("assets").unwrap().fs_type = Some("9p".into()); - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "wsl"), Level::Fail); - assert!(report.render().contains("/mnt/c")); - } - - #[test] - fn missing_cublas_is_fixable_unless_the_tools_are_missing_too() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.libs.insert("libcublas.so.12".into(), None); - facts.libs.insert("libcublasLt.so.12".into(), None); - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "cublas"), - Level::Warn - ); - facts.tools.insert("xz".into(), false); - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "cublas"), - Level::Fail - ); - let mut n = needs(); - n.may_install_cublas = false; - facts.tools.insert("xz".into(), true); - let report = evaluate(&facts, &profile, &n); - assert_eq!(level_of(&report, "cublas"), Level::Fail); - assert!(report.render().contains("--cublas-dir")); - } - - #[test] - fn low_disk_reports_the_volume_before_anything_is_downloaded() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.dirs.get_mut("assets").unwrap().free_bytes = Some(53 * GIB); - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "disk"), Level::Fail); - let text = report.render(); - assert!( - text.contains("assets /data/assets: 53.0 GiB free"), - "{text}" - ); - assert!(text.contains("Nothing was downloaded yet"), "{text}"); - // With the model already present the same volume is fine. - let mut n = needs(); - n.shard_bytes_missing = 0; - n.kar_bytes_missing = 0; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "disk"), - Level::Pass - ); - } - - #[test] - fn memory_is_judged_by_the_profile_kar_source() { - let server = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.memory = Memory { - total: 64 * GIB, - available: 40 * GIB, - swap_total: 0, - }; - let report = evaluate(&facts, &server, &needs()); - assert_eq!(level_of(&report, "ram"), Level::Fail); - assert!( - report - .render() - .contains("sealed archive copy needs the whole archive in RAM") - ); - facts.memory = Memory { - total: 128 * GIB, - available: 100 * GIB, - swap_total: 0, - }; - facts.cgroup_memory_max = Some(32 * GIB); - assert_eq!( - level_of(&evaluate(&facts, &server, &needs()), "ram"), - Level::Fail - ); - } - - #[test] - fn an_inherited_sealed_archive_is_not_counted_twice() { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile.memfd_extents = crate::profile::MemfdExtents::Full; // the full 55 GB copy; the shipped `ple_only` form needs about 39 GB less - let mut facts = server_facts(); - // 70 GiB available: not enough to copy the archive and hold the 50 GB expert bank, enough when the - // parent already holds the sealed archive. - facts.memory = Memory { - total: 121 * GIB, - available: 70 * GIB, - swap_total: 0, - }; - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "ram"), - Level::Fail - ); - let mut n = needs(); - n.kar_fd_inherited = true; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "ram"), - Level::Pass - ); - facts.memory.available = 20 * GIB; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "ram"), - Level::Fail - ); - } - - #[test] - fn a_running_service_owns_its_ports_and_a_stranger_does_not() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.busy_ports = vec![8081]; - assert_eq!( - level_of(&evaluate(&facts, &profile, &needs()), "ports"), - Level::Fail - ); - let mut n = needs(); - n.service_running = true; - assert_eq!( - level_of(&evaluate(&facts, &profile, &n), "ports"), - Level::Pass - ); - } - - #[test] - fn other_platforms_stop_at_the_first_check() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let facts = Facts { - os: "macos".into(), - arch: "aarch64".into(), - ..Facts::default() - }; - let report = evaluate(&facts, &profile, &needs()); - assert!(report.failed()); - assert_eq!(report.checks.len(), 1); - } - - /// The RTX 3080 laptop as `facts::probe` sees it natively on Windows (nvidia-smi.exe, Win32 memory, DLL search). - fn windows_laptop() -> Facts { - let mut facts = Facts { - os: "windows".into(), - arch: "x86_64".into(), - gpus: vec![Gpu { - index: 0, - name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), - driver: "617.42".into(), - vram_total_mib: 16384, - vram_free_mib: 15234, - sm: Some(86), - }], - memory: crate::facts::Memory { - total: 48 << 30, - available: 30 << 30, - swap_total: 8 << 30, - }, - cpu_cores: 16, - nvidia_smi_found: true, - ..Facts::default() - }; - for key in ["assets", "state", "prefix"] { - facts.dirs.insert( - key.into(), - crate::facts::DirFact { - path: format!("C:/{key}").into(), - free_bytes: Some(1 << 40), - fs_type: None, - }, - ); - } - for name in crate::layout::BINARIES { - facts.binaries.insert(name.into(), true); - } - facts - } - - #[test] - fn a_windows_laptop_is_judged_natively_with_dll_names_and_no_systemd_or_memfd() { - let profile = Profile::builtin("rtx3080-16g").unwrap(); - let mut facts = windows_laptop(); - let mut needs = needs(); - needs.binary_has_sm86 = Some(true); - needs.may_install_cublas = false; - ( - needs.wants_systemd, - needs.shard_bytes_missing, - needs.kar_bytes_missing, - ) = (false, 0, 0); - // cuBLAS DLLs missing: a failure that names the DLLs and the remedy, never a download of the Linux tarball. - let report = evaluate(&facts, &profile, &needs); - let cublas = report.checks.iter().find(|c| c.id == "cublas").unwrap(); - assert_eq!(cublas.level, Level::Fail); - assert!( - cublas.detail.contains("cublas64_12.dll") - && cublas.fix.as_deref().unwrap().contains("--cublas-dir"), - "{cublas:?}" - ); - assert_eq!(level_of(&report, "platform"), Level::Pass); - assert_eq!(level_of(&report, "gpu"), Level::Pass); - assert_eq!(level_of(&report, "memfd"), Level::Pass); - facts.libs.insert( - "libcublas.so.12".into(), - Some("C:/cuda/cublas64_12.dll".into()), - ); - facts.libs.insert( - "libcublasLt.so.12".into(), - Some("C:/cuda/cublasLt64_12.dll".into()), - ); - facts.libs.insert( - "libcuda.so.1".into(), - Some("C:/Windows/System32/nvcuda.dll".into()), - ); - let report = evaluate(&facts, &profile, &needs); - assert!(!report.failed(), "{}", report.render()); - // The server profile holds the archive in a sealed memfd: refused with the reason. - let server = Profile::builtin("rtx5090-32g").unwrap(); - let report = evaluate(&facts, &server, &needs); - assert_eq!(level_of(&report, "memfd"), Level::Fail); - assert!( - report - .checks - .iter() - .any(|c| c.id == "expert-source" && c.level == Level::Fail) - ); - } - - #[test] - fn no_systemd_points_at_foreground_mode() { - let profile = Profile::builtin("rtx5090-32g").unwrap(); - let mut facts = server_facts(); - facts.systemd_system = false; - facts.wsl = true; - let report = evaluate(&facts, &profile, &needs()); - assert_eq!(level_of(&report, "systemd"), Level::Fail); - assert!(report.render().contains("--foreground")); - let mut n = needs(); - n.wants_systemd = false; - assert!( - !evaluate(&facts, &profile, &n) - .checks - .iter() - .any(|c| c.id == "systemd") - ); - } -} +mod tests; diff --git a/crates/deploy/src/preflight/tests.rs b/crates/deploy/src/preflight/tests.rs new file mode 100644 index 00000000..d6af7086 --- /dev/null +++ b/crates/deploy/src/preflight/tests.rs @@ -0,0 +1,477 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::facts::{DirFact, Memory}; + +fn server_facts() -> Facts { + let mut facts = Facts { + os: "linux".into(), + arch: "x86_64".into(), + nvidia_smi_found: true, + gpus: vec![Gpu { + index: 0, + name: "NVIDIA GeForce RTX 5090".into(), + driver: "595.99.02".into(), + vram_total_mib: 32607, + vram_free_mib: 32105, + sm: Some(120), + }], + memory: Memory { + total: 121 * GIB, + available: 118 * GIB, + swap_total: 0, + }, + systemd_system: true, + proc_fd: true, + memfd_ok: true, + ..Facts::default() + }; + facts.libs.insert( + "libcublas.so.12".into(), + Some("/opt/c/libcublas.so.12".into()), + ); + facts.libs.insert( + "libcublasLt.so.12".into(), + Some("/opt/c/libcublasLt.so.12".into()), + ); + facts.libs.insert( + "libcuda.so.1".into(), + Some("/usr/lib/x86_64-linux-gnu/libcuda.so.1".into()), + ); + for tool in ["curl", "tar", "xz", "systemctl"] { + facts.tools.insert(tool.into(), true); + } + for key in ["assets", "state", "prefix"] { + facts.dirs.insert( + key.into(), + DirFact { + path: format!("/data/{key}").into(), + free_bytes: Some(900 * GIB), + fs_type: Some("ext4".into()), + }, + ); + } + facts +} + +fn needs() -> Needs { + Needs { + assets_dir: "/data/assets".into(), + shard_bytes_missing: 83_617_662_656, + kar_bytes_missing: ARCHIVE_BYTES * 12 / 10, + install_binaries: true, + may_install_cublas: true, + cublas_download_bytes: 500 << 20, + wants_systemd: true, + service_ports: vec![("api".into(), 8081), ("engine".into(), 18766)], + ..Needs::default() + } +} + +fn level_of(report: &Report, id: &str) -> Level { + report + .checks + .iter() + .find(|c| c.id == id) + .unwrap_or_else(|| panic!("no check {id}")) + .level +} + +#[test] +fn the_expert_tier_is_always_reported_on_or_off() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let report_for = |state: Option| { + let mut n = needs(); + n.expert_profile = state; + evaluate(&server_facts(), &profile, &n) + }; + let report = report_for(Some(ExpertProfileState::Valid)); + assert_eq!(level_of(&report, "expert-profile"), Level::Pass); + assert!( + report.render().contains("ON:") && report.render().contains("8f59b4aa...388975baf") + ); + for (state, needle) in [ + (ExpertProfileState::Absent, "OFF until installed"), + ( + ExpertProfileState::WrongDigest, + "does not have the pinned sha256", + ), + (ExpertProfileState::OptedOut, "--no-expert-tier was given"), + ] { + let report = report_for(Some(state)); + assert_eq!(level_of(&report, "expert-profile"), Level::Warn); + let text = report.render(); + assert!(text.contains("OFF") && text.contains(needle), "{text}"); + } + // an absent table names the way out + assert!( + report_for(Some(ExpertProfileState::Absent)) + .render() + .contains("--expert-profile-file") + ); +} + +#[test] +fn healthy_server_passes_everything() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let report = evaluate(&server_facts(), &profile, &needs()); + assert!(!report.failed(), "{}", report.render()); + assert_eq!(level_of(&report, "arch"), Level::Pass); + assert_eq!(level_of(&report, "memfd"), Level::Pass); +} + +#[test] +fn old_driver_and_busy_gpu_fail_with_actionable_text() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.gpus[0].driver = "580.65.06".into(); + facts.gpus[0].vram_free_mib = 9000; + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "driver"), Level::Fail); + assert_eq!(level_of(&report, "vram"), Level::Fail); + let text = report.render(); + assert!(text.contains("580.65.06 is older than 595"), "{text}"); + assert!(text.contains("--gpu-budget-gib"), "{text}"); +} + +#[test] +fn a_running_lab_holder_is_named_as_the_reason_the_gpu_is_taken() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.gpus[0].vram_free_mib = 1200; + facts.lab_holder = true; + let text = evaluate(&facts, &profile, &needs()).render(); + assert!( + text.contains("kar_holder") && text.contains("Lab mode"), + "{text}" + ); + facts.lab_holder = false; + let text = evaluate(&facts, &profile, &needs()).render(); + assert!( + !text.contains("kar_holder") && text.contains("--gpu-budget-gib"), + "{text}" + ); +} + +#[test] +fn no_gpu_names_the_wsl_remedy_under_wsl() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.gpus.clear(); + facts.nvidia_smi_found = false; + facts.wsl = true; + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "gpu"), Level::Fail); + assert!(report.render().contains("Windows driver")); +} + +#[test] +fn laptop_under_default_wsl_memory_gets_wslconfig_advice() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.wsl = true; + facts.gpus[0] = Gpu { + index: 0, + name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), + driver: "617.42".into(), + vram_total_mib: 16384, + vram_free_mib: 15234, + sm: Some(86), + }; + facts.memory = Memory { + total: 12 * GIB, + available: 9 * GIB, + swap_total: 0, + }; + let mut n = needs(); + n.binary_has_sm86 = Some(true); + let report = evaluate(&facts, &profile, &n); + assert_eq!(level_of(&report, "ram"), Level::Fail); + let text = report.render(); + assert!( + text.contains(".wslconfig") + && text.contains("memory=32GB") + && text.contains("wsl --shutdown"), + "{text}" + ); + assert_eq!(level_of(&report, "arch"), Level::Pass); + // 24 GB as WSL2 gives by default passes. + facts.memory = Memory { + total: 24_447_308 * 1024, + available: 22 * GIB, + swap_total: 0, + }; + let report = evaluate(&facts, &profile, &n); + assert!(!report.failed(), "{}", report.render()); +} + +#[test] +fn sm86_card_needs_binaries_with_the_companion_feature() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.gpus[0].sm = Some(86); + facts.gpus[0].vram_total_mib = 16384; + facts.gpus[0].vram_free_mib = 15000; + let mut n = needs(); + n.binary_has_sm86 = Some(false); + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "arch"), + Level::Fail + ); + n.binary_has_sm86 = None; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "arch"), + Level::Warn + ); +} + +#[test] +fn model_volume_on_a_windows_mount_is_refused_under_wsl() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = server_facts(); + facts.wsl = true; + facts.dirs.get_mut("assets").unwrap().fs_type = Some("9p".into()); + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "wsl"), Level::Fail); + assert!(report.render().contains("/mnt/c")); +} + +#[test] +fn missing_cublas_is_fixable_unless_the_tools_are_missing_too() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.libs.insert("libcublas.so.12".into(), None); + facts.libs.insert("libcublasLt.so.12".into(), None); + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "cublas"), + Level::Warn + ); + facts.tools.insert("xz".into(), false); + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "cublas"), + Level::Fail + ); + let mut n = needs(); + n.may_install_cublas = false; + facts.tools.insert("xz".into(), true); + let report = evaluate(&facts, &profile, &n); + assert_eq!(level_of(&report, "cublas"), Level::Fail); + assert!(report.render().contains("--cublas-dir")); +} + +#[test] +fn low_disk_reports_the_volume_before_anything_is_downloaded() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.dirs.get_mut("assets").unwrap().free_bytes = Some(53 * GIB); + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "disk"), Level::Fail); + let text = report.render(); + assert!( + text.contains("assets /data/assets: 53.0 GiB free"), + "{text}" + ); + assert!(text.contains("Nothing was downloaded yet"), "{text}"); + // With the model already present the same volume is fine. + let mut n = needs(); + n.shard_bytes_missing = 0; + n.kar_bytes_missing = 0; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "disk"), + Level::Pass + ); +} + +#[test] +fn memory_is_judged_by_the_profile_kar_source() { + let server = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.memory = Memory { + total: 64 * GIB, + available: 40 * GIB, + swap_total: 0, + }; + let report = evaluate(&facts, &server, &needs()); + assert_eq!(level_of(&report, "ram"), Level::Fail); + assert!( + report + .render() + .contains("sealed archive copy needs the whole archive in RAM") + ); + facts.memory = Memory { + total: 128 * GIB, + available: 100 * GIB, + swap_total: 0, + }; + facts.cgroup_memory_max = Some(32 * GIB); + assert_eq!( + level_of(&evaluate(&facts, &server, &needs()), "ram"), + Level::Fail + ); +} + +#[test] +fn an_inherited_sealed_archive_is_not_counted_twice() { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memfd_extents = crate::profile::MemfdExtents::Full; // the full 55 GB copy; the shipped `ple_only` form needs about 39 GB less + let mut facts = server_facts(); + // 70 GiB available: not enough to copy the archive and hold the 50 GB expert bank, enough when the + // parent already holds the sealed archive. + facts.memory = Memory { + total: 121 * GIB, + available: 70 * GIB, + swap_total: 0, + }; + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "ram"), + Level::Fail + ); + let mut n = needs(); + n.kar_fd_inherited = true; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "ram"), + Level::Pass + ); + facts.memory.available = 20 * GIB; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "ram"), + Level::Fail + ); +} + +#[test] +fn a_running_service_owns_its_ports_and_a_stranger_does_not() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.busy_ports = vec![8081]; + assert_eq!( + level_of(&evaluate(&facts, &profile, &needs()), "ports"), + Level::Fail + ); + let mut n = needs(); + n.service_running = true; + assert_eq!( + level_of(&evaluate(&facts, &profile, &n), "ports"), + Level::Pass + ); +} + +#[test] +fn other_platforms_stop_at_the_first_check() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let facts = Facts { + os: "macos".into(), + arch: "aarch64".into(), + ..Facts::default() + }; + let report = evaluate(&facts, &profile, &needs()); + assert!(report.failed()); + assert_eq!(report.checks.len(), 1); +} + +/// The RTX 3080 laptop as `facts::probe` sees it natively on Windows (nvidia-smi.exe, Win32 memory, DLL search). +fn windows_laptop() -> Facts { + let mut facts = Facts { + os: "windows".into(), + arch: "x86_64".into(), + gpus: vec![Gpu { + index: 0, + name: "NVIDIA GeForce RTX 3080 Laptop GPU".into(), + driver: "617.42".into(), + vram_total_mib: 16384, + vram_free_mib: 15234, + sm: Some(86), + }], + memory: crate::facts::Memory { + total: 48 << 30, + available: 30 << 30, + swap_total: 8 << 30, + }, + cpu_cores: 16, + nvidia_smi_found: true, + ..Facts::default() + }; + for key in ["assets", "state", "prefix"] { + facts.dirs.insert( + key.into(), + crate::facts::DirFact { + path: format!("C:/{key}").into(), + free_bytes: Some(1 << 40), + fs_type: None, + }, + ); + } + for name in crate::layout::BINARIES { + facts.binaries.insert(name.into(), true); + } + facts +} + +#[test] +fn a_windows_laptop_is_judged_natively_with_dll_names_and_no_systemd_or_memfd() { + let profile = Profile::builtin("rtx3080-16g").unwrap(); + let mut facts = windows_laptop(); + let mut needs = needs(); + needs.binary_has_sm86 = Some(true); + needs.may_install_cublas = false; + ( + needs.wants_systemd, + needs.shard_bytes_missing, + needs.kar_bytes_missing, + ) = (false, 0, 0); + // cuBLAS DLLs missing: a failure that names the DLLs and the remedy, never a download of the Linux tarball. + let report = evaluate(&facts, &profile, &needs); + let cublas = report.checks.iter().find(|c| c.id == "cublas").unwrap(); + assert_eq!(cublas.level, Level::Fail); + assert!( + cublas.detail.contains("cublas64_12.dll") + && cublas.fix.as_deref().unwrap().contains("--cublas-dir"), + "{cublas:?}" + ); + assert_eq!(level_of(&report, "platform"), Level::Pass); + assert_eq!(level_of(&report, "gpu"), Level::Pass); + assert_eq!(level_of(&report, "memfd"), Level::Pass); + facts.libs.insert( + "libcublas.so.12".into(), + Some("C:/cuda/cublas64_12.dll".into()), + ); + facts.libs.insert( + "libcublasLt.so.12".into(), + Some("C:/cuda/cublasLt64_12.dll".into()), + ); + facts.libs.insert( + "libcuda.so.1".into(), + Some("C:/Windows/System32/nvcuda.dll".into()), + ); + let report = evaluate(&facts, &profile, &needs); + assert!(!report.failed(), "{}", report.render()); + // The server profile holds the archive in a sealed memfd: refused with the reason. + let server = Profile::builtin("rtx5090-32g").unwrap(); + let report = evaluate(&facts, &server, &needs); + assert_eq!(level_of(&report, "memfd"), Level::Fail); + assert!( + report + .checks + .iter() + .any(|c| c.id == "expert-source" && c.level == Level::Fail) + ); +} + +#[test] +fn no_systemd_points_at_foreground_mode() { + let profile = Profile::builtin("rtx5090-32g").unwrap(); + let mut facts = server_facts(); + facts.systemd_system = false; + facts.wsl = true; + let report = evaluate(&facts, &profile, &needs()); + assert_eq!(level_of(&report, "systemd"), Level::Fail); + assert!(report.render().contains("--foreground")); + let mut n = needs(); + n.wants_systemd = false; + assert!( + !evaluate(&facts, &profile, &n) + .checks + .iter() + .any(|c| c.id == "systemd") + ); +} diff --git a/crates/deploy/src/reconfigure.rs b/crates/deploy/src/reconfigure.rs index 19c7ee85..45b11d4c 100644 --- a/crates/deploy/src/reconfigure.rs +++ b/crates/deploy/src/reconfigure.rs @@ -509,605 +509,4 @@ pub fn new_request_id() -> String { } #[cfg(test)] -mod tests { - use super::*; - use crate::{config::Ports, facts::Memory, layout::Dirs, profile::KarSource}; - use std::collections::BTreeMap; - - fn gpu(total: u64, free: u64) -> Gpu { - Gpu { - index: 0, - name: "NVIDIA GeForce RTX 5090".into(), - driver: "595.99".into(), - vram_total_mib: total, - vram_free_mib: free, - sm: Some(120), - } - } - - fn host(cores: u32, ram_gib: u64, avail_gib: u64, gpus: Vec) -> Facts { - Facts { - cpu_cores: cores, - memory: Memory { - total: ram_gib * GIB, - available: avail_gib * GIB, - swap_total: 0, - }, - gpus, - ..Facts::default() - } - } - - /// The server as `leleka up` left it (no preset): the dedicated profile of the RTX 5090. - fn server_config() -> RunConfig { - let dirs = Dirs { - prefix: "/opt/leleka".into(), - state: "/var/lib/leleka/state".into(), - assets: "/data".into(), - }; - let ports = Ports { - api: "127.0.0.1:8081".into(), - engine: "127.0.0.1:18766".into(), - daemon: "127.0.0.1:18080".into(), - }; - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - profile.memfd_extents = crate::profile::MemfdExtents::Full; // the tests describe the full copy; the shipped profile is `ple_only` - // `up` resolved the dedicated preset's worker count into the environment - let env = BTreeMap::from([(CPU_WORKERS_ENV.to_owned(), "15".to_owned())]); - let mut config = RunConfig::new(&dirs, ports, 0, profile.clone(), env); - config.base_profile = Some(profile); - config - } - - fn request(budget: Option, preset: Option, settings: Value) -> Request { - Request { - id: "t".into(), - gpu_budget_gib: budget, - preset, - settings: settings.as_object().cloned().unwrap_or_default(), - persist: false, - } - } - - fn big_host() -> Facts { - host(32, 121, 100, vec![gpu(32607, 32100)]) - } - - #[test] - fn runtime_settings_become_profile_fields_with_the_engines_ranges() { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - let settings = json!({ - "context_tokens": 131072, "prefill_capacity": 4096, "kv_resident": 0, "prefix_cache_mib": "20480", - "prefix_cache_tail": "reply", "prefix_cache_block": 4096, "prefix_retention_min": 30, "cpu_workers": 6, "spec_min_p": 0.5 - }); - let changed = apply_settings(&mut profile, settings.as_object().unwrap()).unwrap(); - for name in [ - "context_tokens", - "prefill_capacity", - "prefix_cache_mib", - "prefix_cache_block", - "prefix_retention_min", - "cpu_workers", - "spec_min_p", - ] { - assert!(changed.iter().any(|c| c == name), "{name} in {changed:?}"); - } - assert_eq!( - ( - profile.context_tokens, - profile.prefill_capacity, - profile.kv_resident - ), - (131072, Some(4096), Some(0)) - ); - assert_eq!(profile.memory.prefix_cache_mib.as_deref(), Some("20480")); - assert_eq!(profile.memory.prefix_cache_tail.as_deref(), Some("reply")); - assert_eq!( - ( - profile.memory.prefix_cache_block, - profile.memory.prefix_retention_min - ), - (Some(4096), Some(30)) - ); - assert_eq!( - profile.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), - Some("6") - ); - assert_eq!(profile.spec_min_p, Some(0.5)); - // the same document again changes nothing - assert!( - apply_settings(&mut profile, settings.as_object().unwrap()) - .unwrap() - .is_empty() - ); - // and they reach the engine as flags and environment - let config = RunConfig::new( - &Dirs { - prefix: "/p".into(), - state: "/s".into(), - assets: "/a".into(), - }, - Ports { - api: "127.0.0.1:1".into(), - engine: "127.0.0.1:2".into(), - daemon: "127.0.0.1:3".into(), - }, - 0, - profile, - BTreeMap::new(), - ); - let args = config.engine_args(crate::config::KarArg::Fd).join(" "); - assert!( - args.contains("--context-tokens 131072") - && args.contains("--original-prefill-capacity 4096"), - "{args}" - ); - assert!( - args.contains("--kv-resident 0") && args.contains("--prefix-cache-mib 20480"), - "{args}" - ); - assert!( - args.contains("--prefix-cache-tail reply") - && args.contains("--prefix-cache-block 4096"), - "{args}" - ); - assert!(args.contains("--spec-min-p 0.5"), "{args}"); - let env = config.engine_environment(); - assert_eq!( - env.get("LELEKA_PREFIX_RETENTION_S").map(String::as_str), - Some("1800") - ); - assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("6")); - } - - #[test] - fn invalid_settings_change_nothing_and_say_why() { - for (bad, why) in [ - (json!({"context_tokens": 0}), "context_tokens"), - (json!({"context_tokens": 300000}), "context_tokens"), - (json!({"context_tokens": "big"}), "whole number"), - (json!({"prefill_capacity": 5000}), "prefill_capacity"), - (json!({"kv_resident": 1000}), "kv_resident"), - (json!({"cpu_workers": 0}), "cpu_workers"), - (json!({"cpu_workers": 65}), "cpu_workers"), - (json!({"spec_min_p": 1.5}), "spec_min_p"), - (json!({"prefix_cache_tail": "always"}), "prefix_cache_tail"), - (json!({"prefix_cache_mib": "lots"}), "prefix_cache_mib"), - (json!({"prefix_cache_block": 300}), "multiple of 256"), - ( - json!({"prefill_capacity": 4096, "prefix_cache_block": 8192}), - "larger than the prefill chunk", - ), - (json!({"nonsense": 1}), "unknown setting"), - ] { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - let before = profile.clone(); - let error = apply_settings(&mut profile, bad.as_object().unwrap()).unwrap_err(); - assert!(error.contains(why), "{bad}: {error}"); - assert_eq!(profile, before, "{bad} must change nothing"); - } - } - - #[test] - fn the_prefix_cache_can_be_switched_off_and_a_member_alone_turns_it_on() { - let mut profile = Profile::builtin("rtx5090-32g").unwrap(); - // a `ple_only` profile refuses an `auto` cache (the freed RAM would be refilled); the full form accepts it - profile.memfd_extents = crate::profile::MemfdExtents::Full; - profile.memory.prefix_cache_mib = None; - apply_settings( - &mut profile, - json!({"prefix_cache_tail": "prompt"}).as_object().unwrap(), - ) - .unwrap(); - assert_eq!( - profile.memory.prefix_cache_mib.as_deref(), - Some("auto"), - "the engine opens an auto cache for a lone member" - ); - apply_settings( - &mut profile, - json!({"prefix_cache_mib": "off"}).as_object().unwrap(), - ) - .unwrap(); - assert_eq!(profile.memory.prefix_cache_mib.as_deref(), Some("0")); - profile.memory.prefix_cache_block = Some(512); - let mut config = server_config(); - config.profile = profile; - let args = config.engine_args(crate::config::KarArg::Fd).join(" "); - assert!( - !args.contains("--prefix-cache-block"), - "a block is not passed while the cache is off: {args}" - ); - } - - #[test] - fn a_budget_change_is_planned_against_the_host_and_keeps_everything_else() { - let config = server_config(); - let planned = plan( - &config, - &request(Some(24), None, json!({})), - &big_host(), - true, - ) - .unwrap(); - assert!(!planned.unchanged); - assert_eq!(planned.config.profile.gpu_budget_bytes, 24 * GIB); - assert_eq!( - planned - .config - .base_profile - .as_ref() - .unwrap() - .gpu_budget_bytes, - 24 * GIB - ); - assert_eq!( - planned.config.profile.context_tokens, - config.profile.context_tokens - ); - assert_eq!(planned.config.preset, Preset::Dedicated); - let args = planned - .config - .engine_args(crate::config::KarArg::Fd) - .join(" "); - assert!( - args.contains(&format!("--gpu-budget {}", 24 * GIB)), - "{args}" - ); - // the same budget again is a no-op, not a five-minute restart - // (the shipped 5090 budget is 31,299 MiB, which a whole-GiB request cannot restate: the no-op is checked on the 24 GiB just planned) - let same = plan( - &planned.config, - &request(Some(24), None, json!({})), - &big_host(), - true, - ) - .unwrap(); - assert!(same.unchanged, "the profile already has a 24 GiB budget"); - } - - #[test] - fn the_workstation_preset_applies_and_dedicated_undoes_it() { - let config = server_config(); - let to_workstation = plan( - &config, - &request(None, Some(Preset::Workstation), json!({})), - &big_host(), - true, - ) - .unwrap(); - let ws = &to_workstation.config; - assert_eq!(ws.preset, Preset::Workstation); - assert_eq!( - ws.profile.gpu_budget_bytes, - 29 * GIB, - "32100 MiB free minus the 2 GiB left to the desktop" - ); - assert_eq!(ws.profile.memory.soft_floor_mib, Some(16384)); - assert_eq!( - ws.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), - Some("15") - ); - // back: the unmodified profile is restored from the recorded base - let back = plan( - ws, - &request(None, Some(Preset::Dedicated), json!({})), - &big_host(), - true, - ) - .unwrap(); - assert_eq!(back.config.profile, config.profile); - assert_eq!(back.config.preset, Preset::Dedicated); - // `--gpu-budget-gib N --preset workstation`: the explicit budget is what the engine gets, if the preset allows it - let both = plan( - &config, - &request(Some(24), Some(Preset::Workstation), json!({})), - &big_host(), - true, - ) - .unwrap(); - assert_eq!(both.config.profile.gpu_budget_bytes, 24 * GIB); - assert_eq!(both.config.preset, Preset::Workstation); - assert_eq!(both.config.profile.memory.soft_floor_mib, Some(16384)); - } - - #[test] - fn an_old_installation_without_a_recorded_base_cannot_undo_the_workstation_preset() { - let mut config = server_config(); - config.base_profile = None; - config.preset = Preset::Workstation; - let error = plan( - &config, - &request(None, Some(Preset::Dedicated), json!({})), - &big_host(), - true, - ) - .unwrap_err(); - assert!(error.contains("leleka up --preset dedicated"), "{error}"); - // staying on workstation, or going to it from dedicated, works without a base - assert!( - plan( - &config, - &request(Some(20), None, json!({})), - &big_host(), - true - ) - .is_ok() - ); - config.preset = Preset::Dedicated; - assert!( - plan( - &config, - &request(None, Some(Preset::Workstation), json!({})), - &big_host(), - true - ) - .is_ok() - ); - } - - #[test] - fn unsafe_values_are_refused_by_the_planner() { - let config = server_config(); - let refused = |request: Request, facts: &Facts, resident: bool| { - plan(&config, &request, facts, resident).unwrap_err() - }; - // more than the card has - let error = refused(request(Some(40), None, json!({})), &big_host(), true); - assert!(error.contains("does not fit the 32607 MiB"), "{error}"); - // not a budget at all - assert!(refused(request(Some(0), None, json!({})), &big_host(), true).contains("1..1024")); - assert!( - refused(request(Some(5000), None, json!({})), &big_host(), true).contains("1..1024") - ); - // another process holds the card (checked once the engine is stopped) - let busy = host(32, 121, 100, vec![gpu(32607, 9000)]); - let error = refused(request(Some(24), None, json!({})), &busy, true); - assert!( - error.contains("9000 MiB free") && error.contains("needs"), - "{error}" - ); - // the optimistic view, used before the engine is stopped, does not charge the engine's own VRAM - assert!( - plan( - &config, - &request(Some(24), None, json!({})), - &optimistic(&busy), - true - ) - .is_ok() - ); - // the workstation preset on a card that is mostly taken is a problem, not a silent shrink - let taken = host(32, 121, 100, vec![gpu(32607, 12000)]); - let error = refused( - request(None, Some(Preset::Workstation), json!({})), - &taken, - true, - ); - assert!(error.contains("workstation preset"), "{error}"); - // an explicit budget the preset cannot give - let error = refused( - request(Some(30), Some(Preset::Workstation), json!({})), - &big_host(), - true, - ); - assert!(error.contains("asks for more"), "{error}"); - // a bad runtime setting riding along refuses the whole request - assert!( - refused( - request(Some(24), None, json!({"cpu_workers": 99})), - &big_host(), - true - ) - .contains("cpu_workers") - ); - // a host too small to keep the sealed archive and the preset's free memory: refused rather than switched to the file form - let small = host(32, 64, 10, vec![gpu(32607, 32100)]); - let error = refused( - request(None, Some(Preset::Workstation), json!({})), - &small, - true, - ); - assert!( - error.contains("file-backed form") || error.contains("leleka up"), - "{error}" - ); - } - - #[test] - fn the_resident_archive_is_not_charged_twice_to_the_host() { - // 121 GiB host, 66 GiB available *with* the 55 GB memfd already resident (what the supervisor sees): fits the dedicated preset - let config = server_config(); - assert!( - plan( - &config, - &request(Some(20), None, json!({})), - &host(32, 121, 66, vec![gpu(32607, 32100)]), - true - ) - .is_ok() - ); - // a profile that reads the archive from a file keeps charging it to the planner as before - let mut file = server_config(); - file.profile.kar_source = KarSource::File; - file.base_profile = Some(file.profile.clone()); - assert!( - plan( - &file, - &request(Some(20), None, json!({})), - &host(32, 121, 40, vec![gpu(32607, 32100)]), - false - ) - .is_ok() - ); - } - - #[test] - fn recording_settings_updates_the_profile_and_the_base_and_lets_an_explicit_worker_count_win() { - let mut config = plan( - &server_config(), - &request(None, Some(Preset::Workstation), json!({})), - &big_host(), - true, - ) - .unwrap() - .config; - assert_eq!( - config.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), - Some("15") - ); - let changed = record_settings( - &mut config, - json!({"context_tokens": 65536, "cpu_workers": 5}) - .as_object() - .unwrap(), - ) - .unwrap(); - assert_eq!( - changed, - vec!["context_tokens".to_owned(), "cpu_workers".to_owned()] - ); - assert_eq!(config.profile.context_tokens, 65536); - assert_eq!(config.base_profile.as_ref().unwrap().context_tokens, 65536); - assert_eq!( - config - .engine_environment() - .get(CPU_WORKERS_ENV) - .map(String::as_str), - Some("5") - ); - // an invalid document leaves the configuration alone - let before = config.clone(); - assert!( - record_settings( - &mut config, - json!({"context_tokens": 0}).as_object().unwrap() - ) - .is_err() - ); - assert_eq!(config, before); - // switching preset afterwards keeps the explicit setting - let again = plan( - &config, - &request(None, Some(Preset::Dedicated), json!({})), - &big_host(), - true, - ) - .unwrap() - .config; - assert_eq!(again.profile.context_tokens, 65536); - assert_eq!( - again - .engine_environment() - .get(CPU_WORKERS_ENV) - .map(String::as_str), - Some("5") - ); - } - - #[test] - fn the_request_and_answer_files_round_trip_and_a_request_runs_once() { - let root = std::env::temp_dir().join(format!("leleka-reconf-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let dirs = Dirs { - prefix: root.join("p"), - state: root.join("s"), - assets: root.join("a"), - }; - let paths = dirs.paths(); - std::fs::create_dir_all(paths.run_dir()).unwrap(); - assert!(take_request(&paths).is_none()); - let asked = request( - Some(24), - Some(Preset::Workstation), - json!({"context_tokens": 65536}), - ); - write_request(&paths, &asked).unwrap(); - assert!( - write_request(&paths, &asked) - .unwrap_err() - .contains("waiting") - ); - assert_eq!(take_request(&paths).unwrap().unwrap(), asked); - assert!(take_request(&paths).is_none(), "the file is consumed"); - // a corrupt request is reported, not retried forever - std::fs::write(paths.reconfigure_request(), "{not json").unwrap(); - assert!( - take_request(&paths) - .unwrap() - .unwrap_err() - .contains("invalid") - ); - assert!(!paths.reconfigure_request().exists()); - let outcome = Outcome { - id: asked.id.clone(), - state: State::Refused, - message: "no".into(), - effective: None, - persisted: false, - }; - write_outcome(&paths, &outcome).unwrap(); - assert_eq!(read_outcome(&paths, &asked.id), Some(outcome)); - assert_eq!(read_outcome(&paths, "other"), None); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn persisting_writes_a_private_config_that_reads_back_and_refreshes_the_api_context() { - let root = std::env::temp_dir().join(format!("leleka-persist-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let dirs = Dirs { - prefix: root.join("p"), - state: root.join("s"), - assets: root.join("a"), - }; - let paths = dirs.paths(); - std::fs::create_dir_all(paths.run_dir()).unwrap(); - let mut config = server_config(); - config.prefix = dirs.prefix.display().to_string(); - config.state = dirs.state.display().to_string(); - config.assets = dirs.assets.display().to_string(); - persist(&paths, &config).unwrap(); - let changed = persist_offline( - &paths, - json!({"context_tokens": 100000, "prefix_cache_tail": "prompt"}) - .as_object() - .unwrap(), - ) - .unwrap(); - assert_eq!(changed.len(), 2); - let back = RunConfig::read(&paths.run_config()).unwrap(); - assert_eq!(back.profile.context_tokens, 100000); - assert_eq!( - back.profile.memory.prefix_cache_tail.as_deref(), - Some("prompt") - ); - let strata: Value = - serde_json::from_str(&std::fs::read_to_string(paths.strata_config()).unwrap()).unwrap(); - assert_eq!(strata["runtime"]["max_context"], 100000); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mode = std::fs::metadata(paths.run_config()) - .unwrap() - .permissions() - .mode() - & 0o777; - assert_eq!(mode, 0o600); - } - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn the_effective_summary_names_the_numbers_in_force() { - let summary = effective(&server_config()); - // the 5090 profile ships 32819404800 bytes (31,299 MiB, "31,300 MiB" in the slots-footprint notes), the budget the dense-slab slot gain needs - assert_eq!( - summary["gpu_budget_gib"], - 32819404800_f64 / (1u64 << 30) as f64 - ); - assert_eq!(summary["preset"], "dedicated"); - assert_eq!(summary["context_tokens"], 262144); - assert_eq!(summary["cpu_workers"], 15); - } -} +mod tests; diff --git a/crates/deploy/src/reconfigure/tests.rs b/crates/deploy/src/reconfigure/tests.rs new file mode 100644 index 00000000..e5ed8a77 --- /dev/null +++ b/crates/deploy/src/reconfigure/tests.rs @@ -0,0 +1,602 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::{config::Ports, facts::Memory, layout::Dirs, profile::KarSource}; +use std::collections::BTreeMap; + +fn gpu(total: u64, free: u64) -> Gpu { + Gpu { + index: 0, + name: "NVIDIA GeForce RTX 5090".into(), + driver: "595.99".into(), + vram_total_mib: total, + vram_free_mib: free, + sm: Some(120), + } +} + +fn host(cores: u32, ram_gib: u64, avail_gib: u64, gpus: Vec) -> Facts { + Facts { + cpu_cores: cores, + memory: Memory { + total: ram_gib * GIB, + available: avail_gib * GIB, + swap_total: 0, + }, + gpus, + ..Facts::default() + } +} + +/// The server as `leleka up` left it (no preset): the dedicated profile of the RTX 5090. +fn server_config() -> RunConfig { + let dirs = Dirs { + prefix: "/opt/leleka".into(), + state: "/var/lib/leleka/state".into(), + assets: "/data".into(), + }; + let ports = Ports { + api: "127.0.0.1:8081".into(), + engine: "127.0.0.1:18766".into(), + daemon: "127.0.0.1:18080".into(), + }; + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + profile.memfd_extents = crate::profile::MemfdExtents::Full; // the tests describe the full copy; the shipped profile is `ple_only` + // `up` resolved the dedicated preset's worker count into the environment + let env = BTreeMap::from([(CPU_WORKERS_ENV.to_owned(), "15".to_owned())]); + let mut config = RunConfig::new(&dirs, ports, 0, profile.clone(), env); + config.base_profile = Some(profile); + config +} + +fn request(budget: Option, preset: Option, settings: Value) -> Request { + Request { + id: "t".into(), + gpu_budget_gib: budget, + preset, + settings: settings.as_object().cloned().unwrap_or_default(), + persist: false, + } +} + +fn big_host() -> Facts { + host(32, 121, 100, vec![gpu(32607, 32100)]) +} + +#[test] +fn runtime_settings_become_profile_fields_with_the_engines_ranges() { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + let settings = json!({ + "context_tokens": 131072, "prefill_capacity": 4096, "kv_resident": 0, "prefix_cache_mib": "20480", + "prefix_cache_tail": "reply", "prefix_cache_block": 4096, "prefix_retention_min": 30, "cpu_workers": 6, "spec_min_p": 0.5 + }); + let changed = apply_settings(&mut profile, settings.as_object().unwrap()).unwrap(); + for name in [ + "context_tokens", + "prefill_capacity", + "prefix_cache_mib", + "prefix_cache_block", + "prefix_retention_min", + "cpu_workers", + "spec_min_p", + ] { + assert!(changed.iter().any(|c| c == name), "{name} in {changed:?}"); + } + assert_eq!( + ( + profile.context_tokens, + profile.prefill_capacity, + profile.kv_resident + ), + (131072, Some(4096), Some(0)) + ); + assert_eq!(profile.memory.prefix_cache_mib.as_deref(), Some("20480")); + assert_eq!(profile.memory.prefix_cache_tail.as_deref(), Some("reply")); + assert_eq!( + ( + profile.memory.prefix_cache_block, + profile.memory.prefix_retention_min + ), + (Some(4096), Some(30)) + ); + assert_eq!( + profile.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), + Some("6") + ); + assert_eq!(profile.spec_min_p, Some(0.5)); + // the same document again changes nothing + assert!( + apply_settings(&mut profile, settings.as_object().unwrap()) + .unwrap() + .is_empty() + ); + // and they reach the engine as flags and environment + let config = RunConfig::new( + &Dirs { + prefix: "/p".into(), + state: "/s".into(), + assets: "/a".into(), + }, + Ports { + api: "127.0.0.1:1".into(), + engine: "127.0.0.1:2".into(), + daemon: "127.0.0.1:3".into(), + }, + 0, + profile, + BTreeMap::new(), + ); + let args = config.engine_args(crate::config::KarArg::Fd).join(" "); + assert!( + args.contains("--context-tokens 131072") + && args.contains("--original-prefill-capacity 4096"), + "{args}" + ); + assert!( + args.contains("--kv-resident 0") && args.contains("--prefix-cache-mib 20480"), + "{args}" + ); + assert!( + args.contains("--prefix-cache-tail reply") + && args.contains("--prefix-cache-block 4096"), + "{args}" + ); + assert!(args.contains("--spec-min-p 0.5"), "{args}"); + let env = config.engine_environment(); + assert_eq!( + env.get("LELEKA_PREFIX_RETENTION_S").map(String::as_str), + Some("1800") + ); + assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("6")); +} + +#[test] +fn invalid_settings_change_nothing_and_say_why() { + for (bad, why) in [ + (json!({"context_tokens": 0}), "context_tokens"), + (json!({"context_tokens": 300000}), "context_tokens"), + (json!({"context_tokens": "big"}), "whole number"), + (json!({"prefill_capacity": 5000}), "prefill_capacity"), + (json!({"kv_resident": 1000}), "kv_resident"), + (json!({"cpu_workers": 0}), "cpu_workers"), + (json!({"cpu_workers": 65}), "cpu_workers"), + (json!({"spec_min_p": 1.5}), "spec_min_p"), + (json!({"prefix_cache_tail": "always"}), "prefix_cache_tail"), + (json!({"prefix_cache_mib": "lots"}), "prefix_cache_mib"), + (json!({"prefix_cache_block": 300}), "multiple of 256"), + ( + json!({"prefill_capacity": 4096, "prefix_cache_block": 8192}), + "larger than the prefill chunk", + ), + (json!({"nonsense": 1}), "unknown setting"), + ] { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + let before = profile.clone(); + let error = apply_settings(&mut profile, bad.as_object().unwrap()).unwrap_err(); + assert!(error.contains(why), "{bad}: {error}"); + assert_eq!(profile, before, "{bad} must change nothing"); + } +} + +#[test] +fn the_prefix_cache_can_be_switched_off_and_a_member_alone_turns_it_on() { + let mut profile = Profile::builtin("rtx5090-32g").unwrap(); + // a `ple_only` profile refuses an `auto` cache (the freed RAM would be refilled); the full form accepts it + profile.memfd_extents = crate::profile::MemfdExtents::Full; + profile.memory.prefix_cache_mib = None; + apply_settings( + &mut profile, + json!({"prefix_cache_tail": "prompt"}).as_object().unwrap(), + ) + .unwrap(); + assert_eq!( + profile.memory.prefix_cache_mib.as_deref(), + Some("auto"), + "the engine opens an auto cache for a lone member" + ); + apply_settings( + &mut profile, + json!({"prefix_cache_mib": "off"}).as_object().unwrap(), + ) + .unwrap(); + assert_eq!(profile.memory.prefix_cache_mib.as_deref(), Some("0")); + profile.memory.prefix_cache_block = Some(512); + let mut config = server_config(); + config.profile = profile; + let args = config.engine_args(crate::config::KarArg::Fd).join(" "); + assert!( + !args.contains("--prefix-cache-block"), + "a block is not passed while the cache is off: {args}" + ); +} + +#[test] +fn a_budget_change_is_planned_against_the_host_and_keeps_everything_else() { + let config = server_config(); + let planned = plan( + &config, + &request(Some(24), None, json!({})), + &big_host(), + true, + ) + .unwrap(); + assert!(!planned.unchanged); + assert_eq!(planned.config.profile.gpu_budget_bytes, 24 * GIB); + assert_eq!( + planned + .config + .base_profile + .as_ref() + .unwrap() + .gpu_budget_bytes, + 24 * GIB + ); + assert_eq!( + planned.config.profile.context_tokens, + config.profile.context_tokens + ); + assert_eq!(planned.config.preset, Preset::Dedicated); + let args = planned + .config + .engine_args(crate::config::KarArg::Fd) + .join(" "); + assert!( + args.contains(&format!("--gpu-budget {}", 24 * GIB)), + "{args}" + ); + // the same budget again is a no-op, not a five-minute restart + // (the shipped 5090 budget is 31,299 MiB, which a whole-GiB request cannot restate: the no-op is checked on the 24 GiB just planned) + let same = plan( + &planned.config, + &request(Some(24), None, json!({})), + &big_host(), + true, + ) + .unwrap(); + assert!(same.unchanged, "the profile already has a 24 GiB budget"); +} + +#[test] +fn the_workstation_preset_applies_and_dedicated_undoes_it() { + let config = server_config(); + let to_workstation = plan( + &config, + &request(None, Some(Preset::Workstation), json!({})), + &big_host(), + true, + ) + .unwrap(); + let ws = &to_workstation.config; + assert_eq!(ws.preset, Preset::Workstation); + assert_eq!( + ws.profile.gpu_budget_bytes, + 29 * GIB, + "32100 MiB free minus the 2 GiB left to the desktop" + ); + assert_eq!(ws.profile.memory.soft_floor_mib, Some(16384)); + assert_eq!( + ws.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), + Some("15") + ); + // back: the unmodified profile is restored from the recorded base + let back = plan( + ws, + &request(None, Some(Preset::Dedicated), json!({})), + &big_host(), + true, + ) + .unwrap(); + assert_eq!(back.config.profile, config.profile); + assert_eq!(back.config.preset, Preset::Dedicated); + // `--gpu-budget-gib N --preset workstation`: the explicit budget is what the engine gets, if the preset allows it + let both = plan( + &config, + &request(Some(24), Some(Preset::Workstation), json!({})), + &big_host(), + true, + ) + .unwrap(); + assert_eq!(both.config.profile.gpu_budget_bytes, 24 * GIB); + assert_eq!(both.config.preset, Preset::Workstation); + assert_eq!(both.config.profile.memory.soft_floor_mib, Some(16384)); +} + +#[test] +fn an_old_installation_without_a_recorded_base_cannot_undo_the_workstation_preset() { + let mut config = server_config(); + config.base_profile = None; + config.preset = Preset::Workstation; + let error = plan( + &config, + &request(None, Some(Preset::Dedicated), json!({})), + &big_host(), + true, + ) + .unwrap_err(); + assert!(error.contains("leleka up --preset dedicated"), "{error}"); + // staying on workstation, or going to it from dedicated, works without a base + assert!( + plan( + &config, + &request(Some(20), None, json!({})), + &big_host(), + true + ) + .is_ok() + ); + config.preset = Preset::Dedicated; + assert!( + plan( + &config, + &request(None, Some(Preset::Workstation), json!({})), + &big_host(), + true + ) + .is_ok() + ); +} + +#[test] +fn unsafe_values_are_refused_by_the_planner() { + let config = server_config(); + let refused = |request: Request, facts: &Facts, resident: bool| { + plan(&config, &request, facts, resident).unwrap_err() + }; + // more than the card has + let error = refused(request(Some(40), None, json!({})), &big_host(), true); + assert!(error.contains("does not fit the 32607 MiB"), "{error}"); + // not a budget at all + assert!(refused(request(Some(0), None, json!({})), &big_host(), true).contains("1..1024")); + assert!( + refused(request(Some(5000), None, json!({})), &big_host(), true).contains("1..1024") + ); + // another process holds the card (checked once the engine is stopped) + let busy = host(32, 121, 100, vec![gpu(32607, 9000)]); + let error = refused(request(Some(24), None, json!({})), &busy, true); + assert!( + error.contains("9000 MiB free") && error.contains("needs"), + "{error}" + ); + // the optimistic view, used before the engine is stopped, does not charge the engine's own VRAM + assert!( + plan( + &config, + &request(Some(24), None, json!({})), + &optimistic(&busy), + true + ) + .is_ok() + ); + // the workstation preset on a card that is mostly taken is a problem, not a silent shrink + let taken = host(32, 121, 100, vec![gpu(32607, 12000)]); + let error = refused( + request(None, Some(Preset::Workstation), json!({})), + &taken, + true, + ); + assert!(error.contains("workstation preset"), "{error}"); + // an explicit budget the preset cannot give + let error = refused( + request(Some(30), Some(Preset::Workstation), json!({})), + &big_host(), + true, + ); + assert!(error.contains("asks for more"), "{error}"); + // a bad runtime setting riding along refuses the whole request + assert!( + refused( + request(Some(24), None, json!({"cpu_workers": 99})), + &big_host(), + true + ) + .contains("cpu_workers") + ); + // a host too small to keep the sealed archive and the preset's free memory: refused rather than switched to the file form + let small = host(32, 64, 10, vec![gpu(32607, 32100)]); + let error = refused( + request(None, Some(Preset::Workstation), json!({})), + &small, + true, + ); + assert!( + error.contains("file-backed form") || error.contains("leleka up"), + "{error}" + ); +} + +#[test] +fn the_resident_archive_is_not_charged_twice_to_the_host() { + // 121 GiB host, 66 GiB available *with* the 55 GB memfd already resident (what the supervisor sees): fits the dedicated preset + let config = server_config(); + assert!( + plan( + &config, + &request(Some(20), None, json!({})), + &host(32, 121, 66, vec![gpu(32607, 32100)]), + true + ) + .is_ok() + ); + // a profile that reads the archive from a file keeps charging it to the planner as before + let mut file = server_config(); + file.profile.kar_source = KarSource::File; + file.base_profile = Some(file.profile.clone()); + assert!( + plan( + &file, + &request(Some(20), None, json!({})), + &host(32, 121, 40, vec![gpu(32607, 32100)]), + false + ) + .is_ok() + ); +} + +#[test] +fn recording_settings_updates_the_profile_and_the_base_and_lets_an_explicit_worker_count_win() { + let mut config = plan( + &server_config(), + &request(None, Some(Preset::Workstation), json!({})), + &big_host(), + true, + ) + .unwrap() + .config; + assert_eq!( + config.engine_env.get(CPU_WORKERS_ENV).map(String::as_str), + Some("15") + ); + let changed = record_settings( + &mut config, + json!({"context_tokens": 65536, "cpu_workers": 5}) + .as_object() + .unwrap(), + ) + .unwrap(); + assert_eq!( + changed, + vec!["context_tokens".to_owned(), "cpu_workers".to_owned()] + ); + assert_eq!(config.profile.context_tokens, 65536); + assert_eq!(config.base_profile.as_ref().unwrap().context_tokens, 65536); + assert_eq!( + config + .engine_environment() + .get(CPU_WORKERS_ENV) + .map(String::as_str), + Some("5") + ); + // an invalid document leaves the configuration alone + let before = config.clone(); + assert!( + record_settings( + &mut config, + json!({"context_tokens": 0}).as_object().unwrap() + ) + .is_err() + ); + assert_eq!(config, before); + // switching preset afterwards keeps the explicit setting + let again = plan( + &config, + &request(None, Some(Preset::Dedicated), json!({})), + &big_host(), + true, + ) + .unwrap() + .config; + assert_eq!(again.profile.context_tokens, 65536); + assert_eq!( + again + .engine_environment() + .get(CPU_WORKERS_ENV) + .map(String::as_str), + Some("5") + ); +} + +#[test] +fn the_request_and_answer_files_round_trip_and_a_request_runs_once() { + let root = std::env::temp_dir().join(format!("leleka-reconf-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let dirs = Dirs { + prefix: root.join("p"), + state: root.join("s"), + assets: root.join("a"), + }; + let paths = dirs.paths(); + std::fs::create_dir_all(paths.run_dir()).unwrap(); + assert!(take_request(&paths).is_none()); + let asked = request( + Some(24), + Some(Preset::Workstation), + json!({"context_tokens": 65536}), + ); + write_request(&paths, &asked).unwrap(); + assert!( + write_request(&paths, &asked) + .unwrap_err() + .contains("waiting") + ); + assert_eq!(take_request(&paths).unwrap().unwrap(), asked); + assert!(take_request(&paths).is_none(), "the file is consumed"); + // a corrupt request is reported, not retried forever + std::fs::write(paths.reconfigure_request(), "{not json").unwrap(); + assert!( + take_request(&paths) + .unwrap() + .unwrap_err() + .contains("invalid") + ); + assert!(!paths.reconfigure_request().exists()); + let outcome = Outcome { + id: asked.id.clone(), + state: State::Refused, + message: "no".into(), + effective: None, + persisted: false, + }; + write_outcome(&paths, &outcome).unwrap(); + assert_eq!(read_outcome(&paths, &asked.id), Some(outcome)); + assert_eq!(read_outcome(&paths, "other"), None); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn persisting_writes_a_private_config_that_reads_back_and_refreshes_the_api_context() { + let root = std::env::temp_dir().join(format!("leleka-persist-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let dirs = Dirs { + prefix: root.join("p"), + state: root.join("s"), + assets: root.join("a"), + }; + let paths = dirs.paths(); + std::fs::create_dir_all(paths.run_dir()).unwrap(); + let mut config = server_config(); + config.prefix = dirs.prefix.display().to_string(); + config.state = dirs.state.display().to_string(); + config.assets = dirs.assets.display().to_string(); + persist(&paths, &config).unwrap(); + let changed = persist_offline( + &paths, + json!({"context_tokens": 100000, "prefix_cache_tail": "prompt"}) + .as_object() + .unwrap(), + ) + .unwrap(); + assert_eq!(changed.len(), 2); + let back = RunConfig::read(&paths.run_config()).unwrap(); + assert_eq!(back.profile.context_tokens, 100000); + assert_eq!( + back.profile.memory.prefix_cache_tail.as_deref(), + Some("prompt") + ); + let strata: Value = + serde_json::from_str(&std::fs::read_to_string(paths.strata_config()).unwrap()).unwrap(); + assert_eq!(strata["runtime"]["max_context"], 100000); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(paths.run_config()) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o600); + } + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn the_effective_summary_names_the_numbers_in_force() { + let summary = effective(&server_config()); + // the 5090 profile ships 32819404800 bytes (31,299 MiB, "31,300 MiB" in the slots-footprint notes), the budget the dense-slab slot gain needs + assert_eq!( + summary["gpu_budget_gib"], + 32819404800_f64 / (1u64 << 30) as f64 + ); + assert_eq!(summary["preset"], "dedicated"); + assert_eq!(summary["context_tokens"], 262144); + assert_eq!(summary["cpu_workers"], 15); +} diff --git a/crates/deploy/src/sealed.rs b/crates/deploy/src/sealed.rs index da9fddac..d885108b 100644 --- a/crates/deploy/src/sealed.rs +++ b/crates/deploy/src/sealed.rs @@ -704,66 +704,4 @@ mod linux { } #[cfg(test)] -mod tests { - use super::*; - - fn words(text: &str) -> Vec { - text.split_whitespace().map(str::to_owned).collect() - } - - #[test] - fn seal_exec_arguments_are_parsed_strictly() { - let plan = parse_seal_exec(&words( - "--file /a/b.kar --expect-bytes 55 --sparse-ple -- bash -c x{FD}", - )) - .unwrap(); - assert_eq!( - plan, - SealExecPlan { - file: "/a/b.kar".into(), - expect_bytes: Some(55), - sparse_ple: true, - command: words("bash -c x{FD}") - } - ); - let full = parse_seal_exec(&words("--file f -- true")).unwrap(); - assert!(!full.sparse_ple && full.expect_bytes.is_none()); - for bad in [ - "", - "--file f", - "--file f --", - "-- true", - "--file -- true", - "--file f --expect-bytes x -- true", - "--file f --expect-bytes -- true", - "--file f --bogus -- true", - "--file f true", - ] { - assert!(parse_seal_exec(&words(bad)).is_err(), "{bad:?}"); - } - } - - #[test] - fn archive_serve_extents_refuses_what_is_not_the_pinned_archive() { - let path = std::env::temp_dir().join(format!("leleka-not-a-kar-{}", std::process::id())); - std::fs::write(&path, vec![0u8; 4096]).unwrap(); - let error = archive_serve_extents(&path, 4096).unwrap_err(); - assert!(error.contains("not a valid KAR archive"), "{error}"); - assert!( - archive_serve_extents(std::path::Path::new("/definitely/not/here"), 1) - .unwrap_err() - .contains("cannot open") - ); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn placeholder_substitution() { - let args = vec![ - "--kar-archive-fd".to_owned(), - "{FD}".to_owned(), - "x{FD}y".to_owned(), - ]; - assert_eq!(substitute(&args, 7), ["--kar-archive-fd", "7", "x7y"]); - } -} +mod tests; diff --git a/crates/deploy/src/sealed/tests.rs b/crates/deploy/src/sealed/tests.rs new file mode 100644 index 00000000..40747681 --- /dev/null +++ b/crates/deploy/src/sealed/tests.rs @@ -0,0 +1,63 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn words(text: &str) -> Vec { + text.split_whitespace().map(str::to_owned).collect() +} + +#[test] +fn seal_exec_arguments_are_parsed_strictly() { + let plan = parse_seal_exec(&words( + "--file /a/b.kar --expect-bytes 55 --sparse-ple -- bash -c x{FD}", + )) + .unwrap(); + assert_eq!( + plan, + SealExecPlan { + file: "/a/b.kar".into(), + expect_bytes: Some(55), + sparse_ple: true, + command: words("bash -c x{FD}") + } + ); + let full = parse_seal_exec(&words("--file f -- true")).unwrap(); + assert!(!full.sparse_ple && full.expect_bytes.is_none()); + for bad in [ + "", + "--file f", + "--file f --", + "-- true", + "--file -- true", + "--file f --expect-bytes x -- true", + "--file f --expect-bytes -- true", + "--file f --bogus -- true", + "--file f true", + ] { + assert!(parse_seal_exec(&words(bad)).is_err(), "{bad:?}"); + } +} + +#[test] +fn archive_serve_extents_refuses_what_is_not_the_pinned_archive() { + let path = std::env::temp_dir().join(format!("leleka-not-a-kar-{}", std::process::id())); + std::fs::write(&path, vec![0u8; 4096]).unwrap(); + let error = archive_serve_extents(&path, 4096).unwrap_err(); + assert!(error.contains("not a valid KAR archive"), "{error}"); + assert!( + archive_serve_extents(std::path::Path::new("/definitely/not/here"), 1) + .unwrap_err() + .contains("cannot open") + ); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn placeholder_substitution() { + let args = vec![ + "--kar-archive-fd".to_owned(), + "{FD}".to_owned(), + "x{FD}y".to_owned(), + ]; + assert_eq!(substitute(&args, 7), ["--kar-archive-fd", "7", "x7y"]); +} diff --git a/crates/deploy/src/steps.rs b/crates/deploy/src/steps.rs index a049301e..5d000d17 100644 --- a/crates/deploy/src/steps.rs +++ b/crates/deploy/src/steps.rs @@ -1244,107 +1244,4 @@ pub fn config_of(ctx: &Context) -> Result<&RunConfig, String> { } #[cfg(test)] -mod tests { - use super::*; - - fn temp(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("leleka-steps-{}-{name}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn stamps_track_size_and_mtime() { - let dir = temp("stamp"); - let (a, b) = (dir.join("a.gguf"), dir.join("b.gguf")); - std::fs::write(&a, b"aaaa").unwrap(); - std::fs::write(&b, b"bb").unwrap(); - let stamp = dir.join("model.json"); - assert!(!stamp_current(&stamp, &[a.clone(), b.clone()])); - write_stamp(&stamp, "test", &[a.clone(), b.clone()]).unwrap(); - assert!(stamp_current(&stamp, &[a.clone(), b.clone()])); - std::fs::write(&b, b"bbb").unwrap(); - assert!( - !stamp_current(&stamp, &[a.clone(), b.clone()]), - "a changed size must invalidate the stamp" - ); - assert!(!stamp_current(&stamp, std::slice::from_ref(&a))); - std::fs::remove_file(&a).unwrap(); - assert!(!stamp_current(&stamp, &[a, b])); - std::fs::remove_dir_all(dir).unwrap(); - } - - #[test] - fn mtp_pack_root_is_found_in_a_subdirectory() { - let dir = temp("mtp"); - let nested = dir.join("data/mtp-rt"); - std::fs::create_dir_all(&nested).unwrap(); - assert_eq!(find_pack_root(&dir), None); - for name in MTP_FILES { - std::fs::write(nested.join(name), b"x").unwrap(); - } - assert_eq!(find_pack_root(&dir), Some(nested)); - std::fs::remove_dir_all(dir).unwrap(); - } - - /// Live: the real download path (curl, https only, size cap) through `provision` against the pinned upstream sources. - /// `cargo test -p leleka-deploy --lib -- --ignored provisions_the_pinned_table_from_upstream` - #[test] - #[ignore = "network"] - fn provisions_the_pinned_table_from_upstream() { - use crate::expert_profile::{ - FileState, Outcome, PINNED_BYTES, PINNED_SHA256, Request, SOURCES, file_state, - provision, - }; - let dir = temp("live"); - let dest = dir.join("data").join("expert-profile.bin"); - let log = dir.join("install.log"); - let tool = "curl"; - let request = Request { - dest: &dest, - expected: PINNED_SHA256, - local: None, - embedded: None, - sources: &SOURCES, - }; - let outcome = provision(&request, &mut |url, part| { - download_small(tool, url, part, &log) - }) - .unwrap(); - assert!(matches!(outcome, Outcome::Installed { .. }), "{outcome:?}"); - assert_eq!(file_state(&dest, PINNED_SHA256), FileState::Valid); - assert_eq!(std::fs::metadata(&dest).unwrap().len(), PINNED_BYTES); - assert!(!dest.with_extension("bin.part").exists()); - // A source that answers with something else fails closed: an https URL that is not the table. - let other = dir.join("other.bin"); - let bad = Request { - dest: &other, - expected: PINNED_SHA256, - local: None, - embedded: None, - sources: &[ - "https://raw.githubusercontent.com/Niko1221/Strata/41cf05a06a25dd29103b7b27a2279a3f60c21876/LICENSE", - ], - }; - let error = - provision(&bad, &mut |url, part| download_small(tool, url, part, &log)).unwrap_err(); - assert!( - error.contains("is not the expected") && !other.exists(), - "{error}" - ); - std::fs::remove_dir_all(dir).unwrap(); - } - - #[test] - fn sha256_of_a_file() { - let dir = temp("sha"); - let file = dir.join("f"); - std::fs::write(&file, b"abc").unwrap(); - assert_eq!( - sha256_file(&file).unwrap(), - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" - ); - std::fs::remove_dir_all(dir).unwrap(); - } -} +mod tests; diff --git a/crates/deploy/src/steps/tests.rs b/crates/deploy/src/steps/tests.rs new file mode 100644 index 00000000..7eb8f9fa --- /dev/null +++ b/crates/deploy/src/steps/tests.rs @@ -0,0 +1,104 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn temp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("leleka-steps-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn stamps_track_size_and_mtime() { + let dir = temp("stamp"); + let (a, b) = (dir.join("a.gguf"), dir.join("b.gguf")); + std::fs::write(&a, b"aaaa").unwrap(); + std::fs::write(&b, b"bb").unwrap(); + let stamp = dir.join("model.json"); + assert!(!stamp_current(&stamp, &[a.clone(), b.clone()])); + write_stamp(&stamp, "test", &[a.clone(), b.clone()]).unwrap(); + assert!(stamp_current(&stamp, &[a.clone(), b.clone()])); + std::fs::write(&b, b"bbb").unwrap(); + assert!( + !stamp_current(&stamp, &[a.clone(), b.clone()]), + "a changed size must invalidate the stamp" + ); + assert!(!stamp_current(&stamp, std::slice::from_ref(&a))); + std::fs::remove_file(&a).unwrap(); + assert!(!stamp_current(&stamp, &[a, b])); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn mtp_pack_root_is_found_in_a_subdirectory() { + let dir = temp("mtp"); + let nested = dir.join("data/mtp-rt"); + std::fs::create_dir_all(&nested).unwrap(); + assert_eq!(find_pack_root(&dir), None); + for name in MTP_FILES { + std::fs::write(nested.join(name), b"x").unwrap(); + } + assert_eq!(find_pack_root(&dir), Some(nested)); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// Live: the real download path (curl, https only, size cap) through `provision` against the pinned upstream sources. +/// `cargo test -p leleka-deploy --lib -- --ignored provisions_the_pinned_table_from_upstream` +#[test] +#[ignore = "network"] +fn provisions_the_pinned_table_from_upstream() { + use crate::expert_profile::{ + FileState, Outcome, PINNED_BYTES, PINNED_SHA256, Request, SOURCES, file_state, + provision, + }; + let dir = temp("live"); + let dest = dir.join("data").join("expert-profile.bin"); + let log = dir.join("install.log"); + let tool = "curl"; + let request = Request { + dest: &dest, + expected: PINNED_SHA256, + local: None, + embedded: None, + sources: &SOURCES, + }; + let outcome = provision(&request, &mut |url, part| { + download_small(tool, url, part, &log) + }) + .unwrap(); + assert!(matches!(outcome, Outcome::Installed { .. }), "{outcome:?}"); + assert_eq!(file_state(&dest, PINNED_SHA256), FileState::Valid); + assert_eq!(std::fs::metadata(&dest).unwrap().len(), PINNED_BYTES); + assert!(!dest.with_extension("bin.part").exists()); + // A source that answers with something else fails closed: an https URL that is not the table. + let other = dir.join("other.bin"); + let bad = Request { + dest: &other, + expected: PINNED_SHA256, + local: None, + embedded: None, + sources: &[ + "https://raw.githubusercontent.com/Niko1221/Strata/41cf05a06a25dd29103b7b27a2279a3f60c21876/LICENSE", + ], + }; + let error = + provision(&bad, &mut |url, part| download_small(tool, url, part, &log)).unwrap_err(); + assert!( + error.contains("is not the expected") && !other.exists(), + "{error}" + ); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn sha256_of_a_file() { + let dir = temp("sha"); + let file = dir.join("f"); + std::fs::write(&file, b"abc").unwrap(); + assert_eq!( + sha256_file(&file).unwrap(), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/deploy/src/winfront.rs b/crates/deploy/src/winfront.rs index 1cd9a25c..cc01337a 100644 --- a/crates/deploy/src/winfront.rs +++ b/crates/deploy/src/winfront.rs @@ -883,25 +883,4 @@ async fn doctor(args: &[String]) -> i32 { } #[cfg(test)] -mod tests { - use super::*; - - fn strings(items: &[&str]) -> Vec { - items.iter().map(|s| s.to_string()).collect() - } - - #[test] - fn the_route_flag_wins_over_the_environment_and_is_removed() { - let (route, rest) = - split_route(&strings(&["up", "--native", "--gpu", "0"]), Some("wsl")).unwrap(); - assert_eq!( - (route, rest), - (Some(Route::Native), strings(&["up", "--gpu", "0"])) - ); - let (route, _) = split_route(&strings(&["up"]), Some("wsl")).unwrap(); - assert_eq!(route, Some(Route::Wsl)); - let (route, _) = split_route(&strings(&["up"]), None).unwrap(); - assert_eq!(route, None); - assert!(split_route(&strings(&["up"]), Some("docker")).is_err()); - } -} +mod tests; diff --git a/crates/deploy/src/winfront/tests.rs b/crates/deploy/src/winfront/tests.rs new file mode 100644 index 00000000..720ec339 --- /dev/null +++ b/crates/deploy/src/winfront/tests.rs @@ -0,0 +1,22 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn strings(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() +} + +#[test] +fn the_route_flag_wins_over_the_environment_and_is_removed() { + let (route, rest) = + split_route(&strings(&["up", "--native", "--gpu", "0"]), Some("wsl")).unwrap(); + assert_eq!( + (route, rest), + (Some(Route::Native), strings(&["up", "--gpu", "0"])) + ); + let (route, _) = split_route(&strings(&["up"]), Some("wsl")).unwrap(); + assert_eq!(route, Some(Route::Wsl)); + let (route, _) = split_route(&strings(&["up"]), None).unwrap(); + assert_eq!(route, None); + assert!(split_route(&strings(&["up"]), Some("docker")).is_err()); +} diff --git a/crates/deploy/src/wsl.rs b/crates/deploy/src/wsl.rs index 379957d4..9686b25e 100644 --- a/crates/deploy/src/wsl.rs +++ b/crates/deploy/src/wsl.rs @@ -493,206 +493,4 @@ pub fn list_distros(wsl: &Path) -> Result, String> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn utf16_wsl_output_is_decoded() { - let text = " NAME STATE VERSION\r\n* Ubuntu Running 2\r\n"; - let mut bytes = vec![0xff, 0xfe]; - for unit in text.encode_utf16() { - bytes.extend(unit.to_le_bytes()); - } - assert_eq!(decode_console_text(&bytes), text); - // Without a BOM, and plain UTF-8 from a Linux program. - let no_bom: Vec = text.encode_utf16().flat_map(u16::to_le_bytes).collect(); - assert_eq!(decode_console_text(&no_bom), text); - assert_eq!( - decode_console_text("/home/para\n".as_bytes()), - "/home/para\n" - ); - } - - #[test] - fn the_distribution_list_is_parsed_and_the_right_one_is_picked() { - let list = parse_distro_list( - " NAME STATE VERSION\r\n* docker-desktop Stopped 2\r\n Ubuntu Running 2\r\n Debian Stopped 1\r\n", - ); - assert_eq!(list.len(), 3); - assert!(list[0].default && list[0].name == "docker-desktop"); - // The default distribution belongs to Docker: skip it; Debian is WSL1: skip it too. - assert_eq!(pick_distro(&list, None).unwrap(), "Ubuntu"); - assert_eq!(pick_distro(&list, Some("ubuntu")).unwrap(), "Ubuntu"); - assert!( - pick_distro(&list, Some("Arch")) - .unwrap_err() - .contains("installed: docker-desktop, Ubuntu, Debian") - ); - assert!( - pick_distro(&list[..1], None) - .unwrap_err() - .contains("wsl --install") - ); - let two = parse_distro_list(" NAME STATE VERSION\n A Stopped 2\n* B Stopped 2\n"); - assert_eq!(pick_distro(&two, None).unwrap(), "B"); - assert!(parse_distro_list("garbage in\nthe output").is_empty()); - } - - #[test] - fn windows_paths_become_wsl_paths() { - let to = |p: &str| to_wsl_path(p, "Ubuntu", Some("/home/para")); - assert_eq!( - to("C:\\Users\\para\\leleka").unwrap(), - "/mnt/c/Users/para/leleka" - ); - assert_eq!(to("d:/models/").unwrap(), "/mnt/d/models"); - assert_eq!(to("C:\\").unwrap(), "/mnt/c"); - assert_eq!( - to("\\\\wsl.localhost\\Ubuntu\\home\\para\\laptop").unwrap(), - "/home/para/laptop" - ); - assert_eq!(to("\\\\wsl$\\ubuntu\\home\\para").unwrap(), "/home/para"); - assert!( - to("\\\\wsl$\\Debian\\home\\x") - .unwrap_err() - .contains("Debian") - ); - assert!( - to("\\\\fileserver\\share\\m") - .unwrap_err() - .contains("network share") - ); - assert_eq!(to("/home/para/laptop").unwrap(), "/home/para/laptop"); - assert_eq!(to("~/laptop").unwrap(), "/home/para/laptop"); - assert!(to("relative\\dir").unwrap_err().contains("absolute")); - assert!(to_wsl_path("~/x", "Ubuntu", None).is_err()); - assert!( - is_drvfs("/mnt/c/Users/x") - && is_drvfs("/mnt/d") - && !is_drvfs("/mnt/wsl/x") - && !is_drvfs("/home/para/mnt/c") - ); - assert_eq!( - linux_to_unc("Ubuntu", "/home/para/.local/state/leleka/api-key"), - "\\\\wsl.localhost\\Ubuntu\\home\\para\\.local\\state\\leleka\\api-key" - ); - } - - #[test] - fn forwarded_arguments_translate_only_the_path_flags() { - let args: Vec = [ - "--assets", - "\\\\wsl.localhost\\Ubuntu\\home\\para\\laptop", - "--state-dir=~/state", - "--gpu", - "0", - "--foreground", - "--wsl-distro", - "Ubuntu", - "--profile", - "rtx3080-16g", - "--api-port", - "9000", - "--cublas-dir", - "C:\\cuda\\bin", - ] - .iter() - .map(|s| s.to_string()) - .collect(); - let f = translate_args(&args, "Ubuntu", Some("/home/para")).unwrap(); - assert_eq!(f.distro.as_deref(), Some("Ubuntu")); - assert_eq!(f.assets.as_deref(), Some("/home/para/laptop")); - assert_eq!(f.state_dir.as_deref(), Some("/home/para/state")); - assert_eq!(f.api_port, Some(9000)); - assert_eq!( - f.args, - [ - "--assets", - "/home/para/laptop", - "--state-dir", - "/home/para/state", - "--gpu", - "0", - "--foreground", - "--profile", - "rtx3080-16g", - "--api-port", - "9000", - "--cublas-dir", - "/mnt/c/cuda/bin" - ] - ); - let profile = - translate_args(&["--profile".into(), "C:\\p\\mine.json".into()], "U", None).unwrap(); - assert_eq!(profile.args, ["--profile", "/mnt/c/p/mine.json"]); - assert!( - translate_args(&["--assets".into()], "U", None) - .unwrap_err() - .contains("needs a value") - ); - assert!( - translate_args(&["--assets".into(), "rel".into()], "U", None) - .unwrap_err() - .contains("--assets") - ); - } - - #[test] - fn wslconfig_is_parsed_and_judged() { - assert_eq!(parse_size("40GB"), Some(40 * GIB)); - assert_eq!(parse_size(" 49152 MB "), Some(48 * GIB)); - assert_eq!(parse_size("\"8g\""), Some(8 * GIB)); - assert_eq!(parse_size("lots"), None); - let config = parse_wslconfig( - "[boot]\nmemory=1GB\n[wsl2]\n# c\nMemory=40GB ; inline\nswap=8GB\nprocessors=12\n[experimental]\nmemory=2GB\n", - ); - assert_eq!( - config, - WslConfig { - memory_bytes: Some(40 * GIB), - swap_bytes: Some(8 * GIB), - processors: Some(12) - } - ); - // This laptop: 48 GB, memory=40GB swap=8GB -> fine. - assert_eq!(wslconfig_advice(&config, 48 * GIB, 32), None); - // No file at all: half of 48 GB, no swap. - let advice = wslconfig_advice(&WslConfig::default(), 48 * GIB, 32).unwrap(); - assert!( - advice.contains("24 GiB") - && advice.contains("memory=32GB") - && advice.contains("swap=8GB") - && advice.contains("wsl --shutdown"), - "{advice}" - ); - // Small host: at least 8 GiB stay with Windows. - let advice = wslconfig_advice(&WslConfig::default(), 32 * GIB, 32).unwrap(); - assert!(advice.contains("memory=24GB"), "{advice}"); - // Enough memory but no swap. - let only_memory = WslConfig { - memory_bytes: Some(40 * GIB), - ..WslConfig::default() - }; - assert!( - wslconfig_advice(&only_memory, 48 * GIB, 32) - .unwrap() - .contains("no swap") - ); - } - - #[test] - fn bridge_state_round_trips_through_the_profile_directory() { - let dir = std::env::temp_dir().join(format!("leleka-bridge-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - assert_eq!(BridgeState::read(&dir), None); - let state = BridgeState { - distro: "Ubuntu".into(), - leleka_bin: "/home/para/leleka-bin/leleka".into(), - state_dir: "/home/para/.local/state/leleka".into(), - api: "127.0.0.1:8081".into(), - }; - state.write(&dir).unwrap(); - assert_eq!(BridgeState::read(&dir), Some(state)); - std::fs::remove_dir_all(&dir).unwrap(); - } -} +mod tests; diff --git a/crates/deploy/src/wsl/tests.rs b/crates/deploy/src/wsl/tests.rs new file mode 100644 index 00000000..5a6643ea --- /dev/null +++ b/crates/deploy/src/wsl/tests.rs @@ -0,0 +1,203 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn utf16_wsl_output_is_decoded() { + let text = " NAME STATE VERSION\r\n* Ubuntu Running 2\r\n"; + let mut bytes = vec![0xff, 0xfe]; + for unit in text.encode_utf16() { + bytes.extend(unit.to_le_bytes()); + } + assert_eq!(decode_console_text(&bytes), text); + // Without a BOM, and plain UTF-8 from a Linux program. + let no_bom: Vec = text.encode_utf16().flat_map(u16::to_le_bytes).collect(); + assert_eq!(decode_console_text(&no_bom), text); + assert_eq!( + decode_console_text("/home/para\n".as_bytes()), + "/home/para\n" + ); +} + +#[test] +fn the_distribution_list_is_parsed_and_the_right_one_is_picked() { + let list = parse_distro_list( + " NAME STATE VERSION\r\n* docker-desktop Stopped 2\r\n Ubuntu Running 2\r\n Debian Stopped 1\r\n", + ); + assert_eq!(list.len(), 3); + assert!(list[0].default && list[0].name == "docker-desktop"); + // The default distribution belongs to Docker: skip it; Debian is WSL1: skip it too. + assert_eq!(pick_distro(&list, None).unwrap(), "Ubuntu"); + assert_eq!(pick_distro(&list, Some("ubuntu")).unwrap(), "Ubuntu"); + assert!( + pick_distro(&list, Some("Arch")) + .unwrap_err() + .contains("installed: docker-desktop, Ubuntu, Debian") + ); + assert!( + pick_distro(&list[..1], None) + .unwrap_err() + .contains("wsl --install") + ); + let two = parse_distro_list(" NAME STATE VERSION\n A Stopped 2\n* B Stopped 2\n"); + assert_eq!(pick_distro(&two, None).unwrap(), "B"); + assert!(parse_distro_list("garbage in\nthe output").is_empty()); +} + +#[test] +fn windows_paths_become_wsl_paths() { + let to = |p: &str| to_wsl_path(p, "Ubuntu", Some("/home/para")); + assert_eq!( + to("C:\\Users\\para\\leleka").unwrap(), + "/mnt/c/Users/para/leleka" + ); + assert_eq!(to("d:/models/").unwrap(), "/mnt/d/models"); + assert_eq!(to("C:\\").unwrap(), "/mnt/c"); + assert_eq!( + to("\\\\wsl.localhost\\Ubuntu\\home\\para\\laptop").unwrap(), + "/home/para/laptop" + ); + assert_eq!(to("\\\\wsl$\\ubuntu\\home\\para").unwrap(), "/home/para"); + assert!( + to("\\\\wsl$\\Debian\\home\\x") + .unwrap_err() + .contains("Debian") + ); + assert!( + to("\\\\fileserver\\share\\m") + .unwrap_err() + .contains("network share") + ); + assert_eq!(to("/home/para/laptop").unwrap(), "/home/para/laptop"); + assert_eq!(to("~/laptop").unwrap(), "/home/para/laptop"); + assert!(to("relative\\dir").unwrap_err().contains("absolute")); + assert!(to_wsl_path("~/x", "Ubuntu", None).is_err()); + assert!( + is_drvfs("/mnt/c/Users/x") + && is_drvfs("/mnt/d") + && !is_drvfs("/mnt/wsl/x") + && !is_drvfs("/home/para/mnt/c") + ); + assert_eq!( + linux_to_unc("Ubuntu", "/home/para/.local/state/leleka/api-key"), + "\\\\wsl.localhost\\Ubuntu\\home\\para\\.local\\state\\leleka\\api-key" + ); +} + +#[test] +fn forwarded_arguments_translate_only_the_path_flags() { + let args: Vec = [ + "--assets", + "\\\\wsl.localhost\\Ubuntu\\home\\para\\laptop", + "--state-dir=~/state", + "--gpu", + "0", + "--foreground", + "--wsl-distro", + "Ubuntu", + "--profile", + "rtx3080-16g", + "--api-port", + "9000", + "--cublas-dir", + "C:\\cuda\\bin", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let f = translate_args(&args, "Ubuntu", Some("/home/para")).unwrap(); + assert_eq!(f.distro.as_deref(), Some("Ubuntu")); + assert_eq!(f.assets.as_deref(), Some("/home/para/laptop")); + assert_eq!(f.state_dir.as_deref(), Some("/home/para/state")); + assert_eq!(f.api_port, Some(9000)); + assert_eq!( + f.args, + [ + "--assets", + "/home/para/laptop", + "--state-dir", + "/home/para/state", + "--gpu", + "0", + "--foreground", + "--profile", + "rtx3080-16g", + "--api-port", + "9000", + "--cublas-dir", + "/mnt/c/cuda/bin" + ] + ); + let profile = + translate_args(&["--profile".into(), "C:\\p\\mine.json".into()], "U", None).unwrap(); + assert_eq!(profile.args, ["--profile", "/mnt/c/p/mine.json"]); + assert!( + translate_args(&["--assets".into()], "U", None) + .unwrap_err() + .contains("needs a value") + ); + assert!( + translate_args(&["--assets".into(), "rel".into()], "U", None) + .unwrap_err() + .contains("--assets") + ); +} + +#[test] +fn wslconfig_is_parsed_and_judged() { + assert_eq!(parse_size("40GB"), Some(40 * GIB)); + assert_eq!(parse_size(" 49152 MB "), Some(48 * GIB)); + assert_eq!(parse_size("\"8g\""), Some(8 * GIB)); + assert_eq!(parse_size("lots"), None); + let config = parse_wslconfig( + "[boot]\nmemory=1GB\n[wsl2]\n# c\nMemory=40GB ; inline\nswap=8GB\nprocessors=12\n[experimental]\nmemory=2GB\n", + ); + assert_eq!( + config, + WslConfig { + memory_bytes: Some(40 * GIB), + swap_bytes: Some(8 * GIB), + processors: Some(12) + } + ); + // This laptop: 48 GB, memory=40GB swap=8GB -> fine. + assert_eq!(wslconfig_advice(&config, 48 * GIB, 32), None); + // No file at all: half of 48 GB, no swap. + let advice = wslconfig_advice(&WslConfig::default(), 48 * GIB, 32).unwrap(); + assert!( + advice.contains("24 GiB") + && advice.contains("memory=32GB") + && advice.contains("swap=8GB") + && advice.contains("wsl --shutdown"), + "{advice}" + ); + // Small host: at least 8 GiB stay with Windows. + let advice = wslconfig_advice(&WslConfig::default(), 32 * GIB, 32).unwrap(); + assert!(advice.contains("memory=24GB"), "{advice}"); + // Enough memory but no swap. + let only_memory = WslConfig { + memory_bytes: Some(40 * GIB), + ..WslConfig::default() + }; + assert!( + wslconfig_advice(&only_memory, 48 * GIB, 32) + .unwrap() + .contains("no swap") + ); +} + +#[test] +fn bridge_state_round_trips_through_the_profile_directory() { + let dir = std::env::temp_dir().join(format!("leleka-bridge-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(BridgeState::read(&dir), None); + let state = BridgeState { + distro: "Ubuntu".into(), + leleka_bin: "/home/para/leleka-bin/leleka".into(), + state_dir: "/home/para/.local/state/leleka".into(), + api: "127.0.0.1:8081".into(), + }; + state.write(&dir).unwrap(); + assert_eq!(BridgeState::read(&dir), Some(state)); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/experimental-ref/src/cache.rs b/crates/experimental-ref/src/cache.rs index 02129e7e..524d3705 100644 --- a/crates/experimental-ref/src/cache.rs +++ b/crates/experimental-ref/src/cache.rs @@ -330,100 +330,4 @@ pub fn half_bits(v: &[f32]) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - use crate::fwht; - - const S: QsaShapes = QsaShapes::real(); - - fn cell(seed: u64, scale: f32) -> Vec { - let mut s = seed | 1; - (0..512) - .map(|_| { - s ^= s << 13; - s ^= s >> 7; - s ^= s << 17; - ((s >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * scale - }) - .collect() - } - - fn identity_table(pages: usize) -> Vec { - (0..pages as i32).collect() - } - - #[test] - fn q4_round_trip_stays_within_half_a_step_in_the_rotated_domain() { - let pages = 4; - let rows = pages as u64 * S.rows_per_page(); - let mut pools = PoolSet::new(KvFormat::Q4_0, &S, rows).unwrap(); - let table = identity_table(pages); - let mut k = cell(1, 4.0); - let mut v = cell(2, 4.0); - fwht::fwht256_rows_in_place(&mut k); - fwht::fwht256_rows_in_place(&mut v); - append_cell(KvFormat::Q4_0, &mut pools, None, &table, 5, &k, &v, &S, Contraction::Separate).unwrap(); - let back = dequant_q4(&pools.k_q4, &table, &[5], &S).unwrap(); - for (i, (a, b)) in back.iter().zip(&k).enumerate() { - let blk = i / 32; - let amax = k[blk * 32..blk * 32 + 32].iter().fold(0f32, |m, x| m.max(x.abs())); - assert!((a - b).abs() <= amax / 8.0 * 1.01 + 1e-6, "{i}: {a} {b}"); - } - // nothing else was written - let gather = gather_q4(&pools.k_q4, &table, &[5], &S).unwrap(); - assert_eq!(gather.len(), 512); - let zero_cell = dequant_q4(&pools.k_q4, &table, &[0], &S).unwrap(); - assert!(zero_cell.iter().all(|x| *x == 0.0)); - } - - #[test] - fn streaming_write_rule_host_always_vram_only_when_resident() { - let pages = 4; - let rows = pages as u64 * S.rows_per_page(); - let mut pools = PoolSet::new(KvFormat::Int8, &S, rows).unwrap(); - let mut host = PoolSet::new(KvFormat::Int8, &S, rows).unwrap(); - let table = vec![-1, 0, -1, 1]; // blocks 0 and 2 not resident - let k = cell(3, 2.0); - let v = cell(4, 2.0); - for pos in 0..16 { - append_cell(KvFormat::Int8, &mut pools, Some(&mut host), &table, pos, &k, &v, &S, Contraction::Fused).unwrap(); - } - assert!(host.k_q.iter().any(|b| *b != 0)); - // resident slots (pages 0 and 1 of the VRAM pool) hold blocks 1 and 3, the rest is untouched - let row_bytes = 256; - let slot_rows = |p: usize| (p as u64 * S.rows_per_page()) as usize * row_bytes; - let per_page = S.rows_per_page() as usize * row_bytes; - assert_eq!(pools.k_q[slot_rows(0)..slot_rows(0) + per_page], host.k_q[slot_rows(1)..slot_rows(1) + per_page]); - assert_eq!(pools.k_q[slot_rows(1)..slot_rows(1) + per_page], host.k_q[slot_rows(3)..slot_rows(3) + per_page]); - assert!(pools.k_q[slot_rows(2)..].iter().all(|b| *b == 0)); - } - - #[test] - fn k8v4_composition_writes_int8_k_and_q4_v_only() { - let rows = 2 * S.rows_per_page(); - let mut pools = PoolSet::new(KvFormat::K8V4, &S, rows).unwrap(); - let table = identity_table(2); - let k = cell(5, 3.0); - let mut v = cell(6, 3.0); - fwht::fwht256_rows_in_place(&mut v); - append_cell(KvFormat::K8V4, &mut pools, None, &table, 0, &k, &v, &S, Contraction::Fused).unwrap(); - assert!(pools.k_q.iter().any(|b| *b != 0) && pools.v_q4.iter().any(|b| *b != 0)); - assert!(pools.v_q.is_empty() && pools.k_q4.is_empty()); - let kd = dequant_q8(&pools.k_q, &pools.k_scale, &table, &[0], &S).unwrap(); - for (a, b) in kd.iter().zip(&k) { - assert!((a - b).abs() < 0.05, "{a} {b}"); - } - } - - #[test] - fn fp16_is_refused_and_geometry_is_checked() { - assert_eq!(PoolSet::new(KvFormat::Fp16, &S, 4), Err(CacheError::UnsupportedFormat)); - let mut bad = S; - bad.head_dim = 128; - let mut p = PoolSet::new(KvFormat::Q4_0, &S, 8).unwrap(); - assert_eq!( - append_cell(KvFormat::Q4_0, &mut p, None, &[0, 1], 0, &[0.0; 256], &[0.0; 256], &bad, Contraction::Fused), - Err(CacheError::Geometry) - ); - } -} +mod tests; diff --git a/crates/experimental-ref/src/cache/tests.rs b/crates/experimental-ref/src/cache/tests.rs new file mode 100644 index 00000000..071cd210 --- /dev/null +++ b/crates/experimental-ref/src/cache/tests.rs @@ -0,0 +1,97 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::fwht; + +const S: QsaShapes = QsaShapes::real(); + +fn cell(seed: u64, scale: f32) -> Vec { + let mut s = seed | 1; + (0..512) + .map(|_| { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + ((s >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * scale + }) + .collect() +} + +fn identity_table(pages: usize) -> Vec { + (0..pages as i32).collect() +} + +#[test] +fn q4_round_trip_stays_within_half_a_step_in_the_rotated_domain() { + let pages = 4; + let rows = pages as u64 * S.rows_per_page(); + let mut pools = PoolSet::new(KvFormat::Q4_0, &S, rows).unwrap(); + let table = identity_table(pages); + let mut k = cell(1, 4.0); + let mut v = cell(2, 4.0); + fwht::fwht256_rows_in_place(&mut k); + fwht::fwht256_rows_in_place(&mut v); + append_cell(KvFormat::Q4_0, &mut pools, None, &table, 5, &k, &v, &S, Contraction::Separate).unwrap(); + let back = dequant_q4(&pools.k_q4, &table, &[5], &S).unwrap(); + for (i, (a, b)) in back.iter().zip(&k).enumerate() { + let blk = i / 32; + let amax = k[blk * 32..blk * 32 + 32].iter().fold(0f32, |m, x| m.max(x.abs())); + assert!((a - b).abs() <= amax / 8.0 * 1.01 + 1e-6, "{i}: {a} {b}"); + } + // nothing else was written + let gather = gather_q4(&pools.k_q4, &table, &[5], &S).unwrap(); + assert_eq!(gather.len(), 512); + let zero_cell = dequant_q4(&pools.k_q4, &table, &[0], &S).unwrap(); + assert!(zero_cell.iter().all(|x| *x == 0.0)); +} + +#[test] +fn streaming_write_rule_host_always_vram_only_when_resident() { + let pages = 4; + let rows = pages as u64 * S.rows_per_page(); + let mut pools = PoolSet::new(KvFormat::Int8, &S, rows).unwrap(); + let mut host = PoolSet::new(KvFormat::Int8, &S, rows).unwrap(); + let table = vec![-1, 0, -1, 1]; // blocks 0 and 2 not resident + let k = cell(3, 2.0); + let v = cell(4, 2.0); + for pos in 0..16 { + append_cell(KvFormat::Int8, &mut pools, Some(&mut host), &table, pos, &k, &v, &S, Contraction::Fused).unwrap(); + } + assert!(host.k_q.iter().any(|b| *b != 0)); + // resident slots (pages 0 and 1 of the VRAM pool) hold blocks 1 and 3, the rest is untouched + let row_bytes = 256; + let slot_rows = |p: usize| (p as u64 * S.rows_per_page()) as usize * row_bytes; + let per_page = S.rows_per_page() as usize * row_bytes; + assert_eq!(pools.k_q[slot_rows(0)..slot_rows(0) + per_page], host.k_q[slot_rows(1)..slot_rows(1) + per_page]); + assert_eq!(pools.k_q[slot_rows(1)..slot_rows(1) + per_page], host.k_q[slot_rows(3)..slot_rows(3) + per_page]); + assert!(pools.k_q[slot_rows(2)..].iter().all(|b| *b == 0)); +} + +#[test] +fn k8v4_composition_writes_int8_k_and_q4_v_only() { + let rows = 2 * S.rows_per_page(); + let mut pools = PoolSet::new(KvFormat::K8V4, &S, rows).unwrap(); + let table = identity_table(2); + let k = cell(5, 3.0); + let mut v = cell(6, 3.0); + fwht::fwht256_rows_in_place(&mut v); + append_cell(KvFormat::K8V4, &mut pools, None, &table, 0, &k, &v, &S, Contraction::Fused).unwrap(); + assert!(pools.k_q.iter().any(|b| *b != 0) && pools.v_q4.iter().any(|b| *b != 0)); + assert!(pools.v_q.is_empty() && pools.k_q4.is_empty()); + let kd = dequant_q8(&pools.k_q, &pools.k_scale, &table, &[0], &S).unwrap(); + for (a, b) in kd.iter().zip(&k) { + assert!((a - b).abs() < 0.05, "{a} {b}"); + } +} + +#[test] +fn fp16_is_refused_and_geometry_is_checked() { + assert_eq!(PoolSet::new(KvFormat::Fp16, &S, 4), Err(CacheError::UnsupportedFormat)); + let mut bad = S; + bad.head_dim = 128; + let mut p = PoolSet::new(KvFormat::Q4_0, &S, 8).unwrap(); + assert_eq!( + append_cell(KvFormat::Q4_0, &mut p, None, &[0, 1], 0, &[0.0; 256], &[0.0; 256], &bad, Contraction::Fused), + Err(CacheError::Geometry) + ); +} diff --git a/crates/experimental-ref/src/cvec.rs b/crates/experimental-ref/src/cvec.rs index 8a443292..6628af54 100644 --- a/crates/experimental-ref/src/cvec.rs +++ b/crates/experimental-ref/src/cvec.rs @@ -473,210 +473,4 @@ pub fn apply( } #[cfg(test)] -mod tests { - use super::*; - - // ---- a tiny GGUF writer for the tests (v3, F32 tensors) - fn gguf(arch: &str, hint: Option<&str>, tensors: &[(&str, Vec)]) -> Vec { - let mut b = Vec::new(); - let s = |b: &mut Vec, t: &str| { - b.extend_from_slice(&(t.len() as u64).to_le_bytes()); - b.extend_from_slice(t.as_bytes()); - }; - b.extend_from_slice(&0x4655_4747u32.to_le_bytes()); - b.extend_from_slice(&3u32.to_le_bytes()); - b.extend_from_slice(&(tensors.len() as u64).to_le_bytes()); - b.extend_from_slice(&(1 + u64::from(hint.is_some())).to_le_bytes()); - s(&mut b, "general.architecture"); - b.extend_from_slice(&8u32.to_le_bytes()); - s(&mut b, arch); - if let Some(h) = hint { - s(&mut b, "controlvector.model_hint"); - b.extend_from_slice(&8u32.to_le_bytes()); - s(&mut b, h); - } - let mut off = 0u64; - for (name, v) in tensors { - s(&mut b, name); - b.extend_from_slice(&1u32.to_le_bytes()); - b.extend_from_slice(&(v.len() as u64).to_le_bytes()); - b.extend_from_slice(&0u32.to_le_bytes()); - b.extend_from_slice(&off.to_le_bytes()); - off += (v.len() * 4).div_ceil(32) as u64 * 32; - } - while b.len() % 32 != 0 { - b.push(0); - } - for (_, v) in tensors { - for x in v { - b.extend_from_slice(&x.to_le_bytes()); - } - while b.len() % 32 != 0 { - b.push(0); - } - } - b - } - - fn vec_of(n: usize, seed: f32) -> Vec { - (0..n).map(|i| ((i as f32 + seed) * 0.37).sin()).collect() - } - - #[test] - fn parses_and_ignores_layer_zero_and_past_the_model() { - let n = 8; - let bytes = gguf("controlvector", Some("qwen4exp"), &[("direction.0", vec_of(n, 0.0)), ("direction.2", vec_of(n, 2.0)), ("direction.9", vec_of(n, 9.0))]); - let f = parse_gguf(&bytes).unwrap(); - assert_eq!(f.architecture.as_deref(), Some("controlvector")); - assert_eq!(f.model_hint.as_deref(), Some("qwen4exp")); - assert_eq!(f.tensors.len(), 3); - let t = load_control_vectors(&[("a.gguf".into(), bytes, 1.5)], 4, n as i64, 2, &CvecOptions::default()).unwrap(); - assert_eq!(t.summary, "add:1-3"); - assert!(t.covers(2) && !t.covers(1) && !t.covers(3) && !t.covers(0)); - let want = 1.5 * vec_of(n, 2.0)[3]; - assert_eq!(t.dir[2 * n + 3], want + 0.0); - } - - #[test] - fn project_mode_normalizes_and_scale_is_the_norm() { - let n = 16; - let d = vec_of(n, 1.0); - let bytes = gguf("controlvector", None, &[("direction.1", d.clone())]); - let o = CvecOptions { mode: CvecMode::Project, first: 1, last: 3, single: -1 }; - let t = load_control_vectors(&[("a".into(), bytes, 2.0)], 4, n as i64, 4, &o).unwrap(); - let nrm: f64 = d.iter().map(|v| f64::from(2.0 * v).powi(2)).sum::().sqrt(); - assert!((f64::from(t.s[1]) - nrm).abs() < 1e-5); - let unit: f64 = (0..n).map(|j| f64::from(t.dir[n + j]).powi(2)).sum(); - assert!((unit - 1.0).abs() < 1e-6); - assert_eq!(t.s[2], 0.0); // layer 2 has no direction - assert_eq!(t.summary, "project:1-3"); - } - - #[test] - fn single_layer_direction_steers_every_layer() { - let n = 8; - let bytes = gguf("controlvector", None, &[("direction.2", vec_of(n, 2.0))]); - let o = CvecOptions { mode: CvecMode::Project, first: 1, last: 3, single: 2 }; - let t = load_control_vectors(&[("a".into(), bytes.clone(), 1.0)], 4, n as i64, 2, &o).unwrap(); - assert!(t.covers(1) && t.covers(2) && t.covers(3)); - assert_eq!(t.summary, "project:1-3:single2"); - let o = CvecOptions { single: 3, ..o }; - assert_eq!( - load_control_vectors(&[("a".into(), bytes, 1.0)], 4, n as i64, 2, &o), - Err(CvecError::NoSingleDirection(3)) - ); - } - - #[test] - fn rejections() { - let n = 8; - let ok = gguf("controlvector", None, &[("direction.1", vec_of(n, 1.0))]); - let load = |bytes: Vec, o: CvecOptions| load_control_vectors(&[("f".into(), bytes, 1.0)], 4, n as i64, 2, &o); - let d = CvecOptions::default(); - assert!(matches!(load(gguf("llama", None, &[("direction.1", vec_of(n, 1.0))]), d), Err(CvecError::NotAControlVector(_)))); - assert!(matches!(load(gguf("controlvector", None, &[("direction.1", vec_of(n + 1, 1.0))]), d), Err(CvecError::BadTensor { .. }))); - assert!(matches!(load(gguf("controlvector", None, &[("foo", vec_of(n, 1.0))]), d), Err(CvecError::NoDirections(_)))); - assert!(matches!(load(ok[..20].to_vec(), d), Err(CvecError::Gguf(_)))); - let mut bad_magic = ok.clone(); - bad_magic[0] = 0; - assert!(matches!(load(bad_magic, d), Err(CvecError::Gguf(_)))); - // steered layers outside the requested range - let o = CvecOptions { first: 2, last: 3, ..d }; - assert_eq!(load(ok, o), Err(CvecError::NothingSteered { first: 2, last: 3 })); - // a zero direction in project mode is skipped - let zero = gguf("controlvector", None, &[("direction.1", vec![0.0; n])]); - assert!(matches!(load(zero, CvecOptions { mode: CvecMode::Project, ..d }), Err(CvecError::NothingSteered { .. }))); - assert_eq!(check_tables(&[0.0; 10], &[0.0; 2], 5), Ok(())); - assert_eq!(check_tables(&[0.0; 10], &[0.0; 2], 6), Err(CvecError::BadTables)); - assert_eq!(check_tables(&[], &[], 5), Err(CvecError::BadTables)); - assert_eq!(check_tables(&[0.0; 4097 * 2], &[0.0; 2], 4097), Err(CvecError::UnsupportedEmbd)); - } - - fn tables(mode: CvecMode, n: usize, hc: usize, layer: usize, l: usize, scale: f32) -> CvecTables { - let mut dir = vec![0.0f32; l * n]; - let mut s = vec![0.0f32; l]; - let v = vec_of(n, 3.0); - let nrm = v.iter().map(|x| f64::from(*x).powi(2)).sum::().sqrt(); - match mode { - CvecMode::Project => { - for j in 0..n { - dir[layer * n + j] = (f64::from(v[j]) / nrm) as f32; - } - s[layer] = scale; // s = 1 projects the direction out, s = 2 reflects the component - } - CvecMode::Add => { - dir[layer * n..(layer + 1) * n].copy_from_slice(&v); - s[layer] = 1.0; - } - } - let steered = s.iter().map(|x| *x != 0.0).collect(); - CvecTables { dir, s, mode, first: 1, last: l as i64 - 1, n_embd: n as i64, hc: hc as i64, steered, summary: String::new() } - } - - #[test] - fn project_removes_the_component_and_add_adds() { - let (n, hc, t_count) = (600usize, 3usize, 2usize); - let r_ld = hc * n; - let r0: Vec = (0..t_count * r_ld).map(|i| ((i * 7 % 13) as f32 - 6.0) * 0.3).collect(); - let tp = tables(CvecMode::Project, n, hc, 2, 4, 1.0); - let mut r = r0.clone(); - apply(&mut r, &tp, true, 2, t_count, r_ld, None); - for t in 0..t_count { - for c in 0..hc { - let after: f64 = (0..n).map(|j| f64::from(r[t * r_ld + c * n + j]) * f64::from(tp.dir[2 * n + j])).sum(); - assert!(after.abs() < 1e-3, "{after}"); - } - } - // off: unchanged - let mut r = r0.clone(); - apply(&mut r, &tp, false, 2, t_count, r_ld, None); - assert_eq!(r, r0); - // a layer without a direction is untouched - apply(&mut r, &tp, true, 1, t_count, r_ld, None); - assert_eq!(r, r0); - // add - let ta = tables(CvecMode::Add, n, hc, 2, 4, 1.0); - let mut r = r0.clone(); - apply(&mut r, &ta, true, 2, t_count, r_ld, None); - for t in 0..t_count { - for c in 0..hc { - for j in 0..n { - assert_eq!(r[t * r_ld + c * n + j], r0[t * r_ld + c * n + j] + ta.dir[2 * n + j]); - } - } - } - } - - #[test] - fn pending_write_is_applied_even_when_the_vector_is_off() { - let (n, hc) = (300usize, 2usize); - let r0: Vec = (0..hc * n).map(|i| (i % 11) as f32 * 0.1).collect(); - let bo: Vec = (0..n).map(|i| (i % 5) as f32 - 2.0).collect(); - let inj = vec![0.5f32, -1.0]; - let tp = tables(CvecMode::Project, n, hc, 2, 4, 1.0); - let mut r = r0.clone(); - apply(&mut r, &tp, false, 2, 1, hc * n, Some((&bo, n, &inj, hc))); - for c in 0..hc { - let w = 2.0 * sigmoid(inj[c] / hc as f32); - for j in 0..n { - assert_eq!(r[c * n + j], bo[j].mul_add(w, r0[c * n + j])); - } - } - } - - #[test] - fn warp_sum_is_a_butterfly_tree() { - let mut lanes = [0.0f32; 32]; - for (i, l) in lanes.iter_mut().enumerate() { - *l = (i + 1) as f32; - } - assert_eq!(warp_xor_sum(lanes), 528.0); - // lanes >= 8 zero: the final reduction of 8 warp partials - let mut p = [0.0f32; 32]; - for (i, l) in p.iter_mut().take(8).enumerate() { - *l = 1.0 / (i as f32 + 3.0); - } - let want = ((p[0] + p[4]) + (p[2] + p[6])) + ((p[1] + p[5]) + (p[3] + p[7])); - assert_eq!(warp_xor_sum(p), want); - } -} +mod tests; diff --git a/crates/experimental-ref/src/cvec/tests.rs b/crates/experimental-ref/src/cvec/tests.rs new file mode 100644 index 00000000..81e4d089 --- /dev/null +++ b/crates/experimental-ref/src/cvec/tests.rs @@ -0,0 +1,207 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +// ---- a tiny GGUF writer for the tests (v3, F32 tensors) +fn gguf(arch: &str, hint: Option<&str>, tensors: &[(&str, Vec)]) -> Vec { + let mut b = Vec::new(); + let s = |b: &mut Vec, t: &str| { + b.extend_from_slice(&(t.len() as u64).to_le_bytes()); + b.extend_from_slice(t.as_bytes()); + }; + b.extend_from_slice(&0x4655_4747u32.to_le_bytes()); + b.extend_from_slice(&3u32.to_le_bytes()); + b.extend_from_slice(&(tensors.len() as u64).to_le_bytes()); + b.extend_from_slice(&(1 + u64::from(hint.is_some())).to_le_bytes()); + s(&mut b, "general.architecture"); + b.extend_from_slice(&8u32.to_le_bytes()); + s(&mut b, arch); + if let Some(h) = hint { + s(&mut b, "controlvector.model_hint"); + b.extend_from_slice(&8u32.to_le_bytes()); + s(&mut b, h); + } + let mut off = 0u64; + for (name, v) in tensors { + s(&mut b, name); + b.extend_from_slice(&1u32.to_le_bytes()); + b.extend_from_slice(&(v.len() as u64).to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); + b.extend_from_slice(&off.to_le_bytes()); + off += (v.len() * 4).div_ceil(32) as u64 * 32; + } + while b.len() % 32 != 0 { + b.push(0); + } + for (_, v) in tensors { + for x in v { + b.extend_from_slice(&x.to_le_bytes()); + } + while b.len() % 32 != 0 { + b.push(0); + } + } + b +} + +fn vec_of(n: usize, seed: f32) -> Vec { + (0..n).map(|i| ((i as f32 + seed) * 0.37).sin()).collect() +} + +#[test] +fn parses_and_ignores_layer_zero_and_past_the_model() { + let n = 8; + let bytes = gguf("controlvector", Some("qwen4exp"), &[("direction.0", vec_of(n, 0.0)), ("direction.2", vec_of(n, 2.0)), ("direction.9", vec_of(n, 9.0))]); + let f = parse_gguf(&bytes).unwrap(); + assert_eq!(f.architecture.as_deref(), Some("controlvector")); + assert_eq!(f.model_hint.as_deref(), Some("qwen4exp")); + assert_eq!(f.tensors.len(), 3); + let t = load_control_vectors(&[("a.gguf".into(), bytes, 1.5)], 4, n as i64, 2, &CvecOptions::default()).unwrap(); + assert_eq!(t.summary, "add:1-3"); + assert!(t.covers(2) && !t.covers(1) && !t.covers(3) && !t.covers(0)); + let want = 1.5 * vec_of(n, 2.0)[3]; + assert_eq!(t.dir[2 * n + 3], want + 0.0); +} + +#[test] +fn project_mode_normalizes_and_scale_is_the_norm() { + let n = 16; + let d = vec_of(n, 1.0); + let bytes = gguf("controlvector", None, &[("direction.1", d.clone())]); + let o = CvecOptions { mode: CvecMode::Project, first: 1, last: 3, single: -1 }; + let t = load_control_vectors(&[("a".into(), bytes, 2.0)], 4, n as i64, 4, &o).unwrap(); + let nrm: f64 = d.iter().map(|v| f64::from(2.0 * v).powi(2)).sum::().sqrt(); + assert!((f64::from(t.s[1]) - nrm).abs() < 1e-5); + let unit: f64 = (0..n).map(|j| f64::from(t.dir[n + j]).powi(2)).sum(); + assert!((unit - 1.0).abs() < 1e-6); + assert_eq!(t.s[2], 0.0); // layer 2 has no direction + assert_eq!(t.summary, "project:1-3"); +} + +#[test] +fn single_layer_direction_steers_every_layer() { + let n = 8; + let bytes = gguf("controlvector", None, &[("direction.2", vec_of(n, 2.0))]); + let o = CvecOptions { mode: CvecMode::Project, first: 1, last: 3, single: 2 }; + let t = load_control_vectors(&[("a".into(), bytes.clone(), 1.0)], 4, n as i64, 2, &o).unwrap(); + assert!(t.covers(1) && t.covers(2) && t.covers(3)); + assert_eq!(t.summary, "project:1-3:single2"); + let o = CvecOptions { single: 3, ..o }; + assert_eq!( + load_control_vectors(&[("a".into(), bytes, 1.0)], 4, n as i64, 2, &o), + Err(CvecError::NoSingleDirection(3)) + ); +} + +#[test] +fn rejections() { + let n = 8; + let ok = gguf("controlvector", None, &[("direction.1", vec_of(n, 1.0))]); + let load = |bytes: Vec, o: CvecOptions| load_control_vectors(&[("f".into(), bytes, 1.0)], 4, n as i64, 2, &o); + let d = CvecOptions::default(); + assert!(matches!(load(gguf("llama", None, &[("direction.1", vec_of(n, 1.0))]), d), Err(CvecError::NotAControlVector(_)))); + assert!(matches!(load(gguf("controlvector", None, &[("direction.1", vec_of(n + 1, 1.0))]), d), Err(CvecError::BadTensor { .. }))); + assert!(matches!(load(gguf("controlvector", None, &[("foo", vec_of(n, 1.0))]), d), Err(CvecError::NoDirections(_)))); + assert!(matches!(load(ok[..20].to_vec(), d), Err(CvecError::Gguf(_)))); + let mut bad_magic = ok.clone(); + bad_magic[0] = 0; + assert!(matches!(load(bad_magic, d), Err(CvecError::Gguf(_)))); + // steered layers outside the requested range + let o = CvecOptions { first: 2, last: 3, ..d }; + assert_eq!(load(ok, o), Err(CvecError::NothingSteered { first: 2, last: 3 })); + // a zero direction in project mode is skipped + let zero = gguf("controlvector", None, &[("direction.1", vec![0.0; n])]); + assert!(matches!(load(zero, CvecOptions { mode: CvecMode::Project, ..d }), Err(CvecError::NothingSteered { .. }))); + assert_eq!(check_tables(&[0.0; 10], &[0.0; 2], 5), Ok(())); + assert_eq!(check_tables(&[0.0; 10], &[0.0; 2], 6), Err(CvecError::BadTables)); + assert_eq!(check_tables(&[], &[], 5), Err(CvecError::BadTables)); + assert_eq!(check_tables(&[0.0; 4097 * 2], &[0.0; 2], 4097), Err(CvecError::UnsupportedEmbd)); +} + +fn tables(mode: CvecMode, n: usize, hc: usize, layer: usize, l: usize, scale: f32) -> CvecTables { + let mut dir = vec![0.0f32; l * n]; + let mut s = vec![0.0f32; l]; + let v = vec_of(n, 3.0); + let nrm = v.iter().map(|x| f64::from(*x).powi(2)).sum::().sqrt(); + match mode { + CvecMode::Project => { + for j in 0..n { + dir[layer * n + j] = (f64::from(v[j]) / nrm) as f32; + } + s[layer] = scale; // s = 1 projects the direction out, s = 2 reflects the component + } + CvecMode::Add => { + dir[layer * n..(layer + 1) * n].copy_from_slice(&v); + s[layer] = 1.0; + } + } + let steered = s.iter().map(|x| *x != 0.0).collect(); + CvecTables { dir, s, mode, first: 1, last: l as i64 - 1, n_embd: n as i64, hc: hc as i64, steered, summary: String::new() } +} + +#[test] +fn project_removes_the_component_and_add_adds() { + let (n, hc, t_count) = (600usize, 3usize, 2usize); + let r_ld = hc * n; + let r0: Vec = (0..t_count * r_ld).map(|i| ((i * 7 % 13) as f32 - 6.0) * 0.3).collect(); + let tp = tables(CvecMode::Project, n, hc, 2, 4, 1.0); + let mut r = r0.clone(); + apply(&mut r, &tp, true, 2, t_count, r_ld, None); + for t in 0..t_count { + for c in 0..hc { + let after: f64 = (0..n).map(|j| f64::from(r[t * r_ld + c * n + j]) * f64::from(tp.dir[2 * n + j])).sum(); + assert!(after.abs() < 1e-3, "{after}"); + } + } + // off: unchanged + let mut r = r0.clone(); + apply(&mut r, &tp, false, 2, t_count, r_ld, None); + assert_eq!(r, r0); + // a layer without a direction is untouched + apply(&mut r, &tp, true, 1, t_count, r_ld, None); + assert_eq!(r, r0); + // add + let ta = tables(CvecMode::Add, n, hc, 2, 4, 1.0); + let mut r = r0.clone(); + apply(&mut r, &ta, true, 2, t_count, r_ld, None); + for t in 0..t_count { + for c in 0..hc { + for j in 0..n { + assert_eq!(r[t * r_ld + c * n + j], r0[t * r_ld + c * n + j] + ta.dir[2 * n + j]); + } + } + } +} + +#[test] +fn pending_write_is_applied_even_when_the_vector_is_off() { + let (n, hc) = (300usize, 2usize); + let r0: Vec = (0..hc * n).map(|i| (i % 11) as f32 * 0.1).collect(); + let bo: Vec = (0..n).map(|i| (i % 5) as f32 - 2.0).collect(); + let inj = vec![0.5f32, -1.0]; + let tp = tables(CvecMode::Project, n, hc, 2, 4, 1.0); + let mut r = r0.clone(); + apply(&mut r, &tp, false, 2, 1, hc * n, Some((&bo, n, &inj, hc))); + for c in 0..hc { + let w = 2.0 * sigmoid(inj[c] / hc as f32); + for j in 0..n { + assert_eq!(r[c * n + j], bo[j].mul_add(w, r0[c * n + j])); + } + } +} + +#[test] +fn warp_sum_is_a_butterfly_tree() { + let mut lanes = [0.0f32; 32]; + for (i, l) in lanes.iter_mut().enumerate() { + *l = (i + 1) as f32; + } + assert_eq!(warp_xor_sum(lanes), 528.0); + // lanes >= 8 zero: the final reduction of 8 warp partials + let mut p = [0.0f32; 32]; + for (i, l) in p.iter_mut().take(8).enumerate() { + *l = 1.0 / (i as f32 + 3.0); + } + let want = ((p[0] + p[4]) + (p[2] + p[6])) + ((p[1] + p[5]) + (p[3] + p[7])); + assert_eq!(warp_xor_sum(p), want); +} diff --git a/crates/experimental-ref/src/keyless.rs b/crates/experimental-ref/src/keyless.rs index 6f9d52e6..5a2bbdda 100644 --- a/crates/experimental-ref/src/keyless.rs +++ b/crates/experimental-ref/src/keyless.rs @@ -287,207 +287,4 @@ pub fn parse_artifact<'a>( } #[cfg(test)] -mod tests { - use super::*; - - fn identity_scaled(heads: usize, scale: f32) -> Vec { - let mut m = vec![0.0f32; heads * DIM * DIM]; - for h in 0..heads { - for d in 0..DIM { - m[(h * DIM + d) * DIM + d] = scale; - } - } - m - } - - #[test] - fn routing_by_identity_scales_the_query_and_heads_wrap_by_block() { - let (tokens, heads) = (2, 3); - let mut m = identity_scaled(heads, 1.0); - for d in 0..DIM { - m[(2 * DIM + d) * DIM + d] = 2.0; // head 2 doubles - } - let mut q: Vec = (0..tokens * heads * DIM).map(|i| (i % 7) as f32 - 3.0).collect(); - let orig = q.clone(); - route_query(&mut q, &m, tokens, heads).unwrap(); - for block in 0..tokens * heads { - let k = if block % heads == 2 { 2.0 } else { 1.0 }; - for d in 0..DIM { - assert_eq!(q[block * DIM + d], k * orig[block * DIM + d]); - } - } - } - - #[test] - fn routing_matrix_is_output_major() { - // matrix row 0 sums the first two inputs: out[0] = q0 + q1 - let mut m = vec![0.0f32; DIM * DIM]; - m[0] = 1.0; - m[1] = 1.0; - let mut q = vec![0.0f32; DIM]; - q[0] = 3.0; - q[1] = 4.0; - route_query(&mut q, &m, 1, 1).unwrap(); - assert_eq!(q[0], 7.0); - assert!(q[1..].iter().all(|v| *v == 0.0)); - assert_eq!(route_query(&mut [0.0; 10], &m, 1, 1), Err(KeylessError::Geometry)); - assert!(check_route_geometry(8, 24, 256).is_ok()); - assert!(check_route_geometry(8, 24, 128).is_err()); - assert!(check_route_geometry(i64::from(i32::MAX), 24, 256).is_err()); - } - - #[test] - fn mrope_is_the_cell_index_without_a_table() { - assert_eq!(mrope_pos(None, 17, 5), 17); - let tab = [10, 11, 12, 20, 21, 22]; - assert_eq!(mrope_pos(Some(&tab), 1, 0), 20); - assert_eq!(mrope_pos(Some(&tab), 1, 4), 21); // pair % 3 == 1: h - assert_eq!(mrope_pos(Some(&tab), 0, 5), 12); // pair % 3 == 2: w - } - - #[test] - fn key_reconstruction_rotates_the_first_64_dims_only() { - let v: Vec = (0..DIM).map(|i| i as f32 * 0.01).collect(); - // position 0: cos 1, sin 0 -> identity - let (mut cos, mut sin) = (vec![0.0f32; 4 * 32], vec![0.0f32; 4 * 32]); - for p in 0..4 { - for d in 0..32 { - let a = p as f32 * (d as f32 + 1.0) * 0.1; - cos[p * 32 + d] = a.cos(); - sin[p * 32 + d] = a.sin(); - } - } - assert_eq!(key_from_value(&v, 0, &cos, &sin, None), v); - let k = key_from_value(&v, 2, &cos, &sin, None); - assert_eq!(k[64..], v[64..]); - assert_ne!(k[..64], v[..64]); - // rotation preserves the norm of each (d, d + 32) pair - for d in 0..32 { - let n0 = v[d] * v[d] + v[d + 32] * v[d + 32]; - let n1 = k[d] * k[d] + k[d + 32] * k[d + 32]; - assert!((n0 - n1).abs() < 1e-5); - } - } - - // ------------------------------------------------------------------ artifact - struct Model { - g: KeylessGeometry, - // (layer, role) -> (kind, elements, data) - tensors: Vec<(u32, &'static str, i32, u64, Vec)>, - } - - fn small_model() -> Model { - let mut g = KeylessGeometry::real(); - g.qsa_layers = [3u32, 7].into_iter().collect(); - g.n_head = 2; - g.n_head_kv = 1; - g.n_embd = 256; - let mut tensors = Vec::new(); - for layer in [3u32, 7] { - for (role, mul) in [("q", 2 * 2u64), ("k", 1), ("v", 1)] { - let elements = 256 * 256 * mul; - // Q4_K: 256-element blocks of 144 bytes - let nbytes = (elements / 256 * 144) as usize; - let data: Vec = (0..nbytes).map(|i| ((i * 31 + layer as usize * 7 + role.len()) % 251) as u8).collect(); - tensors.push((layer, role, 12, elements, data)); - } - } - Model { g, tensors } - } - - fn write_artifact(m: &Model, matrix_value: f32) -> Vec { - let mut out = Vec::new(); - out.extend_from_slice(MAGIC); - for v in [1u32, m.g.qsa_layers.len() as u32, m.g.n_head, m.g.head_dim] { - out.extend_from_slice(&v.to_le_bytes()); - } - // layout of scripts/prepare-keyless-routing.py: "<8s4I", then per layer "(m: &'m Model) -> impl Fn(u32, &str) -> Option> + 'm { - move |layer, role| { - m.tensors - .iter() - .find(|t| t.0 == layer && t.1 == role) - .map(|t| SourceTensor { native_type: t.2, elements: t.3, data: &t.4 }) - } - } - - #[test] - fn artifact_round_trip_and_each_admission_failure() { - let m = small_model(); - let good = write_artifact(&m, 0.5); - let routing = parse_artifact(&good, &m.g, &lookup(&m)).unwrap(); - assert_eq!(routing.layers.len(), 2); - assert_eq!(routing.layer(7).unwrap().len(), 2 * DIM * DIM); - assert!(routing.layer(5).is_none()); - - let err = |bytes: &[u8]| parse_artifact(bytes, &m.g, &lookup(&m)).unwrap_err(); - let mut bad = good.clone(); - bad[0] = b'X'; - assert_eq!(err(&bad), KeylessError::Header); - let mut bad = good.clone(); - bad[8] = 2; // version - assert_eq!(err(&bad), KeylessError::Header); - let mut bad = good.clone(); - bad[12] = 3; // layers - assert_eq!(err(&bad), KeylessError::Header); - let mut bad = good.clone(); - bad[20] = 128; // head_dim - assert_eq!(err(&bad), KeylessError::Header); - let mut bad = good.clone(); - bad[24] = 5; // first layer id is not a QSA layer - assert_eq!(err(&bad), KeylessError::InvalidLayer(5)); - assert_eq!(err(&good[..good.len() - 1]), KeylessError::Truncated); - let mut bad = good.clone(); - bad.push(0); - assert_eq!(err(&bad), KeylessError::Trailing); - // matrix NaN - let mut bad = good.clone(); - let at = 24 + 4 + 3 * 20 + 16; - bad[at..at + 4].copy_from_slice(&f32::NAN.to_le_bytes()); - assert_eq!(err(&bad), KeylessError::NonFinite(3)); - // a different source tensor: fingerprint - let mut other = small_model(); - other.tensors[0].4[3] ^= 0xFF; - assert_eq!( - parse_artifact(&good, &m.g, &lookup(&other)).unwrap_err(), - KeylessError::Fingerprint { layer: 3, role: "q" } - ); - // a different encoding - let mut other = small_model(); - other.tensors[1].2 = 14; - assert_eq!( - parse_artifact(&good, &m.g, &lookup(&other)).unwrap_err(), - KeylessError::SourceMismatch { layer: 3, role: "k" } - ); - // duplicate layer - let mut dup = good.clone(); - let layer_len = 4 + 60 + m.g.n_head as usize * DIM * DIM * 4; - let first = dup[24..24 + 4].to_vec(); - dup[24 + layer_len..24 + layer_len + 4].copy_from_slice(&first); - assert_eq!(err(&dup), KeylessError::InvalidLayer(3)); - } - - #[test] - fn block_geometry_table() { - assert_eq!(block_geometry(42), Some((64, 18))); - assert_eq!(block_geometry(8), Some((32, 34))); - assert_eq!(block_geometry(12), Some((256, 144))); - assert_eq!(block_geometry(14), Some((256, 210))); - assert_eq!(block_geometry(1), None); - } -} +mod tests; diff --git a/crates/experimental-ref/src/keyless/tests.rs b/crates/experimental-ref/src/keyless/tests.rs new file mode 100644 index 00000000..14cd86e5 --- /dev/null +++ b/crates/experimental-ref/src/keyless/tests.rs @@ -0,0 +1,204 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn identity_scaled(heads: usize, scale: f32) -> Vec { + let mut m = vec![0.0f32; heads * DIM * DIM]; + for h in 0..heads { + for d in 0..DIM { + m[(h * DIM + d) * DIM + d] = scale; + } + } + m +} + +#[test] +fn routing_by_identity_scales_the_query_and_heads_wrap_by_block() { + let (tokens, heads) = (2, 3); + let mut m = identity_scaled(heads, 1.0); + for d in 0..DIM { + m[(2 * DIM + d) * DIM + d] = 2.0; // head 2 doubles + } + let mut q: Vec = (0..tokens * heads * DIM).map(|i| (i % 7) as f32 - 3.0).collect(); + let orig = q.clone(); + route_query(&mut q, &m, tokens, heads).unwrap(); + for block in 0..tokens * heads { + let k = if block % heads == 2 { 2.0 } else { 1.0 }; + for d in 0..DIM { + assert_eq!(q[block * DIM + d], k * orig[block * DIM + d]); + } + } +} + +#[test] +fn routing_matrix_is_output_major() { + // matrix row 0 sums the first two inputs: out[0] = q0 + q1 + let mut m = vec![0.0f32; DIM * DIM]; + m[0] = 1.0; + m[1] = 1.0; + let mut q = vec![0.0f32; DIM]; + q[0] = 3.0; + q[1] = 4.0; + route_query(&mut q, &m, 1, 1).unwrap(); + assert_eq!(q[0], 7.0); + assert!(q[1..].iter().all(|v| *v == 0.0)); + assert_eq!(route_query(&mut [0.0; 10], &m, 1, 1), Err(KeylessError::Geometry)); + assert!(check_route_geometry(8, 24, 256).is_ok()); + assert!(check_route_geometry(8, 24, 128).is_err()); + assert!(check_route_geometry(i64::from(i32::MAX), 24, 256).is_err()); +} + +#[test] +fn mrope_is_the_cell_index_without_a_table() { + assert_eq!(mrope_pos(None, 17, 5), 17); + let tab = [10, 11, 12, 20, 21, 22]; + assert_eq!(mrope_pos(Some(&tab), 1, 0), 20); + assert_eq!(mrope_pos(Some(&tab), 1, 4), 21); // pair % 3 == 1: h + assert_eq!(mrope_pos(Some(&tab), 0, 5), 12); // pair % 3 == 2: w +} + +#[test] +fn key_reconstruction_rotates_the_first_64_dims_only() { + let v: Vec = (0..DIM).map(|i| i as f32 * 0.01).collect(); + // position 0: cos 1, sin 0 -> identity + let (mut cos, mut sin) = (vec![0.0f32; 4 * 32], vec![0.0f32; 4 * 32]); + for p in 0..4 { + for d in 0..32 { + let a = p as f32 * (d as f32 + 1.0) * 0.1; + cos[p * 32 + d] = a.cos(); + sin[p * 32 + d] = a.sin(); + } + } + assert_eq!(key_from_value(&v, 0, &cos, &sin, None), v); + let k = key_from_value(&v, 2, &cos, &sin, None); + assert_eq!(k[64..], v[64..]); + assert_ne!(k[..64], v[..64]); + // rotation preserves the norm of each (d, d + 32) pair + for d in 0..32 { + let n0 = v[d] * v[d] + v[d + 32] * v[d + 32]; + let n1 = k[d] * k[d] + k[d + 32] * k[d + 32]; + assert!((n0 - n1).abs() < 1e-5); + } +} + +// ------------------------------------------------------------------ artifact +struct Model { + g: KeylessGeometry, + // (layer, role) -> (kind, elements, data) + tensors: Vec<(u32, &'static str, i32, u64, Vec)>, +} + +fn small_model() -> Model { + let mut g = KeylessGeometry::real(); + g.qsa_layers = [3u32, 7].into_iter().collect(); + g.n_head = 2; + g.n_head_kv = 1; + g.n_embd = 256; + let mut tensors = Vec::new(); + for layer in [3u32, 7] { + for (role, mul) in [("q", 2 * 2u64), ("k", 1), ("v", 1)] { + let elements = 256 * 256 * mul; + // Q4_K: 256-element blocks of 144 bytes + let nbytes = (elements / 256 * 144) as usize; + let data: Vec = (0..nbytes).map(|i| ((i * 31 + layer as usize * 7 + role.len()) % 251) as u8).collect(); + tensors.push((layer, role, 12, elements, data)); + } + } + Model { g, tensors } +} + +fn write_artifact(m: &Model, matrix_value: f32) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(MAGIC); + for v in [1u32, m.g.qsa_layers.len() as u32, m.g.n_head, m.g.head_dim] { + out.extend_from_slice(&v.to_le_bytes()); + } + // layout of scripts/prepare-keyless-routing.py: "<8s4I", then per layer "(m: &'m Model) -> impl Fn(u32, &str) -> Option> + 'm { + move |layer, role| { + m.tensors + .iter() + .find(|t| t.0 == layer && t.1 == role) + .map(|t| SourceTensor { native_type: t.2, elements: t.3, data: &t.4 }) + } +} + +#[test] +fn artifact_round_trip_and_each_admission_failure() { + let m = small_model(); + let good = write_artifact(&m, 0.5); + let routing = parse_artifact(&good, &m.g, &lookup(&m)).unwrap(); + assert_eq!(routing.layers.len(), 2); + assert_eq!(routing.layer(7).unwrap().len(), 2 * DIM * DIM); + assert!(routing.layer(5).is_none()); + + let err = |bytes: &[u8]| parse_artifact(bytes, &m.g, &lookup(&m)).unwrap_err(); + let mut bad = good.clone(); + bad[0] = b'X'; + assert_eq!(err(&bad), KeylessError::Header); + let mut bad = good.clone(); + bad[8] = 2; // version + assert_eq!(err(&bad), KeylessError::Header); + let mut bad = good.clone(); + bad[12] = 3; // layers + assert_eq!(err(&bad), KeylessError::Header); + let mut bad = good.clone(); + bad[20] = 128; // head_dim + assert_eq!(err(&bad), KeylessError::Header); + let mut bad = good.clone(); + bad[24] = 5; // first layer id is not a QSA layer + assert_eq!(err(&bad), KeylessError::InvalidLayer(5)); + assert_eq!(err(&good[..good.len() - 1]), KeylessError::Truncated); + let mut bad = good.clone(); + bad.push(0); + assert_eq!(err(&bad), KeylessError::Trailing); + // matrix NaN + let mut bad = good.clone(); + let at = 24 + 4 + 3 * 20 + 16; + bad[at..at + 4].copy_from_slice(&f32::NAN.to_le_bytes()); + assert_eq!(err(&bad), KeylessError::NonFinite(3)); + // a different source tensor: fingerprint + let mut other = small_model(); + other.tensors[0].4[3] ^= 0xFF; + assert_eq!( + parse_artifact(&good, &m.g, &lookup(&other)).unwrap_err(), + KeylessError::Fingerprint { layer: 3, role: "q" } + ); + // a different encoding + let mut other = small_model(); + other.tensors[1].2 = 14; + assert_eq!( + parse_artifact(&good, &m.g, &lookup(&other)).unwrap_err(), + KeylessError::SourceMismatch { layer: 3, role: "k" } + ); + // duplicate layer + let mut dup = good.clone(); + let layer_len = 4 + 60 + m.g.n_head as usize * DIM * DIM * 4; + let first = dup[24..24 + 4].to_vec(); + dup[24 + layer_len..24 + layer_len + 4].copy_from_slice(&first); + assert_eq!(err(&dup), KeylessError::InvalidLayer(3)); +} + +#[test] +fn block_geometry_table() { + assert_eq!(block_geometry(42), Some((64, 18))); + assert_eq!(block_geometry(8), Some((32, 34))); + assert_eq!(block_geometry(12), Some((256, 144))); + assert_eq!(block_geometry(14), Some((256, 210))); + assert_eq!(block_geometry(1), None); +} diff --git a/crates/experimental-ref/src/kv_stream.rs b/crates/experimental-ref/src/kv_stream.rs index ff2210e8..08649c3d 100644 --- a/crates/experimental-ref/src/kv_stream.rs +++ b/crates/experimental-ref/src/kv_stream.rs @@ -434,194 +434,4 @@ pub fn stage_from_host(stage: &mut PoolSet, host: &PoolSet, s: &QsaShapes, fmt: } #[cfg(test)] -mod tests { - use super::*; - - const S: QsaShapes = QsaShapes::real(); - - #[test] - fn plan_matches_the_documented_modes() { - let sw = PlanSwitches::default(); - // not streaming: all pages resident - let p = kv_plan(&S, 262_144, 0, 0, sw); - assert_eq!((p.mode, p.pages, p.slots, p.pooled_rows), (StreamMode::Resident, 65_536, 65_536, 65_538)); - // streaming 32768 cells of a 262144 context: 8192 slots - let p = kv_plan(&S, 262_144, 0, 32_768, sw); - assert_eq!((p.mode, p.slots), (StreamMode::Streamed, 8192)); - // below the minimum the minimum applies (20480 cells = 5120 slots) - let p = kv_plan(&S, 262_144, 0, 1000, sw); - assert_eq!((p.mode, p.slots), (StreamMode::Streamed, 5120)); - // a context that fits is not streamed - let p = kv_plan(&S, 16_384, 0, 20_480, sw); - assert_eq!(p.mode, StreamMode::Resident); - // the drafter's ring - let p = kv_plan(&S, 262_144, 256, 20_480, sw); - assert_eq!((p.mode, p.slots, p.pooled_rows), (StreamMode::Ring, 64, 2)); - // forced fully resident - assert_eq!(kv_plan(&S, 262_144, -1, 20_480, sw).mode, StreamMode::Resident); - // A/B switches - assert_eq!(kv_plan(&S, 262_144, 256, 20_480, PlanSwitches { ring_off: true, main_off: false }).mode, StreamMode::Resident); - assert_eq!(kv_plan(&S, 262_144, 0, 20_480, PlanSwitches { ring_off: false, main_off: true }).mode, StreamMode::Resident); - } - - #[test] - fn resolve_guards() { - assert_eq!(check_resolve(&S, 5120, 8, 2051), Ok(())); - assert_eq!(check_resolve(&S, 1000, 1, 70), Err(StreamError::TooFewSlots)); - assert_eq!(check_resolve(&S, 1024, 8, 2051), Err(StreamError::CallTooLarge)); - let mut odd = S; - odd.n_head_kv = 1; - odd.page_size = 1; // 1 x 1 x 4 groups x 2 B = 8 B per block run - assert_eq!(check_resolve(&odd, 5120, 1, 70), Err(StreamError::ScaleRunAlignment)); - } - - fn lcg(s: &mut u64) -> u32 { - *s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - (*s >> 32) as u32 - } - - /// Selections shaped like the indexer's: ascending, whole 4-cell blocks. - fn selection(seed: &mut u64, n_blocks: u32, nb: usize) -> Vec { - let mut blocks = std::collections::BTreeSet::new(); - while blocks.len() < nb { - blocks.insert((lcg(seed) % n_blocks) as i32); - } - blocks.into_iter().flat_map(|b| (0..4).map(move |i| b * 4 + i)).collect() - } - - fn run_calls(map: &mut StreamMap, calls: usize, nb: usize, n_q: usize) { - let cap = nb * 4; - let mut seed = 99u64; - for _ in 0..calls { - let mut ids = Vec::new(); - let mut steps = Vec::new(); - for _ in 0..n_q { - let sel = selection(&mut seed, map.page_table.len() as u32, nb); - steps.extend_from_slice(&[0, 0, 0, sel.len() as i32]); - ids.extend_from_slice(&sel); - } - let report = map.resolve(&ids, &steps, n_q, cap, 4, &MissOrder::Canonical).unwrap(); - assert_eq!(report.placed, report.misses); - assert!(map.is_consistent()); - // every selected block is resident after the call - for q in 0..n_q { - for i in 0..steps[q * 4 + 3] as usize { - assert!(map.page_table[(ids[q * cap + i] / 4) as usize] >= 0); - } - } - } - } - - #[test] - fn eviction_keeps_the_map_consistent_and_counters_add_up() { - let mut map = StreamMap::new(2000, 1100); - run_calls(&mut map, 60, 20, 3); - let c = map.counters(); - assert!(!c.overflow); - assert_eq!(c.calls, 60); - assert!(c.misses > 0 && c.misses < c.lookups, "{c:?}"); - assert_eq!(map.resident_blocks(), 1100.min(map.resident_blocks())); - assert!(map.resident_blocks() <= 1100); - // a repeated call is all hits - let ids: Vec = (0..40).collect(); - let steps = [0, 0, 0, 40]; - map.resolve(&ids, &steps, 1, 40, 4, &MissOrder::Canonical).unwrap(); - let before = map.counters().misses; - let r = map.resolve(&ids, &steps, 1, 40, 4, &MissOrder::Canonical).unwrap(); - assert_eq!(r.misses, 0); - assert_eq!(map.counters().misses, before); - } - - #[test] - fn a_slot_used_by_the_call_is_never_a_victim() { - let mut map = StreamMap::new(3000, 1030); - // fill every slot with blocks 0..1030 - for chunk in 0..(1030 / 40 + 1) { - let first = chunk * 40; - let ids: Vec = (first * 4..(first + 40) * 4).collect(); - let steps = [0, 0, 0, ids.len() as i32]; - map.resolve(&ids, &steps, 1, ids.len(), 4, &MissOrder::Canonical).unwrap(); - } - assert_eq!(map.resident_blocks(), 1030); - // one call that hits 40 resident blocks and misses 40 new ones: no hit block may be evicted - let mut ids: Vec = (100..140).flat_map(|b| (0..4).map(move |i| b * 4 + i)).collect(); - ids.extend((2000..2040).flat_map(|b| (0..4).map(move |i| b * 4 + i))); - let steps = [0, 0, 0, ids.len() as i32]; - map.resolve(&ids, &steps, 1, ids.len(), 4, &MissOrder::Canonical).unwrap(); - for b in 100..140 { - assert!(map.page_table[b] >= 0, "hit block {b} was evicted"); - } - for b in 2000..2040 { - assert!(map.page_table[b] >= 0); - } - } - - #[test] - fn observed_miss_order_changes_only_the_pairing_not_the_victim_set() { - let ids: Vec = [7, 3, 500, 9].iter().flat_map(|b: &i32| (0..4).map(move |i| b * 4 + i)).collect(); - // ids must be ascending for the dedupe; resolve a sorted selection - let mut sorted = ids.clone(); - sorted.sort_unstable(); - let steps = [0, 0, 0, sorted.len() as i32]; - let mut a = StreamMap::new(600, 1030); - let mut b = a.clone(); - a.resolve(&sorted, &steps, 1, sorted.len(), 4, &MissOrder::Canonical).unwrap(); - b.resolve(&sorted, &steps, 1, sorted.len(), 4, &MissOrder::Observed(vec![500, 9, 3, 7])).unwrap(); - let mut sa = a.miss_slot[..4].to_vec(); - let mut sb = b.miss_slot[..4].to_vec(); - sa.sort_unstable(); - sb.sort_unstable(); - assert_eq!(sa, sb); - assert_ne!(a.page_table, b.page_table); - assert!(a.is_consistent() && b.is_consistent()); - assert_eq!( - a.resolve(&sorted, &steps, 1, sorted.len(), 4, &MissOrder::Observed(vec![1, 2, 3, 4])), - Err(StreamError::BadMissOrder) - ); - } - - #[test] - fn too_many_distinct_blocks_for_the_slots_is_refused() { - let mut map = StreamMap::new(5000, 1024); - let ids: Vec = (0..1025 * 4).collect(); - let steps = [0, 0, 0, ids.len() as i32]; - assert_eq!( - map.resolve(&ids, &steps, 1, ids.len(), 4, &MissOrder::Canonical), - Err(StreamError::CallTooLarge) - ); - } - - #[test] - fn ring_table_and_restore() { - let t = ring_table(10, 4); - assert_eq!(t, [0, 1, 2, 3, 0, 1, 2, 3, 0, 1]); - let rows = 10 * S.rows_per_page(); - let mut host = PoolSet::new(KvFormat::Int8, &S, rows).unwrap(); - for (i, b) in host.k_q.iter_mut().enumerate() { - *b = (i % 251) as u8; - } - for (i, b) in host.k_scale.iter_mut().enumerate() { - *b = (i % 13) as u8; - } - let mut ring = PoolSet::new(KvFormat::Int8, &S, 4 * S.rows_per_page()).unwrap(); - ring_restore(&mut ring, &host, &S, StreamFormat::Int8, 6, 10, 4); - let len = 2048; // k_q bytes of a block - for b in 6..10 { - let sl = b % 4; - assert_eq!(ring.k_q[sl * len..(sl + 1) * len], host.k_q[b * len..(b + 1) * len]); - } - } - - #[test] - fn state_bytes_grow_with_resident_slots_only() { - let sw = PlanSwitches::default(); - let full = qsa_state_bytes(&S, KvFormat::Int8, 262_144, true, 0, 0, sw); - let streamed = qsa_state_bytes(&S, KvFormat::Int8, 262_144, true, 0, 20_480, sw); - assert!(streamed < full); - // the streamed state is the resident one minus the evicted pages' KV, plus the map - let removed = kv_pool_bytes(KvFormat::Int8, &S, 65_536) - kv_pool_bytes(KvFormat::Int8, &S, 5120); - assert_eq!(full - streamed, removed - map_bytes(5120) - 6 * 16); - assert_eq!(host_copy_bytes(&S, KvFormat::Int8, 65_536), Some(65_536 * 4224 + 1024)); - assert_eq!(host_copy_bytes(&S, KvFormat::K8V4, 10), None); - } -} +mod tests; diff --git a/crates/experimental-ref/src/kv_stream/tests.rs b/crates/experimental-ref/src/kv_stream/tests.rs new file mode 100644 index 00000000..efaa7a7e --- /dev/null +++ b/crates/experimental-ref/src/kv_stream/tests.rs @@ -0,0 +1,191 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +const S: QsaShapes = QsaShapes::real(); + +#[test] +fn plan_matches_the_documented_modes() { + let sw = PlanSwitches::default(); + // not streaming: all pages resident + let p = kv_plan(&S, 262_144, 0, 0, sw); + assert_eq!((p.mode, p.pages, p.slots, p.pooled_rows), (StreamMode::Resident, 65_536, 65_536, 65_538)); + // streaming 32768 cells of a 262144 context: 8192 slots + let p = kv_plan(&S, 262_144, 0, 32_768, sw); + assert_eq!((p.mode, p.slots), (StreamMode::Streamed, 8192)); + // below the minimum the minimum applies (20480 cells = 5120 slots) + let p = kv_plan(&S, 262_144, 0, 1000, sw); + assert_eq!((p.mode, p.slots), (StreamMode::Streamed, 5120)); + // a context that fits is not streamed + let p = kv_plan(&S, 16_384, 0, 20_480, sw); + assert_eq!(p.mode, StreamMode::Resident); + // the drafter's ring + let p = kv_plan(&S, 262_144, 256, 20_480, sw); + assert_eq!((p.mode, p.slots, p.pooled_rows), (StreamMode::Ring, 64, 2)); + // forced fully resident + assert_eq!(kv_plan(&S, 262_144, -1, 20_480, sw).mode, StreamMode::Resident); + // A/B switches + assert_eq!(kv_plan(&S, 262_144, 256, 20_480, PlanSwitches { ring_off: true, main_off: false }).mode, StreamMode::Resident); + assert_eq!(kv_plan(&S, 262_144, 0, 20_480, PlanSwitches { ring_off: false, main_off: true }).mode, StreamMode::Resident); +} + +#[test] +fn resolve_guards() { + assert_eq!(check_resolve(&S, 5120, 8, 2051), Ok(())); + assert_eq!(check_resolve(&S, 1000, 1, 70), Err(StreamError::TooFewSlots)); + assert_eq!(check_resolve(&S, 1024, 8, 2051), Err(StreamError::CallTooLarge)); + let mut odd = S; + odd.n_head_kv = 1; + odd.page_size = 1; // 1 x 1 x 4 groups x 2 B = 8 B per block run + assert_eq!(check_resolve(&odd, 5120, 1, 70), Err(StreamError::ScaleRunAlignment)); +} + +fn lcg(s: &mut u64) -> u32 { + *s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (*s >> 32) as u32 +} + +/// Selections shaped like the indexer's: ascending, whole 4-cell blocks. +fn selection(seed: &mut u64, n_blocks: u32, nb: usize) -> Vec { + let mut blocks = std::collections::BTreeSet::new(); + while blocks.len() < nb { + blocks.insert((lcg(seed) % n_blocks) as i32); + } + blocks.into_iter().flat_map(|b| (0..4).map(move |i| b * 4 + i)).collect() +} + +fn run_calls(map: &mut StreamMap, calls: usize, nb: usize, n_q: usize) { + let cap = nb * 4; + let mut seed = 99u64; + for _ in 0..calls { + let mut ids = Vec::new(); + let mut steps = Vec::new(); + for _ in 0..n_q { + let sel = selection(&mut seed, map.page_table.len() as u32, nb); + steps.extend_from_slice(&[0, 0, 0, sel.len() as i32]); + ids.extend_from_slice(&sel); + } + let report = map.resolve(&ids, &steps, n_q, cap, 4, &MissOrder::Canonical).unwrap(); + assert_eq!(report.placed, report.misses); + assert!(map.is_consistent()); + // every selected block is resident after the call + for q in 0..n_q { + for i in 0..steps[q * 4 + 3] as usize { + assert!(map.page_table[(ids[q * cap + i] / 4) as usize] >= 0); + } + } + } +} + +#[test] +fn eviction_keeps_the_map_consistent_and_counters_add_up() { + let mut map = StreamMap::new(2000, 1100); + run_calls(&mut map, 60, 20, 3); + let c = map.counters(); + assert!(!c.overflow); + assert_eq!(c.calls, 60); + assert!(c.misses > 0 && c.misses < c.lookups, "{c:?}"); + assert_eq!(map.resident_blocks(), 1100.min(map.resident_blocks())); + assert!(map.resident_blocks() <= 1100); + // a repeated call is all hits + let ids: Vec = (0..40).collect(); + let steps = [0, 0, 0, 40]; + map.resolve(&ids, &steps, 1, 40, 4, &MissOrder::Canonical).unwrap(); + let before = map.counters().misses; + let r = map.resolve(&ids, &steps, 1, 40, 4, &MissOrder::Canonical).unwrap(); + assert_eq!(r.misses, 0); + assert_eq!(map.counters().misses, before); +} + +#[test] +fn a_slot_used_by_the_call_is_never_a_victim() { + let mut map = StreamMap::new(3000, 1030); + // fill every slot with blocks 0..1030 + for chunk in 0..(1030 / 40 + 1) { + let first = chunk * 40; + let ids: Vec = (first * 4..(first + 40) * 4).collect(); + let steps = [0, 0, 0, ids.len() as i32]; + map.resolve(&ids, &steps, 1, ids.len(), 4, &MissOrder::Canonical).unwrap(); + } + assert_eq!(map.resident_blocks(), 1030); + // one call that hits 40 resident blocks and misses 40 new ones: no hit block may be evicted + let mut ids: Vec = (100..140).flat_map(|b| (0..4).map(move |i| b * 4 + i)).collect(); + ids.extend((2000..2040).flat_map(|b| (0..4).map(move |i| b * 4 + i))); + let steps = [0, 0, 0, ids.len() as i32]; + map.resolve(&ids, &steps, 1, ids.len(), 4, &MissOrder::Canonical).unwrap(); + for b in 100..140 { + assert!(map.page_table[b] >= 0, "hit block {b} was evicted"); + } + for b in 2000..2040 { + assert!(map.page_table[b] >= 0); + } +} + +#[test] +fn observed_miss_order_changes_only_the_pairing_not_the_victim_set() { + let ids: Vec = [7, 3, 500, 9].iter().flat_map(|b: &i32| (0..4).map(move |i| b * 4 + i)).collect(); + // ids must be ascending for the dedupe; resolve a sorted selection + let mut sorted = ids.clone(); + sorted.sort_unstable(); + let steps = [0, 0, 0, sorted.len() as i32]; + let mut a = StreamMap::new(600, 1030); + let mut b = a.clone(); + a.resolve(&sorted, &steps, 1, sorted.len(), 4, &MissOrder::Canonical).unwrap(); + b.resolve(&sorted, &steps, 1, sorted.len(), 4, &MissOrder::Observed(vec![500, 9, 3, 7])).unwrap(); + let mut sa = a.miss_slot[..4].to_vec(); + let mut sb = b.miss_slot[..4].to_vec(); + sa.sort_unstable(); + sb.sort_unstable(); + assert_eq!(sa, sb); + assert_ne!(a.page_table, b.page_table); + assert!(a.is_consistent() && b.is_consistent()); + assert_eq!( + a.resolve(&sorted, &steps, 1, sorted.len(), 4, &MissOrder::Observed(vec![1, 2, 3, 4])), + Err(StreamError::BadMissOrder) + ); +} + +#[test] +fn too_many_distinct_blocks_for_the_slots_is_refused() { + let mut map = StreamMap::new(5000, 1024); + let ids: Vec = (0..1025 * 4).collect(); + let steps = [0, 0, 0, ids.len() as i32]; + assert_eq!( + map.resolve(&ids, &steps, 1, ids.len(), 4, &MissOrder::Canonical), + Err(StreamError::CallTooLarge) + ); +} + +#[test] +fn ring_table_and_restore() { + let t = ring_table(10, 4); + assert_eq!(t, [0, 1, 2, 3, 0, 1, 2, 3, 0, 1]); + let rows = 10 * S.rows_per_page(); + let mut host = PoolSet::new(KvFormat::Int8, &S, rows).unwrap(); + for (i, b) in host.k_q.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + for (i, b) in host.k_scale.iter_mut().enumerate() { + *b = (i % 13) as u8; + } + let mut ring = PoolSet::new(KvFormat::Int8, &S, 4 * S.rows_per_page()).unwrap(); + ring_restore(&mut ring, &host, &S, StreamFormat::Int8, 6, 10, 4); + let len = 2048; // k_q bytes of a block + for b in 6..10 { + let sl = b % 4; + assert_eq!(ring.k_q[sl * len..(sl + 1) * len], host.k_q[b * len..(b + 1) * len]); + } +} + +#[test] +fn state_bytes_grow_with_resident_slots_only() { + let sw = PlanSwitches::default(); + let full = qsa_state_bytes(&S, KvFormat::Int8, 262_144, true, 0, 0, sw); + let streamed = qsa_state_bytes(&S, KvFormat::Int8, 262_144, true, 0, 20_480, sw); + assert!(streamed < full); + // the streamed state is the resident one minus the evicted pages' KV, plus the map + let removed = kv_pool_bytes(KvFormat::Int8, &S, 65_536) - kv_pool_bytes(KvFormat::Int8, &S, 5120); + assert_eq!(full - streamed, removed - map_bytes(5120) - 6 * 16); + assert_eq!(host_copy_bytes(&S, KvFormat::Int8, 65_536), Some(65_536 * 4224 + 1024)); + assert_eq!(host_copy_bytes(&S, KvFormat::K8V4, 10), None); +} diff --git a/crates/experimental-ref/src/layout.rs b/crates/experimental-ref/src/layout.rs index 3ca55293..8d01249d 100644 --- a/crates/experimental-ref/src/layout.rs +++ b/crates/experimental-ref/src/layout.rs @@ -331,134 +331,4 @@ pub const fn physical_row(s: &QsaShapes, page: u64, head: u64, slot: u64) -> u64 } #[cfg(test)] -mod tests { - use super::*; - - const S: QsaShapes = QsaShapes::real(); - - #[test] - fn per_cell_bytes_are_the_documented_figures() { - // Identical to crates/context memory_plan.rs (branch claude/port-rope) golden `kv_pool_bytes` rows. - assert_eq!(KvFormat::Fp16.bytes_per_cell(&S), 2048); - assert_eq!(KvFormat::Int8.bytes_per_cell(&S), 1056); - assert_eq!(KvFormat::Int8Rotated.bytes_per_cell(&S), 1056); - assert_eq!(KvFormat::Q4_0.bytes_per_cell(&S), 576); - assert_eq!(KvFormat::K8V4.bytes_per_cell(&S), 816); - assert_eq!(KvFormat::Int8Keyless.bytes_per_cell(&S), 528); - } - - #[test] - fn pool_arrays_sum_to_the_per_cell_cost() { - for fmt in KvFormat::ALL { - for slots in [1u64, 7, 5120] { - let cells = slots * S.page_size as u64; - let sum: u64 = pool_arrays(fmt, &S, slots).iter().map(|a| a.bytes).sum(); - assert_eq!(sum, cells * fmt.bytes_per_cell(&S), "{fmt:?} {slots}"); - // the Original's closed form stays within its `+ 64` slack plus the 4 x 16 cursor slack - let closed = kv_pool_bytes(fmt, &S, slots); - let arena = pool_arena_bytes(fmt, &S, slots); - assert!(arena <= closed + 4 * 16 && arena >= sum, "{fmt:?} {slots} {arena} {closed}"); - } - } - } - - #[test] - fn arrays_are_16_byte_aligned_and_disjoint() { - for fmt in KvFormat::ALL { - let a = pool_arrays(fmt, &S, 3); - for w in a.windows(2) { - assert!(w[0].offset + w[0].bytes <= w[1].offset); - } - assert!(a.iter().all(|x| x.offset % 16 == 0)); - } - } - - #[test] - fn array_order_matches_qsa_state_init() { - let names = |f| pool_arrays(f, &S, 1).iter().map(|a| a.name).collect::>(); - assert_eq!(names(KvFormat::K8V4), ["k_q", "k_scale", "v_q4"]); - assert_eq!(names(KvFormat::Q4_0), ["k_q4", "v_q4"]); - assert_eq!(names(KvFormat::Int8), ["k_q", "v_q", "k_scale", "v_scale"]); - assert_eq!(names(KvFormat::Int8Keyless), ["v_q", "v_scale"]); - assert_eq!(names(KvFormat::Fp16), ["k_pool", "v_pool"]); - } - - #[test] - fn block_bytes_follow_kv_stream_cu() { - // a block is one page (4 cells): cells x per-cell bytes for the formats that stream - for fmt in [KvFormat::Fp16, KvFormat::Int8, KvFormat::Q4_0, KvFormat::Int8Keyless] { - let sf = StreamFormat::of(fmt).unwrap(); - assert_eq!(kv_block_bytes(&S, sf), 4 * fmt.bytes_per_cell(&S), "{fmt:?}"); - assert_eq!( - stream_runs(&S, sf).iter().map(|r| r.1).sum::(), - kv_block_bytes(&S, sf) - ); - } - assert_eq!(kv_block_bytes(&S, StreamFormat::Int8), 4224); // the "4,224 B in int8" of kv_stream.hpp - assert!(StreamFormat::of(KvFormat::K8V4).is_none()); - } - - #[test] - fn stream_run_lengths_are_multiples_of_16_for_the_uint4_copy() { - for fmt in [StreamFormat::F16, StreamFormat::Int8, StreamFormat::Q4, StreamFormat::ValueInt8] { - assert!(stream_runs(&S, fmt).iter().all(|r| r.1 % 16 == 0), "{fmt:?}"); - } - } - - #[test] - fn selection_rules_are_those_of_generate_cpp() { - let req = |kv| KvRequest { - kv, - kv_rot: false, - keyless_routing: false, - kv_resident: 0, - gpu_stages: false, - diagnostic_dumps: false, - }; - assert_eq!(select_format(&req("fp16")), Ok(KvFormat::Fp16)); - assert_eq!(select_format(&req("q4")), Ok(KvFormat::Q4_0)); - assert_eq!(select_format(&req("q4_0")), Ok(KvFormat::Q4_0)); - assert_eq!(select_format(&req("k8v4")), Ok(KvFormat::K8V4)); - assert_eq!(select_format(&req("bf16")), Err(KvSelectionError::UnknownFormat)); - assert_eq!( - select_format(&KvRequest { kv_rot: true, ..req("int8") }), - Ok(KvFormat::Int8Rotated) - ); - let keyless = KvRequest { keyless_routing: true, ..req("int8") }; - assert_eq!(select_format(&keyless), Ok(KvFormat::Int8Keyless)); - for bad in [ - KvRequest { kv: "fp16", ..keyless }, - KvRequest { kv: "q4_0", ..keyless }, - KvRequest { gpu_stages: true, ..keyless }, - KvRequest { diagnostic_dumps: true, ..keyless }, - KvRequest { kv_rot: true, ..keyless }, - ] { - assert_eq!(select_format(&bad), Err(KvSelectionError::KeylessRequiresPlainInt8)); - } - assert_eq!( - select_format(&KvRequest { kv_resident: -1, ..req("int8") }), - Err(KvSelectionError::NegativeResident) - ); - assert_eq!( - select_format(&KvRequest { kv_resident: 20480, ..req("k8v4") }), - Err(KvSelectionError::K8V4NotStreamable) - ); - assert_eq!( - select_format(&KvRequest { kv_resident: 20480, ..req("q4_0") }), - Ok(KvFormat::Q4_0) - ); - } - - #[test] - fn experimental_flags() { - assert!(!KvFormat::Fp16.is_experimental() && !KvFormat::Int8.is_experimental()); - for f in [KvFormat::Int8Rotated, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { - assert!(f.is_experimental(), "{f:?}"); - } - assert!(KvFormat::K8V4.rotates_v() && !KvFormat::K8V4.rotates_k()); - assert!(KvFormat::K8V4.rotates_output() && !KvFormat::K8V4.rotates_query()); - assert!(KvFormat::Q4_0.rotates_query() && KvFormat::Q4_0.rotates_output()); - assert!(!KvFormat::Int8Keyless.has_k_store()); - assert_eq!(KvFormat::ALL.map(KvFormat::attention_mode), [0, 1, 1, 2, 3, 4]); - } -} +mod tests; diff --git a/crates/experimental-ref/src/layout/tests.rs b/crates/experimental-ref/src/layout/tests.rs new file mode 100644 index 00000000..d60d3d42 --- /dev/null +++ b/crates/experimental-ref/src/layout/tests.rs @@ -0,0 +1,131 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +const S: QsaShapes = QsaShapes::real(); + +#[test] +fn per_cell_bytes_are_the_documented_figures() { + // Identical to crates/context memory_plan.rs (branch claude/port-rope) golden `kv_pool_bytes` rows. + assert_eq!(KvFormat::Fp16.bytes_per_cell(&S), 2048); + assert_eq!(KvFormat::Int8.bytes_per_cell(&S), 1056); + assert_eq!(KvFormat::Int8Rotated.bytes_per_cell(&S), 1056); + assert_eq!(KvFormat::Q4_0.bytes_per_cell(&S), 576); + assert_eq!(KvFormat::K8V4.bytes_per_cell(&S), 816); + assert_eq!(KvFormat::Int8Keyless.bytes_per_cell(&S), 528); +} + +#[test] +fn pool_arrays_sum_to_the_per_cell_cost() { + for fmt in KvFormat::ALL { + for slots in [1u64, 7, 5120] { + let cells = slots * S.page_size as u64; + let sum: u64 = pool_arrays(fmt, &S, slots).iter().map(|a| a.bytes).sum(); + assert_eq!(sum, cells * fmt.bytes_per_cell(&S), "{fmt:?} {slots}"); + // the Original's closed form stays within its `+ 64` slack plus the 4 x 16 cursor slack + let closed = kv_pool_bytes(fmt, &S, slots); + let arena = pool_arena_bytes(fmt, &S, slots); + assert!(arena <= closed + 4 * 16 && arena >= sum, "{fmt:?} {slots} {arena} {closed}"); + } + } +} + +#[test] +fn arrays_are_16_byte_aligned_and_disjoint() { + for fmt in KvFormat::ALL { + let a = pool_arrays(fmt, &S, 3); + for w in a.windows(2) { + assert!(w[0].offset + w[0].bytes <= w[1].offset); + } + assert!(a.iter().all(|x| x.offset % 16 == 0)); + } +} + +#[test] +fn array_order_matches_qsa_state_init() { + let names = |f| pool_arrays(f, &S, 1).iter().map(|a| a.name).collect::>(); + assert_eq!(names(KvFormat::K8V4), ["k_q", "k_scale", "v_q4"]); + assert_eq!(names(KvFormat::Q4_0), ["k_q4", "v_q4"]); + assert_eq!(names(KvFormat::Int8), ["k_q", "v_q", "k_scale", "v_scale"]); + assert_eq!(names(KvFormat::Int8Keyless), ["v_q", "v_scale"]); + assert_eq!(names(KvFormat::Fp16), ["k_pool", "v_pool"]); +} + +#[test] +fn block_bytes_follow_kv_stream_cu() { + // a block is one page (4 cells): cells x per-cell bytes for the formats that stream + for fmt in [KvFormat::Fp16, KvFormat::Int8, KvFormat::Q4_0, KvFormat::Int8Keyless] { + let sf = StreamFormat::of(fmt).unwrap(); + assert_eq!(kv_block_bytes(&S, sf), 4 * fmt.bytes_per_cell(&S), "{fmt:?}"); + assert_eq!( + stream_runs(&S, sf).iter().map(|r| r.1).sum::(), + kv_block_bytes(&S, sf) + ); + } + assert_eq!(kv_block_bytes(&S, StreamFormat::Int8), 4224); // the "4,224 B in int8" of kv_stream.hpp + assert!(StreamFormat::of(KvFormat::K8V4).is_none()); +} + +#[test] +fn stream_run_lengths_are_multiples_of_16_for_the_uint4_copy() { + for fmt in [StreamFormat::F16, StreamFormat::Int8, StreamFormat::Q4, StreamFormat::ValueInt8] { + assert!(stream_runs(&S, fmt).iter().all(|r| r.1 % 16 == 0), "{fmt:?}"); + } +} + +#[test] +fn selection_rules_are_those_of_generate_cpp() { + let req = |kv| KvRequest { + kv, + kv_rot: false, + keyless_routing: false, + kv_resident: 0, + gpu_stages: false, + diagnostic_dumps: false, + }; + assert_eq!(select_format(&req("fp16")), Ok(KvFormat::Fp16)); + assert_eq!(select_format(&req("q4")), Ok(KvFormat::Q4_0)); + assert_eq!(select_format(&req("q4_0")), Ok(KvFormat::Q4_0)); + assert_eq!(select_format(&req("k8v4")), Ok(KvFormat::K8V4)); + assert_eq!(select_format(&req("bf16")), Err(KvSelectionError::UnknownFormat)); + assert_eq!( + select_format(&KvRequest { kv_rot: true, ..req("int8") }), + Ok(KvFormat::Int8Rotated) + ); + let keyless = KvRequest { keyless_routing: true, ..req("int8") }; + assert_eq!(select_format(&keyless), Ok(KvFormat::Int8Keyless)); + for bad in [ + KvRequest { kv: "fp16", ..keyless }, + KvRequest { kv: "q4_0", ..keyless }, + KvRequest { gpu_stages: true, ..keyless }, + KvRequest { diagnostic_dumps: true, ..keyless }, + KvRequest { kv_rot: true, ..keyless }, + ] { + assert_eq!(select_format(&bad), Err(KvSelectionError::KeylessRequiresPlainInt8)); + } + assert_eq!( + select_format(&KvRequest { kv_resident: -1, ..req("int8") }), + Err(KvSelectionError::NegativeResident) + ); + assert_eq!( + select_format(&KvRequest { kv_resident: 20480, ..req("k8v4") }), + Err(KvSelectionError::K8V4NotStreamable) + ); + assert_eq!( + select_format(&KvRequest { kv_resident: 20480, ..req("q4_0") }), + Ok(KvFormat::Q4_0) + ); +} + +#[test] +fn experimental_flags() { + assert!(!KvFormat::Fp16.is_experimental() && !KvFormat::Int8.is_experimental()); + for f in [KvFormat::Int8Rotated, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { + assert!(f.is_experimental(), "{f:?}"); + } + assert!(KvFormat::K8V4.rotates_v() && !KvFormat::K8V4.rotates_k()); + assert!(KvFormat::K8V4.rotates_output() && !KvFormat::K8V4.rotates_query()); + assert!(KvFormat::Q4_0.rotates_query() && KvFormat::Q4_0.rotates_output()); + assert!(!KvFormat::Int8Keyless.has_k_store()); + assert_eq!(KvFormat::ALL.map(KvFormat::attention_mode), [0, 1, 1, 2, 3, 4]); +} diff --git a/crates/experimental-ref/src/remote_experts.rs b/crates/experimental-ref/src/remote_experts.rs index f37d9b4a..8b2964e3 100644 --- a/crates/experimental-ref/src/remote_experts.rs +++ b/crates/experimental-ref/src/remote_experts.rs @@ -372,165 +372,4 @@ impl Totals { } #[cfg(test)] -mod tests { - use super::*; - - fn canonical() -> ExpertSizes { - ExpertSizes { native: false, max_blob: 1_382_400, blob_bytes: Vec::new() } - } - - #[test] - fn meta_layout_is_the_c_struct() { - assert_eq!(META_START_OFFSET, 640); - assert_eq!(META_DST_OFFSET, 964); - assert_eq!(META_TOK_OFFSET, 1284); - assert_eq!(META_COUNT_OFFSET, 1604); - assert_eq!(META_BYTES, 1608); - assert_eq!(CAP, 80); - } - - #[test] - fn selection_skips_primary_claimed_duplicates_and_out_of_range() { - let ranked = [(0, 1), (0, 1), (9, 0), (0, 99), (-1, 0), (1, 2), (2, 3), (1, 5), (3, 3)]; - let mut claimed = vec![0u8; 4 * 8]; - claimed[2 * 8 + 3] = 1; // (2,3) taken by another tier - let primary = |l: i32, e: i32| (l, e) == (1, 2); - let plan = plan_open(1, 2, 24 << 30, 3, 4, 8, &ranked, &primary, &mut claimed, &canonical()).unwrap(); - assert_eq!(plan.selected, [(0, 1), (1, 5), (3, 3)]); - assert_eq!(plan.slot_of(1, 5), 1); - assert_eq!(plan.slot_of(1, 2), -1); - assert_eq!(plan.layers_present, [1, 1, 0, 1]); - // claimed now marks the helper's experts, and nothing else new - let marked: Vec = claimed.iter().enumerate().filter(|(_, v)| **v == 1).map(|(i, _)| i).collect(); - assert_eq!(marked, [1, 2 * 8 + 3, 8 + 5, 3 * 8 + 3].iter().copied().collect::>().into_iter().collect::>()); - assert_eq!(plan.needed_bytes, 3 * 1_382_400); - } - - #[test] - fn open_failures_leave_claimed_untouched() { - let mut claimed = vec![0u8; 32]; - let none = |_: i32, _: i32| false; - let before = claimed.clone(); - let sizes = canonical(); - assert_eq!(plan_open(0, 2, 1 << 40, 2, 4, 8, &[(0, 0)], &none, &mut claimed, &sizes), Err(RemoteError::BadArguments)); - assert_eq!(plan_open(2, 2, 1 << 40, 2, 4, 8, &[(0, 0)], &none, &mut claimed, &sizes), Err(RemoteError::BadArguments)); - assert_eq!(plan_open(1, 2, 1 << 40, 0, 4, 8, &[(0, 0)], &none, &mut claimed, &sizes), Err(RemoteError::BadArguments)); - assert_eq!(plan_open(1, 2, 1 << 40, 2, 4, 8, &[], &none, &mut claimed, &sizes), Err(RemoteError::BadArguments)); - assert_eq!(plan_open(1, 2, 1 << 40, 2, 4, 7, &[(0, 0)], &none, &mut claimed, &sizes), Err(RemoteError::BadArguments)); - let all = |_: i32, _: i32| true; - assert_eq!(plan_open(1, 2, 1 << 40, 2, 4, 8, &[(0, 0)], &all, &mut claimed, &sizes), Err(RemoteError::NoUnclaimedExperts)); - // 2 slots of 1.38 MB plus 512 MiB do not fit in 512 MiB - let e = plan_open(1, 2, 512 << 20, 2, 4, 8, &[(0, 0), (0, 1)], &none, &mut claimed, &sizes).unwrap_err(); - assert!(matches!(e, RemoteError::SlotsLeaveLessThanReserve { .. })); - assert_eq!(e.message(1), "CUDA1 experts: slots leave less than 512 MiB free; reduce --expert-cache-device1"); - assert_eq!(claimed, before); - // the boundary is inclusive - let need = 2 * 1_382_400 + RESERVE_BYTES; - assert!(plan_open(1, 2, need, 2, 4, 8, &[(0, 0), (0, 1)], &none, &mut claimed, &sizes).is_ok()); - } - - #[test] - fn native_packs_round_slots_up_to_256_and_keep_each_layers_size() { - let sizes = ExpertSizes { native: true, max_blob: 2000, blob_bytes: vec![1000, 1025, 2000, 513] }; - assert_eq!(sizes.slot_cost(0), 1024); - assert_eq!(sizes.slot_cost(1), 1280); - let mut claimed = vec![0u8; 4 * 2]; - let none = |_: i32, _: i32| false; - let plan = plan_open(1, 2, 1 << 30, 3, 4, 2, &[(1, 0), (3, 1), (0, 0)], &none, &mut claimed, &sizes).unwrap(); - assert_eq!(plan.slot_sizes, [1025, 513, 1000]); - assert_eq!(plan.needed_bytes, 1280 + 768 + 1024); - } - - fn plan_for_dispatch() -> RemotePlan { - let mut claimed = vec![0u8; 3 * 16]; - let none = |_: i32, _: i32| false; - // layer 1 holds experts 4, 9, 2 (slots 0, 1, 2); layer 0 holds expert 7 (slot 3) - plan_open(1, 2, 1 << 40, 4, 3, 16, &[(1, 4), (1, 9), (1, 2), (0, 7)], &none, &mut claimed, &canonical()).unwrap() - } - - #[test] - fn dispatch_groups_by_expert_in_first_appearance_order() { - let plan = plan_for_dispatch(); - // 2 tokens x 10 routes; layer 1 - let mut ids = vec![0i32; 20]; - ids[..10].copy_from_slice(&[4, 3, 9, 5, 6, 8, 10, 11, 12, 13]); - ids[10..].copy_from_slice(&[9, 4, 1, 2, 0, 3, 5, 6, 7, 8]); - let d = dispatch(&plan, 1, &ids, 2, 10, None, None).unwrap(); - assert_eq!(d.groups, [Group { expert: 4, slot: 0 }, Group { expert: 9, slot: 1 }, Group { expert: 2, slot: 2 }]); - assert_eq!(d.start, [0, 2, 4, 5]); - assert_eq!(d.original_row, [0, 11, 2, 10, 13]); - assert_eq!(d.tok, [0, 1, 0, 1, 1]); - assert_eq!(d.dst, [0, 1, 2, 3, 4]); - assert_eq!(d.computed, 5); - assert_eq!(d.owned.iter().filter(|o| **o == 1).count(), 5); - assert_eq!(d.returned_bytes(), 5 * 2560 * 4); - assert_eq!(d.full_row_bytes(), 20 * 2560 * 4); - } - - #[test] - fn dispatch_respects_kind_primary_residency_and_missing_layers() { - let plan = plan_for_dispatch(); - let ids: Vec = vec![4, 9, 2, 0, 1, 3, 5, 6, 8, 10]; - let mut kind = vec![-1i32; 10]; - kind[1] = 2; // expert 9 was already served on the primary - let d = dispatch(&plan, 1, &ids, 1, 10, Some(&kind), None).unwrap(); - assert_eq!(d.original_row, [0, 2]); - // the primary holds expert 4 of layer 1 - let mut res = vec![-1i32; 3 * 16]; - res[16 + 4] = 5; - let d = dispatch(&plan, 1, &ids, 1, 10, None, Some(&res)).unwrap(); - assert_eq!(d.original_row, [1, 2]); - // a layer the helper holds nothing of - let d = dispatch(&plan, 2, &ids, 1, 10, None, None).unwrap(); - assert!(d.is_empty() && d.owned.iter().all(|o| *o == 0)); - assert!(d.start.is_empty()); - // out-of-range experts are ignored - let d = dispatch(&plan, 1, &[-3, 99, 4, 4, 4, 4, 4, 4, 4, 4], 1, 10, None, None).unwrap(); - assert_eq!(d.groups.len(), 1); - assert_eq!(d.original_row.len(), 8); - } - - #[test] - fn dispatch_validation() { - let plan = plan_for_dispatch(); - let ids = vec![0i32; 100]; - for (layer, n_tok, k) in [(1, 0, 10), (1, 9, 10), (1, 1, 9), (-1, 1, 10), (3, 1, 10)] { - assert_eq!(dispatch(&plan, layer, &ids, n_tok, k, None, None), Err(RemoteError::InvalidDispatch), "{layer} {n_tok} {k}"); - } - assert!(dispatch(&plan, 1, &ids, 8, 10, None, None).is_ok()); - } - - #[test] - fn meta_image_and_scatter() { - let plan = plan_for_dispatch(); - let ids: Vec = vec![4, 9, 4, 0, 1, 3, 5, 6, 8, 10]; - let d = dispatch(&plan, 1, &ids, 1, 10, None, None).unwrap(); - let img = RemoteMeta::to_bytes(&d, &|slot| 0x1000_0000 + slot as u64 * 0x10_0000); - assert_eq!(u64::from_le_bytes(img[0..8].try_into().unwrap()), 0x1000_0000); - assert_eq!(u64::from_le_bytes(img[8..16].try_into().unwrap()), 0x1010_0000); - assert_eq!(i32::from_le_bytes(img[META_START_OFFSET + 4..][..4].try_into().unwrap()), 2); - assert_eq!(i32::from_le_bytes(img[META_START_OFFSET + 8..][..4].try_into().unwrap()), 3); - assert_eq!(i32::from_le_bytes(img[META_COUNT_OFFSET..][..4].try_into().unwrap()), 2); - // scatter: compact rows of width 3 return to their routed rows - let h_out = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0]; - let mut out = vec![0.0f32; 10 * 3]; - scatter(&mut out, &h_out, &d.original_row, 3); - assert_eq!(&out[0..3], [1.0; 3]); - assert_eq!(&out[2 * 3..2 * 3 + 3], [2.0; 3]); - assert_eq!(&out[3..6], [3.0; 3]); // routed row 1 (expert 9) is the group after expert 4's - assert_eq!(out.iter().filter(|v| **v != 0.0).count(), 9); - } - - #[test] - fn device_buffers_fit_a_small_budget() { - // 80 entries x 2560 floats x 2, activation, scales, scratch, meta - let b = device_buffer_bytes(); - assert!(b > 2_000_000 && b < 8_000_000, "{b}"); - assert_eq!(moe_hit_grouped_scratch_bytes(0, 2560, 640), 0); - assert_eq!(native_expert_scratch_bytes(80, 640), 3 * 204_800 + ((80 * 20 * 36 + 255) & !255)); - let mut t = Totals::default(); - let d = dispatch(&plan_for_dispatch(), 1, &[4; 10], 1, 10, None, None).unwrap(); - t.record(&d); - assert_eq!((t.computed, t.launched_layers), (10, 1)); - } -} +mod tests; diff --git a/crates/experimental-ref/src/remote_experts/tests.rs b/crates/experimental-ref/src/remote_experts/tests.rs new file mode 100644 index 00000000..14bd9f12 --- /dev/null +++ b/crates/experimental-ref/src/remote_experts/tests.rs @@ -0,0 +1,162 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn canonical() -> ExpertSizes { + ExpertSizes { native: false, max_blob: 1_382_400, blob_bytes: Vec::new() } +} + +#[test] +fn meta_layout_is_the_c_struct() { + assert_eq!(META_START_OFFSET, 640); + assert_eq!(META_DST_OFFSET, 964); + assert_eq!(META_TOK_OFFSET, 1284); + assert_eq!(META_COUNT_OFFSET, 1604); + assert_eq!(META_BYTES, 1608); + assert_eq!(CAP, 80); +} + +#[test] +fn selection_skips_primary_claimed_duplicates_and_out_of_range() { + let ranked = [(0, 1), (0, 1), (9, 0), (0, 99), (-1, 0), (1, 2), (2, 3), (1, 5), (3, 3)]; + let mut claimed = vec![0u8; 4 * 8]; + claimed[2 * 8 + 3] = 1; // (2,3) taken by another tier + let primary = |l: i32, e: i32| (l, e) == (1, 2); + let plan = plan_open(1, 2, 24 << 30, 3, 4, 8, &ranked, &primary, &mut claimed, &canonical()).unwrap(); + assert_eq!(plan.selected, [(0, 1), (1, 5), (3, 3)]); + assert_eq!(plan.slot_of(1, 5), 1); + assert_eq!(plan.slot_of(1, 2), -1); + assert_eq!(plan.layers_present, [1, 1, 0, 1]); + // claimed now marks the helper's experts, and nothing else new + let marked: Vec = claimed.iter().enumerate().filter(|(_, v)| **v == 1).map(|(i, _)| i).collect(); + assert_eq!(marked, [1, 2 * 8 + 3, 8 + 5, 3 * 8 + 3].iter().copied().collect::>().into_iter().collect::>()); + assert_eq!(plan.needed_bytes, 3 * 1_382_400); +} + +#[test] +fn open_failures_leave_claimed_untouched() { + let mut claimed = vec![0u8; 32]; + let none = |_: i32, _: i32| false; + let before = claimed.clone(); + let sizes = canonical(); + assert_eq!(plan_open(0, 2, 1 << 40, 2, 4, 8, &[(0, 0)], &none, &mut claimed, &sizes), Err(RemoteError::BadArguments)); + assert_eq!(plan_open(2, 2, 1 << 40, 2, 4, 8, &[(0, 0)], &none, &mut claimed, &sizes), Err(RemoteError::BadArguments)); + assert_eq!(plan_open(1, 2, 1 << 40, 0, 4, 8, &[(0, 0)], &none, &mut claimed, &sizes), Err(RemoteError::BadArguments)); + assert_eq!(plan_open(1, 2, 1 << 40, 2, 4, 8, &[], &none, &mut claimed, &sizes), Err(RemoteError::BadArguments)); + assert_eq!(plan_open(1, 2, 1 << 40, 2, 4, 7, &[(0, 0)], &none, &mut claimed, &sizes), Err(RemoteError::BadArguments)); + let all = |_: i32, _: i32| true; + assert_eq!(plan_open(1, 2, 1 << 40, 2, 4, 8, &[(0, 0)], &all, &mut claimed, &sizes), Err(RemoteError::NoUnclaimedExperts)); + // 2 slots of 1.38 MB plus 512 MiB do not fit in 512 MiB + let e = plan_open(1, 2, 512 << 20, 2, 4, 8, &[(0, 0), (0, 1)], &none, &mut claimed, &sizes).unwrap_err(); + assert!(matches!(e, RemoteError::SlotsLeaveLessThanReserve { .. })); + assert_eq!(e.message(1), "CUDA1 experts: slots leave less than 512 MiB free; reduce --expert-cache-device1"); + assert_eq!(claimed, before); + // the boundary is inclusive + let need = 2 * 1_382_400 + RESERVE_BYTES; + assert!(plan_open(1, 2, need, 2, 4, 8, &[(0, 0), (0, 1)], &none, &mut claimed, &sizes).is_ok()); +} + +#[test] +fn native_packs_round_slots_up_to_256_and_keep_each_layers_size() { + let sizes = ExpertSizes { native: true, max_blob: 2000, blob_bytes: vec![1000, 1025, 2000, 513] }; + assert_eq!(sizes.slot_cost(0), 1024); + assert_eq!(sizes.slot_cost(1), 1280); + let mut claimed = vec![0u8; 4 * 2]; + let none = |_: i32, _: i32| false; + let plan = plan_open(1, 2, 1 << 30, 3, 4, 2, &[(1, 0), (3, 1), (0, 0)], &none, &mut claimed, &sizes).unwrap(); + assert_eq!(plan.slot_sizes, [1025, 513, 1000]); + assert_eq!(plan.needed_bytes, 1280 + 768 + 1024); +} + +fn plan_for_dispatch() -> RemotePlan { + let mut claimed = vec![0u8; 3 * 16]; + let none = |_: i32, _: i32| false; + // layer 1 holds experts 4, 9, 2 (slots 0, 1, 2); layer 0 holds expert 7 (slot 3) + plan_open(1, 2, 1 << 40, 4, 3, 16, &[(1, 4), (1, 9), (1, 2), (0, 7)], &none, &mut claimed, &canonical()).unwrap() +} + +#[test] +fn dispatch_groups_by_expert_in_first_appearance_order() { + let plan = plan_for_dispatch(); + // 2 tokens x 10 routes; layer 1 + let mut ids = vec![0i32; 20]; + ids[..10].copy_from_slice(&[4, 3, 9, 5, 6, 8, 10, 11, 12, 13]); + ids[10..].copy_from_slice(&[9, 4, 1, 2, 0, 3, 5, 6, 7, 8]); + let d = dispatch(&plan, 1, &ids, 2, 10, None, None).unwrap(); + assert_eq!(d.groups, [Group { expert: 4, slot: 0 }, Group { expert: 9, slot: 1 }, Group { expert: 2, slot: 2 }]); + assert_eq!(d.start, [0, 2, 4, 5]); + assert_eq!(d.original_row, [0, 11, 2, 10, 13]); + assert_eq!(d.tok, [0, 1, 0, 1, 1]); + assert_eq!(d.dst, [0, 1, 2, 3, 4]); + assert_eq!(d.computed, 5); + assert_eq!(d.owned.iter().filter(|o| **o == 1).count(), 5); + assert_eq!(d.returned_bytes(), 5 * 2560 * 4); + assert_eq!(d.full_row_bytes(), 20 * 2560 * 4); +} + +#[test] +fn dispatch_respects_kind_primary_residency_and_missing_layers() { + let plan = plan_for_dispatch(); + let ids: Vec = vec![4, 9, 2, 0, 1, 3, 5, 6, 8, 10]; + let mut kind = vec![-1i32; 10]; + kind[1] = 2; // expert 9 was already served on the primary + let d = dispatch(&plan, 1, &ids, 1, 10, Some(&kind), None).unwrap(); + assert_eq!(d.original_row, [0, 2]); + // the primary holds expert 4 of layer 1 + let mut res = vec![-1i32; 3 * 16]; + res[16 + 4] = 5; + let d = dispatch(&plan, 1, &ids, 1, 10, None, Some(&res)).unwrap(); + assert_eq!(d.original_row, [1, 2]); + // a layer the helper holds nothing of + let d = dispatch(&plan, 2, &ids, 1, 10, None, None).unwrap(); + assert!(d.is_empty() && d.owned.iter().all(|o| *o == 0)); + assert!(d.start.is_empty()); + // out-of-range experts are ignored + let d = dispatch(&plan, 1, &[-3, 99, 4, 4, 4, 4, 4, 4, 4, 4], 1, 10, None, None).unwrap(); + assert_eq!(d.groups.len(), 1); + assert_eq!(d.original_row.len(), 8); +} + +#[test] +fn dispatch_validation() { + let plan = plan_for_dispatch(); + let ids = vec![0i32; 100]; + for (layer, n_tok, k) in [(1, 0, 10), (1, 9, 10), (1, 1, 9), (-1, 1, 10), (3, 1, 10)] { + assert_eq!(dispatch(&plan, layer, &ids, n_tok, k, None, None), Err(RemoteError::InvalidDispatch), "{layer} {n_tok} {k}"); + } + assert!(dispatch(&plan, 1, &ids, 8, 10, None, None).is_ok()); +} + +#[test] +fn meta_image_and_scatter() { + let plan = plan_for_dispatch(); + let ids: Vec = vec![4, 9, 4, 0, 1, 3, 5, 6, 8, 10]; + let d = dispatch(&plan, 1, &ids, 1, 10, None, None).unwrap(); + let img = RemoteMeta::to_bytes(&d, &|slot| 0x1000_0000 + slot as u64 * 0x10_0000); + assert_eq!(u64::from_le_bytes(img[0..8].try_into().unwrap()), 0x1000_0000); + assert_eq!(u64::from_le_bytes(img[8..16].try_into().unwrap()), 0x1010_0000); + assert_eq!(i32::from_le_bytes(img[META_START_OFFSET + 4..][..4].try_into().unwrap()), 2); + assert_eq!(i32::from_le_bytes(img[META_START_OFFSET + 8..][..4].try_into().unwrap()), 3); + assert_eq!(i32::from_le_bytes(img[META_COUNT_OFFSET..][..4].try_into().unwrap()), 2); + // scatter: compact rows of width 3 return to their routed rows + let h_out = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0]; + let mut out = vec![0.0f32; 10 * 3]; + scatter(&mut out, &h_out, &d.original_row, 3); + assert_eq!(&out[0..3], [1.0; 3]); + assert_eq!(&out[2 * 3..2 * 3 + 3], [2.0; 3]); + assert_eq!(&out[3..6], [3.0; 3]); // routed row 1 (expert 9) is the group after expert 4's + assert_eq!(out.iter().filter(|v| **v != 0.0).count(), 9); +} + +#[test] +fn device_buffers_fit_a_small_budget() { + // 80 entries x 2560 floats x 2, activation, scales, scratch, meta + let b = device_buffer_bytes(); + assert!(b > 2_000_000 && b < 8_000_000, "{b}"); + assert_eq!(moe_hit_grouped_scratch_bytes(0, 2560, 640), 0); + assert_eq!(native_expert_scratch_bytes(80, 640), 3 * 204_800 + ((80 * 20 * 36 + 255) & !255)); + let mut t = Totals::default(); + let d = dispatch(&plan_for_dispatch(), 1, &[4; 10], 1, 10, None, None).unwrap(); + t.record(&d); + assert_eq!((t.computed, t.launched_layers), (10, 1)); +} diff --git a/crates/gateway-text/src/prompt.rs b/crates/gateway-text/src/prompt.rs index a418e215..a8531a90 100644 --- a/crates/gateway-text/src/prompt.rs +++ b/crates/gateway-text/src/prompt.rs @@ -878,496 +878,5 @@ fn render_via_template( } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[derive(Deserialize)] - struct Case { - name: String, - messages: Vec, - #[serde(default)] - tools: Option>, - #[serde(default)] - add_generation_prompt: Option, - #[serde(default)] - enable_thinking: Option, - rendered: String, - hf: String, - error: Option, - } - - fn golden() -> Vec { - serde_json::from_str(include_str!( - "../../../engine/strata/serve/chat_golden.json" - )) - .unwrap() - } - - /// All ten cases of `serve/chat_golden.json`, straight through the Jinja template: system merging, tool - /// definitions, assistant `tool_calls` with mapping arguments, `tool` messages, thinking on and off, and no - /// generation prompt. - #[test] - fn all_ten_golden_cases_render_byte_for_byte() { - let cases = golden(); - assert_eq!(cases.len(), 10); - for case in cases { - assert!(case.error.is_none(), "{}", case.name); - assert_eq!(case.rendered, case.hf, "{}", case.name); - let kwargs = case - .enable_thinking - .map(|b| ("enable_thinking", Json::Bool(b))) - .into_iter() - .collect(); - let got = pinned() - .render(&ChatInput { - messages: &case.messages, - tools: case.tools.as_deref(), - add_generation_prompt: case.add_generation_prompt.unwrap_or(true), - kwargs, - }) - .unwrap_or_else(|e| panic!("{}: {e}", case.name)); - assert_eq!(got, case.rendered, "{}", case.name); - } - } - - #[test] - fn typed_text_prompts_match_the_golden_bytes() { - let cases = golden(); - for name in [ - "single user", - "system + user", - "multi-turn", - "assistant with thinking", - "unicode content", - "empty user", - "whitespace and newlines", - "thinking disabled", - ] { - let case = cases.iter().find(|case| case.name == name).unwrap(); - let messages = case - .messages - .iter() - .map(|message| Message { - role: match message.get("role") { - Some(Json::String(role)) => match role.as_str() { - "system" => Role::System, - "developer" => Role::Developer, - "user" => Role::User, - "assistant" => Role::Assistant, - role => panic!("unsupported role: {role}"), - }, - _ => panic!("role"), - }, - content: match message.get("content") { - Some(Json::String(text)) => text, - _ => panic!("content"), - }, - reasoning: match message.get("reasoning_content") { - Some(Json::String(text)) => Some(text), - _ => None, - }, - parts: None, - }) - .collect::>(); - let effort = if name == "thinking disabled" { - Effort::None - } else { - Effort::XHigh - }; - assert_eq!(render(&messages, effort).unwrap(), case.rendered, "{name}"); - } - } - - /// Random text-only conversations (white space of every kind at the edges of contents, empty contents and reasoning, - /// template-looking text, special-token text, non-ASCII), all efforts, with and without system messages and tools: - /// the native renderer and the template produce the same bytes (or the same error). - #[test] - fn native_render_equals_the_template() { - struct Rng(u64); - impl Rng { - fn below(&mut self, n: usize) -> usize { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - (self.0 % n as u64) as usize - } - } - const ATOMS: &[&str] = &[ - "", - " ", - " ", - "\n", - "\n\n", - "\t", - "\r\n", - "\u{a0}", - "\u{2003}", - "\u{1c}", - "\u{85}", - "\u{200b}", - "word", - "a b", - "{{ x }}", - "{% if %}", - "{# c #}", - "<|im_start|>", - "<|im_end|>", - "", - "", - "", - "", - "\u{fc}\u{4e2d}\u{6587}\u{1f600}", - "\"quoted\"", - "back\\slash", - "0", - "-1.5e10", - "null", - "[1, 2]", - "{\"a\": 1}", - ]; - let tools_pool = [ - json!({"type":"function","name":"exec","description":"Run a command","parameters":{"type":"object","properties":{"cmd":{"type":"string"},"n":{"type":"number"}},"required":["cmd"]}}), - json!({"type":"function","name":"plan","parameters":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"step":{"type":"string"}}}}}},"strict":false}), - json!({"type":"function","name":"bare"}), - ]; - let mut rng = Rng(0x2545_F491_4F6C_DD1D); - let text = |rng: &mut Rng| { - (0..rng.below(5)) - .map(|_| ATOMS[rng.below(ATOMS.len())]) - .collect::() - }; - for case in 0..4000 { - let mut storage: Vec<(Role, String, Option)> = Vec::new(); - for _ in 0..rng.below(3) { - let role = if rng.below(2) == 0 { - Role::System - } else { - Role::Developer - }; - storage.push((role, text(&mut rng), None)); - } - for _ in 0..rng.below(5) { - let role = if rng.below(2) == 0 { - Role::User - } else { - Role::Assistant - }; - let reasoning = (rng.below(2) == 0).then(|| text(&mut rng)); - storage.push(( - role, - text(&mut rng), - if role == Role::Assistant { - reasoning - } else { - None - }, - )); - } - storage.push((Role::User, text(&mut rng), None)); - let messages: Vec> = storage - .iter() - .map(|(role, content, reasoning)| Message { - role: *role, - content, - reasoning: reasoning.as_deref(), - parts: None, - }) - .collect(); - let tools: Vec = tools_pool.iter().take(rng.below(4)).cloned().collect(); - let effort = [ - Effort::None, - Effort::Low, - Effort::Medium, - Effort::High, - Effort::XHigh, - ][rng.below(5)]; - let reference = - render_via_template(&messages, effort, &tools).map(|(prompt, _)| prompt); - let chat_tools = tools - .iter() - .map(chat_tool) - .collect::, _>>() - .unwrap(); - let native = render_native(&without_empty_turns(&messages), effort, &chat_tools); - assert_eq!( - native, - reference, - "case {case}: {storage:?} {effort:?} tools {}", - tools.len() - ); - } - } - - #[test] - fn flattened_tool_continuation_matches_the_golden_bytes() { - let case = golden() - .into_iter() - .find(|c| c.name == "tool call and response") - .unwrap(); - let function = case.tools.as_ref().unwrap()[0].get("function").unwrap(); - let tools = [json!({ - "type":"function", - "name": serde_json::to_value(function.get("name")).unwrap(), - "description": serde_json::to_value(function.get("description")).unwrap(), - "parameters": serde_json::to_value(function.get("parameters")).unwrap(), - })]; - let user = |content| Message { - role: Role::User, - content, - reasoning: None, - parts: None, - }; - let messages = [ - user("Weather in Oslo?"), - Message { - role: Role::Assistant, - content: "\n\n\nOslo\n\n\n", - reasoning: None, - parts: None, - }, - user("\n{\"temp\": 3}\n"), - user("And in Bergen?"), - ]; - assert_eq!( - render_with_tools(&messages, Effort::XHigh, &tools).unwrap(), - case.rendered - ); - } - - /// Strata 0.1.50 `ChatTemplate.render` (#843): completed empty assistant turns are not rendered, the final message is kept - /// whatever it is, and a reasoning content does not keep a turn. The expectation is the unmodified `serve/frontend.py`'s - /// (`scripts/offline/diff_chat_template.py` runs the same comparison over thousands of generated conversations). - #[test] - fn completed_empty_assistant_turns_are_not_rendered() { - let head = "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n"; - let user = |content| Json::object([("role", Json::str("user")), ("content", content)]); - let assistant = |content, extra: Vec<(&str, Json)>| { - let mut fields = vec![("role", Json::str("assistant")), ("content", content)]; - fields.extend(extra); - Json::Object(fields.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()) - }; - let render = |messages: &[Json]| { - pinned() - .render(&ChatInput { - messages, - tools: None, - add_generation_prompt: false, - kwargs: vec![("reasoning_effort", Json::str("xhigh"))], - }) - .unwrap() - }; - let tail = - format!("{head}<|im_start|>user\nhi<|im_end|>\n<|im_start|>user\nagain<|im_end|>\n"); - // null, empty, blank, text-less list content and a reasoning-only turn all vanish between the two user turns - for dropped in [ - assistant(Json::Null, vec![]), - assistant(Json::str(""), vec![]), - assistant(Json::str(" \n\u{3000}"), vec![]), - assistant(Json::Array(vec![]), vec![]), - assistant( - Json::str(""), - vec![("reasoning_content", Json::str("thought"))], - ), - assistant(Json::str(""), vec![("tool_calls", Json::Array(vec![]))]), - ] { - let got = render(&[ - user(Json::str("hi")), - dropped.clone(), - user(Json::str("again")), - ]); - assert_eq!(got, tail, "{dropped:?}"); - } - // kept: a tool call, a picture, and the final message - let call = assistant( - Json::str(""), - vec![( - "tool_calls", - Json::Array(vec![Json::object([("name", Json::str("f"))])]), - )], - ); - let got = render(&[user(Json::str("hi")), call, user(Json::str("again"))]); - assert_eq!(got.matches("<|im_start|>assistant").count(), 1, "{got}"); - let picture = assistant( - Json::Array(vec![Json::object([("type", Json::str("image"))])]), - vec![], - ); - let got = render(&[user(Json::str("hi")), picture, user(Json::str("again"))]); - assert!(got.contains("<|vision_start|>"), "{got}"); - let got = render(&[user(Json::str("hi")), assistant(Json::Null, vec![])]); - assert_eq!(got.matches("<|im_start|>assistant").count(), 1, "{got}"); - // a content Python cannot iterate fails the render instead of being dropped - let error = pinned().render(&ChatInput { - messages: &[ - user(Json::str("hi")), - assistant(Json::Number(42.into()), vec![]), - user(Json::str("again")), - ], - tools: None, - add_generation_prompt: false, - kwargs: vec![], - }); - assert!(error.is_err()); - // the typed path takes the same turns out, native renderer included - let typed = |role, content| Message { - role, - content, - reasoning: Some("thought"), - parts: None, - }; - let messages = [ - typed(Role::User, "hi"), - typed(Role::Assistant, " "), - typed(Role::User, "again"), - ]; - let native = render_with_tools(&messages, Effort::XHigh, &[]).unwrap(); - assert_eq!(native, format!("{tail}<|im_start|>assistant\n\n")); - assert_eq!( - render_via_template(&messages, Effort::XHigh, &[]) - .unwrap() - .0, - native - ); - } - - #[test] - fn rejects_unrepresentable_message_order() { - let system = Message { - role: Role::System, - content: "rules", - reasoning: None, - parts: None, - }; - let user = Message { - role: Role::User, - content: "question", - reasoning: None, - parts: None, - }; - assert!(render(&[user, system], Effort::XHigh).is_err()); - assert!(render(&[system], Effort::XHigh).is_err()); - assert!(render(&[], Effort::XHigh).is_err()); - } - - #[test] - fn efforts_select_the_template_instructions() { - let user = [Message { - role: Role::User, - content: "hi", - reasoning: None, - parts: None, - }]; - let text = |effort| render(&user, effort).unwrap(); - assert!(text(Effort::XHigh).contains("Reasoning effort is set to xhigh.")); - assert!(text(Effort::High).contains("Reasoning effort is set to xhigh.")); - assert!(text(Effort::Low).contains("Reasoning effort is set to low.")); - assert_eq!( - text(Effort::Medium), - "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n" - ); - assert_eq!( - text(Effort::None), - "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" - ); - } - - #[test] - fn raise_exception_surfaces_the_template_message() { - let messages = [Json::object([ - ("role", Json::str("tool")), - ("content", Json::str("x")), - ])]; - let bad = pinned().render(&ChatInput { - messages: &[Json::object([ - ("role", Json::str("robot")), - ("content", Json::str("x")), - ])], - tools: None, - add_generation_prompt: true, - kwargs: vec![], - }); - assert_eq!(bad.unwrap_err(), "Unexpected message role."); - let effort = pinned().render(&ChatInput { - messages: &[Json::object([ - ("role", Json::str("user")), - ("content", Json::str("x")), - ])], - tools: None, - add_generation_prompt: true, - kwargs: vec![("reasoning_effort", Json::str("extreme"))], - }); - assert_eq!( - effort.unwrap_err(), - "Unexpected reasoning effort extreme. Supported types are xhigh (default), medium, and low." - ); - let _ = messages; - } - - #[test] - fn tojson_matches_python_json_dumps() { - let renderer = Renderer::new("{{ value | tojson }}").unwrap(); - let render = |json: &str| { - let value: Json = serde_json::from_str(json).unwrap(); - let mut context = BTreeMap::new(); - context.insert("value", Value::from_serialize(&value)); - renderer - .env - .get_template("chat") - .unwrap() - .render(&context) - .unwrap() - }; - assert_eq!( - render(r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"#), - r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"# - ); - assert_eq!( - render(r#"["é", "\u0001", "\u007f", "😀", "\u2028"]"#), - "[\"é\", \"\\u0001\", \"\u{7f}\", \"😀\", \"\u{2028}\"]" - ); - assert_eq!( - render("[1e16, 1e15, 1.5e-5, 0.0001, 123456789012345680000.0, -0.0, 100.0]"), - "[1e+16, 1000000000000000.0, 1.5e-05, 0.0001, 1.2345678901234568e+20, -0.0, 100.0]" - ); - assert_eq!( - render("[18446744073709551615, -9223372036854775808]"), - "[18446744073709551615, -9223372036854775808]" - ); - } - - #[test] - fn trim_is_pythons_strip() { - let renderer = Renderer::new("[{{ value | trim }}]").unwrap(); - let render = |text: &str| { - let mut context = BTreeMap::new(); - context.insert("value", Value::from(text)); - renderer - .env - .get_template("chat") - .unwrap() - .render(&context) - .unwrap() - }; - // U+001C..U+001F are whitespace to Python's str.strip() but not to Unicode White_Space - assert_eq!(render("\u{1c}\u{1f} a b \u{a0}\u{3000}\n"), "[a b]"); - } - - #[test] - fn objects_keep_the_order_they_were_written_in() { - let tools: Vec = - serde_json::from_str(r#"[{"type":"function","function":{"name":"f","parameters":{"z":1,"a":{"y":2,"b":3}}}}]"#) - .unwrap(); - let out = pinned() - .render(&ChatInput { - messages: &[Json::object([ - ("role", Json::str("user")), - ("content", Json::str("x")), - ])], - tools: Some(&tools), - add_generation_prompt: true, - kwargs: vec![("enable_thinking", Json::Bool(false))], - }) - .unwrap(); - assert!(out.contains(r#"{"type": "function", "function": {"name": "f", "parameters": {"z": 1, "a": {"y": 2, "b": 3}}}}"#), "{out}"); - } -} +#[path = "prompt/tests.rs"] +mod tests; diff --git a/crates/gateway-text/src/prompt/tests.rs b/crates/gateway-text/src/prompt/tests.rs new file mode 100644 index 00000000..43b9dc5a --- /dev/null +++ b/crates/gateway-text/src/prompt/tests.rs @@ -0,0 +1,493 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use serde_json::json; + +#[derive(Deserialize)] +struct Case { + name: String, + messages: Vec, + #[serde(default)] + tools: Option>, + #[serde(default)] + add_generation_prompt: Option, + #[serde(default)] + enable_thinking: Option, + rendered: String, + hf: String, + error: Option, +} + +fn golden() -> Vec { + serde_json::from_str(include_str!( + "../../../../engine/strata/serve/chat_golden.json" + )) + .unwrap() +} + +/// All ten cases of `serve/chat_golden.json`, straight through the Jinja template: system merging, tool +/// definitions, assistant `tool_calls` with mapping arguments, `tool` messages, thinking on and off, and no +/// generation prompt. +#[test] +fn all_ten_golden_cases_render_byte_for_byte() { + let cases = golden(); + assert_eq!(cases.len(), 10); + for case in cases { + assert!(case.error.is_none(), "{}", case.name); + assert_eq!(case.rendered, case.hf, "{}", case.name); + let kwargs = case + .enable_thinking + .map(|b| ("enable_thinking", Json::Bool(b))) + .into_iter() + .collect(); + let got = pinned() + .render(&ChatInput { + messages: &case.messages, + tools: case.tools.as_deref(), + add_generation_prompt: case.add_generation_prompt.unwrap_or(true), + kwargs, + }) + .unwrap_or_else(|e| panic!("{}: {e}", case.name)); + assert_eq!(got, case.rendered, "{}", case.name); + } +} + +#[test] +fn typed_text_prompts_match_the_golden_bytes() { + let cases = golden(); + for name in [ + "single user", + "system + user", + "multi-turn", + "assistant with thinking", + "unicode content", + "empty user", + "whitespace and newlines", + "thinking disabled", + ] { + let case = cases.iter().find(|case| case.name == name).unwrap(); + let messages = case + .messages + .iter() + .map(|message| Message { + role: match message.get("role") { + Some(Json::String(role)) => match role.as_str() { + "system" => Role::System, + "developer" => Role::Developer, + "user" => Role::User, + "assistant" => Role::Assistant, + role => panic!("unsupported role: {role}"), + }, + _ => panic!("role"), + }, + content: match message.get("content") { + Some(Json::String(text)) => text, + _ => panic!("content"), + }, + reasoning: match message.get("reasoning_content") { + Some(Json::String(text)) => Some(text), + _ => None, + }, + parts: None, + }) + .collect::>(); + let effort = if name == "thinking disabled" { + Effort::None + } else { + Effort::XHigh + }; + assert_eq!(render(&messages, effort).unwrap(), case.rendered, "{name}"); + } +} + +/// Random text-only conversations (white space of every kind at the edges of contents, empty contents and reasoning, +/// template-looking text, special-token text, non-ASCII), all efforts, with and without system messages and tools: +/// the native renderer and the template produce the same bytes (or the same error). +#[test] +fn native_render_equals_the_template() { + struct Rng(u64); + impl Rng { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % n as u64) as usize + } + } + const ATOMS: &[&str] = &[ + "", + " ", + " ", + "\n", + "\n\n", + "\t", + "\r\n", + "\u{a0}", + "\u{2003}", + "\u{1c}", + "\u{85}", + "\u{200b}", + "word", + "a b", + "{{ x }}", + "{% if %}", + "{# c #}", + "<|im_start|>", + "<|im_end|>", + "", + "", + "", + "", + "\u{fc}\u{4e2d}\u{6587}\u{1f600}", + "\"quoted\"", + "back\\slash", + "0", + "-1.5e10", + "null", + "[1, 2]", + "{\"a\": 1}", + ]; + let tools_pool = [ + json!({"type":"function","name":"exec","description":"Run a command","parameters":{"type":"object","properties":{"cmd":{"type":"string"},"n":{"type":"number"}},"required":["cmd"]}}), + json!({"type":"function","name":"plan","parameters":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"step":{"type":"string"}}}}}},"strict":false}), + json!({"type":"function","name":"bare"}), + ]; + let mut rng = Rng(0x2545_F491_4F6C_DD1D); + let text = |rng: &mut Rng| { + (0..rng.below(5)) + .map(|_| ATOMS[rng.below(ATOMS.len())]) + .collect::() + }; + for case in 0..4000 { + let mut storage: Vec<(Role, String, Option)> = Vec::new(); + for _ in 0..rng.below(3) { + let role = if rng.below(2) == 0 { + Role::System + } else { + Role::Developer + }; + storage.push((role, text(&mut rng), None)); + } + for _ in 0..rng.below(5) { + let role = if rng.below(2) == 0 { + Role::User + } else { + Role::Assistant + }; + let reasoning = (rng.below(2) == 0).then(|| text(&mut rng)); + storage.push(( + role, + text(&mut rng), + if role == Role::Assistant { + reasoning + } else { + None + }, + )); + } + storage.push((Role::User, text(&mut rng), None)); + let messages: Vec> = storage + .iter() + .map(|(role, content, reasoning)| Message { + role: *role, + content, + reasoning: reasoning.as_deref(), + parts: None, + }) + .collect(); + let tools: Vec = tools_pool.iter().take(rng.below(4)).cloned().collect(); + let effort = [ + Effort::None, + Effort::Low, + Effort::Medium, + Effort::High, + Effort::XHigh, + ][rng.below(5)]; + let reference = + render_via_template(&messages, effort, &tools).map(|(prompt, _)| prompt); + let chat_tools = tools + .iter() + .map(chat_tool) + .collect::, _>>() + .unwrap(); + let native = render_native(&without_empty_turns(&messages), effort, &chat_tools); + assert_eq!( + native, + reference, + "case {case}: {storage:?} {effort:?} tools {}", + tools.len() + ); + } +} + +#[test] +fn flattened_tool_continuation_matches_the_golden_bytes() { + let case = golden() + .into_iter() + .find(|c| c.name == "tool call and response") + .unwrap(); + let function = case.tools.as_ref().unwrap()[0].get("function").unwrap(); + let tools = [json!({ + "type":"function", + "name": serde_json::to_value(function.get("name")).unwrap(), + "description": serde_json::to_value(function.get("description")).unwrap(), + "parameters": serde_json::to_value(function.get("parameters")).unwrap(), + })]; + let user = |content| Message { + role: Role::User, + content, + reasoning: None, + parts: None, + }; + let messages = [ + user("Weather in Oslo?"), + Message { + role: Role::Assistant, + content: "\n\n\nOslo\n\n\n", + reasoning: None, + parts: None, + }, + user("\n{\"temp\": 3}\n"), + user("And in Bergen?"), + ]; + assert_eq!( + render_with_tools(&messages, Effort::XHigh, &tools).unwrap(), + case.rendered + ); +} + +/// Strata 0.1.50 `ChatTemplate.render` (#843): completed empty assistant turns are not rendered, the final message is kept +/// whatever it is, and a reasoning content does not keep a turn. The expectation is the unmodified `serve/frontend.py`'s +/// (`scripts/offline/diff_chat_template.py` runs the same comparison over thousands of generated conversations). +#[test] +fn completed_empty_assistant_turns_are_not_rendered() { + let head = "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n"; + let user = |content| Json::object([("role", Json::str("user")), ("content", content)]); + let assistant = |content, extra: Vec<(&str, Json)>| { + let mut fields = vec![("role", Json::str("assistant")), ("content", content)]; + fields.extend(extra); + Json::Object(fields.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()) + }; + let render = |messages: &[Json]| { + pinned() + .render(&ChatInput { + messages, + tools: None, + add_generation_prompt: false, + kwargs: vec![("reasoning_effort", Json::str("xhigh"))], + }) + .unwrap() + }; + let tail = + format!("{head}<|im_start|>user\nhi<|im_end|>\n<|im_start|>user\nagain<|im_end|>\n"); + // null, empty, blank, text-less list content and a reasoning-only turn all vanish between the two user turns + for dropped in [ + assistant(Json::Null, vec![]), + assistant(Json::str(""), vec![]), + assistant(Json::str(" \n\u{3000}"), vec![]), + assistant(Json::Array(vec![]), vec![]), + assistant( + Json::str(""), + vec![("reasoning_content", Json::str("thought"))], + ), + assistant(Json::str(""), vec![("tool_calls", Json::Array(vec![]))]), + ] { + let got = render(&[ + user(Json::str("hi")), + dropped.clone(), + user(Json::str("again")), + ]); + assert_eq!(got, tail, "{dropped:?}"); + } + // kept: a tool call, a picture, and the final message + let call = assistant( + Json::str(""), + vec![( + "tool_calls", + Json::Array(vec![Json::object([("name", Json::str("f"))])]), + )], + ); + let got = render(&[user(Json::str("hi")), call, user(Json::str("again"))]); + assert_eq!(got.matches("<|im_start|>assistant").count(), 1, "{got}"); + let picture = assistant( + Json::Array(vec![Json::object([("type", Json::str("image"))])]), + vec![], + ); + let got = render(&[user(Json::str("hi")), picture, user(Json::str("again"))]); + assert!(got.contains("<|vision_start|>"), "{got}"); + let got = render(&[user(Json::str("hi")), assistant(Json::Null, vec![])]); + assert_eq!(got.matches("<|im_start|>assistant").count(), 1, "{got}"); + // a content Python cannot iterate fails the render instead of being dropped + let error = pinned().render(&ChatInput { + messages: &[ + user(Json::str("hi")), + assistant(Json::Number(42.into()), vec![]), + user(Json::str("again")), + ], + tools: None, + add_generation_prompt: false, + kwargs: vec![], + }); + assert!(error.is_err()); + // the typed path takes the same turns out, native renderer included + let typed = |role, content| Message { + role, + content, + reasoning: Some("thought"), + parts: None, + }; + let messages = [ + typed(Role::User, "hi"), + typed(Role::Assistant, " "), + typed(Role::User, "again"), + ]; + let native = render_with_tools(&messages, Effort::XHigh, &[]).unwrap(); + assert_eq!(native, format!("{tail}<|im_start|>assistant\n\n")); + assert_eq!( + render_via_template(&messages, Effort::XHigh, &[]) + .unwrap() + .0, + native + ); +} + +#[test] +fn rejects_unrepresentable_message_order() { + let system = Message { + role: Role::System, + content: "rules", + reasoning: None, + parts: None, + }; + let user = Message { + role: Role::User, + content: "question", + reasoning: None, + parts: None, + }; + assert!(render(&[user, system], Effort::XHigh).is_err()); + assert!(render(&[system], Effort::XHigh).is_err()); + assert!(render(&[], Effort::XHigh).is_err()); +} + +#[test] +fn efforts_select_the_template_instructions() { + let user = [Message { + role: Role::User, + content: "hi", + reasoning: None, + parts: None, + }]; + let text = |effort| render(&user, effort).unwrap(); + assert!(text(Effort::XHigh).contains("Reasoning effort is set to xhigh.")); + assert!(text(Effort::High).contains("Reasoning effort is set to xhigh.")); + assert!(text(Effort::Low).contains("Reasoning effort is set to low.")); + assert_eq!( + text(Effort::Medium), + "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n" + ); + assert_eq!( + text(Effort::None), + "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + ); +} + +#[test] +fn raise_exception_surfaces_the_template_message() { + let messages = [Json::object([ + ("role", Json::str("tool")), + ("content", Json::str("x")), + ])]; + let bad = pinned().render(&ChatInput { + messages: &[Json::object([ + ("role", Json::str("robot")), + ("content", Json::str("x")), + ])], + tools: None, + add_generation_prompt: true, + kwargs: vec![], + }); + assert_eq!(bad.unwrap_err(), "Unexpected message role."); + let effort = pinned().render(&ChatInput { + messages: &[Json::object([ + ("role", Json::str("user")), + ("content", Json::str("x")), + ])], + tools: None, + add_generation_prompt: true, + kwargs: vec![("reasoning_effort", Json::str("extreme"))], + }); + assert_eq!( + effort.unwrap_err(), + "Unexpected reasoning effort extreme. Supported types are xhigh (default), medium, and low." + ); + let _ = messages; +} + +#[test] +fn tojson_matches_python_json_dumps() { + let renderer = Renderer::new("{{ value | tojson }}").unwrap(); + let render = |json: &str| { + let value: Json = serde_json::from_str(json).unwrap(); + let mut context = BTreeMap::new(); + context.insert("value", Value::from_serialize(&value)); + renderer + .env + .get_template("chat") + .unwrap() + .render(&context) + .unwrap() + }; + assert_eq!( + render(r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"#), + r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"# + ); + assert_eq!( + render(r#"["é", "\u0001", "\u007f", "😀", "\u2028"]"#), + "[\"é\", \"\\u0001\", \"\u{7f}\", \"😀\", \"\u{2028}\"]" + ); + assert_eq!( + render("[1e16, 1e15, 1.5e-5, 0.0001, 123456789012345680000.0, -0.0, 100.0]"), + "[1e+16, 1000000000000000.0, 1.5e-05, 0.0001, 1.2345678901234568e+20, -0.0, 100.0]" + ); + assert_eq!( + render("[18446744073709551615, -9223372036854775808]"), + "[18446744073709551615, -9223372036854775808]" + ); +} + +#[test] +fn trim_is_pythons_strip() { + let renderer = Renderer::new("[{{ value | trim }}]").unwrap(); + let render = |text: &str| { + let mut context = BTreeMap::new(); + context.insert("value", Value::from(text)); + renderer + .env + .get_template("chat") + .unwrap() + .render(&context) + .unwrap() + }; + // U+001C..U+001F are whitespace to Python's str.strip() but not to Unicode White_Space + assert_eq!(render("\u{1c}\u{1f} a b \u{a0}\u{3000}\n"), "[a b]"); +} + +#[test] +fn objects_keep_the_order_they_were_written_in() { + let tools: Vec = + serde_json::from_str(r#"[{"type":"function","function":{"name":"f","parameters":{"z":1,"a":{"y":2,"b":3}}}}]"#) + .unwrap(); + let out = pinned() + .render(&ChatInput { + messages: &[Json::object([ + ("role", Json::str("user")), + ("content", Json::str("x")), + ])], + tools: Some(&tools), + add_generation_prompt: true, + kwargs: vec![("enable_thinking", Json::Bool(false))], + }) + .unwrap(); + assert!(out.contains(r#"{"type": "function", "function": {"name": "f", "parameters": {"z": 1, "a": {"y": 2, "b": 3}}}}"#), "{out}"); +} diff --git a/crates/gateway-text/src/tool_output.rs b/crates/gateway-text/src/tool_output.rs index 55e62a7d..22089d8e 100644 --- a/crates/gateway-text/src/tool_output.rs +++ b/crates/gateway-text/src/tool_output.rs @@ -1181,664 +1181,4 @@ impl<'a> QuoteBalance<'a> { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn parses_upstream_terminator_fixture_without_truncating_content() { - let content = "Close each value with and the call with .\n\nnot a parameter\n\nend"; - let output = format!( - "\n\n\ndoc.md\n\n\n{content}\n\n\n" - ); - let tools = [ - json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}}), - ]; - assert_eq!( - parse_complete(&output, &tools).unwrap(), - vec![Segment::Call { - name: "write".into(), - arguments: json!({"path":"doc.md","content":content}), - }] - ); - } - - #[test] - fn an_undeclared_apply_patch_call_runs_through_the_declared_shell_tool() { - let patch = "*** Begin Patch\n*** Add File: a.py\n+print(1)\n*** End Patch"; - let output = format!( - "\n\n\n{patch}\n\n\n" - ); - let exec = [ - json!({"name":"exec_command","parameters":{"properties":{"cmd":{"type":"string"},"workdir":{"type":"string"}}}}), - ]; - assert_eq!( - parse_complete(&output, &exec).unwrap(), - vec![Segment::Call { - name: "exec_command".into(), - arguments: json!({"cmd": format!("apply_patch <<'PATCH'\n{patch}\nPATCH")}) - }] - ); - let shell = - [json!({"name":"shell","parameters":{"properties":{"command":{"type":"array"}}}})]; - assert_eq!( - parse_complete(&output, &shell).unwrap(), - vec![Segment::Call { - name: "shell".into(), - arguments: json!({"command": ["bash", "-lc", format!("apply_patch <<'PATCH'\n{patch}\nPATCH")]}) - }] - ); - // a declared apply_patch is left alone, and with no shell tool the call is still an error - let declared = - [json!({"name":"apply_patch","parameters":{"properties":{"input":{"type":"string"}}}})]; - assert_eq!( - parse_complete(&output, &declared).unwrap(), - vec![Segment::Call { - name: "apply_patch".into(), - arguments: json!({"input": patch}) - }] - ); - let none = - [json!({"name":"write_stdin","parameters":{"properties":{"chars":{"type":"string"}}}})]; - assert!( - parse_complete(&output, &none) - .unwrap_err() - .contains("undeclared function") - ); - } - - #[test] - fn other_undeclared_functions_still_fail() { - let exec = - [json!({"name":"exec_command","parameters":{"properties":{"cmd":{"type":"string"}}}})]; - let output = "\n\n\n1\n\n\n"; - assert!( - parse_complete(output, &exec) - .unwrap_err() - .contains("undeclared function in tool call: nope") - ); - } - - fn calls_of(segments: Vec) -> Vec<(String, Value)> { - segments - .into_iter() - .filter_map(|segment| match segment { - Segment::Call { name, arguments } => Some((name, arguments)), - Segment::Text(_) => None, - }) - .collect() - } - - fn stream( - tools: &[Value], - text: &str, - size: usize, - natural_stop: bool, - ) -> Result<(Vec, Notes), String> { - let mut parser = Incremental::new(tools); - let mut out = Vec::new(); - let chars: Vec<(usize, char)> = text.char_indices().collect(); - for chunk in chars.chunks(size) { - let from = chunk[0].0; - let to = chunk.last().map_or(from, |(at, c)| at + c.len_utf8()); - out.extend(parser.feed(&text[from..to])?); - } - out.extend(parser.finish_after(natural_stop)?); - Ok((out, parser.notes().clone())) - } - - #[test] - fn a_call_without_function_close_is_read_when_the_wrapper_closes_it() { - let tools = [ - json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}}), - ]; - let text = "\n\n\nout.txt\n\n\nhello\n\n"; - let want = vec![( - "write".to_owned(), - json!({"path":"out.txt","content":"hello"}), - )]; - let parsed = parse_with(text, &tools, Options::default()).unwrap(); - assert_eq!(calls_of(parsed.segments), want); - assert_eq!(parsed.notes.closers_supplied, 1); - for size in [1, 7, text.len()] { - let (segments, notes) = stream(&tools, text, size, true).unwrap(); - assert_eq!(calls_of(segments), want, "pieces of {size}"); - assert_eq!(notes.closers_supplied, 1); - } - // two such calls, then a well-formed one - let two = format!( - "{text}\n{text}\nz" - ); - assert_eq!(calls_of(parse_complete(&two, &tools).unwrap()).len(), 3); - } - - #[test] - fn a_value_that_quotes_a_malformed_tail_is_not_cut_when_the_real_close_exists() { - // `\n` inside the value is only a candidate end: a real `` follows - let tools = - [json!({"name":"write","parameters":{"properties":{"content":{"type":"string"}}}})]; - let content = - "a call that lost its closer ends like\n\n\nand that is all"; - let text = format!( - "\n\n\n{content}\n\n\n" - ); - let want = vec![("write".to_owned(), json!({"content": content}))]; - assert_eq!(calls_of(parse_complete(&text, &tools).unwrap()), want); - for size in [1, 5, text.len()] { - let (segments, _) = stream(&tools, &text, size, true).unwrap(); - assert_eq!(calls_of(segments), want, "pieces of {size}"); - } - } - - #[test] - fn a_missing_wrapper_close_is_confirmed_only_by_the_next_call_or_a_natural_end() { - let tools = [json!({"name":"read","parameters":{"properties":{"path":{"type":"string"}}}})]; - let open = - "\n\n\na.txt\n\n"; - let whole = format!("{open}\n"); - let want = vec![("read".to_owned(), json!({"path":"a.txt"}))]; - assert_eq!(calls_of(parse_complete(&whole, &tools).unwrap()), want); - // ends on ``: whole only when the generation stopped by itself - assert!(parse_complete(open, &tools).is_err()); - assert!( - parse_with( - open, - &tools, - Options { - natural_stop: false, - ..Options::default() - } - ) - .is_err() - ); - assert_eq!( - calls_of( - parse_with( - open, - &tools, - Options { - natural_stop: true, - ..Options::default() - } - ) - .unwrap() - .segments - ), - want - ); - assert!(stream(&tools, open, 3, false).is_err()); - assert_eq!(calls_of(stream(&tools, open, 3, true).unwrap().0), want); - // prose after `` does not confirm it - let prose = format!("{open}\nand then I will"); - assert!( - parse_with( - &prose, - &tools, - Options { - natural_stop: true, - ..Options::default() - } - ) - .is_err() - ); - // the next call's opener does - let next = format!( - "{open}\n\n\n\nb.txt\n\n\n" - ); - let both = vec![ - want[0].clone(), - ("read".to_owned(), json!({"path":"b.txt"})), - ]; - assert_eq!(calls_of(parse_complete(&next, &tools).unwrap()), both); - for size in [1, 4, next.len()] { - assert_eq!( - calls_of(stream(&tools, &next, size, false).unwrap().0), - both, - "pieces of {size}" - ); - } - } - - #[test] - fn damaged_array_arguments_are_read_as_written_but_never_completed_or_pruned() { - let tools = [ - json!({"name":"todo","parameters":{"properties":{"todos":{"type":"array"},"note":{"type":"string"},"any":{"type":["string","array"]}}}}), - ]; - let read = |value: &str, parameter: &str| { - let text = format!( - "\n{value}\n" - ); - let parsed = parse_with(&text, &tools, Options::default()).unwrap(); - let repaired = parsed.notes.repaired_arguments; - ( - calls_of(parsed.segments).remove(0).1[parameter].clone(), - repaired, - ) - }; - for (value, want) in [ - ("[{'a': 1, 'b': True},]", json!([{"a": 1, "b": true}])), - ("[1,, 2,]", json!([1, 2])), - ("[{\"a\": None}]]", json!([{"a": null}])), - ("\"[{\\\"a\\\": 1}]\"", json!([{"a": 1}])), - ("\"[1, 2,]\"", json!([1, 2])), - ] { - assert_eq!(read(value, "todos"), (want, 1), "{value}"); - } - // valid JSON is not a repair - assert_eq!(read("[1, 2]", "todos"), (json!([1, 2]), 0)); - // not repaired, still the text the model wrote: brackets left open, a bare string, a missing colon, an unknown word - for value in [ - "[{\"a\": 1},", - "[{\"a\": 1, \"b\"}]", - "[{\"a\" 1}]", - "[nope]", - "[\"unterminated]", - ] { - assert_eq!(read(value, "todos"), (json!(value), 0), "{value}"); - } - // string parameters and unions with a string are untouched - assert_eq!(read("[1, 2,]", "note"), (json!("[1, 2,]"), 0)); - assert_eq!(read("[1, 2,]", "any"), (json!("[1, 2,]"), 0)); - } - - #[test] - fn calls_the_reasoning_ends_on_are_calls_and_calls_it_quotes_are_not() { - let tools = [json!({"name":"read","parameters":{"properties":{"path":{"type":"string"}}}})]; - let call = "\n\n\na.txt\n\n\n"; - let at = |text: &str| calls_at_end(text, &tools, Options::default()); - assert_eq!(at(&format!("Plan.\n\n{call}")), Some(7)); - assert_eq!(at(&format!("{call}\n{call}")), Some(0)); - // the call is not the last thing, is in a fence or in inline code, is mid-line, or names an undeclared tool - assert_eq!(at(&format!("{call}\nthen more thinking")), None); - assert_eq!(at(&format!("```\n{call}\n```")), None); - assert_eq!(at(&format!("a `quote {call}")), None); - assert_eq!(at(&format!("so I write {call}")), None); - assert_eq!(at(&call.replace("read", "format_disk")), None); - // a quoted call earlier does not hide the real one at the end - let after_quote = format!("```\n{call}\n```\nNow for real:\n{call}"); - assert_eq!(at(&after_quote), Some(after_quote.len() - call.len())); - } - - #[test] - fn parses_typed_values_and_preserves_text_around_calls() { - let tools = [ - json!({"name":"lookup","parameters":{"properties":{"n":{"type":"integer"},"term":{"type":"string"}}}}), - ]; - let output = "Let me check.\n\n\n\n\n12\n\n\n12\n\n\n\nanswer"; - assert_eq!( - parse_complete(output, &tools).unwrap(), - vec![ - Segment::Text("Let me check.".into()), - Segment::Call { - name: "lookup".into(), - arguments: json!({"n":12,"term":"12"}) - }, - Segment::Text("answer".into()), - ] - ); - } - - #[test] - fn string_type_unions_preserve_raw_text_and_decode_declared_json_types() { - for (types, raw, expected) in [ - (json!(["string", "null"]), "123", json!("123")), - (json!(["null", "string"]), "false", json!("false")), - (json!(["string", "null"]), "{}", json!("{}")), - (json!(["string", "null"]), "[]", json!("[]")), - (json!(["string", "null"]), "null", Value::Null), - (json!(["string", "null"]), "\"123\"", json!("\"123\"")), - (json!(["string", "null"]), " 123 ", json!(" 123 ")), - (json!(["string", "integer"]), "12", json!(12)), - (json!(["string", "integer"]), "1.5", json!("1.5")), - (json!(["string", "integer"]), "1.0", json!(1.0)), - (json!(["string", "number"]), "1.5", json!(1.5)), - (json!(["string", "boolean"]), "false", json!(false)), - (json!(["string", "object"]), "{}", json!({})), - (json!(["string", "array"]), "[]", json!([])), - (json!(["string"]), "null", json!("null")), - (json!("string"), "null", json!("null")), - (json!("string"), "\"x\"", json!("\"x\"")), - (json!(["integer", "null"]), "12", json!(12)), - ] { - let tools = - [json!({"name":"lookup","parameters":{"properties":{"value":{"type":types}}}})]; - let text = format!( - "{raw}" - ); - let expected = vec![Segment::Call { - name: "lookup".into(), - arguments: json!({"value":expected}), - }]; - assert_eq!( - parse_complete(&text, &tools).unwrap(), - expected, - "{types}: {raw}" - ); - let mut parser = Incremental::new(&tools); - let mut streamed = Vec::new(); - for ch in text.chars() { - streamed.extend(parser.feed(&ch.to_string()).unwrap()); - } - streamed.extend(parser.finish().unwrap()); - assert_eq!(streamed, expected, "stream {types}: {raw}"); - } - } - - #[test] - fn incomplete_or_undeclared_calls_are_never_published() { - let tools = [json!({"name":"write","parameters":{"properties":{}}})]; - assert!(parse_complete("half", &tools).is_err()); - assert!( - parse_complete("", &tools).is_err() - ); - assert!(parse_complete("", &tools).is_err()); - } - - #[test] - fn incremental_parser_holds_partial_markers_and_nested_tag_examples() { - let content = - "Close with and .\n\nexample\n\nend"; - let output = format!( - "First.\n\n\n\n\n{content}\n\n\n\nDone." - ); - let tools = - [json!({"name":"write","parameters":{"properties":{"content":{"type":"string"}}}})]; - let mut parser = Incremental::new(&tools); - let mut segments = Vec::new(); - for ch in output.chars() { - segments.extend(parser.feed(&ch.to_string()).unwrap()); - } - segments.extend(parser.finish().unwrap()); - let text = segments - .iter() - .filter_map(|segment| match segment { - Segment::Text(value) => Some(value.as_str()), - _ => None, - }) - .collect::(); - let calls = segments - .iter() - .filter_map(|segment| match segment { - Segment::Call { arguments, .. } => Some(arguments), - _ => None, - }) - .collect::>(); - assert_eq!(text, "First.Done."); - assert_eq!(calls, vec![&json!({"content":content})]); - assert!( - segments - .iter() - .filter_map(|segment| match segment { - Segment::Text(value) => Some(value), - _ => None, - }) - .all(|text| !text.contains("half") - .unwrap(); - assert!(cut.finish().is_err()); - } - - #[test] - fn a_quoted_call_in_a_value_does_not_end_the_value_and_a_cut_outer_call_is_not_published() { - let tools = [ - json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}}), - ]; - let quoted = "\n\n\nx.txt\n\n\n"; - let content = format!("transcript:\n{quoted}\nafter"); - let call = |tail: &str| { - format!( - "\n\n\np.txt\n\n\n{content}{tail}" - ) - }; - let whole = call("\n\n\n"); - assert_eq!( - parse_complete(&whole, &tools).unwrap(), - vec![Segment::Call { - name: "write".into(), - arguments: json!({"path":"p.txt","content":content}) - }] - ); - // the outer call was cut (token limit) right after the quoted one: the quoted call's closers must not end the value, - // or a truncated write would be published as a whole call - let cut = format!( - "\n\n\np.txt\n\n\ntranscript:\n{quoted}" - ); - assert!(parse_complete(&cut, &tools).is_err()); - let mut parser = Incremental::new(&tools); - assert_eq!(parser.feed(&cut).unwrap(), vec![]); - assert!(parser.finish().is_err()); - // a parameter written twice stays refused, not merged into one argument - let twice = "a\n\n\nb"; - assert!( - parse_complete(twice, &tools) - .unwrap_err() - .contains("duplicate tool parameter: content") - ); - } - - const ON: Options = Options { - natural_stop: true, - recovery: true, - }; - - fn write_tools() -> [Value; 2] { - [ - json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}}), - json!({"name":"todo","parameters":{"properties":{"todos":{"type":"array"}}}}), - ] - } - - /// Whole and streamed (several piece sizes, recovery on): the segments, which must agree. - fn read_on(tools: &[Value], text: &str) -> Vec { - let whole = parse_with(text, tools, ON).unwrap().segments; - for size in [1, 2, 3, 7, text.len()] { - let mut parser = Incremental::with_options(tools, ON); - let mut out = Vec::new(); - let chars: Vec<(usize, char)> = text.char_indices().collect(); - for chunk in chars.chunks(size) { - let from = chunk[0].0; - let to = chunk.last().map_or(from, |(at, c)| at + c.len_utf8()); - out.extend(parser.feed(&text[from..to]).unwrap()); - } - out.extend(parser.finish_after(true).unwrap()); - assert_eq!( - join_text(out), - join_text(whole_clone(&whole)), - "pieces of {size}: {text:?}" - ); - } - whole - } - - fn whole_clone(segments: &[Segment]) -> Vec { - segments - .iter() - .map(|segment| match segment { - Segment::Text(text) => Segment::Text(text.clone()), - Segment::Call { name, arguments } => Segment::Call { - name: name.clone(), - arguments: arguments.clone(), - }, - }) - .collect() - } - - /// Adjacent text segments are one text (a stream may cut it anywhere). - fn join_text(segments: Vec) -> Vec { - let mut out: Vec = Vec::new(); - for segment in segments { - match (out.last_mut(), segment) { - (Some(Segment::Text(last)), Segment::Text(next)) => last.push_str(&next), - (_, segment) => out.push(segment), - } - } - out - } - - fn call(name: &str, arguments: Value) -> Segment { - Segment::Call { - name: name.into(), - arguments, - } - } - - const BODY: &str = - "\na.md\n\n\nhi\n\n"; - - #[test] - fn drifted_forms_are_calls_only_with_recovery_and_only_for_declared_tools() { - let tools = write_tools(); - let want = || call("write", json!({"path":"a.md","content":"hi"})); - for (label, text) in [ - ("parameter as opener", format!("\n\n{BODY}\n")), - ("json in the wrapper", "\n{\"name\": \"write\", \"arguments\": {\"path\": \"a.md\", \"content\": \"hi\"}}\n".to_owned()), - ("json in a fence", "\n```json\n{\"name\": \"write\", \"arguments\": \"{\\\"path\\\": \\\"a.md\\\", \\\"content\\\": \\\"hi\\\"}\"}\n```\n".to_owned()), - ("= opener", format!("\n<=write>\n{BODY}\n")), - ("function colon", format!("\n\n{BODY}\n")), - ("function space equals", format!("\n\n{BODY}\n")), - ("bare name", format!("\n\n{BODY}\n")), - ("bare function", format!("\n{BODY}")), - ("bare function then a stray closer", format!("\n{BODY}\n")), - ] { - assert!(parse_complete(&text, &tools).is_err() || label.starts_with("bare function"), "{label} is no call without recovery"); - assert_eq!(read_on(&tools, &text), vec![want()], "{label}"); - } - // text around a bare call, and the same text without recovery is just text - let around = format!("Writing it now.\n\n\n{BODY}\nDone."); - assert_eq!( - read_on(&tools, &around), - vec![ - Segment::Text("Writing it now.".into()), - want(), - Segment::Text("Done.".into()) - ] - ); - assert_eq!( - parse_complete(&around, &tools).unwrap(), - vec![Segment::Text(around.clone())] - ); - // a batch in one wrapper, the second opened as - let second = BODY.replace("a.md", "b.md"); - for opener in ["", ""] { - let batch = - format!("\n\n{BODY}\n{opener}\n{second}\n"); - assert!(parse_complete(&batch, &tools).is_err()); - assert_eq!( - read_on(&tools, &batch), - vec![want(), call("write", json!({"path":"b.md","content":"hi"}))], - "{opener}" - ); - } - // never an undeclared tool, in any form - for text in [ - format!("\n\n{BODY}\n"), - format!("\n\n{BODY}\n"), - format!("\n{BODY}"), - "\n{\"name\": \"format_disk\", \"arguments\": {}}\n".to_owned(), - ] { - let read = parse_with(&text, &tools, ON); - assert!( - read.is_err() - || read - .unwrap() - .segments - .iter() - .all(|segment| matches!(segment, Segment::Text(_))), - "{text:?}" - ); - } - } - - #[test] - fn a_bare_function_is_a_call_only_at_a_line_start_outside_code() { - let tools = write_tools(); - let bare = format!("\n{BODY}"); - for text in [ - format!("```\n{bare}\n```"), - format!("~~~\n{bare}\n~~~"), - format!("the opener `{bare}"), - format!("so I call it with {bare}"), - "A call starts with in the template.".to_owned(), - "\n{value}\n" - ) - }; - let todos = |segments: Vec| calls_of(segments).remove(0).1["todos"].clone(); - assert_eq!( - todos(parse_complete(&text(stray), &tools).unwrap()), - json!(stray) - ); - assert_eq!( - todos(parse_complete(&text(cut), &tools).unwrap()), - json!(cut) - ); - assert_eq!( - todos(read_on(&tools, &text(stray))), - json!([{"content": "a", "status": "pending", "done": false}]) - ); - assert_eq!( - todos(read_on(&tools, &text(cut))), - json!([{"content": "a", "status": "pending"}]) - ); - let notes = parse_with(&text(cut), &tools, ON).unwrap().notes; - assert_eq!(notes.repaired_arguments, 1); - } - - #[test] - fn the_default_reading_is_the_same_with_the_option_off() { - // every shape of the step-3 tests, read with recovery off, is unchanged by the existence of the option - let tools = write_tools(); - let off = Options { - natural_stop: true, - recovery: false, - }; - for text in [ - "\n{\"name\": \"write\", \"arguments\": {}}\n".to_owned(), - format!("\n\n{BODY}\n"), - ] { - assert!(parse_with(&text, &tools, off).is_err()); - } - let around = format!("text\n\n{BODY}"); - assert_eq!( - parse_with(&around, &tools, off).unwrap().segments, - vec![Segment::Text(around)] - ); - } -} +mod tests; diff --git a/crates/gateway-text/src/tool_output/tests.rs b/crates/gateway-text/src/tool_output/tests.rs new file mode 100644 index 00000000..7c9fb030 --- /dev/null +++ b/crates/gateway-text/src/tool_output/tests.rs @@ -0,0 +1,661 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use serde_json::json; + +#[test] +fn parses_upstream_terminator_fixture_without_truncating_content() { + let content = "Close each value with and the call with .\n\nnot a parameter\n\nend"; + let output = format!( + "\n\n\ndoc.md\n\n\n{content}\n\n\n" + ); + let tools = [ + json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}}), + ]; + assert_eq!( + parse_complete(&output, &tools).unwrap(), + vec![Segment::Call { + name: "write".into(), + arguments: json!({"path":"doc.md","content":content}), + }] + ); +} + +#[test] +fn an_undeclared_apply_patch_call_runs_through_the_declared_shell_tool() { + let patch = "*** Begin Patch\n*** Add File: a.py\n+print(1)\n*** End Patch"; + let output = format!( + "\n\n\n{patch}\n\n\n" + ); + let exec = [ + json!({"name":"exec_command","parameters":{"properties":{"cmd":{"type":"string"},"workdir":{"type":"string"}}}}), + ]; + assert_eq!( + parse_complete(&output, &exec).unwrap(), + vec![Segment::Call { + name: "exec_command".into(), + arguments: json!({"cmd": format!("apply_patch <<'PATCH'\n{patch}\nPATCH")}) + }] + ); + let shell = + [json!({"name":"shell","parameters":{"properties":{"command":{"type":"array"}}}})]; + assert_eq!( + parse_complete(&output, &shell).unwrap(), + vec![Segment::Call { + name: "shell".into(), + arguments: json!({"command": ["bash", "-lc", format!("apply_patch <<'PATCH'\n{patch}\nPATCH")]}) + }] + ); + // a declared apply_patch is left alone, and with no shell tool the call is still an error + let declared = + [json!({"name":"apply_patch","parameters":{"properties":{"input":{"type":"string"}}}})]; + assert_eq!( + parse_complete(&output, &declared).unwrap(), + vec![Segment::Call { + name: "apply_patch".into(), + arguments: json!({"input": patch}) + }] + ); + let none = + [json!({"name":"write_stdin","parameters":{"properties":{"chars":{"type":"string"}}}})]; + assert!( + parse_complete(&output, &none) + .unwrap_err() + .contains("undeclared function") + ); +} + +#[test] +fn other_undeclared_functions_still_fail() { + let exec = + [json!({"name":"exec_command","parameters":{"properties":{"cmd":{"type":"string"}}}})]; + let output = "\n\n\n1\n\n\n"; + assert!( + parse_complete(output, &exec) + .unwrap_err() + .contains("undeclared function in tool call: nope") + ); +} + +fn calls_of(segments: Vec) -> Vec<(String, Value)> { + segments + .into_iter() + .filter_map(|segment| match segment { + Segment::Call { name, arguments } => Some((name, arguments)), + Segment::Text(_) => None, + }) + .collect() +} + +fn stream( + tools: &[Value], + text: &str, + size: usize, + natural_stop: bool, +) -> Result<(Vec, Notes), String> { + let mut parser = Incremental::new(tools); + let mut out = Vec::new(); + let chars: Vec<(usize, char)> = text.char_indices().collect(); + for chunk in chars.chunks(size) { + let from = chunk[0].0; + let to = chunk.last().map_or(from, |(at, c)| at + c.len_utf8()); + out.extend(parser.feed(&text[from..to])?); + } + out.extend(parser.finish_after(natural_stop)?); + Ok((out, parser.notes().clone())) +} + +#[test] +fn a_call_without_function_close_is_read_when_the_wrapper_closes_it() { + let tools = [ + json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}}), + ]; + let text = "\n\n\nout.txt\n\n\nhello\n\n"; + let want = vec![( + "write".to_owned(), + json!({"path":"out.txt","content":"hello"}), + )]; + let parsed = parse_with(text, &tools, Options::default()).unwrap(); + assert_eq!(calls_of(parsed.segments), want); + assert_eq!(parsed.notes.closers_supplied, 1); + for size in [1, 7, text.len()] { + let (segments, notes) = stream(&tools, text, size, true).unwrap(); + assert_eq!(calls_of(segments), want, "pieces of {size}"); + assert_eq!(notes.closers_supplied, 1); + } + // two such calls, then a well-formed one + let two = format!( + "{text}\n{text}\nz" + ); + assert_eq!(calls_of(parse_complete(&two, &tools).unwrap()).len(), 3); +} + +#[test] +fn a_value_that_quotes_a_malformed_tail_is_not_cut_when_the_real_close_exists() { + // `\n` inside the value is only a candidate end: a real `` follows + let tools = + [json!({"name":"write","parameters":{"properties":{"content":{"type":"string"}}}})]; + let content = + "a call that lost its closer ends like\n\n\nand that is all"; + let text = format!( + "\n\n\n{content}\n\n\n" + ); + let want = vec![("write".to_owned(), json!({"content": content}))]; + assert_eq!(calls_of(parse_complete(&text, &tools).unwrap()), want); + for size in [1, 5, text.len()] { + let (segments, _) = stream(&tools, &text, size, true).unwrap(); + assert_eq!(calls_of(segments), want, "pieces of {size}"); + } +} + +#[test] +fn a_missing_wrapper_close_is_confirmed_only_by_the_next_call_or_a_natural_end() { + let tools = [json!({"name":"read","parameters":{"properties":{"path":{"type":"string"}}}})]; + let open = + "\n\n\na.txt\n\n"; + let whole = format!("{open}\n"); + let want = vec![("read".to_owned(), json!({"path":"a.txt"}))]; + assert_eq!(calls_of(parse_complete(&whole, &tools).unwrap()), want); + // ends on ``: whole only when the generation stopped by itself + assert!(parse_complete(open, &tools).is_err()); + assert!( + parse_with( + open, + &tools, + Options { + natural_stop: false, + ..Options::default() + } + ) + .is_err() + ); + assert_eq!( + calls_of( + parse_with( + open, + &tools, + Options { + natural_stop: true, + ..Options::default() + } + ) + .unwrap() + .segments + ), + want + ); + assert!(stream(&tools, open, 3, false).is_err()); + assert_eq!(calls_of(stream(&tools, open, 3, true).unwrap().0), want); + // prose after `` does not confirm it + let prose = format!("{open}\nand then I will"); + assert!( + parse_with( + &prose, + &tools, + Options { + natural_stop: true, + ..Options::default() + } + ) + .is_err() + ); + // the next call's opener does + let next = format!( + "{open}\n\n\n\nb.txt\n\n\n" + ); + let both = vec![ + want[0].clone(), + ("read".to_owned(), json!({"path":"b.txt"})), + ]; + assert_eq!(calls_of(parse_complete(&next, &tools).unwrap()), both); + for size in [1, 4, next.len()] { + assert_eq!( + calls_of(stream(&tools, &next, size, false).unwrap().0), + both, + "pieces of {size}" + ); + } +} + +#[test] +fn damaged_array_arguments_are_read_as_written_but_never_completed_or_pruned() { + let tools = [ + json!({"name":"todo","parameters":{"properties":{"todos":{"type":"array"},"note":{"type":"string"},"any":{"type":["string","array"]}}}}), + ]; + let read = |value: &str, parameter: &str| { + let text = format!( + "\n{value}\n" + ); + let parsed = parse_with(&text, &tools, Options::default()).unwrap(); + let repaired = parsed.notes.repaired_arguments; + ( + calls_of(parsed.segments).remove(0).1[parameter].clone(), + repaired, + ) + }; + for (value, want) in [ + ("[{'a': 1, 'b': True},]", json!([{"a": 1, "b": true}])), + ("[1,, 2,]", json!([1, 2])), + ("[{\"a\": None}]]", json!([{"a": null}])), + ("\"[{\\\"a\\\": 1}]\"", json!([{"a": 1}])), + ("\"[1, 2,]\"", json!([1, 2])), + ] { + assert_eq!(read(value, "todos"), (want, 1), "{value}"); + } + // valid JSON is not a repair + assert_eq!(read("[1, 2]", "todos"), (json!([1, 2]), 0)); + // not repaired, still the text the model wrote: brackets left open, a bare string, a missing colon, an unknown word + for value in [ + "[{\"a\": 1},", + "[{\"a\": 1, \"b\"}]", + "[{\"a\" 1}]", + "[nope]", + "[\"unterminated]", + ] { + assert_eq!(read(value, "todos"), (json!(value), 0), "{value}"); + } + // string parameters and unions with a string are untouched + assert_eq!(read("[1, 2,]", "note"), (json!("[1, 2,]"), 0)); + assert_eq!(read("[1, 2,]", "any"), (json!("[1, 2,]"), 0)); +} + +#[test] +fn calls_the_reasoning_ends_on_are_calls_and_calls_it_quotes_are_not() { + let tools = [json!({"name":"read","parameters":{"properties":{"path":{"type":"string"}}}})]; + let call = "\n\n\na.txt\n\n\n"; + let at = |text: &str| calls_at_end(text, &tools, Options::default()); + assert_eq!(at(&format!("Plan.\n\n{call}")), Some(7)); + assert_eq!(at(&format!("{call}\n{call}")), Some(0)); + // the call is not the last thing, is in a fence or in inline code, is mid-line, or names an undeclared tool + assert_eq!(at(&format!("{call}\nthen more thinking")), None); + assert_eq!(at(&format!("```\n{call}\n```")), None); + assert_eq!(at(&format!("a `quote {call}")), None); + assert_eq!(at(&format!("so I write {call}")), None); + assert_eq!(at(&call.replace("read", "format_disk")), None); + // a quoted call earlier does not hide the real one at the end + let after_quote = format!("```\n{call}\n```\nNow for real:\n{call}"); + assert_eq!(at(&after_quote), Some(after_quote.len() - call.len())); +} + +#[test] +fn parses_typed_values_and_preserves_text_around_calls() { + let tools = [ + json!({"name":"lookup","parameters":{"properties":{"n":{"type":"integer"},"term":{"type":"string"}}}}), + ]; + let output = "Let me check.\n\n\n\n\n12\n\n\n12\n\n\n\nanswer"; + assert_eq!( + parse_complete(output, &tools).unwrap(), + vec![ + Segment::Text("Let me check.".into()), + Segment::Call { + name: "lookup".into(), + arguments: json!({"n":12,"term":"12"}) + }, + Segment::Text("answer".into()), + ] + ); +} + +#[test] +fn string_type_unions_preserve_raw_text_and_decode_declared_json_types() { + for (types, raw, expected) in [ + (json!(["string", "null"]), "123", json!("123")), + (json!(["null", "string"]), "false", json!("false")), + (json!(["string", "null"]), "{}", json!("{}")), + (json!(["string", "null"]), "[]", json!("[]")), + (json!(["string", "null"]), "null", Value::Null), + (json!(["string", "null"]), "\"123\"", json!("\"123\"")), + (json!(["string", "null"]), " 123 ", json!(" 123 ")), + (json!(["string", "integer"]), "12", json!(12)), + (json!(["string", "integer"]), "1.5", json!("1.5")), + (json!(["string", "integer"]), "1.0", json!(1.0)), + (json!(["string", "number"]), "1.5", json!(1.5)), + (json!(["string", "boolean"]), "false", json!(false)), + (json!(["string", "object"]), "{}", json!({})), + (json!(["string", "array"]), "[]", json!([])), + (json!(["string"]), "null", json!("null")), + (json!("string"), "null", json!("null")), + (json!("string"), "\"x\"", json!("\"x\"")), + (json!(["integer", "null"]), "12", json!(12)), + ] { + let tools = + [json!({"name":"lookup","parameters":{"properties":{"value":{"type":types}}}})]; + let text = format!( + "{raw}" + ); + let expected = vec![Segment::Call { + name: "lookup".into(), + arguments: json!({"value":expected}), + }]; + assert_eq!( + parse_complete(&text, &tools).unwrap(), + expected, + "{types}: {raw}" + ); + let mut parser = Incremental::new(&tools); + let mut streamed = Vec::new(); + for ch in text.chars() { + streamed.extend(parser.feed(&ch.to_string()).unwrap()); + } + streamed.extend(parser.finish().unwrap()); + assert_eq!(streamed, expected, "stream {types}: {raw}"); + } +} + +#[test] +fn incomplete_or_undeclared_calls_are_never_published() { + let tools = [json!({"name":"write","parameters":{"properties":{}}})]; + assert!(parse_complete("half", &tools).is_err()); + assert!( + parse_complete("", &tools).is_err() + ); + assert!(parse_complete("", &tools).is_err()); +} + +#[test] +fn incremental_parser_holds_partial_markers_and_nested_tag_examples() { + let content = + "Close with and .\n\nexample\n\nend"; + let output = format!( + "First.\n\n\n\n\n{content}\n\n\n\nDone." + ); + let tools = + [json!({"name":"write","parameters":{"properties":{"content":{"type":"string"}}}})]; + let mut parser = Incremental::new(&tools); + let mut segments = Vec::new(); + for ch in output.chars() { + segments.extend(parser.feed(&ch.to_string()).unwrap()); + } + segments.extend(parser.finish().unwrap()); + let text = segments + .iter() + .filter_map(|segment| match segment { + Segment::Text(value) => Some(value.as_str()), + _ => None, + }) + .collect::(); + let calls = segments + .iter() + .filter_map(|segment| match segment { + Segment::Call { arguments, .. } => Some(arguments), + _ => None, + }) + .collect::>(); + assert_eq!(text, "First.Done."); + assert_eq!(calls, vec![&json!({"content":content})]); + assert!( + segments + .iter() + .filter_map(|segment| match segment { + Segment::Text(value) => Some(value), + _ => None, + }) + .all(|text| !text.contains("half") + .unwrap(); + assert!(cut.finish().is_err()); +} + +#[test] +fn a_quoted_call_in_a_value_does_not_end_the_value_and_a_cut_outer_call_is_not_published() { + let tools = [ + json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}}), + ]; + let quoted = "\n\n\nx.txt\n\n\n"; + let content = format!("transcript:\n{quoted}\nafter"); + let call = |tail: &str| { + format!( + "\n\n\np.txt\n\n\n{content}{tail}" + ) + }; + let whole = call("\n\n\n"); + assert_eq!( + parse_complete(&whole, &tools).unwrap(), + vec![Segment::Call { + name: "write".into(), + arguments: json!({"path":"p.txt","content":content}) + }] + ); + // the outer call was cut (token limit) right after the quoted one: the quoted call's closers must not end the value, + // or a truncated write would be published as a whole call + let cut = format!( + "\n\n\np.txt\n\n\ntranscript:\n{quoted}" + ); + assert!(parse_complete(&cut, &tools).is_err()); + let mut parser = Incremental::new(&tools); + assert_eq!(parser.feed(&cut).unwrap(), vec![]); + assert!(parser.finish().is_err()); + // a parameter written twice stays refused, not merged into one argument + let twice = "a\n\n\nb"; + assert!( + parse_complete(twice, &tools) + .unwrap_err() + .contains("duplicate tool parameter: content") + ); +} + +const ON: Options = Options { + natural_stop: true, + recovery: true, +}; + +fn write_tools() -> [Value; 2] { + [ + json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}}), + json!({"name":"todo","parameters":{"properties":{"todos":{"type":"array"}}}}), + ] +} + +/// Whole and streamed (several piece sizes, recovery on): the segments, which must agree. +fn read_on(tools: &[Value], text: &str) -> Vec { + let whole = parse_with(text, tools, ON).unwrap().segments; + for size in [1, 2, 3, 7, text.len()] { + let mut parser = Incremental::with_options(tools, ON); + let mut out = Vec::new(); + let chars: Vec<(usize, char)> = text.char_indices().collect(); + for chunk in chars.chunks(size) { + let from = chunk[0].0; + let to = chunk.last().map_or(from, |(at, c)| at + c.len_utf8()); + out.extend(parser.feed(&text[from..to]).unwrap()); + } + out.extend(parser.finish_after(true).unwrap()); + assert_eq!( + join_text(out), + join_text(whole_clone(&whole)), + "pieces of {size}: {text:?}" + ); + } + whole +} + +fn whole_clone(segments: &[Segment]) -> Vec { + segments + .iter() + .map(|segment| match segment { + Segment::Text(text) => Segment::Text(text.clone()), + Segment::Call { name, arguments } => Segment::Call { + name: name.clone(), + arguments: arguments.clone(), + }, + }) + .collect() +} + +/// Adjacent text segments are one text (a stream may cut it anywhere). +fn join_text(segments: Vec) -> Vec { + let mut out: Vec = Vec::new(); + for segment in segments { + match (out.last_mut(), segment) { + (Some(Segment::Text(last)), Segment::Text(next)) => last.push_str(&next), + (_, segment) => out.push(segment), + } + } + out +} + +fn call(name: &str, arguments: Value) -> Segment { + Segment::Call { + name: name.into(), + arguments, + } +} + +const BODY: &str = + "\na.md\n\n\nhi\n\n"; + +#[test] +fn drifted_forms_are_calls_only_with_recovery_and_only_for_declared_tools() { + let tools = write_tools(); + let want = || call("write", json!({"path":"a.md","content":"hi"})); + for (label, text) in [ + ("parameter as opener", format!("\n\n{BODY}\n")), + ("json in the wrapper", "\n{\"name\": \"write\", \"arguments\": {\"path\": \"a.md\", \"content\": \"hi\"}}\n".to_owned()), + ("json in a fence", "\n```json\n{\"name\": \"write\", \"arguments\": \"{\\\"path\\\": \\\"a.md\\\", \\\"content\\\": \\\"hi\\\"}\"}\n```\n".to_owned()), + ("= opener", format!("\n<=write>\n{BODY}\n")), + ("function colon", format!("\n\n{BODY}\n")), + ("function space equals", format!("\n\n{BODY}\n")), + ("bare name", format!("\n\n{BODY}\n")), + ("bare function", format!("\n{BODY}")), + ("bare function then a stray closer", format!("\n{BODY}\n")), + ] { + assert!(parse_complete(&text, &tools).is_err() || label.starts_with("bare function"), "{label} is no call without recovery"); + assert_eq!(read_on(&tools, &text), vec![want()], "{label}"); + } + // text around a bare call, and the same text without recovery is just text + let around = format!("Writing it now.\n\n\n{BODY}\nDone."); + assert_eq!( + read_on(&tools, &around), + vec![ + Segment::Text("Writing it now.".into()), + want(), + Segment::Text("Done.".into()) + ] + ); + assert_eq!( + parse_complete(&around, &tools).unwrap(), + vec![Segment::Text(around.clone())] + ); + // a batch in one wrapper, the second opened as + let second = BODY.replace("a.md", "b.md"); + for opener in ["", ""] { + let batch = + format!("\n\n{BODY}\n{opener}\n{second}\n"); + assert!(parse_complete(&batch, &tools).is_err()); + assert_eq!( + read_on(&tools, &batch), + vec![want(), call("write", json!({"path":"b.md","content":"hi"}))], + "{opener}" + ); + } + // never an undeclared tool, in any form + for text in [ + format!("\n\n{BODY}\n"), + format!("\n\n{BODY}\n"), + format!("\n{BODY}"), + "\n{\"name\": \"format_disk\", \"arguments\": {}}\n".to_owned(), + ] { + let read = parse_with(&text, &tools, ON); + assert!( + read.is_err() + || read + .unwrap() + .segments + .iter() + .all(|segment| matches!(segment, Segment::Text(_))), + "{text:?}" + ); + } +} + +#[test] +fn a_bare_function_is_a_call_only_at_a_line_start_outside_code() { + let tools = write_tools(); + let bare = format!("\n{BODY}"); + for text in [ + format!("```\n{bare}\n```"), + format!("~~~\n{bare}\n~~~"), + format!("the opener `{bare}"), + format!("so I call it with {bare}"), + "A call starts with in the template.".to_owned(), + "\n{value}\n" + ) + }; + let todos = |segments: Vec| calls_of(segments).remove(0).1["todos"].clone(); + assert_eq!( + todos(parse_complete(&text(stray), &tools).unwrap()), + json!(stray) + ); + assert_eq!( + todos(parse_complete(&text(cut), &tools).unwrap()), + json!(cut) + ); + assert_eq!( + todos(read_on(&tools, &text(stray))), + json!([{"content": "a", "status": "pending", "done": false}]) + ); + assert_eq!( + todos(read_on(&tools, &text(cut))), + json!([{"content": "a", "status": "pending"}]) + ); + let notes = parse_with(&text(cut), &tools, ON).unwrap().notes; + assert_eq!(notes.repaired_arguments, 1); +} + +#[test] +fn the_default_reading_is_the_same_with_the_option_off() { + // every shape of the step-3 tests, read with recovery off, is unchanged by the existence of the option + let tools = write_tools(); + let off = Options { + natural_stop: true, + recovery: false, + }; + for text in [ + "\n{\"name\": \"write\", \"arguments\": {}}\n".to_owned(), + format!("\n\n{BODY}\n"), + ] { + assert!(parse_with(&text, &tools, off).is_err()); + } + let around = format!("text\n\n{BODY}"); + assert_eq!( + parse_with(&around, &tools, off).unwrap().segments, + vec![Segment::Text(around)] + ); +} diff --git a/crates/gptoss/src/ops.rs b/crates/gptoss/src/ops.rs index 81c19f08..66d42171 100644 --- a/crates/gptoss/src/ops.rs +++ b/crates/gptoss/src/ops.rs @@ -207,346 +207,4 @@ pub fn swiglu_oai(gate: f32, linear: f32, alpha: f32, limit: f32) -> f32 { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn rms_norm_matches_an_f64_formula() { - let x: Vec = (0..2880) - .map(|i| ((i * 37 % 101) as f32 - 50.0) * 0.07) - .collect(); - let w: Vec = (0..2880).map(|i| 0.5 + (i % 7) as f32 * 0.1).collect(); - let mut out = vec![0.0; 2880]; - rms_norm(&x, &w, 1e-5, &mut out); - let mean: f64 = x.iter().map(|v| f64::from(*v).powi(2)).sum::() / 2880.0; - for i in 0..2880 { - let expected = f64::from(x[i]) / (mean + 1e-5).sqrt() * f64::from(w[i]); - assert!( - (f64::from(out[i]) - expected).abs() <= 2e-6 * expected.abs().max(1.0), - "element {i}" - ); - } - } - - #[test] - fn yarn_correction_range_for_gpt_oss() { - // n_dims 64, original context 4096, base 150000: values computed independently in f64. - let y = Yarn::gpt_oss(150000.0, 32.0, 4096); - let corr = |n_rot: f64| { - 64.0 * (4096.0 / (n_rot * 2.0 * std::f64::consts::PI)).ln() / (2.0 * 150000f64.ln()) - }; - let expected = [corr(32.0).floor().max(0.0), corr(1.0).ceil().min(63.0)]; - let got = y.corr_dims(64); - assert_eq!([f64::from(got[0]), f64::from(got[1])], expected); - assert!(got[0] < got[1]); - } - - #[test] - fn rotation_at_position_zero_is_the_scaled_identity() { - let y = Yarn::gpt_oss(150000.0, 32.0, 4096); - let mut r = vec![(0.0, 0.0); 32]; - y.rotation(0, 64, &mut r); - let m = 1.0 + 0.1 * 32f32.ln(); - for (c, s) in r { - assert!((c - m).abs() < 1e-6 && s.abs() < 1e-6); - } - } - - #[test] - fn rotation_matches_the_closed_form_for_the_first_and_last_pairs() { - let y = Yarn::gpt_oss(150000.0, 32.0, 4096); - let mut r = vec![(0.0, 0.0); 32]; - let pos = 1234u32; - y.rotation(pos, 64, &mut r); - let mscale = 1.0 + 0.1 * 32f64.ln(); - let corr = y.corr_dims(64); - for i in [0usize, 5, 17, 31] { - let extrap = f64::from(pos) * 150000f64.powf(-2.0 * i as f64 / 64.0); - let ramp = 1.0 - - ((i as f64 - f64::from(corr[0])) - / (f64::from(corr[1]) - f64::from(corr[0])).max(0.001)) - .clamp(0.0, 1.0); - let theta = extrap / 32.0 * (1.0 - ramp) + extrap * ramp; - let (c, s) = r[i]; - // f32 angle recurrence versus the f64 closed form: allow the accumulated f32 error. - assert!( - (f64::from(c) - theta.cos() * mscale).abs() < 5e-3, - "pair {i} cos" - ); - assert!( - (f64::from(s) - theta.sin() * mscale).abs() < 5e-3, - "pair {i} sin" - ); - } - } - - #[test] - fn rope_preserves_the_norm_up_to_the_magnitude_scale() { - let y = Yarn::gpt_oss(150000.0, 32.0, 4096); - let mut r = vec![(0.0, 0.0); 32]; - y.rotation(777, 64, &mut r); - let mut head: Vec = (0..64).map(|i| (i as f32 * 0.37).sin()).collect(); - let before: f32 = head.iter().map(|v| v * v).sum::().sqrt(); - rope_neox(&mut head, &r); - let after: f32 = head.iter().map(|v| v * v).sum::().sqrt(); - let m = 1.0 + 0.1 * 32f32.ln(); - assert!((after / before - m).abs() < 1e-4); - } - - fn flat(rows: &[[f32; N]]) -> Vec { - rows.iter().flatten().copied().collect() - } - - /// Round to half precision and back: what the cache holds, so references can use the same values. - fn round_half(values: &[f32]) -> Vec { - values - .iter() - .map(|v| leleka_cpu_sys::simd::f16_to_f32(leleka_cpu_sys::simd::f32_to_f16(*v))) - .collect() - } - - fn to_bits(values: &[f32]) -> Vec { - values - .iter() - .map(|v| leleka_cpu_sys::simd::f32_to_f16(*v)) - .collect() - } - - /// Runs `attend_with_sink` at every kernel level this machine supports. - fn attend_everywhere( - query: &[f32], - scale: f32, - sink: f32, - keys: &[f32], - values: &[f32], - stride: usize, - n: usize, - ) -> Vec> { - let (keys, values) = (to_bits(keys), to_bits(values)); - let mut results = Vec::new(); - for isa in leleka_cpu_kernels::Isa::ALL { - let Ok(dispatch) = Dispatch::with_isa(isa) else { - continue; - }; - let mut scores = vec![0.0f32; n.max(1)]; - let mut out = vec![9.0f32; query.len()]; - attend_with_sink( - Head { query, scale, sink }, - KvRows { - keys: &keys, - values: &values, - stride, - }, - n, - &dispatch, - &mut scores, - &mut out, - ) - .unwrap(); - results.push(out); - } - results - } - - #[test] - fn attention_with_a_huge_sink_attends_to_nothing_and_a_very_negative_sink_is_plain_softmax() { - let q = [1.0f32, 0.0]; - let ks = flat(&[[1.0f32, 0.0], [0.0, 1.0], [2.0, 0.0]]); - let vs = flat(&[[1.0f32, 10.0], [2.0, 20.0], [3.0, 30.0]]); - for out in attend_everywhere(&q, 1.0, 1000.0, &ks, &vs, 2, 3) { - assert!( - out.iter().all(|v| v.abs() < 1e-6), - "sink absorbs all weight: {out:?}" - ); - } - let e: Vec = [1.0f64, 0.0, 2.0].iter().map(|s| s.exp()).collect(); - let z: f64 = e.iter().sum(); - let expected0 = (e[0] * 1.0 + e[1] * 2.0 + e[2] * 3.0) / z; - for out in attend_everywhere(&q, 1.0, -1000.0, &ks, &vs, 2, 3) { - assert!((f64::from(out[0]) - expected0).abs() < 1e-5); - } - } - - #[test] - fn attention_with_a_finite_sink_matches_an_f64_reference() { - let q = [0.3f32, -0.7, 0.2]; - let ks: Vec<[f32; 3]> = (0..6) - .map(|i| [(i as f32).sin(), (i as f32 * 0.5).cos(), 0.1 * i as f32]) - .collect(); - let vs: Vec<[f32; 3]> = (0..6).map(|i| [i as f32, -(i as f32), 1.0]).collect(); - let sink = 0.8f32; - let scale = 0.125f32; - // positions 1..6: the slices begin at position 1 - let (kf, vf) = (round_half(&flat(&ks)), round_half(&flat(&vs))); - let logits: Vec = (1..6) - .map(|p| { - (0..3) - .map(|d| f64::from(q[d]) * f64::from(kf[p * 3 + d])) - .sum::() - * f64::from(scale) - }) - .collect(); - let m = logits.iter().cloned().fold(f64::from(sink), f64::max); - let z: f64 = - logits.iter().map(|l| (l - m).exp()).sum::() + (f64::from(sink) - m).exp(); - for out in attend_everywhere(&q, scale, sink, &kf[3..], &vf[3..], 3, 5) { - for d in 0..3 { - let expected: f64 = (1..6) - .map(|p| (logits[p - 1] - m).exp() / z * f64::from(vf[p * 3 + d])) - .sum(); - assert!((f64::from(out[d]) - expected).abs() < 1e-5, "dim {d}"); - } - } - } - - #[test] - fn a_group_of_heads_equals_the_same_heads_one_at_a_time() { - let (hd, stride, n, heads) = (64usize, 128usize, 100usize, 4usize); - let mut state = 0xABCDu64; - let mut rnd = move || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - ((state >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 3.0 - }; - let queries: Vec = (0..heads * hd).map(|_| rnd()).collect(); - let sinks: Vec = (0..heads).map(|_| rnd()).collect(); - let ks: Vec = (0..(n - 1) * stride + hd).map(|_| rnd()).collect(); - let vs: Vec = (0..(n - 1) * stride + hd).map(|_| rnd()).collect(); - let (ks, vs) = (to_bits(&ks), to_bits(&vs)); - for isa in leleka_cpu_kernels::Isa::ALL { - let Ok(dispatch) = Dispatch::with_isa(isa) else { - continue; - }; - let kv = || KvRows { - keys: &ks, - values: &vs, - stride, - }; - let mut grouped = vec![0.0f32; heads * hd]; - attend_group_with_sink( - Group { - queries: &queries, - sinks: &sinks, - scale: 0.125, - }, - kv(), - n, - &dispatch, - &mut vec![0.0; heads * n], - &mut grouped, - ) - .unwrap(); - for g in 0..heads { - let mut single = vec![0.0f32; hd]; - attend_with_sink( - Head { - query: &queries[g * hd..(g + 1) * hd], - scale: 0.125, - sink: sinks[g], - }, - kv(), - n, - &dispatch, - &mut vec![0.0; n], - &mut single, - ) - .unwrap(); - assert_eq!( - &grouped[g * hd..(g + 1) * hd], - &single[..], - "{isa} head {g}" - ); - } - } - } - #[test] - fn attention_over_a_realistic_cache_agrees_across_kernel_levels() { - // 64-wide heads at the cache stride of a KV head pair, 300 positions - let (hd, stride, n) = (64usize, 128usize, 300usize); - let mut state = 0x1234_5678u64; - let mut rnd = move || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - ((state >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 4.0 - }; - let q: Vec = (0..hd).map(|_| rnd()).collect(); - let ks: Vec = round_half( - &(0..(n - 1) * stride + hd) - .map(|_| rnd()) - .collect::>(), - ); - let vs: Vec = round_half( - &(0..(n - 1) * stride + hd) - .map(|_| rnd()) - .collect::>(), - ); - let results = attend_everywhere(&q, 0.125, 0.5, &ks, &vs, stride, n); - assert!(!results.is_empty()); - for out in &results[1..] { - for (a, b) in results[0].iter().zip(out) { - assert!((a - b).abs() < 2e-5 * (1.0 + a.abs()), "{a} vs {b}"); - } - } - // against an f64 softmax - let scale = 0.125f64; - let logits: Vec = (0..n) - .map(|i| { - (0..hd) - .map(|j| f64::from(q[j]) * f64::from(ks[i * stride + j])) - .sum::() - * scale - }) - .collect(); - let m = logits.iter().cloned().fold(0.5f64, f64::max); - let z: f64 = logits.iter().map(|l| (l - m).exp()).sum::() + (0.5f64 - m).exp(); - for j in 0..hd { - let expected: f64 = (0..n) - .map(|i| (logits[i] - m).exp() / z * f64::from(vs[i * stride + j])) - .sum(); - assert!( - (f64::from(results[0][j]) - expected).abs() < 1e-4 * (1.0 + expected.abs()), - "column {j}" - ); - } - } - #[test] - fn routing_picks_the_largest_logits_and_softmaxes_only_those() { - let logits = [0.1f32, 2.0, -1.0, 2.0, 0.5, 1.0]; - let r = route_top_k(&logits, 3); - assert_eq!(r.iter().map(|(i, _)| *i).collect::>(), vec![1, 3, 5]); - let sum: f32 = r.iter().map(|(_, w)| w).sum(); - assert!((sum - 1.0).abs() < 1e-6); - let e: Vec = [2.0f64, 2.0, 1.0].iter().map(|v| v.exp()).collect(); - let z: f64 = e.iter().sum(); - assert!((f64::from(r[0].1) - e[0] / z).abs() < 1e-6); - assert!((f64::from(r[2].1) - e[2] / z).abs() < 1e-6); - } - - #[test] - fn swiglu_oai_matches_the_definition_including_both_clamps() { - let f = |g: f64, l: f64| { - let x = g.min(7.0); - let y = l.clamp(-7.0, 7.0); - x * (1.0 / (1.0 + (-1.702 * x).exp())) * (y + 1.0) - }; - for (g, l) in [ - (0.0, 0.0), - (1.0, 2.0), - (-3.0, 0.5), - (9.0, 1.0), - (2.0, 20.0), - (2.0, -20.0), - (-20.0, 3.0), - ] { - let got = f64::from(swiglu_oai(g as f32, l as f32, 1.702, 7.0)); - assert!( - (got - f(g, l)).abs() < 1e-5 * f(g, l).abs().max(1.0), - "gate {g} linear {l}" - ); - } - // The gate is clamped only from above. - assert!(swiglu_oai(-50.0, 1.0, 1.702, 7.0).abs() < 1e-6); - } -} +mod tests; diff --git a/crates/gptoss/src/ops/tests.rs b/crates/gptoss/src/ops/tests.rs new file mode 100644 index 00000000..6026c590 --- /dev/null +++ b/crates/gptoss/src/ops/tests.rs @@ -0,0 +1,343 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn rms_norm_matches_an_f64_formula() { + let x: Vec = (0..2880) + .map(|i| ((i * 37 % 101) as f32 - 50.0) * 0.07) + .collect(); + let w: Vec = (0..2880).map(|i| 0.5 + (i % 7) as f32 * 0.1).collect(); + let mut out = vec![0.0; 2880]; + rms_norm(&x, &w, 1e-5, &mut out); + let mean: f64 = x.iter().map(|v| f64::from(*v).powi(2)).sum::() / 2880.0; + for i in 0..2880 { + let expected = f64::from(x[i]) / (mean + 1e-5).sqrt() * f64::from(w[i]); + assert!( + (f64::from(out[i]) - expected).abs() <= 2e-6 * expected.abs().max(1.0), + "element {i}" + ); + } +} + +#[test] +fn yarn_correction_range_for_gpt_oss() { + // n_dims 64, original context 4096, base 150000: values computed independently in f64. + let y = Yarn::gpt_oss(150000.0, 32.0, 4096); + let corr = |n_rot: f64| { + 64.0 * (4096.0 / (n_rot * 2.0 * std::f64::consts::PI)).ln() / (2.0 * 150000f64.ln()) + }; + let expected = [corr(32.0).floor().max(0.0), corr(1.0).ceil().min(63.0)]; + let got = y.corr_dims(64); + assert_eq!([f64::from(got[0]), f64::from(got[1])], expected); + assert!(got[0] < got[1]); +} + +#[test] +fn rotation_at_position_zero_is_the_scaled_identity() { + let y = Yarn::gpt_oss(150000.0, 32.0, 4096); + let mut r = vec![(0.0, 0.0); 32]; + y.rotation(0, 64, &mut r); + let m = 1.0 + 0.1 * 32f32.ln(); + for (c, s) in r { + assert!((c - m).abs() < 1e-6 && s.abs() < 1e-6); + } +} + +#[test] +fn rotation_matches_the_closed_form_for_the_first_and_last_pairs() { + let y = Yarn::gpt_oss(150000.0, 32.0, 4096); + let mut r = vec![(0.0, 0.0); 32]; + let pos = 1234u32; + y.rotation(pos, 64, &mut r); + let mscale = 1.0 + 0.1 * 32f64.ln(); + let corr = y.corr_dims(64); + for i in [0usize, 5, 17, 31] { + let extrap = f64::from(pos) * 150000f64.powf(-2.0 * i as f64 / 64.0); + let ramp = 1.0 + - ((i as f64 - f64::from(corr[0])) + / (f64::from(corr[1]) - f64::from(corr[0])).max(0.001)) + .clamp(0.0, 1.0); + let theta = extrap / 32.0 * (1.0 - ramp) + extrap * ramp; + let (c, s) = r[i]; + // f32 angle recurrence versus the f64 closed form: allow the accumulated f32 error. + assert!( + (f64::from(c) - theta.cos() * mscale).abs() < 5e-3, + "pair {i} cos" + ); + assert!( + (f64::from(s) - theta.sin() * mscale).abs() < 5e-3, + "pair {i} sin" + ); + } +} + +#[test] +fn rope_preserves_the_norm_up_to_the_magnitude_scale() { + let y = Yarn::gpt_oss(150000.0, 32.0, 4096); + let mut r = vec![(0.0, 0.0); 32]; + y.rotation(777, 64, &mut r); + let mut head: Vec = (0..64).map(|i| (i as f32 * 0.37).sin()).collect(); + let before: f32 = head.iter().map(|v| v * v).sum::().sqrt(); + rope_neox(&mut head, &r); + let after: f32 = head.iter().map(|v| v * v).sum::().sqrt(); + let m = 1.0 + 0.1 * 32f32.ln(); + assert!((after / before - m).abs() < 1e-4); +} + +fn flat(rows: &[[f32; N]]) -> Vec { + rows.iter().flatten().copied().collect() +} + +/// Round to half precision and back: what the cache holds, so references can use the same values. +fn round_half(values: &[f32]) -> Vec { + values + .iter() + .map(|v| leleka_cpu_sys::simd::f16_to_f32(leleka_cpu_sys::simd::f32_to_f16(*v))) + .collect() +} + +fn to_bits(values: &[f32]) -> Vec { + values + .iter() + .map(|v| leleka_cpu_sys::simd::f32_to_f16(*v)) + .collect() +} + +/// Runs `attend_with_sink` at every kernel level this machine supports. +fn attend_everywhere( + query: &[f32], + scale: f32, + sink: f32, + keys: &[f32], + values: &[f32], + stride: usize, + n: usize, +) -> Vec> { + let (keys, values) = (to_bits(keys), to_bits(values)); + let mut results = Vec::new(); + for isa in leleka_cpu_kernels::Isa::ALL { + let Ok(dispatch) = Dispatch::with_isa(isa) else { + continue; + }; + let mut scores = vec![0.0f32; n.max(1)]; + let mut out = vec![9.0f32; query.len()]; + attend_with_sink( + Head { query, scale, sink }, + KvRows { + keys: &keys, + values: &values, + stride, + }, + n, + &dispatch, + &mut scores, + &mut out, + ) + .unwrap(); + results.push(out); + } + results +} + +#[test] +fn attention_with_a_huge_sink_attends_to_nothing_and_a_very_negative_sink_is_plain_softmax() { + let q = [1.0f32, 0.0]; + let ks = flat(&[[1.0f32, 0.0], [0.0, 1.0], [2.0, 0.0]]); + let vs = flat(&[[1.0f32, 10.0], [2.0, 20.0], [3.0, 30.0]]); + for out in attend_everywhere(&q, 1.0, 1000.0, &ks, &vs, 2, 3) { + assert!( + out.iter().all(|v| v.abs() < 1e-6), + "sink absorbs all weight: {out:?}" + ); + } + let e: Vec = [1.0f64, 0.0, 2.0].iter().map(|s| s.exp()).collect(); + let z: f64 = e.iter().sum(); + let expected0 = (e[0] * 1.0 + e[1] * 2.0 + e[2] * 3.0) / z; + for out in attend_everywhere(&q, 1.0, -1000.0, &ks, &vs, 2, 3) { + assert!((f64::from(out[0]) - expected0).abs() < 1e-5); + } +} + +#[test] +fn attention_with_a_finite_sink_matches_an_f64_reference() { + let q = [0.3f32, -0.7, 0.2]; + let ks: Vec<[f32; 3]> = (0..6) + .map(|i| [(i as f32).sin(), (i as f32 * 0.5).cos(), 0.1 * i as f32]) + .collect(); + let vs: Vec<[f32; 3]> = (0..6).map(|i| [i as f32, -(i as f32), 1.0]).collect(); + let sink = 0.8f32; + let scale = 0.125f32; + // positions 1..6: the slices begin at position 1 + let (kf, vf) = (round_half(&flat(&ks)), round_half(&flat(&vs))); + let logits: Vec = (1..6) + .map(|p| { + (0..3) + .map(|d| f64::from(q[d]) * f64::from(kf[p * 3 + d])) + .sum::() + * f64::from(scale) + }) + .collect(); + let m = logits.iter().cloned().fold(f64::from(sink), f64::max); + let z: f64 = + logits.iter().map(|l| (l - m).exp()).sum::() + (f64::from(sink) - m).exp(); + for out in attend_everywhere(&q, scale, sink, &kf[3..], &vf[3..], 3, 5) { + for d in 0..3 { + let expected: f64 = (1..6) + .map(|p| (logits[p - 1] - m).exp() / z * f64::from(vf[p * 3 + d])) + .sum(); + assert!((f64::from(out[d]) - expected).abs() < 1e-5, "dim {d}"); + } + } +} + +#[test] +fn a_group_of_heads_equals_the_same_heads_one_at_a_time() { + let (hd, stride, n, heads) = (64usize, 128usize, 100usize, 4usize); + let mut state = 0xABCDu64; + let mut rnd = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + ((state >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 3.0 + }; + let queries: Vec = (0..heads * hd).map(|_| rnd()).collect(); + let sinks: Vec = (0..heads).map(|_| rnd()).collect(); + let ks: Vec = (0..(n - 1) * stride + hd).map(|_| rnd()).collect(); + let vs: Vec = (0..(n - 1) * stride + hd).map(|_| rnd()).collect(); + let (ks, vs) = (to_bits(&ks), to_bits(&vs)); + for isa in leleka_cpu_kernels::Isa::ALL { + let Ok(dispatch) = Dispatch::with_isa(isa) else { + continue; + }; + let kv = || KvRows { + keys: &ks, + values: &vs, + stride, + }; + let mut grouped = vec![0.0f32; heads * hd]; + attend_group_with_sink( + Group { + queries: &queries, + sinks: &sinks, + scale: 0.125, + }, + kv(), + n, + &dispatch, + &mut vec![0.0; heads * n], + &mut grouped, + ) + .unwrap(); + for g in 0..heads { + let mut single = vec![0.0f32; hd]; + attend_with_sink( + Head { + query: &queries[g * hd..(g + 1) * hd], + scale: 0.125, + sink: sinks[g], + }, + kv(), + n, + &dispatch, + &mut vec![0.0; n], + &mut single, + ) + .unwrap(); + assert_eq!( + &grouped[g * hd..(g + 1) * hd], + &single[..], + "{isa} head {g}" + ); + } + } +} +#[test] +fn attention_over_a_realistic_cache_agrees_across_kernel_levels() { + // 64-wide heads at the cache stride of a KV head pair, 300 positions + let (hd, stride, n) = (64usize, 128usize, 300usize); + let mut state = 0x1234_5678u64; + let mut rnd = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + ((state >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 4.0 + }; + let q: Vec = (0..hd).map(|_| rnd()).collect(); + let ks: Vec = round_half( + &(0..(n - 1) * stride + hd) + .map(|_| rnd()) + .collect::>(), + ); + let vs: Vec = round_half( + &(0..(n - 1) * stride + hd) + .map(|_| rnd()) + .collect::>(), + ); + let results = attend_everywhere(&q, 0.125, 0.5, &ks, &vs, stride, n); + assert!(!results.is_empty()); + for out in &results[1..] { + for (a, b) in results[0].iter().zip(out) { + assert!((a - b).abs() < 2e-5 * (1.0 + a.abs()), "{a} vs {b}"); + } + } + // against an f64 softmax + let scale = 0.125f64; + let logits: Vec = (0..n) + .map(|i| { + (0..hd) + .map(|j| f64::from(q[j]) * f64::from(ks[i * stride + j])) + .sum::() + * scale + }) + .collect(); + let m = logits.iter().cloned().fold(0.5f64, f64::max); + let z: f64 = logits.iter().map(|l| (l - m).exp()).sum::() + (0.5f64 - m).exp(); + for j in 0..hd { + let expected: f64 = (0..n) + .map(|i| (logits[i] - m).exp() / z * f64::from(vs[i * stride + j])) + .sum(); + assert!( + (f64::from(results[0][j]) - expected).abs() < 1e-4 * (1.0 + expected.abs()), + "column {j}" + ); + } +} +#[test] +fn routing_picks_the_largest_logits_and_softmaxes_only_those() { + let logits = [0.1f32, 2.0, -1.0, 2.0, 0.5, 1.0]; + let r = route_top_k(&logits, 3); + assert_eq!(r.iter().map(|(i, _)| *i).collect::>(), vec![1, 3, 5]); + let sum: f32 = r.iter().map(|(_, w)| w).sum(); + assert!((sum - 1.0).abs() < 1e-6); + let e: Vec = [2.0f64, 2.0, 1.0].iter().map(|v| v.exp()).collect(); + let z: f64 = e.iter().sum(); + assert!((f64::from(r[0].1) - e[0] / z).abs() < 1e-6); + assert!((f64::from(r[2].1) - e[2] / z).abs() < 1e-6); +} + +#[test] +fn swiglu_oai_matches_the_definition_including_both_clamps() { + let f = |g: f64, l: f64| { + let x = g.min(7.0); + let y = l.clamp(-7.0, 7.0); + x * (1.0 / (1.0 + (-1.702 * x).exp())) * (y + 1.0) + }; + for (g, l) in [ + (0.0, 0.0), + (1.0, 2.0), + (-3.0, 0.5), + (9.0, 1.0), + (2.0, 20.0), + (2.0, -20.0), + (-20.0, 3.0), + ] { + let got = f64::from(swiglu_oai(g as f32, l as f32, 1.702, 7.0)); + assert!( + (got - f(g, l)).abs() < 1e-5 * f(g, l).abs().max(1.0), + "gate {g} linear {l}" + ); + } + // The gate is clamped only from above. + assert!(swiglu_oai(-50.0, 1.0, 1.702, 7.0).abs() < 1e-6); +} diff --git a/crates/harmony/src/parse.rs b/crates/harmony/src/parse.rs index 5daeb91b..07d7449a 100644 --- a/crates/harmony/src/parse.rs +++ b/crates/harmony/src/parse.rs @@ -228,202 +228,4 @@ impl HarmonyParser { } #[cfg(test)] -mod tests { - use super::*; - use Piece::{Special as S, Text as T}; - - fn run(pieces: &[Piece]) -> Vec { - let mut p = HarmonyParser::new(); - pieces.iter().flat_map(|x| p.push(*x)).collect() - } - - fn reasoning(s: &str) -> Event { - Event::Reasoning(s.into()) - } - - fn content(s: &str) -> Event { - Event::Content(s.into()) - } - - #[test] - fn analysis_then_final_then_return() { - let events = run(&[ - S(Special::Channel), - T("analysis"), - S(Special::Message), - T("Let me "), - T("think."), - S(Special::End), - S(Special::Start), - T("assistant"), - S(Special::Channel), - T("final"), - S(Special::Message), - T("Paris."), - S(Special::Return), - ]); - assert_eq!( - events, - vec![ - reasoning("Let me "), - reasoning("think."), - content("Paris."), - Event::Returned - ] - ); - } - - #[test] - fn tool_call_with_recipient_after_the_channel() { - let events = run(&[ - S(Special::Channel), - T("commentary to=functions.get_weather "), - S(Special::Constrain), - T("json"), - S(Special::Message), - T("{\"city\":"), - T("\"Paris\"}"), - S(Special::Call), - ]); - assert_eq!( - events, - vec![ - Event::ToolCallStart { - index: 0, - name: "get_weather".into() - }, - Event::ToolCallArguments("{\"city\":".into()), - Event::ToolCallArguments("\"Paris\"}".into()), - Event::ToolCallEnd, - Event::Called - ] - ); - } - - #[test] - fn tool_call_with_recipient_in_the_start_header() { - let events = run(&[ - S(Special::Start), - T("assistant to=functions.f"), - S(Special::Channel), - T("commentary json"), - S(Special::Message), - T("{}"), - S(Special::Call), - ]); - assert_eq!( - events, - vec![ - Event::ToolCallStart { - index: 0, - name: "f".into() - }, - Event::ToolCallArguments("{}".into()), - Event::ToolCallEnd, - Event::Called - ] - ); - } - - #[test] - fn analysis_a_preamble_and_two_tool_calls_in_one_generation() { - let events = run(&[ - S(Special::Channel), - T("analysis"), - S(Special::Message), - T("plan"), - S(Special::End), - S(Special::Start), - T("assistant"), - S(Special::Channel), - T("commentary"), - S(Special::Message), - T("I will check."), - S(Special::End), - S(Special::Start), - T("assistant"), - S(Special::Channel), - T("commentary to=functions.a "), - S(Special::Constrain), - T("json"), - S(Special::Message), - T("{}"), - S(Special::End), - S(Special::Start), - T("assistant"), - S(Special::Channel), - T("commentary to=functions.b "), - S(Special::Constrain), - T("json"), - S(Special::Message), - T("{\"x\":1}"), - S(Special::Call), - ]); - assert_eq!( - events, - vec![ - reasoning("plan"), - content("I will check."), - Event::ToolCallStart { - index: 0, - name: "a".into() - }, - Event::ToolCallArguments("{}".into()), - Event::ToolCallEnd, - Event::ToolCallStart { - index: 1, - name: "b".into() - }, - Event::ToolCallArguments("{\"x\":1}".into()), - Event::ToolCallEnd, - Event::Called - ] - ); - } - - #[test] - fn unknown_channels_and_other_specials_are_dropped() { - let events = run(&[ - S(Special::Other), - S(Special::Channel), - T("mystery"), - S(Special::Message), - T("secret"), - S(Special::End), - S(Special::Start), - T("assistant"), - S(Special::Channel), - T("final"), - S(Special::Message), - T("ok"), - S(Special::Other), - S(Special::Return), - ]); - assert_eq!(events, vec![content("ok"), Event::Returned]); - } - - #[test] - fn a_cut_off_tool_call_is_closed_by_finish() { - let mut p = HarmonyParser::new(); - let mut events = Vec::new(); - for piece in [ - S(Special::Channel), - T("commentary to=functions.f"), - S(Special::Message), - T("{\"a\""), - ] { - events.extend(p.push(piece)); - } - events.extend(p.finish()); - assert_eq!(events.last(), Some(&Event::ToolCallEnd)); - assert!(p.finish().is_empty()); - } - - #[test] - fn special_markers_are_recognized_by_their_text() { - assert_eq!(Special::from_token_text("<|call|>"), Special::Call); - assert_eq!(Special::from_token_text("<|return|>"), Special::Return); - assert_eq!(Special::from_token_text("<|endoftext|>"), Special::Other); - assert_eq!(Special::from_token_text("hello"), Special::Other); - } -} +mod tests; diff --git a/crates/harmony/src/parse/tests.rs b/crates/harmony/src/parse/tests.rs new file mode 100644 index 00000000..690f4501 --- /dev/null +++ b/crates/harmony/src/parse/tests.rs @@ -0,0 +1,199 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use Piece::{Special as S, Text as T}; + +fn run(pieces: &[Piece]) -> Vec { + let mut p = HarmonyParser::new(); + pieces.iter().flat_map(|x| p.push(*x)).collect() +} + +fn reasoning(s: &str) -> Event { + Event::Reasoning(s.into()) +} + +fn content(s: &str) -> Event { + Event::Content(s.into()) +} + +#[test] +fn analysis_then_final_then_return() { + let events = run(&[ + S(Special::Channel), + T("analysis"), + S(Special::Message), + T("Let me "), + T("think."), + S(Special::End), + S(Special::Start), + T("assistant"), + S(Special::Channel), + T("final"), + S(Special::Message), + T("Paris."), + S(Special::Return), + ]); + assert_eq!( + events, + vec![ + reasoning("Let me "), + reasoning("think."), + content("Paris."), + Event::Returned + ] + ); +} + +#[test] +fn tool_call_with_recipient_after_the_channel() { + let events = run(&[ + S(Special::Channel), + T("commentary to=functions.get_weather "), + S(Special::Constrain), + T("json"), + S(Special::Message), + T("{\"city\":"), + T("\"Paris\"}"), + S(Special::Call), + ]); + assert_eq!( + events, + vec![ + Event::ToolCallStart { + index: 0, + name: "get_weather".into() + }, + Event::ToolCallArguments("{\"city\":".into()), + Event::ToolCallArguments("\"Paris\"}".into()), + Event::ToolCallEnd, + Event::Called + ] + ); +} + +#[test] +fn tool_call_with_recipient_in_the_start_header() { + let events = run(&[ + S(Special::Start), + T("assistant to=functions.f"), + S(Special::Channel), + T("commentary json"), + S(Special::Message), + T("{}"), + S(Special::Call), + ]); + assert_eq!( + events, + vec![ + Event::ToolCallStart { + index: 0, + name: "f".into() + }, + Event::ToolCallArguments("{}".into()), + Event::ToolCallEnd, + Event::Called + ] + ); +} + +#[test] +fn analysis_a_preamble_and_two_tool_calls_in_one_generation() { + let events = run(&[ + S(Special::Channel), + T("analysis"), + S(Special::Message), + T("plan"), + S(Special::End), + S(Special::Start), + T("assistant"), + S(Special::Channel), + T("commentary"), + S(Special::Message), + T("I will check."), + S(Special::End), + S(Special::Start), + T("assistant"), + S(Special::Channel), + T("commentary to=functions.a "), + S(Special::Constrain), + T("json"), + S(Special::Message), + T("{}"), + S(Special::End), + S(Special::Start), + T("assistant"), + S(Special::Channel), + T("commentary to=functions.b "), + S(Special::Constrain), + T("json"), + S(Special::Message), + T("{\"x\":1}"), + S(Special::Call), + ]); + assert_eq!( + events, + vec![ + reasoning("plan"), + content("I will check."), + Event::ToolCallStart { + index: 0, + name: "a".into() + }, + Event::ToolCallArguments("{}".into()), + Event::ToolCallEnd, + Event::ToolCallStart { + index: 1, + name: "b".into() + }, + Event::ToolCallArguments("{\"x\":1}".into()), + Event::ToolCallEnd, + Event::Called + ] + ); +} + +#[test] +fn unknown_channels_and_other_specials_are_dropped() { + let events = run(&[ + S(Special::Other), + S(Special::Channel), + T("mystery"), + S(Special::Message), + T("secret"), + S(Special::End), + S(Special::Start), + T("assistant"), + S(Special::Channel), + T("final"), + S(Special::Message), + T("ok"), + S(Special::Other), + S(Special::Return), + ]); + assert_eq!(events, vec![content("ok"), Event::Returned]); +} + +#[test] +fn a_cut_off_tool_call_is_closed_by_finish() { + let mut p = HarmonyParser::new(); + let mut events = Vec::new(); + for piece in [ + S(Special::Channel), + T("commentary to=functions.f"), + S(Special::Message), + T("{\"a\""), + ] { + events.extend(p.push(piece)); + } + events.extend(p.finish()); + assert_eq!(events.last(), Some(&Event::ToolCallEnd)); + assert!(p.finish().is_empty()); +} + +#[test] +fn special_markers_are_recognized_by_their_text() { + assert_eq!(Special::from_token_text("<|call|>"), Special::Call); + assert_eq!(Special::from_token_text("<|return|>"), Special::Return); + assert_eq!(Special::from_token_text("<|endoftext|>"), Special::Other); + assert_eq!(Special::from_token_text("hello"), Special::Other); +} diff --git a/crates/leleka-memory/src/governor.rs b/crates/leleka-memory/src/governor.rs index a92770b8..86edc665 100644 --- a/crates/leleka-memory/src/governor.rs +++ b/crates/leleka-memory/src/governor.rs @@ -1001,184 +1001,4 @@ impl Drop for SamplerGuard { } #[cfg(test)] -mod tests { - use super::*; - use crate::host::FakeProc; - use std::sync::RwLock; - - /// A host whose meminfo the test can change under the governor. - struct Live(RwLock); - impl ProcSource for Live { - fn read(&self, path: &str) -> std::io::Result { - self.0.read().unwrap().read(path) - } - fn count_entries(&self, path: &str) -> std::io::Result { - self.0.read().unwrap().count_entries(path) - } - } - fn live(avail_gib: u64) -> Arc { - let mut p = FakeProc::default(); - p.set("/proc/meminfo", &format!("MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", 121 * 1024 * 1024, avail_gib * 1024 * 1024)); - p.set("/proc/self/status", "VmRSS: 1000 kB\nThreads: 3\n"); - Arc::new(Live(RwLock::new(p))) - } - fn set_avail(h: &Live, avail_mib: u64) { - h.0.write().unwrap().set("/proc/meminfo", &format!("MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", 121 * 1024 * 1024, avail_mib * 1024)); - } - fn governor(host: Arc) -> Governor { - let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); - cfg.log = false; - let g = Governor::new(cfg, host); - g.set_prefix_budget(8 * GIB); - g - } - const SHAPE: RequestShape = RequestShape { prompt_tokens: 1000, max_new_tokens: 100, max_context: 262_144 }; - - #[test] - fn requests_are_admitted_with_room_and_context_errors_are_400s() { - let h = live(20); - let g = governor(h); - assert_eq!(g.admit(&SHAPE), Admission::Admit); - let Admission::Refuse(r) = g.admit(&RequestShape { prompt_tokens: 262_144, ..SHAPE }) else { panic!() }; - assert_eq!((r.status, r.code), (400, "context_length_exceeded")); - assert!(r.message.contains("262144"), "{}", r.message); - let Admission::Refuse(r) = g.admit(&RequestShape { prompt_tokens: u64::MAX, max_new_tokens: u64::MAX, ..SHAPE }) else { panic!() }; - assert_eq!(r.status, 400, "overflow must not wrap into an admit"); - } - - #[test] - fn shedding_runs_in_order_prefix_cache_first_then_reject_with_retry_after() { - let h = live(20); - let g = governor(h.clone()); - assert_eq!(g.directive(8 * GIB), ShedDirective { level: Level::Normal, prefix_budget: None, drop_conversation: false }); - // below the 4 GiB soft floor: shed in steps of a quarter, one step per second - set_avail(&h, 3 * 1024); - let t = g.sample_at(1000).unwrap(); - assert_eq!(t.to, Level::Shed); - let d = g.directive(8 * GIB); - assert_eq!(d.level, Level::Shed); - assert_eq!(d.prefix_budget, Some(6 * GIB)); - assert!(d.drop_conversation); - assert_eq!(g.directive(6 * GIB).prefix_budget, Some(6 * GIB), "no second step within the same second"); - // requests are still served while only shedding - assert_eq!(g.admit(&SHAPE), Admission::Admit); - // below the hard floor: everything goes, new requests are refused with Retry-After - set_avail(&h, 1024); - assert_eq!(g.sample_at(2000).unwrap().to, Level::Reject); - assert_eq!(g.directive(6 * GIB).prefix_budget, Some(0)); - let Admission::Refuse(r) = g.admit(&SHAPE) else { panic!("must refuse") }; - assert_eq!((r.status, r.code), (503, "memory_pressure")); - assert!(r.retry_after_secs >= 5); - // memory comes back: three calm samples per step down, then the configured budget is restored - set_avail(&h, 30 * 1024); - for i in 0..3 { - g.sample_at(3000 + i * 1000); - } - assert_eq!(g.level(), Level::Shed); - for i in 0..3 { - g.sample_at(7000 + i * 1000); - } - assert_eq!(g.level(), Level::Normal); - assert_eq!(g.directive(0).prefix_budget, None, "the configured budget is restored"); - assert_eq!(g.admit(&SHAPE), Admission::Admit); - } - - #[test] - fn a_request_whose_own_transient_would_cross_the_hard_floor_is_refused_before_it_starts() { - // 2.1 GiB available: above the 2 GiB hard floor, but the 256 MiB transient of a request would cross it - let h = live(20); - let g = governor(h.clone()); - set_avail(&h, 2150); - let Admission::Refuse(r) = g.admit(&SHAPE) else { panic!("must refuse") }; - assert_eq!(r.code, "memory_pressure"); - assert!(r.message.contains("hard floor"), "{}", r.message); - } - - #[test] - fn counters_and_report_json_describe_the_decisions() { - let h = live(20); - let g = governor(h.clone()); - g.admit(&SHAPE); - set_avail(&h, 1024); - g.sample_at(1000); - g.admit(&SHAPE); - g.admit(&RequestShape { prompt_tokens: 999_999, ..SHAPE }); - let j = g.report(); - assert_eq!(j["version"], 1); - assert_eq!(j["gate"]["level"], "reject"); - assert!(j["gate"]["retry_after_secs"].as_u64().unwrap() >= 5); - assert_eq!(j["counters"]["admitted"], 1); - assert_eq!(j["counters"]["rejected_memory_pressure"], 1); - assert_eq!(j["counters"]["rejected_context"], 1); - assert_eq!(j["transitions"].as_array().unwrap().len(), 1); - assert_eq!(j["policy"]["soft_floor"], 4 * GIB); - g.publish(); - assert!(published_report().unwrap().contains("\"gate\"")); - } - - #[test] - fn env_overrides_are_validated_not_ignored() { - let env = |pairs: &[(&str, &str)]| { - let owned: Vec<(String, String)> = pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); - move |k: &str| owned.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()) - }; - let cfg = GovernorConfig::from_env(121 * GIB, false, &env(&[("LELEKA_MEMORY_SOFT_FLOOR_MIB", "19000"), ("LELEKA_MEMORY_HARD_FLOOR_MIB", "16000"), ("LELEKA_MEMORY_LOCK", "require")])).unwrap(); - assert_eq!((cfg.policy.soft_floor, cfg.policy.hard_floor, cfg.lock_mode), (19000 * MIB, 16000 * MIB, LockMode::Require)); - for bad in [ - &[("LELEKA_MEMORY_SOFT_FLOOR_MIB", "lots")][..], - &[("LELEKA_MEMORY_LOCK", "maybe")][..], - &[("LELEKA_MEMORY_CACHE_SHARE_PERCENT", "0")][..], - &[("LELEKA_MEMORY_HARD_FLOOR_MIB", "9000"), ("LELEKA_MEMORY_SOFT_FLOOR_MIB", "8000")][..], - ] { - assert!(GovernorConfig::from_env(121 * GIB, false, &env(bad)).is_err(), "{bad:?}"); - } - assert!(GovernorConfig::from_env(121 * GIB, false, &|_| None).is_ok()); - } - - #[test] - fn a_dead_sampler_cannot_leave_the_gate_stuck_closed() { - let h = live(20); - let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); - cfg.log = false; - cfg.sample_interval_ms = 50; - let g = Governor::new(cfg, h.clone()); - set_avail(&h, 1024); - g.sample_at(0); - assert_eq!(g.level(), Level::Reject); - // the sampler thread is gone (never started here) and the memory is back: the requests themselves drive the monitor - set_avail(&h, 30 * 1024); - let deadline = Instant::now() + Duration::from_secs(10); - let mut admitted = false; - while Instant::now() < deadline { - if g.admit(&SHAPE) == Admission::Admit { - admitted = true; - break; - } - std::thread::sleep(Duration::from_millis(60)); - } - assert!(admitted, "a stale reject outlived the sampler"); - } - - #[test] - #[cfg_attr(miri, ignore = "wall-clock thread timing")] - fn the_sampler_thread_samples_publishes_and_stops_on_drop() { - let h = live(20); - let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); - cfg.log = false; - cfg.sample_interval_ms = 50; - let g = Governor::new(cfg, h.clone()); - let guard = g.spawn_sampler(); - std::thread::sleep(Duration::from_millis(300)); - assert!(g.report()["counters"]["samples"].as_u64().unwrap() >= 2); - set_avail(&h, 1024); - let deadline = Instant::now() + Duration::from_secs(5); - while g.level() != Level::Reject && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(20)); - } - assert_eq!(g.level(), Level::Reject, "the sampler thread must notice the drop on its own"); - drop(guard); - let n = g.report()["counters"]["samples"].as_u64().unwrap(); - std::thread::sleep(Duration::from_millis(200)); - assert_eq!(g.report()["counters"]["samples"].as_u64().unwrap(), n, "no sampling after drop"); - } -} +mod tests; diff --git a/crates/leleka-memory/src/governor/tests.rs b/crates/leleka-memory/src/governor/tests.rs new file mode 100644 index 00000000..8273485d --- /dev/null +++ b/crates/leleka-memory/src/governor/tests.rs @@ -0,0 +1,181 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::host::FakeProc; +use std::sync::RwLock; + +/// A host whose meminfo the test can change under the governor. +struct Live(RwLock); +impl ProcSource for Live { + fn read(&self, path: &str) -> std::io::Result { + self.0.read().unwrap().read(path) + } + fn count_entries(&self, path: &str) -> std::io::Result { + self.0.read().unwrap().count_entries(path) + } +} +fn live(avail_gib: u64) -> Arc { + let mut p = FakeProc::default(); + p.set("/proc/meminfo", &format!("MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", 121 * 1024 * 1024, avail_gib * 1024 * 1024)); + p.set("/proc/self/status", "VmRSS: 1000 kB\nThreads: 3\n"); + Arc::new(Live(RwLock::new(p))) +} +fn set_avail(h: &Live, avail_mib: u64) { + h.0.write().unwrap().set("/proc/meminfo", &format!("MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", 121 * 1024 * 1024, avail_mib * 1024)); +} +fn governor(host: Arc) -> Governor { + let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); + cfg.log = false; + let g = Governor::new(cfg, host); + g.set_prefix_budget(8 * GIB); + g +} +const SHAPE: RequestShape = RequestShape { prompt_tokens: 1000, max_new_tokens: 100, max_context: 262_144 }; + +#[test] +fn requests_are_admitted_with_room_and_context_errors_are_400s() { + let h = live(20); + let g = governor(h); + assert_eq!(g.admit(&SHAPE), Admission::Admit); + let Admission::Refuse(r) = g.admit(&RequestShape { prompt_tokens: 262_144, ..SHAPE }) else { panic!() }; + assert_eq!((r.status, r.code), (400, "context_length_exceeded")); + assert!(r.message.contains("262144"), "{}", r.message); + let Admission::Refuse(r) = g.admit(&RequestShape { prompt_tokens: u64::MAX, max_new_tokens: u64::MAX, ..SHAPE }) else { panic!() }; + assert_eq!(r.status, 400, "overflow must not wrap into an admit"); +} + +#[test] +fn shedding_runs_in_order_prefix_cache_first_then_reject_with_retry_after() { + let h = live(20); + let g = governor(h.clone()); + assert_eq!(g.directive(8 * GIB), ShedDirective { level: Level::Normal, prefix_budget: None, drop_conversation: false }); + // below the 4 GiB soft floor: shed in steps of a quarter, one step per second + set_avail(&h, 3 * 1024); + let t = g.sample_at(1000).unwrap(); + assert_eq!(t.to, Level::Shed); + let d = g.directive(8 * GIB); + assert_eq!(d.level, Level::Shed); + assert_eq!(d.prefix_budget, Some(6 * GIB)); + assert!(d.drop_conversation); + assert_eq!(g.directive(6 * GIB).prefix_budget, Some(6 * GIB), "no second step within the same second"); + // requests are still served while only shedding + assert_eq!(g.admit(&SHAPE), Admission::Admit); + // below the hard floor: everything goes, new requests are refused with Retry-After + set_avail(&h, 1024); + assert_eq!(g.sample_at(2000).unwrap().to, Level::Reject); + assert_eq!(g.directive(6 * GIB).prefix_budget, Some(0)); + let Admission::Refuse(r) = g.admit(&SHAPE) else { panic!("must refuse") }; + assert_eq!((r.status, r.code), (503, "memory_pressure")); + assert!(r.retry_after_secs >= 5); + // memory comes back: three calm samples per step down, then the configured budget is restored + set_avail(&h, 30 * 1024); + for i in 0..3 { + g.sample_at(3000 + i * 1000); + } + assert_eq!(g.level(), Level::Shed); + for i in 0..3 { + g.sample_at(7000 + i * 1000); + } + assert_eq!(g.level(), Level::Normal); + assert_eq!(g.directive(0).prefix_budget, None, "the configured budget is restored"); + assert_eq!(g.admit(&SHAPE), Admission::Admit); +} + +#[test] +fn a_request_whose_own_transient_would_cross_the_hard_floor_is_refused_before_it_starts() { + // 2.1 GiB available: above the 2 GiB hard floor, but the 256 MiB transient of a request would cross it + let h = live(20); + let g = governor(h.clone()); + set_avail(&h, 2150); + let Admission::Refuse(r) = g.admit(&SHAPE) else { panic!("must refuse") }; + assert_eq!(r.code, "memory_pressure"); + assert!(r.message.contains("hard floor"), "{}", r.message); +} + +#[test] +fn counters_and_report_json_describe_the_decisions() { + let h = live(20); + let g = governor(h.clone()); + g.admit(&SHAPE); + set_avail(&h, 1024); + g.sample_at(1000); + g.admit(&SHAPE); + g.admit(&RequestShape { prompt_tokens: 999_999, ..SHAPE }); + let j = g.report(); + assert_eq!(j["version"], 1); + assert_eq!(j["gate"]["level"], "reject"); + assert!(j["gate"]["retry_after_secs"].as_u64().unwrap() >= 5); + assert_eq!(j["counters"]["admitted"], 1); + assert_eq!(j["counters"]["rejected_memory_pressure"], 1); + assert_eq!(j["counters"]["rejected_context"], 1); + assert_eq!(j["transitions"].as_array().unwrap().len(), 1); + assert_eq!(j["policy"]["soft_floor"], 4 * GIB); + g.publish(); + assert!(published_report().unwrap().contains("\"gate\"")); +} + +#[test] +fn env_overrides_are_validated_not_ignored() { + let env = |pairs: &[(&str, &str)]| { + let owned: Vec<(String, String)> = pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); + move |k: &str| owned.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()) + }; + let cfg = GovernorConfig::from_env(121 * GIB, false, &env(&[("LELEKA_MEMORY_SOFT_FLOOR_MIB", "19000"), ("LELEKA_MEMORY_HARD_FLOOR_MIB", "16000"), ("LELEKA_MEMORY_LOCK", "require")])).unwrap(); + assert_eq!((cfg.policy.soft_floor, cfg.policy.hard_floor, cfg.lock_mode), (19000 * MIB, 16000 * MIB, LockMode::Require)); + for bad in [ + &[("LELEKA_MEMORY_SOFT_FLOOR_MIB", "lots")][..], + &[("LELEKA_MEMORY_LOCK", "maybe")][..], + &[("LELEKA_MEMORY_CACHE_SHARE_PERCENT", "0")][..], + &[("LELEKA_MEMORY_HARD_FLOOR_MIB", "9000"), ("LELEKA_MEMORY_SOFT_FLOOR_MIB", "8000")][..], + ] { + assert!(GovernorConfig::from_env(121 * GIB, false, &env(bad)).is_err(), "{bad:?}"); + } + assert!(GovernorConfig::from_env(121 * GIB, false, &|_| None).is_ok()); +} + +#[test] +fn a_dead_sampler_cannot_leave_the_gate_stuck_closed() { + let h = live(20); + let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); + cfg.log = false; + cfg.sample_interval_ms = 50; + let g = Governor::new(cfg, h.clone()); + set_avail(&h, 1024); + g.sample_at(0); + assert_eq!(g.level(), Level::Reject); + // the sampler thread is gone (never started here) and the memory is back: the requests themselves drive the monitor + set_avail(&h, 30 * 1024); + let deadline = Instant::now() + Duration::from_secs(10); + let mut admitted = false; + while Instant::now() < deadline { + if g.admit(&SHAPE) == Admission::Admit { + admitted = true; + break; + } + std::thread::sleep(Duration::from_millis(60)); + } + assert!(admitted, "a stale reject outlived the sampler"); +} + +#[test] +#[cfg_attr(miri, ignore = "wall-clock thread timing")] +fn the_sampler_thread_samples_publishes_and_stops_on_drop() { + let h = live(20); + let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); + cfg.log = false; + cfg.sample_interval_ms = 50; + let g = Governor::new(cfg, h.clone()); + let guard = g.spawn_sampler(); + std::thread::sleep(Duration::from_millis(300)); + assert!(g.report()["counters"]["samples"].as_u64().unwrap() >= 2); + set_avail(&h, 1024); + let deadline = Instant::now() + Duration::from_secs(5); + while g.level() != Level::Reject && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + assert_eq!(g.level(), Level::Reject, "the sampler thread must notice the drop on its own"); + drop(guard); + let n = g.report()["counters"]["samples"].as_u64().unwrap(); + std::thread::sleep(Duration::from_millis(200)); + assert_eq!(g.report()["counters"]["samples"].as_u64().unwrap(), n, "no sampling after drop"); +} diff --git a/crates/leleka-memory/src/lock.rs b/crates/leleka-memory/src/lock.rs index c433cd9e..90bc8a4b 100644 --- a/crates/leleka-memory/src/lock.rs +++ b/crates/leleka-memory/src/lock.rs @@ -515,84 +515,4 @@ mod sys { } #[cfg(test)] -mod tests { - use super::*; - - fn status(cap: Option, lck: u64) -> ProcStatus { - ProcStatus { cap_eff: cap, vm_lck: Some(lck), ..ProcStatus::default() } - } - const G: u64 = 1 << 30; - - #[test] - fn the_5090_server_default_limit_cannot_lock_the_55gb_archive_and_says_how_to() { - // para@homelab: soft = hard = 8 MiB, no CAP_IPC_LOCK - let d = plan_lock(LockMode::Try, 55 * G, Some((8 << 20, 8 << 20)), &status(Some(0), 8 << 10)); - let LockDecision::Insufficient { need, soft, hard, advice } = d else { panic!("{d:?}") }; - assert!(need > 55 * G && soft == 8 << 20 && hard == 8 << 20); - let text = advice.join("\n"); - assert!(text.contains("LimitMEMLOCK=infinity") && text.contains("CAP_IPC_LOCK") && text.contains("MADV_POPULATE_READ"), "{text}"); - } - - #[test] - fn unlimited_limits_or_the_capability_allow_the_lock() { - assert_eq!(plan_lock(LockMode::Try, 55 * G, Some((u64::MAX, u64::MAX)), &status(Some(0), 0)), LockDecision::Attempt { raise_soft_to: None }); - assert_eq!(plan_lock(LockMode::Try, 55 * G, Some((8 << 20, 8 << 20)), &status(Some(CAP_IPC_LOCK_BIT), 0)), LockDecision::Attempt { raise_soft_to: None }); - assert_eq!(plan_lock(LockMode::Try, 55 * G, None, &status(None, 0)), LockDecision::Attempt { raise_soft_to: None }, "unknown limits: try and see"); - } - - #[test] - fn a_hard_limit_that_covers_it_lifts_the_soft_one_first() { - let d = plan_lock(LockMode::Try, 55 * G, Some((8 << 20, u64::MAX)), &status(Some(0), 0)); - assert_eq!(d, LockDecision::Attempt { raise_soft_to: Some(55 * G) }); - } - - #[test] - fn spans_are_checked_summed_and_walked_in_compact_space() { - let p = PAGE; - let spans = [(2 * p, 3 * p), (10 * p, 2 * p), (20 * p, p + 100)]; - assert_eq!(spans_bytes(&spans), 6 * p + 100); - assert!(check_spans(&spans, 21 * p + 100).is_ok()); - assert!(check_spans(&spans, 21 * p + 99).is_err(), "the last span ends past the mapping"); - assert!(check_spans(&[], 0).is_ok()); - assert!(check_spans(&[(1, p)], 10 * p).is_err() && check_spans(&[(0, 0)], p).is_err()); - assert!(check_spans(&[(0, 2 * p), (p, p)], 10 * p).is_err() && check_spans(&[(4 * p, p), (0, p)], 10 * p).is_err()); - // compact space: positions 0..3p are the first span, 3p..5p the second, 5p.. the third - assert_eq!(compact_piece(&spans, 0, u64::MAX), Some((2 * p, 3 * p))); - assert_eq!(compact_piece(&spans, p, p), Some((3 * p, p))); - assert_eq!(compact_piece(&spans, 3 * p - 10, 100), Some((5 * p - 10, 10)), "never across the end of a span"); - assert_eq!(compact_piece(&spans, 3 * p, 5 * p), Some((10 * p, 2 * p))); - assert_eq!(compact_piece(&spans, 5 * p, 1), Some((20 * p, 1))); - assert_eq!(compact_piece(&spans, 6 * p + 100, 1), None); - assert_eq!(compact_piece(&spans, 0, 0), None); - // walking the whole compact space with a small step visits every byte exactly once and nothing outside the spans - let (mut pos, mut seen) = (0u64, 0u64); - while let Some((offset, n)) = compact_piece(&spans, pos, 3000) { - assert!(spans.iter().any(|&(o, l)| offset >= o && offset + n <= o + l), "{offset}+{n} left the spans"); - pos += n; - seen += n; - } - assert_eq!(seen, spans_bytes(&spans)); - } - - #[test] - fn off_never_locks() { - assert_eq!(plan_lock(LockMode::Off, 1, Some((u64::MAX, u64::MAX)), &status(None, 0)), LockDecision::Off); - assert_eq!(LockMode::parse("require"), Some(LockMode::Require)); - assert_eq!(LockMode::parse("nope"), None); - } - - #[test] - fn already_locked_pages_count_against_the_limit() { - let d = plan_lock(LockMode::Try, 4 * G, Some((6 * G, 6 * G)), &status(Some(0), 3 * G)); - assert!(matches!(d, LockDecision::Insufficient { .. }), "{d:?}"); - } - - #[test] - fn residency_is_read_from_the_mapping_that_starts_at_our_address() { - let smaps = "7f0000000000-7f0100000000 r--s 00000000 00:01 4242 /memfd:kar-archive (deleted)\nSize: 4194304 kB\nRss: 4000000 kB\nSwap: 194304 kB\nLocked: 0 kB\n"; - let r = residency_from_smaps(smaps, 0x7f00_0000_0000, 1 << 30).unwrap(); - assert_eq!((r.swapped_bytes, r.rss_bytes), (194_304 * 1024, 4_000_000 * 1024)); - assert!(residency_from_smaps(smaps, 0x1000, 1).is_none()); - assert!(residency_from_smaps(smaps, 0x7f00_0000_0000, 1 << 40).is_none(), "a smaller mapping is not ours"); - } -} +mod tests; diff --git a/crates/leleka-memory/src/lock/tests.rs b/crates/leleka-memory/src/lock/tests.rs new file mode 100644 index 00000000..1e580c93 --- /dev/null +++ b/crates/leleka-memory/src/lock/tests.rs @@ -0,0 +1,81 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn status(cap: Option, lck: u64) -> ProcStatus { + ProcStatus { cap_eff: cap, vm_lck: Some(lck), ..ProcStatus::default() } +} +const G: u64 = 1 << 30; + +#[test] +fn the_5090_server_default_limit_cannot_lock_the_55gb_archive_and_says_how_to() { + // para@homelab: soft = hard = 8 MiB, no CAP_IPC_LOCK + let d = plan_lock(LockMode::Try, 55 * G, Some((8 << 20, 8 << 20)), &status(Some(0), 8 << 10)); + let LockDecision::Insufficient { need, soft, hard, advice } = d else { panic!("{d:?}") }; + assert!(need > 55 * G && soft == 8 << 20 && hard == 8 << 20); + let text = advice.join("\n"); + assert!(text.contains("LimitMEMLOCK=infinity") && text.contains("CAP_IPC_LOCK") && text.contains("MADV_POPULATE_READ"), "{text}"); +} + +#[test] +fn unlimited_limits_or_the_capability_allow_the_lock() { + assert_eq!(plan_lock(LockMode::Try, 55 * G, Some((u64::MAX, u64::MAX)), &status(Some(0), 0)), LockDecision::Attempt { raise_soft_to: None }); + assert_eq!(plan_lock(LockMode::Try, 55 * G, Some((8 << 20, 8 << 20)), &status(Some(CAP_IPC_LOCK_BIT), 0)), LockDecision::Attempt { raise_soft_to: None }); + assert_eq!(plan_lock(LockMode::Try, 55 * G, None, &status(None, 0)), LockDecision::Attempt { raise_soft_to: None }, "unknown limits: try and see"); +} + +#[test] +fn a_hard_limit_that_covers_it_lifts_the_soft_one_first() { + let d = plan_lock(LockMode::Try, 55 * G, Some((8 << 20, u64::MAX)), &status(Some(0), 0)); + assert_eq!(d, LockDecision::Attempt { raise_soft_to: Some(55 * G) }); +} + +#[test] +fn spans_are_checked_summed_and_walked_in_compact_space() { + let p = PAGE; + let spans = [(2 * p, 3 * p), (10 * p, 2 * p), (20 * p, p + 100)]; + assert_eq!(spans_bytes(&spans), 6 * p + 100); + assert!(check_spans(&spans, 21 * p + 100).is_ok()); + assert!(check_spans(&spans, 21 * p + 99).is_err(), "the last span ends past the mapping"); + assert!(check_spans(&[], 0).is_ok()); + assert!(check_spans(&[(1, p)], 10 * p).is_err() && check_spans(&[(0, 0)], p).is_err()); + assert!(check_spans(&[(0, 2 * p), (p, p)], 10 * p).is_err() && check_spans(&[(4 * p, p), (0, p)], 10 * p).is_err()); + // compact space: positions 0..3p are the first span, 3p..5p the second, 5p.. the third + assert_eq!(compact_piece(&spans, 0, u64::MAX), Some((2 * p, 3 * p))); + assert_eq!(compact_piece(&spans, p, p), Some((3 * p, p))); + assert_eq!(compact_piece(&spans, 3 * p - 10, 100), Some((5 * p - 10, 10)), "never across the end of a span"); + assert_eq!(compact_piece(&spans, 3 * p, 5 * p), Some((10 * p, 2 * p))); + assert_eq!(compact_piece(&spans, 5 * p, 1), Some((20 * p, 1))); + assert_eq!(compact_piece(&spans, 6 * p + 100, 1), None); + assert_eq!(compact_piece(&spans, 0, 0), None); + // walking the whole compact space with a small step visits every byte exactly once and nothing outside the spans + let (mut pos, mut seen) = (0u64, 0u64); + while let Some((offset, n)) = compact_piece(&spans, pos, 3000) { + assert!(spans.iter().any(|&(o, l)| offset >= o && offset + n <= o + l), "{offset}+{n} left the spans"); + pos += n; + seen += n; + } + assert_eq!(seen, spans_bytes(&spans)); +} + +#[test] +fn off_never_locks() { + assert_eq!(plan_lock(LockMode::Off, 1, Some((u64::MAX, u64::MAX)), &status(None, 0)), LockDecision::Off); + assert_eq!(LockMode::parse("require"), Some(LockMode::Require)); + assert_eq!(LockMode::parse("nope"), None); +} + +#[test] +fn already_locked_pages_count_against_the_limit() { + let d = plan_lock(LockMode::Try, 4 * G, Some((6 * G, 6 * G)), &status(Some(0), 3 * G)); + assert!(matches!(d, LockDecision::Insufficient { .. }), "{d:?}"); +} + +#[test] +fn residency_is_read_from_the_mapping_that_starts_at_our_address() { + let smaps = "7f0000000000-7f0100000000 r--s 00000000 00:01 4242 /memfd:kar-archive (deleted)\nSize: 4194304 kB\nRss: 4000000 kB\nSwap: 194304 kB\nLocked: 0 kB\n"; + let r = residency_from_smaps(smaps, 0x7f00_0000_0000, 1 << 30).unwrap(); + assert_eq!((r.swapped_bytes, r.rss_bytes), (194_304 * 1024, 4_000_000 * 1024)); + assert!(residency_from_smaps(smaps, 0x1000, 1).is_none()); + assert!(residency_from_smaps(smaps, 0x7f00_0000_0000, 1 << 40).is_none(), "a smaller mapping is not ours"); +} diff --git a/crates/leleka-memory/src/plan.rs b/crates/leleka-memory/src/plan.rs index 0ba46621..27460f20 100644 --- a/crates/leleka-memory/src/plan.rs +++ b/crates/leleka-memory/src/plan.rs @@ -405,231 +405,4 @@ pub fn explicit_prefix_budget(wish: u64, available: Option, policy: &Policy } #[cfg(test)] -mod tests { - use super::*; - use crate::host::FakeProc; - - fn host(total_kib: u64, avail_kib: u64) -> HostFacts { - HostFacts::probe(&FakeProc::default().with( - "/proc/meminfo", - &format!("MemTotal: {total_kib} kB\nMemAvailable: {avail_kib} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"), - )) - } - const fn g(n: u64) -> u64 { - n * GIB - } - - /// The 5090 server before the engine allocates: 121 GiB, the sealed memfd resident, ~67 GB available. - fn server_input(available_gib: u64) -> PlanInput { - PlanInput { - host: host(124_112_000, available_gib * 1024 * 1024), - policy: Policy::for_host(g(121), false), - kar: KarForm::MemfdInherited { bytes: 55_295_529_472 }, - fixed: vec![ - FixedItem::new("expert_bank", 54_000_000_000, Space::HostPinned, "routed experts of shard 0"), - FixedItem::new("kv_host", 3_321_901_056, Space::HostPinned, "12 layers x 262144 cells x 1056 B"), - FixedItem::new("rings", 2 * g(1), Space::HostPinned, "staging rings"), - ], - prefix: CacheWish::Auto, - conversation_checkpoints: 6, - checkpoint_bytes: 118 * MIB, - resident_complement: None, - vram: Some(VramFacts { free: g(31), total: g(32) }), - vram_budget: g(24), - vram_fixed_estimate: None, - } - } - - #[test] - fn the_5090_server_gets_an_auto_prefix_cache_from_what_is_left() { - let plan = plan(&server_input(75)).unwrap(); - // 75 GiB - (54e9 + 3.32e9 + 2 GiB) = ~19.3 GiB left; soft 4 + reserve 1 -> 14.3 GiB elastic; 75% -> ~10.7 GiB - assert!(plan.available_after_fixed.unwrap() > g(19) && plan.available_after_fixed.unwrap() < g(20), "{plan:?}"); - assert!(plan.prefix_bytes > g(10) && plan.prefix_bytes < g(11), "{}", plan.prefix_bytes); - assert_eq!(plan.prefix_bytes % MIB, 0); - assert_eq!(plan.soft_floor, g(4)); - assert_eq!(plan.hard_floor, g(2)); - assert!(!plan.blind); - } - - #[test] - fn a_host_that_cannot_hold_the_fixed_footprint_is_refused_with_numbers_and_advice() { - let refusal = plan(&server_input(58)).unwrap_err(); - assert_eq!(refusal.code, "host_ram"); - let text = refusal.to_string(); - assert!(text.contains("available = 58.00 GiB"), "{text}"); - assert!(text.contains("fixed host footprint = 55.") || text.contains("fixed host footprint = 56."), "{text}"); - assert!(text.contains("--expert-source mapped") && text.contains("--kar-archive-file"), "{text}"); - assert!(refusal.numbers.iter().any(|(n, v)| n == "short by" && *v > 0)); - } - - #[test] - fn a_second_model_process_beside_the_holder_is_refused() { - // history (1): the 55 GB memfd is resident and a second process asks for its own 54 GB bank with ~20 GiB available - let refusal = plan(&server_input(20)).unwrap_err(); - assert_eq!(refusal.code, "host_ram"); - assert!(refusal.message.contains("below the")); - } - - #[test] - fn creating_the_memfd_ourselves_counts_against_available() { - let mut input = server_input(75); - input.kar = KarForm::MemfdToCreate { bytes: 55_295_529_472 }; - assert_eq!(plan(&input).unwrap_err().code, "host_ram"); - input.host = host(124_112_000, 140 * 1024 * 1024); - let ok = plan(&input).unwrap(); - assert_eq!(ok.kar_to_create, 55_295_529_472); - assert!(ok.prefix_bytes > 0); - } - - #[test] - fn an_explicit_cache_larger_than_the_elastic_memory_is_clamped_and_reported() { - let mut input = server_input(75); - input.prefix = CacheWish::Bytes(g(40)); - let p = plan(&input).unwrap(); - assert!(p.prefix_bytes < g(15), "{}", p.prefix_bytes); - assert!(p.notes.iter().any(|n| n.contains("clamped")), "{:?}", p.notes); - input.prefix = CacheWish::Bytes(g(2)); - assert_eq!(plan(&input).unwrap().prefix_bytes, g(2)); - } - - #[test] - fn the_resident_complement_is_served_first_and_the_prefix_cache_gets_the_rest() { - let mut input = server_input(75); - input.resident_complement = Some(g(8)); - let p = plan(&input).unwrap(); - assert_eq!(p.resident_complement_bytes, g(8)); - let without = plan(&server_input(75)).unwrap(); - assert!(p.prefix_bytes < without.prefix_bytes); - input.resident_complement = Some(g(100)); - let p = plan(&input).unwrap(); - assert!(p.resident_complement_bytes < g(15) && p.prefix_bytes == 0, "{p:?}"); - } - - #[test] - fn the_conversation_cache_shrinks_instead_of_overrunning() { - let mut input = server_input(75); - input.prefix = CacheWish::Off; - assert_eq!(plan(&input).unwrap().conversation_checkpoints, 6); - input.checkpoint_bytes = g(4); - let p = plan(&input).unwrap(); - assert_eq!(p.conversation_checkpoints, 3, "14.3 GiB elastic / 4 GiB"); - assert!(p.notes.iter().any(|n| n.contains("reduced"))); - } - - #[test] - fn missing_telemetry_turns_the_caches_off_and_marks_the_plan_blind() { - let mut input = server_input(75); - input.host = HostFacts::probe(&FakeProc::default()); - let p = plan(&input).unwrap(); - assert!(p.blind); - assert_eq!((p.prefix_bytes, p.conversation_checkpoints), (0, 0)); - } - - #[test] - fn the_laptop_profile_with_a_file_archive_and_mapped_experts_fits_in_wsl() { - // RTX 3080 laptop, WSL2 with ~38 GiB, mapped experts: only the pinned K/V image and the rings are fixed - let mut input = server_input(35); - input.host = host(39_800_000, 35 * 1024 * 1024); - input.policy = Policy::for_host(g(38), true); - input.kar = KarForm::File { bytes: 55_295_529_472 }; - input.fixed = vec![FixedItem::new("kv_host", 2 * g(1), Space::HostPinned, "12 x cells x 1056")]; - let p = plan(&input).unwrap(); - assert!(p.prefix_bytes > g(15) && p.prefix_bytes <= g(24), "{}", p.prefix_bytes); - } - - #[test] - fn wsl_refusals_carry_the_wslconfig_advice() { - let mut input = server_input(40); - input.host.wsl = true; - let text = plan(&input).unwrap_err().to_string(); - assert!(text.contains(".wslconfig"), "{text}"); - } - - #[test] - fn enforcement_off_turns_a_refusal_into_a_logged_note() { - let mut input = server_input(58); - input.policy.enforce = false; - let p = plan(&input).unwrap(); - assert!(p.notes.iter().any(|n| n.contains("ENFORCEMENT OFF"))); - assert_eq!(p.prefix_bytes, 0); - } - - #[test] - fn a_vram_estimate_that_does_not_fit_refuses_and_a_missing_one_only_warns() { - let mut input = server_input(75); - input.vram = Some(VramFacts { free: g(10), total: g(32) }); - let p = plan(&input).unwrap(); - assert!(p.notes.iter().any(|n| n.contains("--gpu-budget")), "{:?}", p.notes); - input.vram_fixed_estimate = Some(g(20)); - let r = plan(&input).unwrap_err(); - assert_eq!(r.code, "vram"); - assert!(r.to_string().contains("vram free = 10.00 GiB")); - } - - #[test] - fn auto_budget_at_open_follows_the_same_rule_and_fails_closed() { - let p = Policy::for_host(g(121), false); - assert_eq!(auto_prefix_budget(None, &p, 0), 0); - assert_eq!(auto_prefix_budget(Some(g(5)), &p, 0), 0); - // job 922: 22 GiB available at open - let b = auto_prefix_budget(Some(g(22)), &p, 0); - assert!(b >= g(12) && b < g(13), "{b}"); // (22 - 4 - 2) x 75% - assert!(auto_prefix_budget(Some(g(22)), &p, g(8)) < b); - // the real Codex CRM session (e2e job 945): 14,064 MiB available at open. The old rule granted 7,476 MiB and the host sat at 7.4 GiB - // available once the cache was full; the governor keeps soft floor + reserve (6 GiB) out and takes 75% of the rest - let crm = auto_prefix_budget(Some(14_064 * MIB), &p, 0); - assert!(crm > 5 * GIB + 800 * MIB && crm < 6 * GIB + 100 * MIB, "{crm}"); - assert!(14_064 * MIB - crm > 7 * GIB + 900 * MIB, "at least ~8 GiB stays available with the cache full"); - assert_eq!(auto_prefix_budget(Some(g(1000)), &p, 0), g(96)); - } - - #[test] - fn floors_scale_with_very_large_hosts_only() { - let small = Policy::for_host(g(38), true); - assert_eq!((small.soft_floor, small.hard_floor), (g(4), g(2))); - let big = Policy::for_host(g(1024), false); - assert_eq!(big.soft_floor, g(32)); - assert_eq!(big.hard_floor, g(16)); - } - - #[test] - fn an_explicit_cap_never_grows_when_ram_is_freed_but_auto_does() { - let p = Policy::for_host(g(121), false); - let cap = 6144 * MIB; - // the 5090 at turn 5 today (MemAvailable 8.6 GiB after the stack opened is the PLAN's view of the open-time figure ~14 GiB) - let before = 14_064 * MIB; - // the sparse memfd frees ~36.6 GiB of shmem: MemAvailable at open rises by that much - let after = before + 36_600 * MIB; - let (granted_before, _) = explicit_prefix_budget(cap, Some(before), &p, 0); - let (granted_after, elastic_after) = explicit_prefix_budget(cap, Some(after), &p, 0); - assert_eq!(granted_before, cap - cap % MIB, "inside the cap today: the cap is the budget (auto would give {} MiB)", auto_prefix_budget(Some(before), &p, 0) >> 20); - assert_eq!(granted_after, cap, "freed RAM does not grow an explicit cap"); - assert!(elastic_after > 40 * GIB); - // the hazard the cap exists for: auto would hand the freed memory to the cache - assert!(auto_prefix_budget(Some(after), &p, 0) > 30 * GIB); - // the same for the startup plan: 37 GiB more available, the same explicit cap, a bigger auto cache - let mut small_input = server_input(75); - small_input.prefix = CacheWish::Bytes(cap); - let mut big_input = server_input(75 + 37); - big_input.prefix = CacheWish::Bytes(cap); - assert_eq!((plan(&small_input).unwrap().prefix_bytes, plan(&big_input).unwrap().prefix_bytes), (cap, cap)); - small_input.prefix = CacheWish::Auto; - big_input.prefix = CacheWish::Auto; - assert!(plan(&big_input).unwrap().prefix_bytes > plan(&small_input).unwrap().prefix_bytes + 20 * GIB); - } - - #[test] - fn an_explicit_cap_is_clamped_to_the_host_and_fails_closed_without_telemetry() { - let p = Policy::for_host(g(121), false); - // 5 GiB available: below soft floor + reserve (6 GiB), nothing elastic - assert_eq!(explicit_prefix_budget(6144 * MIB, Some(g(5)), &p, 0).0, 0); - // 9 GiB available: 3 GiB elastic - assert_eq!(explicit_prefix_budget(6144 * MIB, Some(g(9)), &p, 0), (g(3), g(3))); - // pinned complement pending comes off first - assert_eq!(explicit_prefix_budget(6144 * MIB, Some(g(9)), &p, g(2)).0, g(1)); - assert_eq!(explicit_prefix_budget(6144 * MIB, None, &p, 0), (0, 0)); - // the grant is whole MiB - assert_eq!(explicit_prefix_budget(MIB + 1, Some(g(100)), &p, 0).0, MIB); - } -} +mod tests; diff --git a/crates/leleka-memory/src/plan/tests.rs b/crates/leleka-memory/src/plan/tests.rs new file mode 100644 index 00000000..949a02fc --- /dev/null +++ b/crates/leleka-memory/src/plan/tests.rs @@ -0,0 +1,228 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::host::FakeProc; + +fn host(total_kib: u64, avail_kib: u64) -> HostFacts { + HostFacts::probe(&FakeProc::default().with( + "/proc/meminfo", + &format!("MemTotal: {total_kib} kB\nMemAvailable: {avail_kib} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"), + )) +} +const fn g(n: u64) -> u64 { + n * GIB +} + +/// The 5090 server before the engine allocates: 121 GiB, the sealed memfd resident, ~67 GB available. +fn server_input(available_gib: u64) -> PlanInput { + PlanInput { + host: host(124_112_000, available_gib * 1024 * 1024), + policy: Policy::for_host(g(121), false), + kar: KarForm::MemfdInherited { bytes: 55_295_529_472 }, + fixed: vec![ + FixedItem::new("expert_bank", 54_000_000_000, Space::HostPinned, "routed experts of shard 0"), + FixedItem::new("kv_host", 3_321_901_056, Space::HostPinned, "12 layers x 262144 cells x 1056 B"), + FixedItem::new("rings", 2 * g(1), Space::HostPinned, "staging rings"), + ], + prefix: CacheWish::Auto, + conversation_checkpoints: 6, + checkpoint_bytes: 118 * MIB, + resident_complement: None, + vram: Some(VramFacts { free: g(31), total: g(32) }), + vram_budget: g(24), + vram_fixed_estimate: None, + } +} + +#[test] +fn the_5090_server_gets_an_auto_prefix_cache_from_what_is_left() { + let plan = plan(&server_input(75)).unwrap(); + // 75 GiB - (54e9 + 3.32e9 + 2 GiB) = ~19.3 GiB left; soft 4 + reserve 1 -> 14.3 GiB elastic; 75% -> ~10.7 GiB + assert!(plan.available_after_fixed.unwrap() > g(19) && plan.available_after_fixed.unwrap() < g(20), "{plan:?}"); + assert!(plan.prefix_bytes > g(10) && plan.prefix_bytes < g(11), "{}", plan.prefix_bytes); + assert_eq!(plan.prefix_bytes % MIB, 0); + assert_eq!(plan.soft_floor, g(4)); + assert_eq!(plan.hard_floor, g(2)); + assert!(!plan.blind); +} + +#[test] +fn a_host_that_cannot_hold_the_fixed_footprint_is_refused_with_numbers_and_advice() { + let refusal = plan(&server_input(58)).unwrap_err(); + assert_eq!(refusal.code, "host_ram"); + let text = refusal.to_string(); + assert!(text.contains("available = 58.00 GiB"), "{text}"); + assert!(text.contains("fixed host footprint = 55.") || text.contains("fixed host footprint = 56."), "{text}"); + assert!(text.contains("--expert-source mapped") && text.contains("--kar-archive-file"), "{text}"); + assert!(refusal.numbers.iter().any(|(n, v)| n == "short by" && *v > 0)); +} + +#[test] +fn a_second_model_process_beside_the_holder_is_refused() { + // history (1): the 55 GB memfd is resident and a second process asks for its own 54 GB bank with ~20 GiB available + let refusal = plan(&server_input(20)).unwrap_err(); + assert_eq!(refusal.code, "host_ram"); + assert!(refusal.message.contains("below the")); +} + +#[test] +fn creating_the_memfd_ourselves_counts_against_available() { + let mut input = server_input(75); + input.kar = KarForm::MemfdToCreate { bytes: 55_295_529_472 }; + assert_eq!(plan(&input).unwrap_err().code, "host_ram"); + input.host = host(124_112_000, 140 * 1024 * 1024); + let ok = plan(&input).unwrap(); + assert_eq!(ok.kar_to_create, 55_295_529_472); + assert!(ok.prefix_bytes > 0); +} + +#[test] +fn an_explicit_cache_larger_than_the_elastic_memory_is_clamped_and_reported() { + let mut input = server_input(75); + input.prefix = CacheWish::Bytes(g(40)); + let p = plan(&input).unwrap(); + assert!(p.prefix_bytes < g(15), "{}", p.prefix_bytes); + assert!(p.notes.iter().any(|n| n.contains("clamped")), "{:?}", p.notes); + input.prefix = CacheWish::Bytes(g(2)); + assert_eq!(plan(&input).unwrap().prefix_bytes, g(2)); +} + +#[test] +fn the_resident_complement_is_served_first_and_the_prefix_cache_gets_the_rest() { + let mut input = server_input(75); + input.resident_complement = Some(g(8)); + let p = plan(&input).unwrap(); + assert_eq!(p.resident_complement_bytes, g(8)); + let without = plan(&server_input(75)).unwrap(); + assert!(p.prefix_bytes < without.prefix_bytes); + input.resident_complement = Some(g(100)); + let p = plan(&input).unwrap(); + assert!(p.resident_complement_bytes < g(15) && p.prefix_bytes == 0, "{p:?}"); +} + +#[test] +fn the_conversation_cache_shrinks_instead_of_overrunning() { + let mut input = server_input(75); + input.prefix = CacheWish::Off; + assert_eq!(plan(&input).unwrap().conversation_checkpoints, 6); + input.checkpoint_bytes = g(4); + let p = plan(&input).unwrap(); + assert_eq!(p.conversation_checkpoints, 3, "14.3 GiB elastic / 4 GiB"); + assert!(p.notes.iter().any(|n| n.contains("reduced"))); +} + +#[test] +fn missing_telemetry_turns_the_caches_off_and_marks_the_plan_blind() { + let mut input = server_input(75); + input.host = HostFacts::probe(&FakeProc::default()); + let p = plan(&input).unwrap(); + assert!(p.blind); + assert_eq!((p.prefix_bytes, p.conversation_checkpoints), (0, 0)); +} + +#[test] +fn the_laptop_profile_with_a_file_archive_and_mapped_experts_fits_in_wsl() { + // RTX 3080 laptop, WSL2 with ~38 GiB, mapped experts: only the pinned K/V image and the rings are fixed + let mut input = server_input(35); + input.host = host(39_800_000, 35 * 1024 * 1024); + input.policy = Policy::for_host(g(38), true); + input.kar = KarForm::File { bytes: 55_295_529_472 }; + input.fixed = vec![FixedItem::new("kv_host", 2 * g(1), Space::HostPinned, "12 x cells x 1056")]; + let p = plan(&input).unwrap(); + assert!(p.prefix_bytes > g(15) && p.prefix_bytes <= g(24), "{}", p.prefix_bytes); +} + +#[test] +fn wsl_refusals_carry_the_wslconfig_advice() { + let mut input = server_input(40); + input.host.wsl = true; + let text = plan(&input).unwrap_err().to_string(); + assert!(text.contains(".wslconfig"), "{text}"); +} + +#[test] +fn enforcement_off_turns_a_refusal_into_a_logged_note() { + let mut input = server_input(58); + input.policy.enforce = false; + let p = plan(&input).unwrap(); + assert!(p.notes.iter().any(|n| n.contains("ENFORCEMENT OFF"))); + assert_eq!(p.prefix_bytes, 0); +} + +#[test] +fn a_vram_estimate_that_does_not_fit_refuses_and_a_missing_one_only_warns() { + let mut input = server_input(75); + input.vram = Some(VramFacts { free: g(10), total: g(32) }); + let p = plan(&input).unwrap(); + assert!(p.notes.iter().any(|n| n.contains("--gpu-budget")), "{:?}", p.notes); + input.vram_fixed_estimate = Some(g(20)); + let r = plan(&input).unwrap_err(); + assert_eq!(r.code, "vram"); + assert!(r.to_string().contains("vram free = 10.00 GiB")); +} + +#[test] +fn auto_budget_at_open_follows_the_same_rule_and_fails_closed() { + let p = Policy::for_host(g(121), false); + assert_eq!(auto_prefix_budget(None, &p, 0), 0); + assert_eq!(auto_prefix_budget(Some(g(5)), &p, 0), 0); + // job 922: 22 GiB available at open + let b = auto_prefix_budget(Some(g(22)), &p, 0); + assert!(b >= g(12) && b < g(13), "{b}"); // (22 - 4 - 2) x 75% + assert!(auto_prefix_budget(Some(g(22)), &p, g(8)) < b); + // the real Codex CRM session (e2e job 945): 14,064 MiB available at open. The old rule granted 7,476 MiB and the host sat at 7.4 GiB + // available once the cache was full; the governor keeps soft floor + reserve (6 GiB) out and takes 75% of the rest + let crm = auto_prefix_budget(Some(14_064 * MIB), &p, 0); + assert!(crm > 5 * GIB + 800 * MIB && crm < 6 * GIB + 100 * MIB, "{crm}"); + assert!(14_064 * MIB - crm > 7 * GIB + 900 * MIB, "at least ~8 GiB stays available with the cache full"); + assert_eq!(auto_prefix_budget(Some(g(1000)), &p, 0), g(96)); +} + +#[test] +fn floors_scale_with_very_large_hosts_only() { + let small = Policy::for_host(g(38), true); + assert_eq!((small.soft_floor, small.hard_floor), (g(4), g(2))); + let big = Policy::for_host(g(1024), false); + assert_eq!(big.soft_floor, g(32)); + assert_eq!(big.hard_floor, g(16)); +} + +#[test] +fn an_explicit_cap_never_grows_when_ram_is_freed_but_auto_does() { + let p = Policy::for_host(g(121), false); + let cap = 6144 * MIB; + // the 5090 at turn 5 today (MemAvailable 8.6 GiB after the stack opened is the PLAN's view of the open-time figure ~14 GiB) + let before = 14_064 * MIB; + // the sparse memfd frees ~36.6 GiB of shmem: MemAvailable at open rises by that much + let after = before + 36_600 * MIB; + let (granted_before, _) = explicit_prefix_budget(cap, Some(before), &p, 0); + let (granted_after, elastic_after) = explicit_prefix_budget(cap, Some(after), &p, 0); + assert_eq!(granted_before, cap - cap % MIB, "inside the cap today: the cap is the budget (auto would give {} MiB)", auto_prefix_budget(Some(before), &p, 0) >> 20); + assert_eq!(granted_after, cap, "freed RAM does not grow an explicit cap"); + assert!(elastic_after > 40 * GIB); + // the hazard the cap exists for: auto would hand the freed memory to the cache + assert!(auto_prefix_budget(Some(after), &p, 0) > 30 * GIB); + // the same for the startup plan: 37 GiB more available, the same explicit cap, a bigger auto cache + let mut small_input = server_input(75); + small_input.prefix = CacheWish::Bytes(cap); + let mut big_input = server_input(75 + 37); + big_input.prefix = CacheWish::Bytes(cap); + assert_eq!((plan(&small_input).unwrap().prefix_bytes, plan(&big_input).unwrap().prefix_bytes), (cap, cap)); + small_input.prefix = CacheWish::Auto; + big_input.prefix = CacheWish::Auto; + assert!(plan(&big_input).unwrap().prefix_bytes > plan(&small_input).unwrap().prefix_bytes + 20 * GIB); +} + +#[test] +fn an_explicit_cap_is_clamped_to_the_host_and_fails_closed_without_telemetry() { + let p = Policy::for_host(g(121), false); + // 5 GiB available: below soft floor + reserve (6 GiB), nothing elastic + assert_eq!(explicit_prefix_budget(6144 * MIB, Some(g(5)), &p, 0).0, 0); + // 9 GiB available: 3 GiB elastic + assert_eq!(explicit_prefix_budget(6144 * MIB, Some(g(9)), &p, 0), (g(3), g(3))); + // pinned complement pending comes off first + assert_eq!(explicit_prefix_budget(6144 * MIB, Some(g(9)), &p, g(2)).0, g(1)); + assert_eq!(explicit_prefix_budget(6144 * MIB, None, &p, 0), (0, 0)); + // the grant is whole MiB + assert_eq!(explicit_prefix_budget(MIB + 1, Some(g(100)), &p, 0).0, MIB); +} diff --git a/crates/leleka-memory/src/procfs.rs b/crates/leleka-memory/src/procfs.rs index a6e7e38b..2b216c49 100644 --- a/crates/leleka-memory/src/procfs.rs +++ b/crates/leleka-memory/src/procfs.rs @@ -309,111 +309,4 @@ pub fn parse_smaps(text: &str) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - const MEMINFO: &str = "MemTotal: 127091644 kB\nMemFree: 2612464 kB\nMemAvailable: 20699384 kB\nBuffers: 37200 kB\n\ -Cached: 73044620 kB\nSwapCached: 22052 kB\nSwapTotal: 65535996 kB\nSwapFree: 65452100 kB\nShmem: 54338244 kB\n\ -Mlocked: 8724 kB\nUnevictable: 8724 kB\nHugePages_Total: 0\nHugepagesize: 2048 kB\nHugetlb: 0 kB\n"; - - #[test] - fn meminfo_reads_the_5090_server_snapshot() { - let m = parse_meminfo(MEMINFO); - assert_eq!(m.mem_total, Some(127_091_644 * 1024)); - assert_eq!(m.mem_available, Some(20_699_384 * 1024)); - assert_eq!(m.swap_total, Some(65_535_996 * 1024)); - assert_eq!(m.shmem, Some(54_338_244 * 1024)); - assert_eq!(m.hugepages_total, Some(0)); - assert_eq!(m.hugepage_size, Some(2048 * 1024)); - assert_eq!(m.hugetlb, Some(0)); - } - - #[test] - fn meminfo_never_turns_a_malformed_or_duplicated_number_into_a_value() { - for bad in [ - "MemAvailable: -1 kB\n", - "MemAvailable: 1 MB\n", - "MemAvailable: x kB\n", - "MemAvailable: 18446744073709551615 kB\n", - "MemAvailable: 1 kB extra\n", - "MemAvailable: 1 kB\nMemAvailable: 2 kB\n", - ] { - assert_eq!(parse_meminfo(bad).mem_available, None, "{bad:?}"); - } - assert_eq!(parse_meminfo("").mem_total, None); - assert_eq!(parse_meminfo("MemAvailableX: 5 kB\n").mem_available, None); - assert_eq!(parse_meminfo("MemAvailable:\t7\tkB\r\n").mem_available, Some(7 * 1024)); - } - - #[test] - fn status_reads_pinned_locked_and_swap() { - let t = "Name:\tleleka\nVmPeak:\t 1 kB\nVmPin:\t 52428800 kB\nVmHWM:\t 70000000 kB\nVmRSS:\t 61000000 kB\nRssAnon:\t 1000 kB\nRssFile:\t 2000 kB\n\ -RssShmem:\t 3000 kB\nVmSwap:\t 12 kB\nVmLck:\t 8 kB\nThreads:\t 41\nCapEff:\t0000000000004000\n"; - let s = parse_status(t); - assert_eq!(s.vm_pin, Some(52_428_800 * 1024)); - assert_eq!(s.vm_rss, Some(61_000_000 * 1024)); - assert_eq!(s.vm_swap, Some(12 * 1024)); - assert_eq!(s.vm_lck, Some(8 * 1024)); - assert_eq!(s.threads, Some(41)); - assert_eq!(s.cap_eff.map(|c| c & (1 << 14) != 0), Some(true)); - assert_eq!(parse_status("VmRSS: 5 MB\n").vm_rss, None); - } - - #[test] - fn memlock_limit_reads_numbers_and_unlimited() { - let t = "Limit Soft Limit Hard Limit Units \nMax locked memory 8388608 8388608 bytes \nMax address space unlimited unlimited bytes \n"; - assert_eq!(parse_memlock_limit(t), Some((8 << 20, 8 << 20))); - let u = "Max locked memory unlimited unlimited bytes \n"; - assert_eq!(parse_memlock_limit(u), Some((u64::MAX, u64::MAX))); - assert_eq!(parse_memlock_limit("Max stack size 1 2 bytes\n"), None); - } - - #[test] - fn psi_needs_both_lines_and_all_fields() { - let t = "some avg10=0.00 avg60=0.01 avg300=0.00 total=2586497190\nfull avg10=1.50 avg60=0.01 avg300=0.00 total=2572226352\n"; - let p = parse_psi(t).unwrap(); - assert_eq!(p.some.total_us, 2_586_497_190); - assert!((p.full.avg10 - 1.5).abs() < 1e-9); - assert!(parse_psi("some avg10=0.00 avg60=0.01 avg300=0.00 total=1\n").is_none()); - assert!(parse_psi("some avg10=nan avg60=0 avg300=0 total=1\nfull avg10=0 avg60=0 avg300=0 total=1\n").is_none()); - assert!(parse_psi("some avg10=0 avg60=0 total=1\nfull avg10=0 avg60=0 avg300=0 total=1\n").is_none()); - } - - #[test] - fn keyed_files_reject_duplicates_and_trailing_fields() { - assert_eq!(flat_keyed("pswpout 12\npswpin 3\n", "pswpout"), Some(12)); - assert_eq!(flat_keyed("a 1\na 2\n", "a"), None); - assert_eq!(flat_keyed("a 1 2\n", "a"), None); - assert_eq!(flat_keyed("a x\n", "a"), None); - assert_eq!(flat_keyed("", "a"), None); - } - - #[test] - fn cgroup_files() { - assert_eq!(parse_cgroup_limit("max\n"), Some(None)); - assert_eq!(parse_cgroup_limit("1073741824\n"), Some(Some(1 << 30))); - assert_eq!(parse_cgroup_limit("lots"), None); - assert_eq!(parse_cgroup_path("0::/user.slice/user-1000.slice/session-578.scope\n").as_deref(), Some("/user.slice/user-1000.slice/session-578.scope")); - assert_eq!(parse_cgroup_path("12:memory:/x\n"), None); - assert_eq!(parse_cgroup_v1_memory_path("0::/init.scope\n5:memory:/docker/abc\n").as_deref(), Some("/docker/abc")); - assert_eq!(parse_cgroup_v1_memory_path("5:cpu,cpuacct:/x\n0::/y\n"), None); - let e = parse_cgroup_events("low 0\nhigh 3\nmax 4\noom 1\noom_kill 1\n").unwrap(); - assert_eq!((e.high, e.max, e.oom, e.oom_kill), (3, 4, 1, 1)); - assert!(parse_cgroup_events("low 0\nhigh 3\n").is_none()); - } - - #[test] - fn smaps_finds_the_memfd_mapping_with_its_swap() { - let t = "7f0000000000-7f0100000000 r--s 00000000 00:01 4242 /memfd:kar-archive (deleted)\n\ -Size: 4194304 kB\nKernelPageSize: 4 kB\nRss: 4000000 kB\nSwap: 194304 kB\nLocked: 0 kB\n\ -55e0-55e1 r-xp 00000000 08:01 1 /usr/bin/x\nSize: 4 kB\nRss: 4 kB\nSwap: 0 kB\nLocked: 0 kB\n"; - let e = parse_smaps(t); - assert_eq!(e.len(), 2); - assert_eq!(e[0].path, "/memfd:kar-archive (deleted)"); - assert_eq!(e[0].swap, 194_304 * 1024); - assert_eq!(e[0].rss, 4_000_000 * 1024); - assert_eq!(e[0].end - e[0].start, 0x1_0000_0000); - assert_eq!(e[1].path, "/usr/bin/x"); - assert!(parse_smaps("garbage\nSwap: 1 kB\n").is_empty()); - } -} +mod tests; diff --git a/crates/leleka-memory/src/procfs/tests.rs b/crates/leleka-memory/src/procfs/tests.rs new file mode 100644 index 00000000..c6f30195 --- /dev/null +++ b/crates/leleka-memory/src/procfs/tests.rs @@ -0,0 +1,108 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +const MEMINFO: &str = "MemTotal: 127091644 kB\nMemFree: 2612464 kB\nMemAvailable: 20699384 kB\nBuffers: 37200 kB\n\ +Cached: 73044620 kB\nSwapCached: 22052 kB\nSwapTotal: 65535996 kB\nSwapFree: 65452100 kB\nShmem: 54338244 kB\n\ +Mlocked: 8724 kB\nUnevictable: 8724 kB\nHugePages_Total: 0\nHugepagesize: 2048 kB\nHugetlb: 0 kB\n"; + +#[test] +fn meminfo_reads_the_5090_server_snapshot() { + let m = parse_meminfo(MEMINFO); + assert_eq!(m.mem_total, Some(127_091_644 * 1024)); + assert_eq!(m.mem_available, Some(20_699_384 * 1024)); + assert_eq!(m.swap_total, Some(65_535_996 * 1024)); + assert_eq!(m.shmem, Some(54_338_244 * 1024)); + assert_eq!(m.hugepages_total, Some(0)); + assert_eq!(m.hugepage_size, Some(2048 * 1024)); + assert_eq!(m.hugetlb, Some(0)); +} + +#[test] +fn meminfo_never_turns_a_malformed_or_duplicated_number_into_a_value() { + for bad in [ + "MemAvailable: -1 kB\n", + "MemAvailable: 1 MB\n", + "MemAvailable: x kB\n", + "MemAvailable: 18446744073709551615 kB\n", + "MemAvailable: 1 kB extra\n", + "MemAvailable: 1 kB\nMemAvailable: 2 kB\n", + ] { + assert_eq!(parse_meminfo(bad).mem_available, None, "{bad:?}"); + } + assert_eq!(parse_meminfo("").mem_total, None); + assert_eq!(parse_meminfo("MemAvailableX: 5 kB\n").mem_available, None); + assert_eq!(parse_meminfo("MemAvailable:\t7\tkB\r\n").mem_available, Some(7 * 1024)); +} + +#[test] +fn status_reads_pinned_locked_and_swap() { + let t = "Name:\tleleka\nVmPeak:\t 1 kB\nVmPin:\t 52428800 kB\nVmHWM:\t 70000000 kB\nVmRSS:\t 61000000 kB\nRssAnon:\t 1000 kB\nRssFile:\t 2000 kB\n\ +RssShmem:\t 3000 kB\nVmSwap:\t 12 kB\nVmLck:\t 8 kB\nThreads:\t 41\nCapEff:\t0000000000004000\n"; + let s = parse_status(t); + assert_eq!(s.vm_pin, Some(52_428_800 * 1024)); + assert_eq!(s.vm_rss, Some(61_000_000 * 1024)); + assert_eq!(s.vm_swap, Some(12 * 1024)); + assert_eq!(s.vm_lck, Some(8 * 1024)); + assert_eq!(s.threads, Some(41)); + assert_eq!(s.cap_eff.map(|c| c & (1 << 14) != 0), Some(true)); + assert_eq!(parse_status("VmRSS: 5 MB\n").vm_rss, None); +} + +#[test] +fn memlock_limit_reads_numbers_and_unlimited() { + let t = "Limit Soft Limit Hard Limit Units \nMax locked memory 8388608 8388608 bytes \nMax address space unlimited unlimited bytes \n"; + assert_eq!(parse_memlock_limit(t), Some((8 << 20, 8 << 20))); + let u = "Max locked memory unlimited unlimited bytes \n"; + assert_eq!(parse_memlock_limit(u), Some((u64::MAX, u64::MAX))); + assert_eq!(parse_memlock_limit("Max stack size 1 2 bytes\n"), None); +} + +#[test] +fn psi_needs_both_lines_and_all_fields() { + let t = "some avg10=0.00 avg60=0.01 avg300=0.00 total=2586497190\nfull avg10=1.50 avg60=0.01 avg300=0.00 total=2572226352\n"; + let p = parse_psi(t).unwrap(); + assert_eq!(p.some.total_us, 2_586_497_190); + assert!((p.full.avg10 - 1.5).abs() < 1e-9); + assert!(parse_psi("some avg10=0.00 avg60=0.01 avg300=0.00 total=1\n").is_none()); + assert!(parse_psi("some avg10=nan avg60=0 avg300=0 total=1\nfull avg10=0 avg60=0 avg300=0 total=1\n").is_none()); + assert!(parse_psi("some avg10=0 avg60=0 total=1\nfull avg10=0 avg60=0 avg300=0 total=1\n").is_none()); +} + +#[test] +fn keyed_files_reject_duplicates_and_trailing_fields() { + assert_eq!(flat_keyed("pswpout 12\npswpin 3\n", "pswpout"), Some(12)); + assert_eq!(flat_keyed("a 1\na 2\n", "a"), None); + assert_eq!(flat_keyed("a 1 2\n", "a"), None); + assert_eq!(flat_keyed("a x\n", "a"), None); + assert_eq!(flat_keyed("", "a"), None); +} + +#[test] +fn cgroup_files() { + assert_eq!(parse_cgroup_limit("max\n"), Some(None)); + assert_eq!(parse_cgroup_limit("1073741824\n"), Some(Some(1 << 30))); + assert_eq!(parse_cgroup_limit("lots"), None); + assert_eq!(parse_cgroup_path("0::/user.slice/user-1000.slice/session-578.scope\n").as_deref(), Some("/user.slice/user-1000.slice/session-578.scope")); + assert_eq!(parse_cgroup_path("12:memory:/x\n"), None); + assert_eq!(parse_cgroup_v1_memory_path("0::/init.scope\n5:memory:/docker/abc\n").as_deref(), Some("/docker/abc")); + assert_eq!(parse_cgroup_v1_memory_path("5:cpu,cpuacct:/x\n0::/y\n"), None); + let e = parse_cgroup_events("low 0\nhigh 3\nmax 4\noom 1\noom_kill 1\n").unwrap(); + assert_eq!((e.high, e.max, e.oom, e.oom_kill), (3, 4, 1, 1)); + assert!(parse_cgroup_events("low 0\nhigh 3\n").is_none()); +} + +#[test] +fn smaps_finds_the_memfd_mapping_with_its_swap() { + let t = "7f0000000000-7f0100000000 r--s 00000000 00:01 4242 /memfd:kar-archive (deleted)\n\ +Size: 4194304 kB\nKernelPageSize: 4 kB\nRss: 4000000 kB\nSwap: 194304 kB\nLocked: 0 kB\n\ +55e0-55e1 r-xp 00000000 08:01 1 /usr/bin/x\nSize: 4 kB\nRss: 4 kB\nSwap: 0 kB\nLocked: 0 kB\n"; + let e = parse_smaps(t); + assert_eq!(e.len(), 2); + assert_eq!(e[0].path, "/memfd:kar-archive (deleted)"); + assert_eq!(e[0].swap, 194_304 * 1024); + assert_eq!(e[0].rss, 4_000_000 * 1024); + assert_eq!(e[0].end - e[0].start, 0x1_0000_0000); + assert_eq!(e[1].path, "/usr/bin/x"); + assert!(parse_smaps("garbage\nSwap: 1 kB\n").is_empty()); +} diff --git a/crates/leleka-memory/src/telemetry.rs b/crates/leleka-memory/src/telemetry.rs index 4d0a3cfa..341d6f68 100644 --- a/crates/leleka-memory/src/telemetry.rs +++ b/crates/leleka-memory/src/telemetry.rs @@ -627,181 +627,4 @@ pub fn start(gpu_probe: Option, period: Duration) -> Sampler { } #[cfg(test)] -mod tests { - use super::*; - - static SERIAL: Mutex<()> = Mutex::new(()); - - fn measured() -> Measured { - Measured { - now_ms: 1, - uptime_s: 5, - gpu: Some(GpuSample { index: 0, util_pct: 91, mem_util_pct: 40, vram_used_mib: 30000, vram_total_mib: 32607, power_w: Some(480.0), sm_clock_mhz: Some(2900), temp_c: Some(61), name: Some("NVIDIA GeForce RTX 5090".into()), ..Default::default() }), - meminfo: procfs::parse_meminfo("MemTotal: 125829120 kB\nMemAvailable: 70000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"), - status: procfs::parse_status("VmRSS:\t55000000 kB\nVmPin:\t3000000 kB\n"), - cores: 32, - cpu: Some((7.4, 31.0)), - } - } - - #[test] - fn self_stat_survives_a_command_name_with_spaces_and_parentheses() { - let line = "123 (a b) c) S 1 2 3 4 5 6 7 8 9 10 250 50 0 0 20 0 1 0"; - assert_eq!(parse_self_stat_ticks(line), Some(300)); - assert_eq!(parse_self_stat_ticks("garbage"), None); - } - - #[test] - fn system_cpu_counts_idle_and_iowait_as_not_busy() { - let (busy, total) = parse_stat_cpu("cpu 100 0 50 800 50 0 0 0 0 0\ncpu0 1 2 3 4\n").unwrap(); - assert_eq!((busy, total), (150, 1000)); - let before = CpuReading { process_ticks: 1000, system_busy: 0, system_total: 0 }; - let after = CpuReading { process_ticks: 1740, system_busy: 150, system_total: 1000 }; - let (process, system) = cpu_usage(&before, &after, Duration::from_secs(1)); - assert!((process - 7.4).abs() < 1e-9 && (system - 15.0).abs() < 1e-9, "{process} {system}"); - } - - #[test] - fn the_nan_guard_reports_each_healed_and_unhealed_window() { - let _serial = lock(&SERIAL); - *lock(&STATE) = None; - let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert_eq!((doc["nan_guard"]["healed_windows"].as_u64(), doc["nan_guard"]["unhealed_windows"].as_u64()), (Some(0), Some(0))); - assert!(doc["nan_guard"]["last"].is_null()); - nan_guard_healed("position 4096, 4 rows, retry 1 of 2: NonFinite"); - nan_guard_healed("position 4100, 2 rows, retry 1 of 2: NonFinite"); - nan_guard_unhealed("position 8000, 4 rows, retry 2 of 2: NonFinite"); - let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert_eq!((doc["nan_guard"]["healed_windows"].as_u64(), doc["nan_guard"]["unhealed_windows"].as_u64()), (Some(2), Some(1))); - assert_eq!(doc["nan_guard"]["last"], "unhealed: position 8000, 4 rows, retry 2 of 2: NonFinite"); - *lock(&STATE) = None; - } - - #[test] - fn the_engine_line_carries_the_figures_of_one_request_and_stays_small() { - use leleka_obs::{Format, Level, Settings}; - let json = Settings { min_level: Level::Info, format: Format::Json, debug: false, legacy: false }; - let line = |r: &RequestLine<'_>| format_line_for_test(&json, r); - fn format_line_for_test(json: &Settings, r: &RequestLine<'_>) -> String { - leleka_obs::format_line(json, 1_793_613_072_345, Level::Info, "engine", "request", &request_line_fields(r), 0) - } - let full = RequestLine { - request_id: "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d", - input_tokens: 182_341, - reused_tokens: 181_900, - output_tokens: 412, - prefill_ms: 912.34, - decode_ms: 5_760.0, - produced: 412, - rounds: 131, - shares: Some((91.4, 5.1, 3.5)), - }; - let text = line(&full); - for expected in ["\"comp\":\"engine\"", "\"rid\":\"0b1c2d3e", "\"rounds\":131", "\"tok_per_round\":3.15", "\"dec_tps\":71.5", "\"tier_vram_pct\":91.4"] { - assert!(text.contains(expected), "{expected} missing: {text}"); - } - assert!(text.len() < 512, "{} bytes: {text}", text.len()); - eprintln!("ENGINE-LINE-BYTES {} {text}", text.len()); - // without the expert tier the three shares are left out; an idle request has no rates - let idle = line(&RequestLine { request_id: "r", input_tokens: 0, reused_tokens: 0, output_tokens: 0, prefill_ms: 0.0, decode_ms: 0.0, produced: 0, rounds: 0, shares: None }); - assert!(!idle.contains("tier_") && idle.contains("\"tok_per_round\":null"), "{idle}"); - } - - #[test] - fn the_tier_share_of_a_request_is_the_difference_to_the_previous_one() { - let first = TierCounters { vram_entries: 900, pcie_entries: 60, cpu_entries: 40, ..Default::default() }; - assert_eq!(tier_shares(None, &first), (90.0, 6.0, 4.0)); - let second = TierCounters { vram_entries: 1_500, pcie_entries: 160, cpu_entries: 40, ..Default::default() }; - // 600 / 100 / 0 more entries - let (v, p, c) = tier_shares(Some(&first), &second); - assert!((v - 85.7).abs() < 1e-9 && (p - 14.3).abs() < 1e-9 && c == 0.0, "{v} {p} {c}"); - // counters that went back (the stack was reopened) are taken as they are - assert_eq!(tier_shares(Some(&second), &first), (90.0, 6.0, 4.0)); - } - - #[test] - fn the_engine_reports_the_speculative_loop_and_the_expert_tier_per_request() { - let _serial = lock(&SERIAL); - *lock(&STATE) = None; - let first: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert!(first["last_request"].is_null() && first["expert_tier"].is_null()); - assert_eq!(first["spec"]["rounds"], 0); - assert!(first["spec"]["tokens_per_round"].is_null()); - request_started(1000); - tokens_delivered(300); - request_finished(1000, 400, 300, 600.0, 3000.0); - request_detail("req-1", 100, Some(TierCounters { groups: 40, vram_entries: 900, pcie_entries: 60, cpu_entries: 40, adaptations: 2, swaps: 7 })); - request_started(1000); - request_finished(1000, 0, 100, 1200.0, 1000.0); - request_detail("req-2", 50, None); - let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert_eq!(doc["spec"]["rounds"], 150); - assert_eq!(doc["spec"]["tokens"], 400); - assert_eq!(doc["spec"]["tokens_per_round"], 2.67); - assert_eq!(doc["last_request"]["request_id"], "req-2"); - assert_eq!(doc["last_request"]["tokens_per_round"], 2.0); - assert_eq!(doc["last_request"]["rounds"], 50); - // a request without tier counters keeps the last known ones - assert_eq!(doc["expert_tier"]["vram_entries"], 900); - assert_eq!(doc["expert_tier"]["vram_ratio"], 0.9); - *lock(&STATE) = None; - } - - #[test] - fn requests_fold_into_rates_cache_and_context() { - let _serial = lock(&SERIAL); - *lock(&STATE) = None; - set_context_max(262_144); - request_started(100_000); - tokens_delivered(4); - request_finished(100_000, 80_000, 400, 4_000.0, 4_000.0); - request_started(101_000); - request_finished(101_000, 0, 200, 20_000.0, 2_000.0); - let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert_eq!(doc["phase"], "idle"); - assert_eq!(doc["cache"]["requests"], 2); - assert_eq!(doc["cache"]["hit_requests"], 1); - assert_eq!(doc["cache"]["hit_ratio"], 0.5); - // 100000+101000 prompt tokens, 80000 reused - assert_eq!(doc["cache"]["token_hit_ratio"], 0.398); - // prefill: 20000 tokens in 4000 ms = 5000/s, then 101000 in 20000 ms = 5050/s - assert_eq!(doc["throughput"]["prefill_tok_s_last"], 5050.0); - assert_eq!(doc["throughput"]["decode_tok_s_last"], 100.0); - assert_eq!(doc["throughput"]["decode_tok_s_lifetime"], 100.0); - assert_eq!(doc["context"]["live_tokens"], 101_200); - assert_eq!(doc["context"]["max_tokens"], 262_144); - assert_eq!(doc["gpu"]["util_pct"], 91); - assert_eq!(doc["gpu"]["temp_c"], 61); - assert_eq!(doc["gpu"]["name"], "NVIDIA GeForce RTX 5090"); - assert!(doc["request"].is_null(), "no request in flight after the last one finished"); - assert_eq!(doc["ram"]["total_mib"], 122_880); - assert_eq!(doc["cpu"]["process_busy_cores"], 7.4); - } - - #[test] - fn a_request_in_flight_is_reported_with_its_progress() { - let _serial = lock(&SERIAL); - *lock(&STATE) = None; - request_started(5_000); - tokens_delivered(3); - tokens_delivered(4); - let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert_eq!(doc["phase"], "decode"); - assert_eq!(doc["request"]["prompt_tokens"], 5_000); - assert_eq!(doc["request"]["generated_tokens"], 7); - assert!(doc["request"]["elapsed_s"].as_f64().unwrap() >= 0.0); - request_aborted(); - let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert!(doc["request"].is_null()); - } - - #[test] - fn an_empty_state_renders_nulls_not_zeros_for_unmeasured_rates() { - let _serial = lock(&SERIAL); - *lock(&STATE) = None; - let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert!(doc["throughput"]["decode_tok_s_last"].is_null()); - assert!(doc["cache"]["hit_ratio"].is_null()); - assert!(doc["context"]["used_pct"].is_null()); - } -} +mod tests; diff --git a/crates/leleka-memory/src/telemetry/tests.rs b/crates/leleka-memory/src/telemetry/tests.rs new file mode 100644 index 00000000..f22f7285 --- /dev/null +++ b/crates/leleka-memory/src/telemetry/tests.rs @@ -0,0 +1,178 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +static SERIAL: Mutex<()> = Mutex::new(()); + +fn measured() -> Measured { + Measured { + now_ms: 1, + uptime_s: 5, + gpu: Some(GpuSample { index: 0, util_pct: 91, mem_util_pct: 40, vram_used_mib: 30000, vram_total_mib: 32607, power_w: Some(480.0), sm_clock_mhz: Some(2900), temp_c: Some(61), name: Some("NVIDIA GeForce RTX 5090".into()), ..Default::default() }), + meminfo: procfs::parse_meminfo("MemTotal: 125829120 kB\nMemAvailable: 70000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"), + status: procfs::parse_status("VmRSS:\t55000000 kB\nVmPin:\t3000000 kB\n"), + cores: 32, + cpu: Some((7.4, 31.0)), + } +} + +#[test] +fn self_stat_survives_a_command_name_with_spaces_and_parentheses() { + let line = "123 (a b) c) S 1 2 3 4 5 6 7 8 9 10 250 50 0 0 20 0 1 0"; + assert_eq!(parse_self_stat_ticks(line), Some(300)); + assert_eq!(parse_self_stat_ticks("garbage"), None); +} + +#[test] +fn system_cpu_counts_idle_and_iowait_as_not_busy() { + let (busy, total) = parse_stat_cpu("cpu 100 0 50 800 50 0 0 0 0 0\ncpu0 1 2 3 4\n").unwrap(); + assert_eq!((busy, total), (150, 1000)); + let before = CpuReading { process_ticks: 1000, system_busy: 0, system_total: 0 }; + let after = CpuReading { process_ticks: 1740, system_busy: 150, system_total: 1000 }; + let (process, system) = cpu_usage(&before, &after, Duration::from_secs(1)); + assert!((process - 7.4).abs() < 1e-9 && (system - 15.0).abs() < 1e-9, "{process} {system}"); +} + +#[test] +fn the_nan_guard_reports_each_healed_and_unhealed_window() { + let _serial = lock(&SERIAL); + *lock(&STATE) = None; + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert_eq!((doc["nan_guard"]["healed_windows"].as_u64(), doc["nan_guard"]["unhealed_windows"].as_u64()), (Some(0), Some(0))); + assert!(doc["nan_guard"]["last"].is_null()); + nan_guard_healed("position 4096, 4 rows, retry 1 of 2: NonFinite"); + nan_guard_healed("position 4100, 2 rows, retry 1 of 2: NonFinite"); + nan_guard_unhealed("position 8000, 4 rows, retry 2 of 2: NonFinite"); + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert_eq!((doc["nan_guard"]["healed_windows"].as_u64(), doc["nan_guard"]["unhealed_windows"].as_u64()), (Some(2), Some(1))); + assert_eq!(doc["nan_guard"]["last"], "unhealed: position 8000, 4 rows, retry 2 of 2: NonFinite"); + *lock(&STATE) = None; +} + +#[test] +fn the_engine_line_carries_the_figures_of_one_request_and_stays_small() { + use leleka_obs::{Format, Level, Settings}; + let json = Settings { min_level: Level::Info, format: Format::Json, debug: false, legacy: false }; + let line = |r: &RequestLine<'_>| format_line_for_test(&json, r); + fn format_line_for_test(json: &Settings, r: &RequestLine<'_>) -> String { + leleka_obs::format_line(json, 1_793_613_072_345, Level::Info, "engine", "request", &request_line_fields(r), 0) + } + let full = RequestLine { + request_id: "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d", + input_tokens: 182_341, + reused_tokens: 181_900, + output_tokens: 412, + prefill_ms: 912.34, + decode_ms: 5_760.0, + produced: 412, + rounds: 131, + shares: Some((91.4, 5.1, 3.5)), + }; + let text = line(&full); + for expected in ["\"comp\":\"engine\"", "\"rid\":\"0b1c2d3e", "\"rounds\":131", "\"tok_per_round\":3.15", "\"dec_tps\":71.5", "\"tier_vram_pct\":91.4"] { + assert!(text.contains(expected), "{expected} missing: {text}"); + } + assert!(text.len() < 512, "{} bytes: {text}", text.len()); + eprintln!("ENGINE-LINE-BYTES {} {text}", text.len()); + // without the expert tier the three shares are left out; an idle request has no rates + let idle = line(&RequestLine { request_id: "r", input_tokens: 0, reused_tokens: 0, output_tokens: 0, prefill_ms: 0.0, decode_ms: 0.0, produced: 0, rounds: 0, shares: None }); + assert!(!idle.contains("tier_") && idle.contains("\"tok_per_round\":null"), "{idle}"); +} + +#[test] +fn the_tier_share_of_a_request_is_the_difference_to_the_previous_one() { + let first = TierCounters { vram_entries: 900, pcie_entries: 60, cpu_entries: 40, ..Default::default() }; + assert_eq!(tier_shares(None, &first), (90.0, 6.0, 4.0)); + let second = TierCounters { vram_entries: 1_500, pcie_entries: 160, cpu_entries: 40, ..Default::default() }; + // 600 / 100 / 0 more entries + let (v, p, c) = tier_shares(Some(&first), &second); + assert!((v - 85.7).abs() < 1e-9 && (p - 14.3).abs() < 1e-9 && c == 0.0, "{v} {p} {c}"); + // counters that went back (the stack was reopened) are taken as they are + assert_eq!(tier_shares(Some(&second), &first), (90.0, 6.0, 4.0)); +} + +#[test] +fn the_engine_reports_the_speculative_loop_and_the_expert_tier_per_request() { + let _serial = lock(&SERIAL); + *lock(&STATE) = None; + let first: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert!(first["last_request"].is_null() && first["expert_tier"].is_null()); + assert_eq!(first["spec"]["rounds"], 0); + assert!(first["spec"]["tokens_per_round"].is_null()); + request_started(1000); + tokens_delivered(300); + request_finished(1000, 400, 300, 600.0, 3000.0); + request_detail("req-1", 100, Some(TierCounters { groups: 40, vram_entries: 900, pcie_entries: 60, cpu_entries: 40, adaptations: 2, swaps: 7 })); + request_started(1000); + request_finished(1000, 0, 100, 1200.0, 1000.0); + request_detail("req-2", 50, None); + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert_eq!(doc["spec"]["rounds"], 150); + assert_eq!(doc["spec"]["tokens"], 400); + assert_eq!(doc["spec"]["tokens_per_round"], 2.67); + assert_eq!(doc["last_request"]["request_id"], "req-2"); + assert_eq!(doc["last_request"]["tokens_per_round"], 2.0); + assert_eq!(doc["last_request"]["rounds"], 50); + // a request without tier counters keeps the last known ones + assert_eq!(doc["expert_tier"]["vram_entries"], 900); + assert_eq!(doc["expert_tier"]["vram_ratio"], 0.9); + *lock(&STATE) = None; +} + +#[test] +fn requests_fold_into_rates_cache_and_context() { + let _serial = lock(&SERIAL); + *lock(&STATE) = None; + set_context_max(262_144); + request_started(100_000); + tokens_delivered(4); + request_finished(100_000, 80_000, 400, 4_000.0, 4_000.0); + request_started(101_000); + request_finished(101_000, 0, 200, 20_000.0, 2_000.0); + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert_eq!(doc["phase"], "idle"); + assert_eq!(doc["cache"]["requests"], 2); + assert_eq!(doc["cache"]["hit_requests"], 1); + assert_eq!(doc["cache"]["hit_ratio"], 0.5); + // 100000+101000 prompt tokens, 80000 reused + assert_eq!(doc["cache"]["token_hit_ratio"], 0.398); + // prefill: 20000 tokens in 4000 ms = 5000/s, then 101000 in 20000 ms = 5050/s + assert_eq!(doc["throughput"]["prefill_tok_s_last"], 5050.0); + assert_eq!(doc["throughput"]["decode_tok_s_last"], 100.0); + assert_eq!(doc["throughput"]["decode_tok_s_lifetime"], 100.0); + assert_eq!(doc["context"]["live_tokens"], 101_200); + assert_eq!(doc["context"]["max_tokens"], 262_144); + assert_eq!(doc["gpu"]["util_pct"], 91); + assert_eq!(doc["gpu"]["temp_c"], 61); + assert_eq!(doc["gpu"]["name"], "NVIDIA GeForce RTX 5090"); + assert!(doc["request"].is_null(), "no request in flight after the last one finished"); + assert_eq!(doc["ram"]["total_mib"], 122_880); + assert_eq!(doc["cpu"]["process_busy_cores"], 7.4); +} + +#[test] +fn a_request_in_flight_is_reported_with_its_progress() { + let _serial = lock(&SERIAL); + *lock(&STATE) = None; + request_started(5_000); + tokens_delivered(3); + tokens_delivered(4); + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert_eq!(doc["phase"], "decode"); + assert_eq!(doc["request"]["prompt_tokens"], 5_000); + assert_eq!(doc["request"]["generated_tokens"], 7); + assert!(doc["request"]["elapsed_s"].as_f64().unwrap() >= 0.0); + request_aborted(); + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert!(doc["request"].is_null()); +} + +#[test] +fn an_empty_state_renders_nulls_not_zeros_for_unmeasured_rates() { + let _serial = lock(&SERIAL); + *lock(&STATE) = None; + let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert!(doc["throughput"]["decode_tok_s_last"].is_null()); + assert!(doc["cache"]["hit_ratio"].is_null()); + assert!(doc["context"]["used_pct"].is_null()); +} diff --git a/crates/leleka-runtime/src/conversation/cache.rs b/crates/leleka-runtime/src/conversation/cache.rs index 26e77afb..4cb999cb 100644 --- a/crates/leleka-runtime/src/conversation/cache.rs +++ b/crates/leleka-runtime/src/conversation/cache.rs @@ -490,410 +490,4 @@ impl ConversationCache { } #[cfg(test)] -mod tests { - use super::*; - - fn image(ids: &[i32]) -> SavedConversation { - image_mode(ids, true) - } - fn image_mode(ids: &[i32], cvec: bool) -> SavedConversation { - let mut s = SavedConversation::default(); - s.live.ids = ids.to_vec(); - s.live.gdn = vec![7; 64]; - s.cvec = cvec; - s - } - fn cp(ids: &[i32]) -> ConversationCheckpoint { - ConversationCheckpoint { - ids: ids.to_vec(), - ..Default::default() - } - } - fn with(prefix: &[i32], more: &[i32]) -> Vec { - let mut v = prefix.to_vec(); - v.extend_from_slice(more); - v - } - fn exact_kv_layers() -> Vec { - let mut layer = ConversationKv::default(); - layer.k.resize(400, 0).unwrap(); - vec![layer] - } - const A: [i64; 4] = [1, 2, 3, 4]; - const B: [i64; 4] = [9, 8, 7, 6]; - - #[test] - fn retained_buffers_count_against_bytes_but_not_slots() { - let layers = exact_kv_layers(); - let retained = layers.capacity() * size_of::() + layers[0].bytes(); - let parked = image(&[1, 2, 3]).bytes(); - let mut cache = ConversationCache::new(retained + parked, 4); - assert!( - cache.put(image(&[1, 2, 3]), 0).is_ok(), - "park before retaining active storage" - ); - cache.retain(layers, 16); - assert!( - cache.bytes() == retained + parked && cache.size() == 1, - "active retained storage consumes bytes but no parked slot" - ); - cache.limit_reuse(9); - cache.limit_reuse(12); - let reuse = cache.take_reuse(); - assert_eq!( - reuse.unchanged_tokens, 9, - "a later continuation cannot undo a rewind's dirty boundary" - ); - assert_eq!( - cache.bytes(), - parked, - "taking retained buffers releases their budget accounting" - ); - cache.retain(reuse.kv, 16); - assert!( - !cache.can_fit(parked, 0), - "retained storage is counted when checking a capture without eviction" - ); - assert!( - cache.retained_bytes() == retained && cache.size() == 1 && cache.evictions() == 0, - "optional reuse admission does not evict or release anything" - ); - assert!( - !cache.can_fit(usize::MAX, 0) && !cache.can_fit(1, usize::MAX), - "non-mutating reservation rejects overflow" - ); - assert!( - cache.make_room(parked, 0), - "reservation can discard optional active buffers" - ); - assert!( - cache.retained_bytes() == 0 && cache.size() == 1 && cache.evictions() == 0, - "pressure drops retained storage before evicting parked conversations" - ); - } - - #[test] - fn a_b_a_recovery_and_slot_eviction() { - let mut cache = ConversationCache::new(1024, 2); - assert!(cache.put(image(&[1, 2, 3]), 0).is_ok(), "park A"); - assert!(cache.put(image(&[9, 8, 7]), 0).is_ok(), "park B"); - let m = cache.best(&A, &[], true); - assert!(m.tokens == 3 && m.live, "A/B/A: recover A"); - let restored = cache.take(m.index).unwrap(); - assert_eq!( - restored.live.ids, - vec![1, 2, 3], - "taking selected A preserves identity" - ); - assert!( - cache.size() == 1 && cache.best(&B, &[], true).tokens == 3, - "B remains parked" - ); - assert_eq!( - cache.bytes(), - image(&[9, 8, 7]).bytes(), - "byte accounting after take" - ); - assert!(cache.put(restored, 0).is_ok(), "park returned A as newest"); - assert!( - cache.put(image(&[5, 6]), 0).is_ok(), - "evict oldest by slot limit" - ); - assert!( - cache.best(&B, &[], true).tokens == 0 && cache.best(&A, &[], true).tokens == 3, - "B evicted before A" - ); - assert_eq!(cache.evictions(), 1, "eviction counter"); - } - - #[test] - fn checkpoints_steering_and_boundary_rules() { - let mut s = image(&[1, 2, 3]); - s.checkpoints.push(cp(&[1, 2])); - let mut cache = ConversationCache::new(4096, 4); - cache.put(s, 0).unwrap(); - let m = cache.best(&[1i64, 2, 9, 4], &[], true); - assert!( - m.tokens == 2 && !m.live, - "edited suffix falls back to parked checkpoint" - ); - assert_eq!( - cache.best(&A, &[], true).tokens, - 3, - "live prefix beats shorter checkpoint" - ); - assert_eq!( - cache.best(&A, &[], false).tokens, - 0, - "steering mode is isolated" - ); - assert_eq!( - cache.best(&[1i64, 2], &[], true).tokens, - 0, - "equal-length checkpoint cannot consume last token" - ); - assert_eq!( - cache.best(&[1i64], &[], true).tokens, - 0, - "short prompt cannot match" - ); - assert_eq!( - cache.best::(&[], &[], true).tokens, - 0, - "empty prompt cannot match" - ); - cache.put(image(&[1, 2, 3]), 0).unwrap(); - assert_eq!( - cache.best(&A, &[], true).index, - 1, - "ties prefer most recently parked" - ); - } - - #[test] - fn image_identity_is_part_of_the_prefix() { - let mut s = image(&[1, 2, 3]); - s.live.imgs = vec![ConversationImageKey { - start: 1, - hash: 123, - }]; - let mut cache = ConversationCache::new(1024, 3); - cache.put(s, 0).unwrap(); - let key = |start, hash| ConversationImageKey { start, hash }; - assert_eq!( - cache.best(&A, &[key(1, 123)], true).tokens, - 3, - "same image can resume" - ); - assert_eq!( - cache.best(&A, &[key(1, 124)], true).tokens, - 0, - "different image pixels invalidate same pad tokens" - ); - assert_eq!( - cache.best(&A, &[], true).tokens, - 0, - "missing image invalidates prefix" - ); - assert_eq!( - cache.best(&A, &[key(1, 123), key(2, 45)], true).tokens, - 0, - "additional image in cached prefix invalidates" - ); - assert_eq!( - cache.best(&A, &[key(1, 123), key(3, 45)], true).tokens, - 3, - "image after cached prefix does not invalidate" - ); - } - - #[test] - fn in_flight_image_is_counted_during_an_exchange() { - let one = image(&[1, 2, 3]).bytes(); - let mut cache = ConversationCache::new(one * 2, 8); - cache.put(image(&[1, 2, 3]), 0).unwrap(); - cache.put(image(&[9, 8, 7]), 0).unwrap(); - assert_eq!( - cache.bytes(), - one * 2, - "budget holds two exact-sized images" - ); - let held = cache.take(cache.best(&A, &[], true).index).unwrap(); - assert!( - cache.make_room(one, held.bytes()), - "count in-flight image when reserving outgoing snapshot" - ); - assert_eq!( - cache.size(), - 0, - "in-flight reservation evicts otherwise fitting B" - ); - assert!( - cache.put(image(&[5, 6, 7]), held.bytes()).is_ok(), - "insert with in-flight accounting" - ); - assert!( - cache.bytes() + held.bytes() <= one * 2, - "exchange obeys byte budget" - ); - assert!( - !cache.make_room(one + 1, one), - "oversized exchange rejected" - ); - assert_eq!( - cache.size(), - 1, - "oversized snapshot does not evict useful entries" - ); - let mut huge = image(&[1]); - huge.live.gdn = vec![0; one * 3]; - let back = cache.put(huge, 0).unwrap_err(); - assert_eq!(back.live.ids, vec![1], "a refused image is handed back"); - assert_eq!(cache.size(), 1, "oversized put leaves cache unchanged"); - assert!( - !cache.make_room(0, one * 2 + 1), - "held larger than budget cannot underflow" - ); - } - - /// Upstream 41cf05a0 `940011da`: a full cache dropped the new snapshot instead of evicting for it. Full by slots or by bytes, the - /// oldest conversation goes and the new one is parked; only an image that cannot fit at all is refused, and then nothing is dropped. - #[test] - fn a_full_cache_evicts_the_oldest_for_the_new_snapshot_by_slots_and_by_bytes() { - let one = image(&[1, 2, 3]).bytes(); - // full by bytes (slots to spare): three images do not fit in 2.5 - let mut cache = ConversationCache::new(one * 5 / 2, 8); - cache.put(image(&[1, 1, 1]), 0).unwrap(); - cache.put(image(&[2, 2, 2]), 0).unwrap(); - assert_eq!((cache.size(), cache.evictions()), (2, 0)); - cache.put(image(&[3, 3, 3]), 0).unwrap(); - assert_eq!((cache.size(), cache.evictions()), (2, 1), "the oldest went, the new one stayed"); - assert_eq!(cache.best(&[1, 1, 1, 0], &[], true).tokens, 0); - assert_eq!(cache.best(&[2, 2, 2, 0], &[], true).tokens, 3); - assert_eq!(cache.best(&[3, 3, 3, 0], &[], true).tokens, 3); - assert!(cache.bytes() <= cache.budget()); - // full by slots (bytes to spare), the same - let mut cache = ConversationCache::new(one * 100, 2); - for k in 1..=5 { - cache.put(image(&[k, k, k]), 0).unwrap(); - assert!(cache.size() <= 2); - assert_eq!(cache.best(&[k, k, k, 0], &[], true).tokens, 3, "the newest is always parked: {k}"); - } - assert_eq!(cache.evictions(), 3); - // an image bigger than the whole budget is refused up front and evicts nothing - let mut huge = image(&[9]); - huge.live.gdn = vec![0; one * 200]; - let evictions = cache.evictions(); - assert!(cache.put(huge, 0).is_err()); - assert_eq!((cache.size(), cache.evictions()), (2, evictions)); - } - - #[test] - fn superseded_copies_of_one_conversation_do_not_push_out_another() { - // #342: MAIN -> SUB (9 turns) -> MAIN with 4 slots. - let root = [1, 2, 3, 4]; - let mut main = image(&[]); - main.live.ids = with(&with(&root, &[10, 11, 12]), &[13, 14]); - main.checkpoints = vec![cp(&root), cp(&with(&root, &[10, 11, 12]))]; - let mut cache = ConversationCache::new(1 << 20, 4); - assert!(cache.put(main, 0).is_ok(), "park MAIN"); - let mut history = with(&root, &[20]); - let mut chain = vec![cp(&root)]; - for turn in 1..=9 { - chain.push(cp(&history)); - let mut sub = image(&[]); - sub.live.ids = with(&history, &[900, turn]); - sub.checkpoints = chain.clone(); - assert!(cache.put(sub, 0).is_ok(), "park SUB turn"); - assert!(cache.size() <= 2, "one parked copy of SUB at a time"); - history = with(&history, &[30, turn]); - } - assert!( - cache.evictions() == 0 && cache.superseded() == 8, - "8 superseded copies dropped, nothing evicted" - ); - let prompt: Vec = with(&with(&root, &[10, 11, 12]), &[13, 14, 15]) - .into_iter() - .map(i64::from) - .collect(); - let m = cache.best(&prompt, &[], true); - assert!(m.tokens == 9 && m.live, "MAIN still restores in full"); - let prompt: Vec = with(&history, &[40]); - let s = cache.best(&prompt, &[], true); - assert_eq!( - s.tokens, - history.len() as i64 - 2, - "SUB resumes from its last turn boundary" - ); - } - - #[test] - fn what_is_not_superseded() { - let mut cache = ConversationCache::new(1 << 20, 8); - let mut other = image(&[1, 2, 3, 4, 50, 51, 52]); - other.checkpoints = vec![cp(&[1, 2, 3, 4]), cp(&[1, 2, 3, 4, 50, 51])]; - cache.put(other, 0).unwrap(); - cache.put(image(&[1, 2, 3, 4, 7, 7]), 0).unwrap(); // no checkpoints - let mut steered = image_mode(&[1, 2, 3, 4, 60, 61], false); - steered.checkpoints = vec![cp(&[1, 2, 3, 4, 60])]; - cache.put(steered, 0).unwrap(); - let mut branch = image(&[1, 2, 3, 4, 60, 70, 71]); - branch.checkpoints = vec![cp(&[1, 2, 3, 4]), cp(&[1, 2, 3, 4, 60, 70])]; - cache.put(branch, 0).unwrap(); - let mut incoming = image(&[1, 2, 3, 4, 60, 80, 81]); - incoming.checkpoints = vec![cp(&[1, 2, 3, 4]), cp(&[1, 2, 3, 4, 60])]; - assert!( - cache.put(incoming, 0).is_ok(), - "park a conversation sharing roots with all of them" - ); - assert!( - cache.size() == 5 && cache.superseded() == 0, - "none of them is superseded" - ); - let mut same_state = image(&[1, 2, 3, 4, 60, 70]); // live equal to the branch's deepest point - same_state.checkpoints = vec![cp(&[1, 2, 3, 4])]; - assert!( - cache.put(same_state, 0).is_ok() && cache.superseded() == 1 && cache.size() == 5, - "the live state equal to an entry's deepest checkpoint supersedes it" - ); - let mut huge = image(&[1, 2, 3, 4, 60, 80]); - huge.checkpoints = vec![cp(&[1, 2, 3, 4]), cp(&[1, 2, 3, 4, 60])]; - huge.live.gdn = vec![0; 2 << 20]; - assert!( - cache.put(huge, 0).is_err() && cache.size() == 5 && cache.superseded() == 1, - "an oversized put drops nothing" - ); - } - - #[test] - fn disabled_caches_store_nothing() { - let disabled = ConversationCache::::new(0, 4); - let no_slots = ConversationCache::::new(1024, 0); - assert!( - !disabled.enabled() && !no_slots.enabled(), - "both disable switches" - ); - let (mut disabled, mut no_slots) = (disabled, no_slots); - assert!( - disabled.put(image(&[1, 2, 3]), 0).is_err() - && no_slots.put(image(&[1, 2, 3]), 0).is_err() - ); - assert_eq!( - disabled.best(&A, &[], true).tokens, - 0, - "disabled cache has no matches" - ); - assert!(!disabled.make_room(0, 0) && !disabled.can_fit(0, 0)); - disabled.retain(exact_kv_layers(), 4); - assert_eq!( - disabled.retained_bytes(), - 0, - "a disabled cache retains nothing" - ); - } - - #[test] - fn take_out_of_range_is_none_and_prefix_len_is_generic_over_token_types() { - let mut cache = ConversationCache::new(1024, 2); - assert!(cache.take(0).is_none()); - cache.put(image(&[1, 2, 3]), 0).unwrap(); - assert!(cache.take(1).is_none()); - assert_eq!(cache.best(&[1u32, 2, 3, 4], &[], true).tokens, 3); - assert_eq!(cache.best(&[1i32, 2, 3, 4], &[], true).tokens, 3); - assert_eq!( - cache.best(&[1i64, 2, 4, 4], &[], true).tokens, - 0, - "diverging token" - ); - assert_eq!(B.len(), 4); - } - - #[test] - fn struct_sizes_match_the_64_bit_original_layout() { - // The accounting charges sizeof(ConversationCheckpoint)/sizeof(ConversationKv) - // per directory slot; the C++ harness prints 200 and 216 on LP64. - assert_eq!(size_of::(), 200); - assert_eq!(size_of::(), 216); - assert_eq!(size_of::(), 16); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/conversation/cache/tests.rs b/crates/leleka-runtime/src/conversation/cache/tests.rs new file mode 100644 index 00000000..f969c9fd --- /dev/null +++ b/crates/leleka-runtime/src/conversation/cache/tests.rs @@ -0,0 +1,407 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn image(ids: &[i32]) -> SavedConversation { + image_mode(ids, true) +} +fn image_mode(ids: &[i32], cvec: bool) -> SavedConversation { + let mut s = SavedConversation::default(); + s.live.ids = ids.to_vec(); + s.live.gdn = vec![7; 64]; + s.cvec = cvec; + s +} +fn cp(ids: &[i32]) -> ConversationCheckpoint { + ConversationCheckpoint { + ids: ids.to_vec(), + ..Default::default() + } +} +fn with(prefix: &[i32], more: &[i32]) -> Vec { + let mut v = prefix.to_vec(); + v.extend_from_slice(more); + v +} +fn exact_kv_layers() -> Vec { + let mut layer = ConversationKv::default(); + layer.k.resize(400, 0).unwrap(); + vec![layer] +} +const A: [i64; 4] = [1, 2, 3, 4]; +const B: [i64; 4] = [9, 8, 7, 6]; + +#[test] +fn retained_buffers_count_against_bytes_but_not_slots() { + let layers = exact_kv_layers(); + let retained = layers.capacity() * size_of::() + layers[0].bytes(); + let parked = image(&[1, 2, 3]).bytes(); + let mut cache = ConversationCache::new(retained + parked, 4); + assert!( + cache.put(image(&[1, 2, 3]), 0).is_ok(), + "park before retaining active storage" + ); + cache.retain(layers, 16); + assert!( + cache.bytes() == retained + parked && cache.size() == 1, + "active retained storage consumes bytes but no parked slot" + ); + cache.limit_reuse(9); + cache.limit_reuse(12); + let reuse = cache.take_reuse(); + assert_eq!( + reuse.unchanged_tokens, 9, + "a later continuation cannot undo a rewind's dirty boundary" + ); + assert_eq!( + cache.bytes(), + parked, + "taking retained buffers releases their budget accounting" + ); + cache.retain(reuse.kv, 16); + assert!( + !cache.can_fit(parked, 0), + "retained storage is counted when checking a capture without eviction" + ); + assert!( + cache.retained_bytes() == retained && cache.size() == 1 && cache.evictions() == 0, + "optional reuse admission does not evict or release anything" + ); + assert!( + !cache.can_fit(usize::MAX, 0) && !cache.can_fit(1, usize::MAX), + "non-mutating reservation rejects overflow" + ); + assert!( + cache.make_room(parked, 0), + "reservation can discard optional active buffers" + ); + assert!( + cache.retained_bytes() == 0 && cache.size() == 1 && cache.evictions() == 0, + "pressure drops retained storage before evicting parked conversations" + ); +} + +#[test] +fn a_b_a_recovery_and_slot_eviction() { + let mut cache = ConversationCache::new(1024, 2); + assert!(cache.put(image(&[1, 2, 3]), 0).is_ok(), "park A"); + assert!(cache.put(image(&[9, 8, 7]), 0).is_ok(), "park B"); + let m = cache.best(&A, &[], true); + assert!(m.tokens == 3 && m.live, "A/B/A: recover A"); + let restored = cache.take(m.index).unwrap(); + assert_eq!( + restored.live.ids, + vec![1, 2, 3], + "taking selected A preserves identity" + ); + assert!( + cache.size() == 1 && cache.best(&B, &[], true).tokens == 3, + "B remains parked" + ); + assert_eq!( + cache.bytes(), + image(&[9, 8, 7]).bytes(), + "byte accounting after take" + ); + assert!(cache.put(restored, 0).is_ok(), "park returned A as newest"); + assert!( + cache.put(image(&[5, 6]), 0).is_ok(), + "evict oldest by slot limit" + ); + assert!( + cache.best(&B, &[], true).tokens == 0 && cache.best(&A, &[], true).tokens == 3, + "B evicted before A" + ); + assert_eq!(cache.evictions(), 1, "eviction counter"); +} + +#[test] +fn checkpoints_steering_and_boundary_rules() { + let mut s = image(&[1, 2, 3]); + s.checkpoints.push(cp(&[1, 2])); + let mut cache = ConversationCache::new(4096, 4); + cache.put(s, 0).unwrap(); + let m = cache.best(&[1i64, 2, 9, 4], &[], true); + assert!( + m.tokens == 2 && !m.live, + "edited suffix falls back to parked checkpoint" + ); + assert_eq!( + cache.best(&A, &[], true).tokens, + 3, + "live prefix beats shorter checkpoint" + ); + assert_eq!( + cache.best(&A, &[], false).tokens, + 0, + "steering mode is isolated" + ); + assert_eq!( + cache.best(&[1i64, 2], &[], true).tokens, + 0, + "equal-length checkpoint cannot consume last token" + ); + assert_eq!( + cache.best(&[1i64], &[], true).tokens, + 0, + "short prompt cannot match" + ); + assert_eq!( + cache.best::(&[], &[], true).tokens, + 0, + "empty prompt cannot match" + ); + cache.put(image(&[1, 2, 3]), 0).unwrap(); + assert_eq!( + cache.best(&A, &[], true).index, + 1, + "ties prefer most recently parked" + ); +} + +#[test] +fn image_identity_is_part_of_the_prefix() { + let mut s = image(&[1, 2, 3]); + s.live.imgs = vec![ConversationImageKey { + start: 1, + hash: 123, + }]; + let mut cache = ConversationCache::new(1024, 3); + cache.put(s, 0).unwrap(); + let key = |start, hash| ConversationImageKey { start, hash }; + assert_eq!( + cache.best(&A, &[key(1, 123)], true).tokens, + 3, + "same image can resume" + ); + assert_eq!( + cache.best(&A, &[key(1, 124)], true).tokens, + 0, + "different image pixels invalidate same pad tokens" + ); + assert_eq!( + cache.best(&A, &[], true).tokens, + 0, + "missing image invalidates prefix" + ); + assert_eq!( + cache.best(&A, &[key(1, 123), key(2, 45)], true).tokens, + 0, + "additional image in cached prefix invalidates" + ); + assert_eq!( + cache.best(&A, &[key(1, 123), key(3, 45)], true).tokens, + 3, + "image after cached prefix does not invalidate" + ); +} + +#[test] +fn in_flight_image_is_counted_during_an_exchange() { + let one = image(&[1, 2, 3]).bytes(); + let mut cache = ConversationCache::new(one * 2, 8); + cache.put(image(&[1, 2, 3]), 0).unwrap(); + cache.put(image(&[9, 8, 7]), 0).unwrap(); + assert_eq!( + cache.bytes(), + one * 2, + "budget holds two exact-sized images" + ); + let held = cache.take(cache.best(&A, &[], true).index).unwrap(); + assert!( + cache.make_room(one, held.bytes()), + "count in-flight image when reserving outgoing snapshot" + ); + assert_eq!( + cache.size(), + 0, + "in-flight reservation evicts otherwise fitting B" + ); + assert!( + cache.put(image(&[5, 6, 7]), held.bytes()).is_ok(), + "insert with in-flight accounting" + ); + assert!( + cache.bytes() + held.bytes() <= one * 2, + "exchange obeys byte budget" + ); + assert!( + !cache.make_room(one + 1, one), + "oversized exchange rejected" + ); + assert_eq!( + cache.size(), + 1, + "oversized snapshot does not evict useful entries" + ); + let mut huge = image(&[1]); + huge.live.gdn = vec![0; one * 3]; + let back = cache.put(huge, 0).unwrap_err(); + assert_eq!(back.live.ids, vec![1], "a refused image is handed back"); + assert_eq!(cache.size(), 1, "oversized put leaves cache unchanged"); + assert!( + !cache.make_room(0, one * 2 + 1), + "held larger than budget cannot underflow" + ); +} + +/// Upstream 41cf05a0 `940011da`: a full cache dropped the new snapshot instead of evicting for it. Full by slots or by bytes, the +/// oldest conversation goes and the new one is parked; only an image that cannot fit at all is refused, and then nothing is dropped. +#[test] +fn a_full_cache_evicts_the_oldest_for_the_new_snapshot_by_slots_and_by_bytes() { + let one = image(&[1, 2, 3]).bytes(); + // full by bytes (slots to spare): three images do not fit in 2.5 + let mut cache = ConversationCache::new(one * 5 / 2, 8); + cache.put(image(&[1, 1, 1]), 0).unwrap(); + cache.put(image(&[2, 2, 2]), 0).unwrap(); + assert_eq!((cache.size(), cache.evictions()), (2, 0)); + cache.put(image(&[3, 3, 3]), 0).unwrap(); + assert_eq!((cache.size(), cache.evictions()), (2, 1), "the oldest went, the new one stayed"); + assert_eq!(cache.best(&[1, 1, 1, 0], &[], true).tokens, 0); + assert_eq!(cache.best(&[2, 2, 2, 0], &[], true).tokens, 3); + assert_eq!(cache.best(&[3, 3, 3, 0], &[], true).tokens, 3); + assert!(cache.bytes() <= cache.budget()); + // full by slots (bytes to spare), the same + let mut cache = ConversationCache::new(one * 100, 2); + for k in 1..=5 { + cache.put(image(&[k, k, k]), 0).unwrap(); + assert!(cache.size() <= 2); + assert_eq!(cache.best(&[k, k, k, 0], &[], true).tokens, 3, "the newest is always parked: {k}"); + } + assert_eq!(cache.evictions(), 3); + // an image bigger than the whole budget is refused up front and evicts nothing + let mut huge = image(&[9]); + huge.live.gdn = vec![0; one * 200]; + let evictions = cache.evictions(); + assert!(cache.put(huge, 0).is_err()); + assert_eq!((cache.size(), cache.evictions()), (2, evictions)); +} + +#[test] +fn superseded_copies_of_one_conversation_do_not_push_out_another() { + // #342: MAIN -> SUB (9 turns) -> MAIN with 4 slots. + let root = [1, 2, 3, 4]; + let mut main = image(&[]); + main.live.ids = with(&with(&root, &[10, 11, 12]), &[13, 14]); + main.checkpoints = vec![cp(&root), cp(&with(&root, &[10, 11, 12]))]; + let mut cache = ConversationCache::new(1 << 20, 4); + assert!(cache.put(main, 0).is_ok(), "park MAIN"); + let mut history = with(&root, &[20]); + let mut chain = vec![cp(&root)]; + for turn in 1..=9 { + chain.push(cp(&history)); + let mut sub = image(&[]); + sub.live.ids = with(&history, &[900, turn]); + sub.checkpoints = chain.clone(); + assert!(cache.put(sub, 0).is_ok(), "park SUB turn"); + assert!(cache.size() <= 2, "one parked copy of SUB at a time"); + history = with(&history, &[30, turn]); + } + assert!( + cache.evictions() == 0 && cache.superseded() == 8, + "8 superseded copies dropped, nothing evicted" + ); + let prompt: Vec = with(&with(&root, &[10, 11, 12]), &[13, 14, 15]) + .into_iter() + .map(i64::from) + .collect(); + let m = cache.best(&prompt, &[], true); + assert!(m.tokens == 9 && m.live, "MAIN still restores in full"); + let prompt: Vec = with(&history, &[40]); + let s = cache.best(&prompt, &[], true); + assert_eq!( + s.tokens, + history.len() as i64 - 2, + "SUB resumes from its last turn boundary" + ); +} + +#[test] +fn what_is_not_superseded() { + let mut cache = ConversationCache::new(1 << 20, 8); + let mut other = image(&[1, 2, 3, 4, 50, 51, 52]); + other.checkpoints = vec![cp(&[1, 2, 3, 4]), cp(&[1, 2, 3, 4, 50, 51])]; + cache.put(other, 0).unwrap(); + cache.put(image(&[1, 2, 3, 4, 7, 7]), 0).unwrap(); // no checkpoints + let mut steered = image_mode(&[1, 2, 3, 4, 60, 61], false); + steered.checkpoints = vec![cp(&[1, 2, 3, 4, 60])]; + cache.put(steered, 0).unwrap(); + let mut branch = image(&[1, 2, 3, 4, 60, 70, 71]); + branch.checkpoints = vec![cp(&[1, 2, 3, 4]), cp(&[1, 2, 3, 4, 60, 70])]; + cache.put(branch, 0).unwrap(); + let mut incoming = image(&[1, 2, 3, 4, 60, 80, 81]); + incoming.checkpoints = vec![cp(&[1, 2, 3, 4]), cp(&[1, 2, 3, 4, 60])]; + assert!( + cache.put(incoming, 0).is_ok(), + "park a conversation sharing roots with all of them" + ); + assert!( + cache.size() == 5 && cache.superseded() == 0, + "none of them is superseded" + ); + let mut same_state = image(&[1, 2, 3, 4, 60, 70]); // live equal to the branch's deepest point + same_state.checkpoints = vec![cp(&[1, 2, 3, 4])]; + assert!( + cache.put(same_state, 0).is_ok() && cache.superseded() == 1 && cache.size() == 5, + "the live state equal to an entry's deepest checkpoint supersedes it" + ); + let mut huge = image(&[1, 2, 3, 4, 60, 80]); + huge.checkpoints = vec![cp(&[1, 2, 3, 4]), cp(&[1, 2, 3, 4, 60])]; + huge.live.gdn = vec![0; 2 << 20]; + assert!( + cache.put(huge, 0).is_err() && cache.size() == 5 && cache.superseded() == 1, + "an oversized put drops nothing" + ); +} + +#[test] +fn disabled_caches_store_nothing() { + let disabled = ConversationCache::::new(0, 4); + let no_slots = ConversationCache::::new(1024, 0); + assert!( + !disabled.enabled() && !no_slots.enabled(), + "both disable switches" + ); + let (mut disabled, mut no_slots) = (disabled, no_slots); + assert!( + disabled.put(image(&[1, 2, 3]), 0).is_err() + && no_slots.put(image(&[1, 2, 3]), 0).is_err() + ); + assert_eq!( + disabled.best(&A, &[], true).tokens, + 0, + "disabled cache has no matches" + ); + assert!(!disabled.make_room(0, 0) && !disabled.can_fit(0, 0)); + disabled.retain(exact_kv_layers(), 4); + assert_eq!( + disabled.retained_bytes(), + 0, + "a disabled cache retains nothing" + ); +} + +#[test] +fn take_out_of_range_is_none_and_prefix_len_is_generic_over_token_types() { + let mut cache = ConversationCache::new(1024, 2); + assert!(cache.take(0).is_none()); + cache.put(image(&[1, 2, 3]), 0).unwrap(); + assert!(cache.take(1).is_none()); + assert_eq!(cache.best(&[1u32, 2, 3, 4], &[], true).tokens, 3); + assert_eq!(cache.best(&[1i32, 2, 3, 4], &[], true).tokens, 3); + assert_eq!( + cache.best(&[1i64, 2, 4, 4], &[], true).tokens, + 0, + "diverging token" + ); + assert_eq!(B.len(), 4); +} + +#[test] +fn struct_sizes_match_the_64_bit_original_layout() { + // The accounting charges sizeof(ConversationCheckpoint)/sizeof(ConversationKv) + // per directory slot; the C++ harness prints 200 and 216 on LP64. + assert_eq!(size_of::(), 200); + assert_eq!(size_of::(), 216); + assert_eq!(size_of::(), 16); +} diff --git a/crates/leleka-runtime/src/conversation/resident.rs b/crates/leleka-runtime/src/conversation/resident.rs index 7af21b5f..a2c7d96f 100644 --- a/crates/leleka-runtime/src/conversation/resident.rs +++ b/crates/leleka-runtime/src/conversation/resident.rs @@ -305,223 +305,4 @@ impl ResidentConversations { } #[cfg(test)] -mod tests { - use super::*; - - fn policy(budget_gib: usize, slots: usize) -> ResidentPolicy { - ResidentPolicy { - budget_bytes: budget_gib << 30, - slots, - fixed_bytes: 100 << 20, - bytes_per_token: 20_000, - } - } - fn toks(salt: u32, n: u32) -> Vec { - (0..n).map(|i| salt * 1000 + i).collect() - } - - #[test] - fn disabled_policy_keeps_exactly_the_old_single_continuation() { - let mut store = ResidentConversations::<&'static str>::new(ResidentPolicy::disabled()); - store.publish(&toks(1, 10), "a"); - let mut p = toks(1, 10); - p.push(7); - let r = store.take_for(&p, |_| true).unwrap(); - assert_eq!( - (r.session, r.tokens, r.source), - ("a", 10, ResumeSource::Live) - ); - store.publish(&toks(1, 12), "a2"); - // Another conversation replaces it; nothing is parked. - assert!(store.take_for(&toks(2, 9), |_| true).is_none()); - assert_eq!(store.parked(), 0); - assert!(!store.has_live()); - } - - #[test] - fn an_identical_prompt_may_reuse_the_live_session_but_not_a_parked_one() { - let mut store = ResidentConversations::::new(policy(8, 4)); - store.publish(&toks(1, 10), 1); - assert_eq!( - store.take_for(&toks(1, 10), |_| true).unwrap().tokens, - 10, - "live: equal length allowed" - ); - store.publish(&toks(1, 10), 1); - assert!(store.take_for(&toks(2, 5), |_| true).is_none()); // parks 1 - assert_eq!(store.parked(), 1); - let mut other = toks(2, 5); - other.push(1); - store.publish(&toks(2, 5), 2); - // The parked session holds exactly the prompt: the last token must be read. - assert!(store.take_for(&toks(1, 10), |_| true).is_none()); - assert_eq!(store.parked(), 2, "both conversations are parked now"); - } - - #[test] - fn a_b_a_swaps_through_the_cache_and_prefers_the_longest_prefix() { - let mut store = ResidentConversations::<&'static str>::new(policy(8, 4)); - store.publish(&toks(1, 20), "A"); - assert!(store.take_for(&toks(2, 8), |_| true).is_none()); - store.publish(&toks(2, 8), "B"); - // A again, one token longer. - let mut a = toks(1, 20); - a.push(5); - let r = store.take_for(&a, |_| true).unwrap(); - assert_eq!( - (r.session, r.tokens, r.source), - ("A", 20, ResumeSource::Parked) - ); - assert_eq!(store.parked(), 1, "B was parked in exchange"); - store.publish(&a, "A2"); - // A branch of A that diverges after 12 tokens finds nothing reusable - // in A2 (not a prefix), but B is unrelated: nothing resumes. - let mut branch = toks(1, 12); - branch.push(999_999); - assert!(store.take_for(&branch, |_| true).is_none()); - assert_eq!(store.parked(), 2, "A2 is parked rather than lost"); - let events = store.take_events(); - assert!( - events.iter().any(|e| e.contains("restored 20 tokens")), - "{events:?}" - ); - } - - #[test] - fn the_longest_parked_prefix_wins_and_ties_go_to_the_newest() { - let mut store = ResidentConversations::<&'static str>::new(policy(8, 4)); - store.publish(&toks(1, 10), "short"); - assert!(store.take_for(&toks(3, 3), |_| true).is_none()); - store.publish(&toks(1, 14), "long"); - assert!(store.take_for(&toks(4, 3), |_| true).is_none()); - store.publish(&toks(1, 14), "long-dup"); - assert!(store.take_for(&toks(5, 3), |_| true).is_none()); - // All three share toks(1, 10) as a prefix of the request. - let mut request = toks(1, 14); - request.push(0); - let r = store.take_for(&request, |_| true).unwrap(); - assert_eq!( - (r.session, r.tokens), - ("long-dup", 14), - "equal length: the most recently parked" - ); - } - - #[test] - fn slots_and_bytes_bound_the_parked_set_oldest_first() { - let mut store = ResidentConversations::::new(policy(8, 2)); - for salt in 1..=4u32 { - store.publish(&toks(salt, 10), salt); - assert!(store.take_for(&toks(100 + salt, 3), |_| true).is_none()); - } - assert_eq!(store.parked(), 2); - assert_eq!(store.cache().evictions(), 2); - // The two oldest conversations are gone, the two newest remain. - for (salt, expect) in [(1, false), (2, false), (3, true), (4, true)] { - let mut p = toks(salt, 10); - p.push(1); - let hit = store.cache().best(&p, &[], true).tokens > 0; - assert_eq!(hit, expect, "conversation {salt}"); - } - // A budget smaller than one session parks nothing. - let mut tiny = ResidentConversations::::new(ResidentPolicy { - budget_bytes: 1 << 20, - ..policy(8, 4) - }); - tiny.publish(&toks(1, 10), 1); - assert!(tiny.take_for(&toks(2, 3), |_| true).is_none()); - assert_eq!(tiny.parked(), 0); - let events = tiny.take_events(); - assert!( - events.iter().any(|e| e.contains("skip parking")), - "{events:?}" - ); - } - - #[test] - fn unusable_candidates_are_dropped_not_resumed() { - let mut store = ResidentConversations::<&'static str>::new(policy(8, 4)); - store.publish(&toks(1, 10), "A"); - assert!(store.take_for(&toks(2, 3), |_| true).is_none()); - store.publish(&toks(2, 3), "B"); - let mut a = toks(1, 10); - a.push(1); - // The parked A fails the actor's admission: it is discarded, B (live) is parked. - assert!(store.take_for(&a, |s| *s != "A").is_none()); - assert_eq!(store.parked(), 1); - // A live session that fails admission is dropped too. - store.publish(&toks(9, 4), "C"); - let mut c = toks(9, 4); - c.push(1); - assert!(store.take_for(&c, |s| *s != "C").is_none()); - assert!(!store.has_live()); - } - - #[test] - fn publishing_nothing_or_unrepresentable_tokens_leaves_no_live_session() { - let mut store = ResidentConversations::::new(policy(8, 2)); - store.publish(&[], 1); - assert!(!store.has_live()); - store.publish(&[u32::MAX], 1); - assert!(!store.has_live()); - store.publish(&[1, 2], 1); - assert!(store.take_for(&[u32::MAX], |_| true).is_none()); - assert!( - !store.has_live(), - "an unrepresentable prompt invalidates the live session" - ); - store.publish(&[1, 2], 1); - store.clear(); - assert!(!store.has_live() && store.parked() == 0); - } - - #[test] - fn operator_settings_are_parsed_strictly() { - let p = ResidentPolicy::from_values(Some("2048"), Some("3")).unwrap(); - assert_eq!((p.budget_bytes, p.slots), (2048 << 20, 3)); - assert_eq!( - ResidentPolicy::from_values(None, None).unwrap(), - ResidentPolicy::disabled() - ); - assert!(!ResidentPolicy::disabled().enabled()); - for bad in [ - "", - "-1", - "+1", - " 1", - "1 ", - "1e3", - "0x10", - "99999999999999999999", - "٣", - ] { - assert!( - ResidentPolicy::from_values(Some(bad), None).is_err(), - "{bad:?}" - ); - assert!( - ResidentPolicy::from_values(None, Some(bad)).is_err(), - "{bad:?}" - ); - } - assert!(ResidentPolicy::from_values(None, Some("65")).is_err()); - assert!(ResidentPolicy::from_values(Some("4194305"), None).is_err()); - assert_eq!( - ResidentPolicy::from_values(Some("0"), Some("0")) - .unwrap() - .budget_bytes, - 0 - ); - } - - #[test] - fn the_accounting_estimate_saturates() { - let p = ResidentPolicy::disabled(); - assert_eq!(p.estimate(0), p.fixed_bytes); - assert_eq!( - p.estimate(100_000), - p.fixed_bytes + 100_000 * p.bytes_per_token - ); - assert_eq!(p.estimate(usize::MAX), usize::MAX); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/conversation/resident/tests.rs b/crates/leleka-runtime/src/conversation/resident/tests.rs new file mode 100644 index 00000000..4937f122 --- /dev/null +++ b/crates/leleka-runtime/src/conversation/resident/tests.rs @@ -0,0 +1,220 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn policy(budget_gib: usize, slots: usize) -> ResidentPolicy { + ResidentPolicy { + budget_bytes: budget_gib << 30, + slots, + fixed_bytes: 100 << 20, + bytes_per_token: 20_000, + } +} +fn toks(salt: u32, n: u32) -> Vec { + (0..n).map(|i| salt * 1000 + i).collect() +} + +#[test] +fn disabled_policy_keeps_exactly_the_old_single_continuation() { + let mut store = ResidentConversations::<&'static str>::new(ResidentPolicy::disabled()); + store.publish(&toks(1, 10), "a"); + let mut p = toks(1, 10); + p.push(7); + let r = store.take_for(&p, |_| true).unwrap(); + assert_eq!( + (r.session, r.tokens, r.source), + ("a", 10, ResumeSource::Live) + ); + store.publish(&toks(1, 12), "a2"); + // Another conversation replaces it; nothing is parked. + assert!(store.take_for(&toks(2, 9), |_| true).is_none()); + assert_eq!(store.parked(), 0); + assert!(!store.has_live()); +} + +#[test] +fn an_identical_prompt_may_reuse_the_live_session_but_not_a_parked_one() { + let mut store = ResidentConversations::::new(policy(8, 4)); + store.publish(&toks(1, 10), 1); + assert_eq!( + store.take_for(&toks(1, 10), |_| true).unwrap().tokens, + 10, + "live: equal length allowed" + ); + store.publish(&toks(1, 10), 1); + assert!(store.take_for(&toks(2, 5), |_| true).is_none()); // parks 1 + assert_eq!(store.parked(), 1); + let mut other = toks(2, 5); + other.push(1); + store.publish(&toks(2, 5), 2); + // The parked session holds exactly the prompt: the last token must be read. + assert!(store.take_for(&toks(1, 10), |_| true).is_none()); + assert_eq!(store.parked(), 2, "both conversations are parked now"); +} + +#[test] +fn a_b_a_swaps_through_the_cache_and_prefers_the_longest_prefix() { + let mut store = ResidentConversations::<&'static str>::new(policy(8, 4)); + store.publish(&toks(1, 20), "A"); + assert!(store.take_for(&toks(2, 8), |_| true).is_none()); + store.publish(&toks(2, 8), "B"); + // A again, one token longer. + let mut a = toks(1, 20); + a.push(5); + let r = store.take_for(&a, |_| true).unwrap(); + assert_eq!( + (r.session, r.tokens, r.source), + ("A", 20, ResumeSource::Parked) + ); + assert_eq!(store.parked(), 1, "B was parked in exchange"); + store.publish(&a, "A2"); + // A branch of A that diverges after 12 tokens finds nothing reusable + // in A2 (not a prefix), but B is unrelated: nothing resumes. + let mut branch = toks(1, 12); + branch.push(999_999); + assert!(store.take_for(&branch, |_| true).is_none()); + assert_eq!(store.parked(), 2, "A2 is parked rather than lost"); + let events = store.take_events(); + assert!( + events.iter().any(|e| e.contains("restored 20 tokens")), + "{events:?}" + ); +} + +#[test] +fn the_longest_parked_prefix_wins_and_ties_go_to_the_newest() { + let mut store = ResidentConversations::<&'static str>::new(policy(8, 4)); + store.publish(&toks(1, 10), "short"); + assert!(store.take_for(&toks(3, 3), |_| true).is_none()); + store.publish(&toks(1, 14), "long"); + assert!(store.take_for(&toks(4, 3), |_| true).is_none()); + store.publish(&toks(1, 14), "long-dup"); + assert!(store.take_for(&toks(5, 3), |_| true).is_none()); + // All three share toks(1, 10) as a prefix of the request. + let mut request = toks(1, 14); + request.push(0); + let r = store.take_for(&request, |_| true).unwrap(); + assert_eq!( + (r.session, r.tokens), + ("long-dup", 14), + "equal length: the most recently parked" + ); +} + +#[test] +fn slots_and_bytes_bound_the_parked_set_oldest_first() { + let mut store = ResidentConversations::::new(policy(8, 2)); + for salt in 1..=4u32 { + store.publish(&toks(salt, 10), salt); + assert!(store.take_for(&toks(100 + salt, 3), |_| true).is_none()); + } + assert_eq!(store.parked(), 2); + assert_eq!(store.cache().evictions(), 2); + // The two oldest conversations are gone, the two newest remain. + for (salt, expect) in [(1, false), (2, false), (3, true), (4, true)] { + let mut p = toks(salt, 10); + p.push(1); + let hit = store.cache().best(&p, &[], true).tokens > 0; + assert_eq!(hit, expect, "conversation {salt}"); + } + // A budget smaller than one session parks nothing. + let mut tiny = ResidentConversations::::new(ResidentPolicy { + budget_bytes: 1 << 20, + ..policy(8, 4) + }); + tiny.publish(&toks(1, 10), 1); + assert!(tiny.take_for(&toks(2, 3), |_| true).is_none()); + assert_eq!(tiny.parked(), 0); + let events = tiny.take_events(); + assert!( + events.iter().any(|e| e.contains("skip parking")), + "{events:?}" + ); +} + +#[test] +fn unusable_candidates_are_dropped_not_resumed() { + let mut store = ResidentConversations::<&'static str>::new(policy(8, 4)); + store.publish(&toks(1, 10), "A"); + assert!(store.take_for(&toks(2, 3), |_| true).is_none()); + store.publish(&toks(2, 3), "B"); + let mut a = toks(1, 10); + a.push(1); + // The parked A fails the actor's admission: it is discarded, B (live) is parked. + assert!(store.take_for(&a, |s| *s != "A").is_none()); + assert_eq!(store.parked(), 1); + // A live session that fails admission is dropped too. + store.publish(&toks(9, 4), "C"); + let mut c = toks(9, 4); + c.push(1); + assert!(store.take_for(&c, |s| *s != "C").is_none()); + assert!(!store.has_live()); +} + +#[test] +fn publishing_nothing_or_unrepresentable_tokens_leaves_no_live_session() { + let mut store = ResidentConversations::::new(policy(8, 2)); + store.publish(&[], 1); + assert!(!store.has_live()); + store.publish(&[u32::MAX], 1); + assert!(!store.has_live()); + store.publish(&[1, 2], 1); + assert!(store.take_for(&[u32::MAX], |_| true).is_none()); + assert!( + !store.has_live(), + "an unrepresentable prompt invalidates the live session" + ); + store.publish(&[1, 2], 1); + store.clear(); + assert!(!store.has_live() && store.parked() == 0); +} + +#[test] +fn operator_settings_are_parsed_strictly() { + let p = ResidentPolicy::from_values(Some("2048"), Some("3")).unwrap(); + assert_eq!((p.budget_bytes, p.slots), (2048 << 20, 3)); + assert_eq!( + ResidentPolicy::from_values(None, None).unwrap(), + ResidentPolicy::disabled() + ); + assert!(!ResidentPolicy::disabled().enabled()); + for bad in [ + "", + "-1", + "+1", + " 1", + "1 ", + "1e3", + "0x10", + "99999999999999999999", + "٣", + ] { + assert!( + ResidentPolicy::from_values(Some(bad), None).is_err(), + "{bad:?}" + ); + assert!( + ResidentPolicy::from_values(None, Some(bad)).is_err(), + "{bad:?}" + ); + } + assert!(ResidentPolicy::from_values(None, Some("65")).is_err()); + assert!(ResidentPolicy::from_values(Some("4194305"), None).is_err()); + assert_eq!( + ResidentPolicy::from_values(Some("0"), Some("0")) + .unwrap() + .budget_bytes, + 0 + ); +} + +#[test] +fn the_accounting_estimate_saturates() { + let p = ResidentPolicy::disabled(); + assert_eq!(p.estimate(0), p.fixed_bytes); + assert_eq!( + p.estimate(100_000), + p.fixed_bytes + 100_000 * p.bytes_per_token + ); + assert_eq!(p.estimate(usize::MAX), usize::MAX); +} diff --git a/crates/leleka-runtime/src/experimental.rs b/crates/leleka-runtime/src/experimental.rs index 3db3a8dd..cb87c82e 100644 --- a/crates/leleka-runtime/src/experimental.rs +++ b/crates/leleka-runtime/src/experimental.rs @@ -260,190 +260,4 @@ pub fn ensure_consumed(plan: &Option) -> Result<(), ExperimentalError> { } #[cfg(test)] -mod tests { - use super::*; - - fn cfg(modes: &[Mode], resident: i64) -> ExperimentalConfig { - let mut opt_in = OptIn::default(); - for m in modes { - opt_in = opt_in.with(*m); - } - ExperimentalConfig { - opt_in, - kv_resident: resident, - ..Default::default() - } - } - - #[test] - fn default_is_off_and_changes_nothing() { - let c = ExperimentalConfig::default(); - assert!(c.is_off()); - assert_eq!(plan(&c), Ok(None)); - assert_eq!(mode_digest("sha256:abc", &c), "sha256:abc"); - assert_eq!(ensure_consumed(&None), Ok(())); - // stray values without their mode are refused, not ignored - assert!( - plan(&ExperimentalConfig { - kv_resident: 8, - ..Default::default() - }) - .is_err() - ); - assert!( - plan(&ExperimentalConfig { - control_vectors: vec![("a".into(), 1.0)], - ..Default::default() - }) - .is_err() - ); - } - - #[test] - fn each_mode_selects_the_originals_format_and_programs() { - let p = plan(&cfg(&[Mode::KvQ40], 0)).unwrap().unwrap(); - assert_eq!(p.format, Some(KvFormat::Q4_0)); - assert_eq!(p.programs, [Program::KvQ4, Program::QsaAttn]); - let p = plan(&cfg(&[Mode::KvK8V4], 0)).unwrap().unwrap(); - assert_eq!(p.format, Some(KvFormat::K8V4)); - assert_eq!(p.programs, [Program::KvQ4, Program::KvQ8, Program::QsaAttn]); - let p = plan(&cfg(&[Mode::KvRotatedInt8], 0)).unwrap().unwrap(); - assert_eq!(p.format, Some(KvFormat::Int8Rotated)); - let p = plan(&cfg(&[Mode::KeylessVOnly], 0)).unwrap().unwrap(); - assert_eq!(p.format, Some(KvFormat::Int8Keyless)); - assert_eq!( - p.programs, - [Program::Keyless, Program::KvQ8, Program::QsaAttn] - ); - let p = plan(&cfg(&[Mode::KvQ40, Mode::KvStreamed], 20_480)) - .unwrap() - .unwrap(); - assert!(p.streamed); - assert_eq!( - p.programs, - [Program::KvQ4, Program::QsaAttn, Program::KvStream] - ); - let mut c = cfg(&[Mode::ControlVectors], 0); - c.control_vectors.push(("v.gguf".into(), 1.0)); - let p = plan(&c).unwrap().unwrap(); - assert_eq!( - (p.format, p.programs.as_slice()), - (None, &[Program::Cvec][..]) - ); - } - - #[test] - fn exclusions_follow_the_originals_selection_rules() { - let bad = |modes: &[Mode], resident| plan(&cfg(modes, resident)).unwrap_err(); - assert!( - bad(&[Mode::KvQ40, Mode::KvK8V4], 0) - .to_string() - .contains("exclusive") - ); - assert!( - bad(&[Mode::KvRotatedInt8, Mode::KvQ40], 0) - .to_string() - .contains("exclusive") - ); - assert!( - bad(&[Mode::KeylessVOnly, Mode::KvQ40], 0) - .to_string() - .contains("keyless requires INT8") - ); - assert!( - bad(&[Mode::KeylessVOnly, Mode::KvRotatedInt8], 0) - .to_string() - .contains("keyless requires INT8") - ); - assert!( - bad(&[Mode::KvK8V4, Mode::KvStreamed], 4096) - .to_string() - .contains("k8v4 does not support") - ); - assert!( - bad(&[Mode::KvStreamed], 0) - .to_string() - .contains("kv-streamed needs") - ); - assert!( - bad(&[Mode::KvQ40], 4096) - .to_string() - .contains("kv-streamed needs") - ); - assert!( - bad(&[Mode::ControlVectors], 0) - .to_string() - .contains("control-vectors needs") - ); - // keyless streams (the Original's V-only stream format) - assert!( - plan(&cfg(&[Mode::KeylessVOnly, Mode::KvStreamed], 20_480)) - .unwrap() - .is_some() - ); - } - - #[test] - fn pool_bytes_use_the_originals_per_cell_sizes() { - let p = plan(&cfg(&[Mode::KvQ40], 0)).unwrap().unwrap(); - assert_eq!(pool_bytes(&p, 100), Some(100 * 4 * 576 + 64)); - let p = plan(&cfg(&[Mode::KvK8V4], 0)).unwrap().unwrap(); - assert_eq!(pool_bytes(&p, 100), Some(100 * 4 * 816 + 64)); - let p = plan(&cfg(&[Mode::KeylessVOnly], 0)).unwrap().unwrap(); - assert_eq!(pool_bytes(&p, 100), Some(100 * 4 * 528 + 64)); - } - - #[test] - fn digest_binds_modes_values_and_files() { - let a = mode_digest("sha256:abc", &cfg(&[Mode::KvQ40], 0)); - let b = mode_digest("sha256:abc", &cfg(&[Mode::KvK8V4], 0)); - let c = mode_digest("sha256:abd", &cfg(&[Mode::KvQ40], 0)); - let d = mode_digest("sha256:abc", &cfg(&[Mode::KvQ40, Mode::KvStreamed], 4096)); - let e = mode_digest("sha256:abc", &cfg(&[Mode::KvQ40, Mode::KvStreamed], 8192)); - let mut all = vec![a.clone(), b, c, d, e]; - all.sort(); - all.dedup(); - assert_eq!(all.len(), 5); - assert!(a.starts_with("sha256:") && a.len() == 7 + 64 && a != "sha256:abc"); - let mut f1 = cfg(&[Mode::ControlVectors], 0); - f1.control_vectors.push(("a.gguf".into(), 1.0)); - let mut f2 = f1.clone(); - f2.control_vectors[0].1 = 0.5; - assert_ne!(mode_digest("x", &f1), mode_digest("x", &f2)); - } - - #[test] - fn an_enabled_mode_is_refused_until_the_forward_pass_consumes_it() { - let p = plan(&cfg(&[Mode::KvQ40], 0)).unwrap(); - assert!(matches!( - ensure_consumed(&p), - Err(ExperimentalError::Unsupported(_)) - )); - } - - #[test] - fn control_vector_files_are_validated_at_load() { - let mut c = cfg(&[Mode::ControlVectors], 0); - c.control_vectors - .push((PathBuf::from("/nonexistent/leleka-cvec.gguf"), 1.0)); - assert_eq!( - load_control_vector_tables(&c, 6, 40, 4), - Err(ExperimentalError::Invalid( - "control-vector file cannot be opened" - )) - ); - // a real (tiny, invalid) file is rejected by the Original's GGUF checks - let dir = std::env::temp_dir().join(format!("leleka-cvec-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("bad.gguf"); - std::fs::write(&path, b"not a gguf").unwrap(); - c.control_vectors[0].0 = path; - assert_eq!( - load_control_vector_tables(&c, 6, 40, 4), - Err(ExperimentalError::Invalid( - "control-vector file or options rejected" - )) - ); - std::fs::remove_dir_all(&dir).ok(); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/experimental/tests.rs b/crates/leleka-runtime/src/experimental/tests.rs new file mode 100644 index 00000000..3d730642 --- /dev/null +++ b/crates/leleka-runtime/src/experimental/tests.rs @@ -0,0 +1,187 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn cfg(modes: &[Mode], resident: i64) -> ExperimentalConfig { + let mut opt_in = OptIn::default(); + for m in modes { + opt_in = opt_in.with(*m); + } + ExperimentalConfig { + opt_in, + kv_resident: resident, + ..Default::default() + } +} + +#[test] +fn default_is_off_and_changes_nothing() { + let c = ExperimentalConfig::default(); + assert!(c.is_off()); + assert_eq!(plan(&c), Ok(None)); + assert_eq!(mode_digest("sha256:abc", &c), "sha256:abc"); + assert_eq!(ensure_consumed(&None), Ok(())); + // stray values without their mode are refused, not ignored + assert!( + plan(&ExperimentalConfig { + kv_resident: 8, + ..Default::default() + }) + .is_err() + ); + assert!( + plan(&ExperimentalConfig { + control_vectors: vec![("a".into(), 1.0)], + ..Default::default() + }) + .is_err() + ); +} + +#[test] +fn each_mode_selects_the_originals_format_and_programs() { + let p = plan(&cfg(&[Mode::KvQ40], 0)).unwrap().unwrap(); + assert_eq!(p.format, Some(KvFormat::Q4_0)); + assert_eq!(p.programs, [Program::KvQ4, Program::QsaAttn]); + let p = plan(&cfg(&[Mode::KvK8V4], 0)).unwrap().unwrap(); + assert_eq!(p.format, Some(KvFormat::K8V4)); + assert_eq!(p.programs, [Program::KvQ4, Program::KvQ8, Program::QsaAttn]); + let p = plan(&cfg(&[Mode::KvRotatedInt8], 0)).unwrap().unwrap(); + assert_eq!(p.format, Some(KvFormat::Int8Rotated)); + let p = plan(&cfg(&[Mode::KeylessVOnly], 0)).unwrap().unwrap(); + assert_eq!(p.format, Some(KvFormat::Int8Keyless)); + assert_eq!( + p.programs, + [Program::Keyless, Program::KvQ8, Program::QsaAttn] + ); + let p = plan(&cfg(&[Mode::KvQ40, Mode::KvStreamed], 20_480)) + .unwrap() + .unwrap(); + assert!(p.streamed); + assert_eq!( + p.programs, + [Program::KvQ4, Program::QsaAttn, Program::KvStream] + ); + let mut c = cfg(&[Mode::ControlVectors], 0); + c.control_vectors.push(("v.gguf".into(), 1.0)); + let p = plan(&c).unwrap().unwrap(); + assert_eq!( + (p.format, p.programs.as_slice()), + (None, &[Program::Cvec][..]) + ); +} + +#[test] +fn exclusions_follow_the_originals_selection_rules() { + let bad = |modes: &[Mode], resident| plan(&cfg(modes, resident)).unwrap_err(); + assert!( + bad(&[Mode::KvQ40, Mode::KvK8V4], 0) + .to_string() + .contains("exclusive") + ); + assert!( + bad(&[Mode::KvRotatedInt8, Mode::KvQ40], 0) + .to_string() + .contains("exclusive") + ); + assert!( + bad(&[Mode::KeylessVOnly, Mode::KvQ40], 0) + .to_string() + .contains("keyless requires INT8") + ); + assert!( + bad(&[Mode::KeylessVOnly, Mode::KvRotatedInt8], 0) + .to_string() + .contains("keyless requires INT8") + ); + assert!( + bad(&[Mode::KvK8V4, Mode::KvStreamed], 4096) + .to_string() + .contains("k8v4 does not support") + ); + assert!( + bad(&[Mode::KvStreamed], 0) + .to_string() + .contains("kv-streamed needs") + ); + assert!( + bad(&[Mode::KvQ40], 4096) + .to_string() + .contains("kv-streamed needs") + ); + assert!( + bad(&[Mode::ControlVectors], 0) + .to_string() + .contains("control-vectors needs") + ); + // keyless streams (the Original's V-only stream format) + assert!( + plan(&cfg(&[Mode::KeylessVOnly, Mode::KvStreamed], 20_480)) + .unwrap() + .is_some() + ); +} + +#[test] +fn pool_bytes_use_the_originals_per_cell_sizes() { + let p = plan(&cfg(&[Mode::KvQ40], 0)).unwrap().unwrap(); + assert_eq!(pool_bytes(&p, 100), Some(100 * 4 * 576 + 64)); + let p = plan(&cfg(&[Mode::KvK8V4], 0)).unwrap().unwrap(); + assert_eq!(pool_bytes(&p, 100), Some(100 * 4 * 816 + 64)); + let p = plan(&cfg(&[Mode::KeylessVOnly], 0)).unwrap().unwrap(); + assert_eq!(pool_bytes(&p, 100), Some(100 * 4 * 528 + 64)); +} + +#[test] +fn digest_binds_modes_values_and_files() { + let a = mode_digest("sha256:abc", &cfg(&[Mode::KvQ40], 0)); + let b = mode_digest("sha256:abc", &cfg(&[Mode::KvK8V4], 0)); + let c = mode_digest("sha256:abd", &cfg(&[Mode::KvQ40], 0)); + let d = mode_digest("sha256:abc", &cfg(&[Mode::KvQ40, Mode::KvStreamed], 4096)); + let e = mode_digest("sha256:abc", &cfg(&[Mode::KvQ40, Mode::KvStreamed], 8192)); + let mut all = vec![a.clone(), b, c, d, e]; + all.sort(); + all.dedup(); + assert_eq!(all.len(), 5); + assert!(a.starts_with("sha256:") && a.len() == 7 + 64 && a != "sha256:abc"); + let mut f1 = cfg(&[Mode::ControlVectors], 0); + f1.control_vectors.push(("a.gguf".into(), 1.0)); + let mut f2 = f1.clone(); + f2.control_vectors[0].1 = 0.5; + assert_ne!(mode_digest("x", &f1), mode_digest("x", &f2)); +} + +#[test] +fn an_enabled_mode_is_refused_until_the_forward_pass_consumes_it() { + let p = plan(&cfg(&[Mode::KvQ40], 0)).unwrap(); + assert!(matches!( + ensure_consumed(&p), + Err(ExperimentalError::Unsupported(_)) + )); +} + +#[test] +fn control_vector_files_are_validated_at_load() { + let mut c = cfg(&[Mode::ControlVectors], 0); + c.control_vectors + .push((PathBuf::from("/nonexistent/leleka-cvec.gguf"), 1.0)); + assert_eq!( + load_control_vector_tables(&c, 6, 40, 4), + Err(ExperimentalError::Invalid( + "control-vector file cannot be opened" + )) + ); + // a real (tiny, invalid) file is rejected by the Original's GGUF checks + let dir = std::env::temp_dir().join(format!("leleka-cvec-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("bad.gguf"); + std::fs::write(&path, b"not a gguf").unwrap(); + c.control_vectors[0].0 = path; + assert_eq!( + load_control_vector_tables(&c, 6, 40, 4), + Err(ExperimentalError::Invalid( + "control-vector file or options rejected" + )) + ); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_gdn.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_gdn.rs index 7a4ebd7c..63b337cb 100644 --- a/crates/leleka-runtime/src/model_binding/qwen4exp_gdn.rs +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_gdn.rs @@ -373,49 +373,5 @@ fn read_row( Ok(bytes) } #[cfg(test)] -mod tests { - use super::*; - #[test] - fn epsilon_is_exact_original_layer_operand() { - assert_eq!(NATIVE_EPSILON.to_bits(), 0x358637bd); - let admitted_nearby_metadata = 1.0e-6_f64 + 5.0e-13; - assert_ne!( - (admitted_nearby_metadata as f32).to_bits(), - NATIVE_EPSILON.to_bits() - ); - } - #[test] - fn closed_projection_kinds_and_exact_containers() { - for k in [0, 8, 12, 13, 14, 20, 23, 30] { - assert!(kind(k, false).is_ok()); - } - for k in [1, 18, 21, 22, 42, u32::MAX] { - assert_eq!(kind(k, false), Err(E::UnsupportedKind)); - } - for k in [8, 12, 13, 14, 20, 23] { - assert_eq!(kind(k, true), Err(E::UnsupportedKind)); - } - assert_eq!(exact_bf16(0x80000000), Ok(0x8000)); - assert_eq!(exact_bf16(0x3f800001), Err(E::UnsupportedKind)); - assert_eq!(exact_bf16(0x7f800000), Err(E::NonFinite)); - } - #[test] - fn fixed_shapes_and_bounded_rows_before_read() { - assert_eq!( - descriptor(30, &[2560, 10240], 52428800, 2560, 10240, false), - Ok(()) - ); - assert_eq!( - descriptor(30, &[10240, 2560], 52428800, 2560, 10240, false), - Err(E::Geometry) - ); - assert_eq!( - descriptor(13, &[2560, 48], 84480, 2560, 48, true), - Err(E::UnsupportedKind) - ); - for (first, count) in [(0, 0), (0, 65), (usize::MAX, 1), (10239, 2)] { - assert_eq!(block_range(first, count, 10240), Err(E::Range)); - } - assert_eq!(block_range(10176, 64, 10240), Ok(())); - } -} +#[path = "qwen4exp_gdn/tests.rs"] +mod tests; diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_gdn/tests.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_gdn/tests.rs new file mode 100644 index 00000000..374d087b --- /dev/null +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_gdn/tests.rs @@ -0,0 +1,46 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +#[test] +fn epsilon_is_exact_original_layer_operand() { + assert_eq!(NATIVE_EPSILON.to_bits(), 0x358637bd); + let admitted_nearby_metadata = 1.0e-6_f64 + 5.0e-13; + assert_ne!( + (admitted_nearby_metadata as f32).to_bits(), + NATIVE_EPSILON.to_bits() + ); +} +#[test] +fn closed_projection_kinds_and_exact_containers() { + for k in [0, 8, 12, 13, 14, 20, 23, 30] { + assert!(kind(k, false).is_ok()); + } + for k in [1, 18, 21, 22, 42, u32::MAX] { + assert_eq!(kind(k, false), Err(E::UnsupportedKind)); + } + for k in [8, 12, 13, 14, 20, 23] { + assert_eq!(kind(k, true), Err(E::UnsupportedKind)); + } + assert_eq!(exact_bf16(0x80000000), Ok(0x8000)); + assert_eq!(exact_bf16(0x3f800001), Err(E::UnsupportedKind)); + assert_eq!(exact_bf16(0x7f800000), Err(E::NonFinite)); +} +#[test] +fn fixed_shapes_and_bounded_rows_before_read() { + assert_eq!( + descriptor(30, &[2560, 10240], 52428800, 2560, 10240, false), + Ok(()) + ); + assert_eq!( + descriptor(30, &[10240, 2560], 52428800, 2560, 10240, false), + Err(E::Geometry) + ); + assert_eq!( + descriptor(13, &[2560, 48], 84480, 2560, 48, true), + Err(E::UnsupportedKind) + ); + for (first, count) in [(0, 0), (0, 65), (usize::MAX, 1), (10239, 2)] { + assert_eq!(block_range(first, count, 10240), Err(E::Range)); + } + assert_eq!(block_range(10176, 64, 10240), Ok(())); +} diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_gr.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_gr.rs index f9b02b44..07211d8c 100644 --- a/crates/leleka-runtime/src/model_binding/qwen4exp_gr.rs +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_gr.rs @@ -385,47 +385,5 @@ fn read_row( } #[cfg(test)] -mod tests { - use super::*; - #[test] - fn gr_binding_accepts_only_exact_finite_bf16_containers() { - for bits in [0, 0x80000000, 0x3f800000, 0x00010000, 0x7f7f0000] { - assert_eq!(u32::from(exact_bf16(bits).unwrap()) << 16, bits); - } - assert_eq!( - exact_bf16(0x3f800001), - Err(InputBindingError::UnsupportedKind) - ); - for bits in [0x7f800000, 0xff800000, 0x7fc00000] { - assert_eq!(exact_bf16(bits), Err(InputBindingError::NonFinite)); - } - } - #[test] - fn gr_binding_freezes_role_shapes_and_final_has_no_injection() { - assert!(role_set(GrRole::Final, 48).unwrap()[3].is_none()); - assert_eq!( - role_set(GrRole::Attention(48), 48), - Err(InputBindingError::Range) - ); - assert_eq!( - validate_descriptor(30, &[10240, 320], 6553600, 10240, 320, false), - Ok(()) - ); - assert_eq!( - validate_descriptor(0, &[10240, 320], 13107200, 10240, 320, false), - Ok(()) - ); - assert_eq!( - validate_descriptor(30, &[320, 10240], 6553600, 10240, 320, false), - Err(InputBindingError::Geometry) - ); - assert_eq!( - validate_descriptor(0, &[10240], 40960, 10240, 1, true), - Ok(()) - ); - assert_eq!( - validate_descriptor(30, &[10240], 20480, 10240, 1, true), - Err(InputBindingError::UnsupportedKind) - ); - } -} +#[path = "qwen4exp_gr/tests.rs"] +mod tests; diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_gr/tests.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_gr/tests.rs new file mode 100644 index 00000000..f42bb7ba --- /dev/null +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_gr/tests.rs @@ -0,0 +1,44 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +#[test] +fn gr_binding_accepts_only_exact_finite_bf16_containers() { + for bits in [0, 0x80000000, 0x3f800000, 0x00010000, 0x7f7f0000] { + assert_eq!(u32::from(exact_bf16(bits).unwrap()) << 16, bits); + } + assert_eq!( + exact_bf16(0x3f800001), + Err(InputBindingError::UnsupportedKind) + ); + for bits in [0x7f800000, 0xff800000, 0x7fc00000] { + assert_eq!(exact_bf16(bits), Err(InputBindingError::NonFinite)); + } +} +#[test] +fn gr_binding_freezes_role_shapes_and_final_has_no_injection() { + assert!(role_set(GrRole::Final, 48).unwrap()[3].is_none()); + assert_eq!( + role_set(GrRole::Attention(48), 48), + Err(InputBindingError::Range) + ); + assert_eq!( + validate_descriptor(30, &[10240, 320], 6553600, 10240, 320, false), + Ok(()) + ); + assert_eq!( + validate_descriptor(0, &[10240, 320], 13107200, 10240, 320, false), + Ok(()) + ); + assert_eq!( + validate_descriptor(30, &[320, 10240], 6553600, 10240, 320, false), + Err(InputBindingError::Geometry) + ); + assert_eq!( + validate_descriptor(0, &[10240], 40960, 10240, 1, true), + Ok(()) + ); + assert_eq!( + validate_descriptor(30, &[10240], 20480, 10240, 1, true), + Err(InputBindingError::UnsupportedKind) + ); +} diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_mtp.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_mtp.rs index ec35bab3..9ded9d45 100644 --- a/crates/leleka-runtime/src/model_binding/qwen4exp_mtp.rs +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_mtp.rs @@ -1602,154 +1602,5 @@ mod backing { } #[cfg(test)] -mod tests { - use super::*; - fn index() -> String { - DESCRIPTORS - .iter() - .filter_map(|d| { - d.dense.map(|m| { - format!( - "{} {} {} {} {} {}\n", - d.name, - match m.kind { - MtpKind::Q8_0 => "q8_0", - MtpKind::Bf16 => "bf16", - MtpKind::F32 => "f32", - MtpKind::Q2_0 => unreachable!(), - }, - m.rows, - m.columns, - m.offset, - m.bytes - ) - }) - }) - .collect() - } - #[test] - fn exact_closed_receipts_and_runtime_index() { - assert_eq!(DESCRIPTORS.len(), 31); - assert_eq!( - DESCRIPTORS.iter().map(|d| d.source_bytes).sum::(), - 5_214_301_696 - ); - for d in DESCRIPTORS { - assert_eq!(d.source_shape.iter().product::() * 2, d.source_bytes); - assert_eq!(d.source_sha256.len(), 64); - assert_eq!(d.source_file, format!("tensors/{}.bin", d.source_name)); - } - let text = index(); - assert_eq!(text.len(), 1851); - assert!(MtpIndex::inspect(text.as_bytes()).is_ok()); - use sha2::{Digest, Sha256}; - assert_eq!( - <[u8; 32]>::from(Sha256::digest(text.as_bytes())), - [ - 153, 20, 86, 207, 78, 178, 102, 235, 138, 136, 140, 52, 158, 84, 141, 17, 188, 100, - 15, 93, 189, 145, 73, 67, 154, 169, 120, 106, 240, 247, 50, 253 - ] - ); - } - #[test] - fn rt_contract_lists_the_consumed_dense_roles_by_name() { - let roles = rt_dense_roles(); - assert_eq!(roles.len(), 26); - assert!(!roles.contains(&MtpRole::ExpertDown) && !roles.contains(&MtpRole::IndexProjection)); - let mut names: Vec<_> = roles.iter().map(|r| rt_dense_name(*r).unwrap()).collect(); - assert!(names.contains(&"fc_embedding.weight")); - assert!(names.contains(&"pre_fc_norm_hidden.weight")); - names.sort_unstable(); - names.dedup(); - assert_eq!(names.len(), 26); - assert_eq!(rt_dense_shape(MtpRole::QueryProjection), Some((MtpKind::Q8_0, 12288, 2560))); - assert_eq!(rt_dense_shape(MtpRole::Router), Some((MtpKind::Bf16, 512, 2560))); - assert_eq!(rt_dense_shape(MtpRole::KeyNorm), Some((MtpKind::F32, 1, 256))); - assert_eq!(rt_dense_shape(MtpRole::ExpertGateUp), None); - assert_eq!(rt_dense_name(MtpRole::ExpertDown), None); - // every nine-name requirement of the Original loader is a q8_0 role here - for name in ["fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", - "self_attn.k_proj.weight", "self_attn.v_proj.weight", "self_attn.o_proj.weight", - "mlp.shared_expert.gate_proj.weight", "mlp.shared_expert.up_proj.weight", - "mlp.shared_expert.down_proj.weight"] { - let role = DESCRIPTORS.iter().find(|d| d.name == name).unwrap().role; - assert_eq!(rt_dense_shape(role).unwrap().0, MtpKind::Q8_0, "{name}"); - } - } - #[test] - fn malformed_descriptor_input_never_becomes_index() { - let good = index(); - for bad in [ - good.replace("q8_0 2560 2560 0 6963200", "bf16 2560 2560 0 6963200"), - good.replace("fc_embedding.weight", "unknown"), - good.replace("6963200 6963200", "1 6963200"), - good.replace("2560 2560 0", "2560 2561 0"), - good.replace("116058112 40960", "18446744073709551615 40960"), - format!("{good}{}", good.lines().next().unwrap()), - good.lines().skip(1).map(|s| format!("{s}\n")).collect(), - good.replacen("6963200\n", "6963200 extra\n", 1), - "x".repeat(INDEX_LIMIT + 1), - "\u{00e9}".to_owned(), - ] { - assert!(MtpIndex::inspect(bad.as_bytes()).is_err()); - } - } - #[test] - fn bounded_rows_and_lossless_q2_planes_preserve_signed_zero_and_codes() { - assert_eq!(row_range(640, 720, 639, 1), Ok((460080, 720))); - assert!(row_range(640, 720, 640, 1).is_err()); - assert!(row_range(640, 720, 0, 65).is_err()); - assert!(row_range(640, 720, usize::MAX, 1).is_err()); - assert!(row_range(640, usize::MAX, 1, 1).is_err()); - let codes: Vec = (0..32).collect(); - let scales = [0, 0x3c, 0, 0x80]; - let mut out = [0u8; 36]; - interleave_q2(&codes, &scales, &mut out).unwrap(); - assert_eq!(&out[..2], &[0, 0x3c]); - assert_eq!(&out[2..18], &codes[..16]); - assert_eq!(&out[18..20], &[0, 0x80]); - assert_eq!(&out[20..], &codes[16..]); - assert_eq!( - interleave_q2(&codes, &[0, 0x7c, 0, 0], &mut out), - Err(InputBindingError::NonFinite) - ); - assert!(interleave_q2(&codes, &[], &mut out).is_err()); - } - #[test] - fn nonfinite_weights_refuse_and_zero_signs_remain_exact() { - for (kind, bytes) in [ - (MtpKind::Bf16, vec![0x80, 0x7f]), - (MtpKind::F32, f32::INFINITY.to_le_bytes().to_vec()), - (MtpKind::Q8_0, { - let mut v = vec![0; 34]; - v[1] = 0x7c; - v - }), - (MtpKind::Q2_0, { - let mut v = vec![0; 18]; - v[1] = 0x7e; - v - }), - ] { - assert_eq!( - validate_numeric(kind, &bytes), - Err(InputBindingError::NonFinite) - ); - } - assert_eq!(validate_numeric(MtpKind::Bf16, &[0, 0x80]), Ok(())); - assert_eq!( - validate_numeric(MtpKind::F32, &(-0.0f32).to_le_bytes()), - Ok(()) - ); - } - #[test] - fn identity_is_opaque_and_not_recreated_from_metadata() { - let first = BindingIdentity::test_identity(); - let second = BindingIdentity::test_identity(); - assert_eq!(validate_identity(&first, &first.clone()), Ok(())); - assert_eq!( - validate_identity(&first, &second), - Err(InputBindingError::Metadata) - ); - } -} +#[path = "qwen4exp_mtp/tests.rs"] +mod tests; diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_mtp/tests.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_mtp/tests.rs new file mode 100644 index 00000000..978a4219 --- /dev/null +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_mtp/tests.rs @@ -0,0 +1,151 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +fn index() -> String { + DESCRIPTORS + .iter() + .filter_map(|d| { + d.dense.map(|m| { + format!( + "{} {} {} {} {} {}\n", + d.name, + match m.kind { + MtpKind::Q8_0 => "q8_0", + MtpKind::Bf16 => "bf16", + MtpKind::F32 => "f32", + MtpKind::Q2_0 => unreachable!(), + }, + m.rows, + m.columns, + m.offset, + m.bytes + ) + }) + }) + .collect() +} +#[test] +fn exact_closed_receipts_and_runtime_index() { + assert_eq!(DESCRIPTORS.len(), 31); + assert_eq!( + DESCRIPTORS.iter().map(|d| d.source_bytes).sum::(), + 5_214_301_696 + ); + for d in DESCRIPTORS { + assert_eq!(d.source_shape.iter().product::() * 2, d.source_bytes); + assert_eq!(d.source_sha256.len(), 64); + assert_eq!(d.source_file, format!("tensors/{}.bin", d.source_name)); + } + let text = index(); + assert_eq!(text.len(), 1851); + assert!(MtpIndex::inspect(text.as_bytes()).is_ok()); + use sha2::{Digest, Sha256}; + assert_eq!( + <[u8; 32]>::from(Sha256::digest(text.as_bytes())), + [ + 153, 20, 86, 207, 78, 178, 102, 235, 138, 136, 140, 52, 158, 84, 141, 17, 188, 100, + 15, 93, 189, 145, 73, 67, 154, 169, 120, 106, 240, 247, 50, 253 + ] + ); +} +#[test] +fn rt_contract_lists_the_consumed_dense_roles_by_name() { + let roles = rt_dense_roles(); + assert_eq!(roles.len(), 26); + assert!(!roles.contains(&MtpRole::ExpertDown) && !roles.contains(&MtpRole::IndexProjection)); + let mut names: Vec<_> = roles.iter().map(|r| rt_dense_name(*r).unwrap()).collect(); + assert!(names.contains(&"fc_embedding.weight")); + assert!(names.contains(&"pre_fc_norm_hidden.weight")); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), 26); + assert_eq!(rt_dense_shape(MtpRole::QueryProjection), Some((MtpKind::Q8_0, 12288, 2560))); + assert_eq!(rt_dense_shape(MtpRole::Router), Some((MtpKind::Bf16, 512, 2560))); + assert_eq!(rt_dense_shape(MtpRole::KeyNorm), Some((MtpKind::F32, 1, 256))); + assert_eq!(rt_dense_shape(MtpRole::ExpertGateUp), None); + assert_eq!(rt_dense_name(MtpRole::ExpertDown), None); + // every nine-name requirement of the Original loader is a q8_0 role here + for name in ["fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", + "self_attn.k_proj.weight", "self_attn.v_proj.weight", "self_attn.o_proj.weight", + "mlp.shared_expert.gate_proj.weight", "mlp.shared_expert.up_proj.weight", + "mlp.shared_expert.down_proj.weight"] { + let role = DESCRIPTORS.iter().find(|d| d.name == name).unwrap().role; + assert_eq!(rt_dense_shape(role).unwrap().0, MtpKind::Q8_0, "{name}"); + } +} +#[test] +fn malformed_descriptor_input_never_becomes_index() { + let good = index(); + for bad in [ + good.replace("q8_0 2560 2560 0 6963200", "bf16 2560 2560 0 6963200"), + good.replace("fc_embedding.weight", "unknown"), + good.replace("6963200 6963200", "1 6963200"), + good.replace("2560 2560 0", "2560 2561 0"), + good.replace("116058112 40960", "18446744073709551615 40960"), + format!("{good}{}", good.lines().next().unwrap()), + good.lines().skip(1).map(|s| format!("{s}\n")).collect(), + good.replacen("6963200\n", "6963200 extra\n", 1), + "x".repeat(INDEX_LIMIT + 1), + "\u{00e9}".to_owned(), + ] { + assert!(MtpIndex::inspect(bad.as_bytes()).is_err()); + } +} +#[test] +fn bounded_rows_and_lossless_q2_planes_preserve_signed_zero_and_codes() { + assert_eq!(row_range(640, 720, 639, 1), Ok((460080, 720))); + assert!(row_range(640, 720, 640, 1).is_err()); + assert!(row_range(640, 720, 0, 65).is_err()); + assert!(row_range(640, 720, usize::MAX, 1).is_err()); + assert!(row_range(640, usize::MAX, 1, 1).is_err()); + let codes: Vec = (0..32).collect(); + let scales = [0, 0x3c, 0, 0x80]; + let mut out = [0u8; 36]; + interleave_q2(&codes, &scales, &mut out).unwrap(); + assert_eq!(&out[..2], &[0, 0x3c]); + assert_eq!(&out[2..18], &codes[..16]); + assert_eq!(&out[18..20], &[0, 0x80]); + assert_eq!(&out[20..], &codes[16..]); + assert_eq!( + interleave_q2(&codes, &[0, 0x7c, 0, 0], &mut out), + Err(InputBindingError::NonFinite) + ); + assert!(interleave_q2(&codes, &[], &mut out).is_err()); +} +#[test] +fn nonfinite_weights_refuse_and_zero_signs_remain_exact() { + for (kind, bytes) in [ + (MtpKind::Bf16, vec![0x80, 0x7f]), + (MtpKind::F32, f32::INFINITY.to_le_bytes().to_vec()), + (MtpKind::Q8_0, { + let mut v = vec![0; 34]; + v[1] = 0x7c; + v + }), + (MtpKind::Q2_0, { + let mut v = vec![0; 18]; + v[1] = 0x7e; + v + }), + ] { + assert_eq!( + validate_numeric(kind, &bytes), + Err(InputBindingError::NonFinite) + ); + } + assert_eq!(validate_numeric(MtpKind::Bf16, &[0, 0x80]), Ok(())); + assert_eq!( + validate_numeric(MtpKind::F32, &(-0.0f32).to_le_bytes()), + Ok(()) + ); +} +#[test] +fn identity_is_opaque_and_not_recreated_from_metadata() { + let first = BindingIdentity::test_identity(); + let second = BindingIdentity::test_identity(); + assert_eq!(validate_identity(&first, &first.clone()), Ok(())); + assert_eq!( + validate_identity(&first, &second), + Err(InputBindingError::Metadata) + ); +} diff --git a/crates/leleka-runtime/src/prefix_cache/store.rs b/crates/leleka-runtime/src/prefix_cache/store.rs index 785d074d..766b3b52 100644 --- a/crates/leleka-runtime/src/prefix_cache/store.rs +++ b/crates/leleka-runtime/src/prefix_cache/store.rs @@ -770,585 +770,4 @@ fn decayed(value: f64, age: u64, half_life: f64) -> f64 { } #[cfg(test)] -mod tests { - use super::*; - use crate::prefix_cache::hash::chain; - - #[derive(Debug)] - struct Payload(usize); - impl ByteSize for Payload { - fn byte_size(&self) -> usize { - self.0 - } - } - const G: usize = 8; - const STATE: usize = 100; - const BLOCK: usize = 30; - - fn store(budget: usize) -> PrefixStore { - PrefixStore::new(StoreConfig { block_tokens: G, budget_bytes: budget, max_nodes: 64, policy: PolicyParams::default() }) - } - fn tokens(session: i32, shared_blocks: usize, blocks: usize) -> Vec { - // `shared_blocks` identical leading blocks, then blocks private to `session` - let mut t = Vec::new(); - for j in 0..blocks { - for i in 0..G { - t.push(if j < shared_blocks { (j * G + i) as i32 } else { session * 10_000 + (j * G + i) as i32 }); - } - } - t - } - /// Insert the node at `blocks` of `t` the way the serving code does. `Exists` stands for "now cached". - fn put(s: &mut PrefixStore, t: &[i32], blocks: usize, frontier: bool) -> Consider { - let prefix = &t[..blocks * G]; - match s.consider(prefix, frontier, STATE, BLOCK) { - Consider::Admit(c) => { - let blocks_in: Vec<(usize, Payload)> = c.missing.iter().map(|j| (*j, Payload(BLOCK))).collect(); - s.commit(c, prefix, Payload(STATE), blocks_in).unwrap(); - s.check_invariants(); - Consider::Exists - } - other => other, - } - } - - #[test] - fn a_request_resumes_from_the_deepest_node_of_any_session() { - let mut s = store(10_000); - let a = tokens(1, 2, 5); - let b = tokens(2, 2, 5); - assert_eq!(put(&mut s, &a, 2, false), Consider::Exists); - assert_eq!(put(&mut s, &a, 5, true), Consider::Exists); - // session B shares the first two blocks only - let m = s.longest_match(&b, b.len()).unwrap(); - assert_eq!(m.tokens, 2 * G); - let m = s.longest_match(&a, a.len()).unwrap(); - assert_eq!(m.tokens, 5 * G); - // the limit keeps the last prompt token out of the cached part - assert_eq!(s.longest_match(&a, 5 * G - 1).unwrap().tokens, 2 * G); - assert_eq!(s.longest_match(&a, G - 1), None); - // an unrelated prompt matches nothing, and so does a prompt shorter than a block - assert_eq!(s.longest_match(&tokens(3, 0, 5), 40), None); - assert_eq!(s.longest_match(&a[..G - 1], G - 1), None); - } - - #[test] - fn common_prefixes_are_stored_once() { - let mut s = store(100_000); - let a = tokens(1, 4, 6); - let b = tokens(2, 4, 6); - put(&mut s, &a, 6, true); - let after_a = s.block_bytes(); - assert_eq!(after_a, 6 * BLOCK); - put(&mut s, &b, 6, true); - // B adds its two private blocks only - assert_eq!(s.block_bytes(), 8 * BLOCK); - assert_eq!(s.block_count(), 8); - assert_eq!(s.node_bytes(), 2 * STATE); - // the shared blocks are referenced by both nodes - let ma = s.longest_match(&a, a.len()).unwrap(); - let mb = s.longest_match(&b, b.len()).unwrap(); - assert_ne!(ma.key, mb.key); - assert_eq!(s.blocks_from(ma.key, 4).unwrap().len(), 2); - assert_eq!(s.blocks_from(ma.key, 0).unwrap().len(), 6); - s.check_invariants(); - } - - #[test] - fn a_node_with_descendants_is_a_branch_point_and_a_frontier_is_not() { - let mut s = store(100_000); - let a = tokens(1, 2, 5); - let b = tokens(2, 2, 5); - put(&mut s, &a, 2, false); - put(&mut s, &a, 5, true); - let shared = s.longest_match(&b, b.len()).unwrap(); - let own = s.longest_match(&a, a.len()).unwrap(); - assert!(s.is_branch_point(shared.key), "A's chain continues below the shared prefix"); - assert!(!s.is_branch_point(own.key)); - s.record_hit(&shared); - s.record_hit(&own); - assert_eq!(s.stats().shared_hits, 1); - assert_eq!(s.stats().hits, 2); - // once B has built its own chain the shared node has two branches below it - put(&mut s, &b, 5, true); - assert!(s.is_branch_point(shared.key)); - assert!(!s.is_branch_point(0xdead)); - } - - /// Insert a tail node (a checkpoint between two grid points) the way the serving code does. - fn put_tail(s: &mut PrefixStore, t: &[i32], len: usize) -> Consider { - let prefix = &t[..len]; - match s.consider_tail(prefix, true, STATE, BLOCK) { - Consider::Admit(c) => { - let blocks_in: Vec<(usize, Payload)> = c.missing.iter().map(|j| (*j, Payload(BLOCK))).collect(); - s.commit_tail(c, prefix, Payload(STATE), blocks_in, Payload(BLOCK / 2)).unwrap(); - s.check_invariants(); - Consider::Exists - } - other => other, - } - } - - /// Insert a tail node that leaves the tail ending at `keep` standing (the decode-end checkpoint of a request). - fn put_tail_keeping(s: &mut PrefixStore, t: &[i32], len: usize, keep: usize) { - let prefix = &t[..len]; - match s.consider_tail(prefix, true, STATE, BLOCK) { - Consider::Admit(c) => { - let blocks_in: Vec<(usize, Payload)> = c.missing.iter().map(|j| (*j, Payload(BLOCK))).collect(); - s.commit_tail_keeping(c, prefix, Payload(STATE), blocks_in, Payload(BLOCK / 2), Some(keep)).unwrap(); - s.check_invariants(); - } - other => panic!("not admitted: {other:?}"), - } - } - - #[test] - fn the_prompt_end_checkpoint_survives_the_decode_end_checkpoint_of_its_request() { - let mut s = store(100_000); - let a = tokens(1, 2, 8); - put(&mut s, &a, 3, true); - // the prompt ended 5 tokens after the third grid point, the decode added 4 more - assert_eq!(put_tail(&mut s, &a, 3 * G + 5), Consider::Exists); - let before = s.node_count(); - put_tail_keeping(&mut s, &a, 3 * G + 9, 3 * G + 5); - assert_eq!(s.node_count(), before + 1, "the decode end is added and the prompt end stays"); - // the next prompt resends the prompt but not the reply: it continues from the prompt end - let mut next = a[..3 * G + 5].to_vec(); - next.extend_from_slice(&[900, 901, 902]); - let m = s.longest_match(&next, next.len()).unwrap(); - assert_eq!(m.tokens, 3 * G + 5); - // the next request's own prompt-end checkpoint supersedes the earlier prompt end as before - assert_eq!(put_tail(&mut s, &next, 3 * G + 7), Consider::Exists); - let m = s.longest_match(&next, next.len()).unwrap(); - assert_eq!(m.tokens, 3 * G + 7); - } - - #[test] - fn a_checkpoint_between_two_grid_points_is_matched_exactly_and_supersedes_the_one_before_it() { - let mut s = store(100_000); - let a = tokens(1, 2, 8); - put(&mut s, &a, 3, true); - // the request ended 5 tokens after the third grid point - assert_eq!(put_tail(&mut s, &a, 3 * G + 5), Consider::Exists); - let m = s.longest_match(&a, a.len()).unwrap(); - assert_eq!(m.tokens, 3 * G + 5, "the tail node is deeper than the grid node under it"); - assert_eq!(s.node_tokens(m.key), Some(3 * G + 5)); - let (_, first, len) = s.tail_of(m.key).unwrap(); - assert_eq!((first, len), (3 * G, 5)); - assert_eq!(s.blocks_from(m.key, 2).unwrap().len(), 1, "its full blocks are the grid node's"); - // the limit keeps it out when the prompt is too short to resume from it - assert_eq!(s.longest_match(&a, 3 * G + 4).unwrap().tokens, 3 * G); - // tokens that differ inside the tail do not match - let mut other = a.clone(); - other[3 * G + 2] += 1; - assert_eq!(s.longest_match(&other, other.len()).unwrap().tokens, 3 * G); - // the next request of the session ends later: its node supersedes the first one - let nodes = s.node_count(); - assert_eq!(put_tail(&mut s, &a, 3 * G + 7), Consider::Exists); - assert_eq!(s.node_count(), nodes, "one added, one superseded"); - assert_eq!(s.longest_match(&a, a.len()).unwrap().tokens, 3 * G + 7); - // a tail that starts a new block after a later grid point supersedes it too - put(&mut s, &a, 4, true); - assert_eq!(put_tail(&mut s, &a, 4 * G + 3), Consider::Exists); - assert_eq!(s.longest_match(&a, a.len()).unwrap().tokens, 4 * G + 3); - assert_eq!(s.longest_match(&a, 4 * G + 2).unwrap().tokens, 4 * G, "the older tails are gone, the grid nodes remain"); - // summaries and router queries only know grid nodes - assert!(s.heads().iter().all(|h| h.1 % G == 0)); - assert_eq!(s.heads_by_value().len(), s.heads().len()); - assert_eq!(s.prefix_match(&crate::prefix_cache::hash::chain(&a, G)), 4 * G); - s.check_invariants(); - } - - #[test] - fn evicting_a_tail_node_removes_it_from_the_index_and_frees_its_tail() { - let mut s = store(100_000); - let a = tokens(1, 0, 6); - put(&mut s, &a, 2, false); - put_tail(&mut s, &a, 2 * G + 6); - let m = s.longest_match(&a, a.len()).unwrap(); - assert_eq!(m.tokens, 2 * G + 6); - let before = s.bytes(); - s.evict(m.key); - s.check_invariants(); - assert_eq!(s.bytes(), before - STATE - BLOCK / 2); - assert_eq!(s.longest_match(&a, a.len()).unwrap().tokens, 2 * G); - assert!(s.tail_of(m.key).is_none()); - } - - #[test] - fn a_tail_node_competes_by_value_like_any_other_and_a_budget_squeeze_keeps_the_newest_frontier() { - // room for about three single-block nodes - let mut s = store(3 * (STATE + BLOCK) + 10); - for session in 1..=6 { - s.tick(10); - let t = tokens(session, 0, 2); - put_tail(&mut s, &t, G + 3); - assert!(s.bytes() <= s.config().budget_bytes); - s.check_invariants(); - } - let newest = tokens(6, 0, 2); - assert_eq!(s.longest_match(&newest, newest.len()).unwrap().tokens, G + 3); - } - - const MINUTE: u64 = 60_000; - - #[test] - fn a_session_is_kept_for_the_retention_time_and_dropped_after_it() { - let mut s = store(100_000); - let a = tokens(1, 0, 4); - s.tick_at(a.len(), 0); - put(&mut s, &a, 4, true); - // 59 minutes idle: still there - s.set_now(59 * MINUTE); - assert_eq!(s.expire(), 0); - assert!(s.longest_match(&a, a.len() + 1).is_some()); - // a request that uses it renews the clock - s.tick_at(a.len(), 59 * MINUTE); - let m = s.longest_match(&a, a.len()).unwrap(); - s.record_hit(&m); - s.set_now(100 * MINUTE); - assert_eq!(s.expire(), 0, "41 minutes since the last use"); - // 61 minutes without a request: gone, with its blocks - s.set_now(121 * MINUTE); - assert_eq!(s.expire(), 1); - assert_eq!((s.node_count(), s.block_count(), s.bytes()), (0, 0, 0)); - assert_eq!((s.stats().expired, s.stats().evicted), (1, 1)); - s.check_invariants(); - } - - #[test] - fn retention_zero_never_expires() { - let mut s = PrefixStore::::new(StoreConfig { block_tokens: G, budget_bytes: 100_000, max_nodes: 64, policy: PolicyParams { retention_ms: 0, ..PolicyParams::default() } }); - let a = tokens(1, 0, 2); - put(&mut s, &a, 2, true); - s.set_now(1_000_000 * MINUTE); - assert_eq!(s.expire(), 0); - assert_eq!(s.node_count(), 1); - } - - #[test] - fn when_the_budget_runs_out_the_session_idle_longest_is_displaced_first() { - // room for two 3-block sessions (3 blocks + state = 190 bytes each), not three - let mut s = store(2 * (3 * BLOCK + STATE) + 20); - let (a, b, c) = (tokens(1, 0, 3), tokens(2, 0, 3), tokens(3, 0, 3)); - s.tick_at(a.len(), 0); - put(&mut s, &a, 3, true); - s.tick_at(b.len(), 30 * MINUTE); - put(&mut s, &b, 3, true); - // A has been idle for 40 minutes, B for 10: C displaces A, not B - s.tick_at(c.len(), 40 * MINUTE); - assert_eq!(put(&mut s, &c, 3, true), Consider::Exists); - assert!(s.longest_match(&a, a.len() + 1).is_none(), "the oldest session was displaced"); - assert!(s.longest_match(&b, b.len() + 1).is_some(), "the newer session stays"); - assert!(s.longest_match(&c, c.len() + 1).is_some()); - s.check_invariants(); - } - - #[test] - fn an_existing_node_is_only_touched() { - let mut s = store(10_000); - let a = tokens(1, 0, 3); - put(&mut s, &a, 3, true); - let before = (s.bytes(), s.stats().admitted); - assert_eq!(s.consider(&a, true, STATE, BLOCK), Consider::Exists); - assert_eq!((s.bytes(), s.stats().admitted), before); - assert_eq!(s.stats().already_cached, 1); - } - - #[test] - fn eviction_frees_a_block_only_when_no_node_covers_it() { - let mut s = store(100_000); - let a = tokens(1, 4, 6); - let b = tokens(2, 4, 6); - put(&mut s, &a, 6, true); - put(&mut s, &b, 6, true); - let ma = s.longest_match(&a, a.len()).unwrap(); - s.evict(ma.key); - s.check_invariants(); - // the four shared blocks survive for B, A's two private ones are gone - assert_eq!(s.block_count(), 6); - assert_eq!(s.longest_match(&a, a.len()), None); - assert_eq!(s.longest_match(&b, b.len()).unwrap().tokens, 6 * G); - let mb = s.longest_match(&b, b.len()).unwrap(); - s.evict(mb.key); - assert_eq!((s.block_count(), s.bytes()), (0, 0)); - } - - #[test] - fn a_full_store_evicts_the_least_valuable_entry_for_a_more_valuable_one() { - // room for about two single-block nodes - let mut s = store(2 * (STATE + BLOCK) + 10); - let old = tokens(1, 0, 1); - let other = tokens(2, 0, 1); - put(&mut s, &old, 1, true); - put(&mut s, &other, 1, true); - for _ in 0..200 { - s.tick(10); - } - // `old` idles for 200 requests while `other` is used again and again - for _ in 0..3 { - s.tick(10); - let m = s.longest_match(&other, other.len() + 1).unwrap(); - s.record_hit_as(&m, false); - } - let fresh = tokens(3, 0, 1); - assert_eq!(put(&mut s, &fresh, 1, true), Consider::Exists, "a new frontier beats an idle one"); - assert!(s.longest_match(&old, 100).is_none(), "the idle entry went"); - assert!(s.longest_match(&other, 100).is_some(), "the used entry stayed"); - assert!(s.longest_match(&fresh, 100).is_some()); - assert_eq!(s.stats().evicted, 1); - assert!(s.bytes() <= s.config().budget_bytes); - } - - #[test] - fn a_low_value_candidate_does_not_evict_a_hot_entry() { - let mut s = store(STATE + BLOCK + 10); - let hot = tokens(1, 0, 1); - put(&mut s, &hot, 1, true); - for _ in 0..4 { - s.tick(10); - let m = s.longest_match(&hot, 100).unwrap(); - s.record_hit_as(&m, true); - } - // an interior (non-frontier) candidate of another prompt is worth far less than the shared, used root - let cold = tokens(2, 0, 1); - assert_eq!(s.consider(&cold, false, STATE, BLOCK), Consider::Rejected(Reject::NotWorth)); - assert!(s.longest_match(&hot, 100).is_some()); - assert_eq!(s.stats().rejected, 1); - assert_eq!(s.stats().evicted, 0); - } - - #[test] - fn an_entry_bigger_than_the_budget_is_refused_up_front() { - let mut s = store(100); - let a = tokens(1, 0, 2); - assert_eq!(s.consider(&a, true, STATE, BLOCK), Consider::Rejected(Reject::TooLarge)); - assert_eq!(s.bytes(), 0); - } - - #[test] - fn a_hit_by_another_session_makes_a_shared_root_outlive_private_leaves() { - // budget for the shared root chain + 3 private frontier leaves - let mut s = store(STATE * 5 + BLOCK * 8); - let root = tokens(0, 2, 2); - put(&mut s, &root, 2, false); - // sessions branch off the root, one after the other; every new session hits the root - for session in 1..=6 { - s.tick(100); - let t = tokens(session, 2, 4); - let m = s.longest_match(&t, t.len()).unwrap(); - assert!(m.tokens >= 2 * G); - s.record_hit_as(&m, true); - put(&mut s, &t, 4, true); - s.check_invariants(); - assert!(s.bytes() <= s.config().budget_bytes); - } - // the root survives all the churn, the oldest private leaves went - assert_eq!(s.longest_match(&root, root.len()).map(|m| m.tokens), Some(2 * G)); - assert!(s.longest_match(&tokens(1, 2, 4), 100).map(|m| m.tokens) == Some(2 * G), "session 1's leaf was evicted"); - assert_eq!(s.longest_match(&tokens(6, 2, 4), 100).map(|m| m.tokens), Some(4 * G), "the newest leaf stays"); - } - - #[test] - fn thinning_a_chain_keeps_the_deepest_node_and_the_blocks_it_needs() { - let mut s = store(6 * STATE + 12 * BLOCK); - let long = tokens(1, 0, 12); - for k in 1..=12 { - s.tick(100); - put(&mut s, &long, k, k == 12); - assert!(s.bytes() <= s.config().budget_bytes); - } - s.check_invariants(); - // the frontier is cached with its whole chain of blocks - let m = s.longest_match(&long, long.len()).unwrap(); - assert_eq!(m.tokens, 12 * G); - assert_eq!(s.blocks_from(m.key, 0).unwrap().len(), 12); - assert!(s.node_count() <= 6, "{} nodes", s.node_count()); - } - - #[test] - fn the_budget_is_enforced_again_when_the_real_payload_is_bigger_than_the_estimate() { - let mut s = store(STATE + BLOCK + 10); - let a = tokens(1, 0, 1); - match s.consider(&a, true, STATE, BLOCK) { - Consider::Admit(c) => { - s.commit(c, &a, Payload(STATE * 3), vec![(0, Payload(BLOCK))]).unwrap(); - } - other => panic!("{other:?}"), - } - assert_eq!(s.bytes(), 0, "the oversized node was dropped at once"); - assert_eq!(s.stats().rejected_after_build, 1); - s.check_invariants(); - } - - #[test] - fn commit_refuses_blocks_that_are_not_the_candidates() { - let mut s = store(10_000); - let a = tokens(1, 0, 2); - let Consider::Admit(c) = s.consider(&a, true, STATE, BLOCK) else { panic!() }; - assert_eq!(c.missing, vec![0, 1]); - assert_eq!(s.commit(c, &a, Payload(STATE), vec![(0, Payload(BLOCK))]), Err(Reject::Mismatch)); - assert_eq!(s.bytes(), 0); - } - - #[test] - fn a_colliding_block_is_never_cached_or_matched() { - let mut s = store(10_000); - let a = tokens(1, 0, 1); - put(&mut s, &a, 1, true); - // forge a block under a's chain value that holds other tokens - let h = chain(&a, G)[0]; - s.blocks.get_mut(&h).unwrap().tokens = vec![9; G].into(); - assert_eq!(s.longest_match(&a, 100), None); - assert_eq!(s.consider(&a, true, STATE, BLOCK), Consider::Rejected(Reject::Collision)); - } - - #[test] - fn the_node_cap_makes_room_by_value() { - let mut s = PrefixStore::::new(StoreConfig { - block_tokens: G, - budget_bytes: 1 << 20, - max_nodes: 2, - policy: PolicyParams::default(), - }); - for session in 1..=4 { - s.tick(10); - put(&mut s, &tokens(session, 0, 1), 1, true); - assert!(s.node_count() <= 2); - } - s.check_invariants(); - assert!(s.longest_match(&tokens(4, 0, 1), 100).is_some()); - assert!(s.longest_match(&tokens(1, 0, 1), 100).is_none()); - } - - #[test] - fn prefix_match_reports_the_deepest_known_chain_value() { - let mut s = store(100_000); - let a = tokens(1, 3, 6); - put(&mut s, &a, 3, false); - put(&mut s, &a, 6, true); - let c = chain(&a, G); - assert_eq!(s.prefix_match(&c), 6 * G); - assert_eq!(s.prefix_match(&c[..4]), 3 * G); - assert_eq!(s.prefix_match(&c[..2]), 0); - let other = chain(&tokens(2, 3, 6), G); - assert_eq!(s.prefix_match(&other), 3 * G); - assert_eq!(s.prefix_match(&[]), 0); - assert_eq!(s.heads().iter().map(|h| h.1).collect::>(), vec![6 * G, 3 * G]); - assert_eq!(s.heads_by_value().len(), 2); - } - - #[test] - fn shrinking_the_budget_evicts_down_to_it() { - let mut s = store(100_000); - for session in 1..=5 { - s.tick(10); - put(&mut s, &tokens(session, 0, 2), 2, true); - } - assert_eq!(s.node_count(), 5); - s.set_budget(2 * (STATE + 2 * BLOCK)); - assert!(s.bytes() <= 2 * (STATE + 2 * BLOCK)); - assert_eq!(s.node_count(), 2); - s.check_invariants(); - s.clear(); - assert_eq!((s.bytes(), s.node_count(), s.block_count()), (0, 0, 0)); - } - - #[test] - fn a_long_agent_session_costs_a_sparse_chain_not_a_node_per_block() { - // one session growing 1..=40 blocks, frontier each time; budget for ~8 states - let mut s = store(8 * STATE + 40 * BLOCK); - let t = tokens(1, 0, 40); - for k in 1..=40 { - s.tick(100); - if let Some(m) = s.longest_match(&t, k * G) { - s.record_hit_as(&m, false); - } - put(&mut s, &t, k, true); - assert!(s.bytes() <= s.config().budget_bytes); - } - s.check_invariants(); - let m = s.longest_match(&t, t.len()).unwrap(); - assert_eq!(m.tokens, 40 * G, "the frontier is always kept"); - assert!(s.node_count() <= 8); - // the surviving ancestors are spread, not clustered at the tail only - let depths: Vec = s.heads().iter().map(|h| h.1 / G).collect(); - assert!(depths.iter().any(|d| *d < 39), "{depths:?}"); - } - - /// The pool at the production size, model-free: 12 agent sessions behind one runtime, an 8k shared system prompt, histories - /// growing by 4k tokens per request up to 180k, interleaved round robin, 2048-token blocks, the sizes a real node and block have - /// (127 MB of state, 29 MB per block) against a 13 GB budget. Checks the budget, the hit rate, the cost of the policy and of a - /// lookup over a 180k-token prompt. - #[test] - #[ignore = "scale simulation, seconds in release: cargo test --release -p leleka-runtime --lib -- --ignored twelve_sessions"] - fn twelve_sessions_growing_to_180k_tokens_stay_inside_the_budget_and_the_lookup_stays_fast() { - const BLOCK_TOKENS: usize = 2048; - const STATE_BYTES: usize = 127 << 20; - const BLOCK_BYTES: usize = 29 << 20; - let mut s = PrefixStore::::new(StoreConfig { - block_tokens: BLOCK_TOKENS, - budget_bytes: 13 << 30, - max_nodes: 1024, - policy: PolicyParams::default(), - }); - let token = |session: i32, i: usize| -> i32 { - if i < 4 * BLOCK_TOKENS { (i as i32 * 31) % 247_000 + 1 } else { ((i64::from(session) * 1_000_003 + i as i64 * 7919) % 247_000 + 1) as i32 } - }; - let sessions = 12; - let mut lengths = vec![8_192usize; sessions]; - let (mut match_us, mut policy_us) = (Vec::new(), Vec::new()); - let (mut reused, mut prompt_total) = (0usize, 0usize); - for _round in 0..43 { - for session in 0..sessions { - let n = lengths[session]; - let prompt: Vec = (0..n).map(|i| token(session as i32, i)).collect(); - s.tick(n); - let limit = n - 1; - let started = std::time::Instant::now(); - let hit = s.longest_match(&prompt, limit); - match_us.push(started.elapsed().as_secs_f64() * 1e6); - let resume = hit.map_or(0, |m| m.tokens); - match hit { - Some(m) => s.record_hit(&m), - None => s.record_miss(), - } - reused += resume; - prompt_total += limit; - let last_grid = limit / BLOCK_TOKENS * BLOCK_TOKENS; - let started = std::time::Instant::now(); - let mut end = (resume / BLOCK_TOKENS + 1) * BLOCK_TOKENS; - while end <= last_grid { - if let Consider::Admit(c) = s.consider(&prompt[..end], end == last_grid, STATE_BYTES, BLOCK_BYTES) { - let blocks = c.missing.iter().map(|j| (*j, Payload(BLOCK_BYTES))).collect(); - s.commit(c, &prompt[..end], Payload(STATE_BYTES), blocks).unwrap(); - } - end += BLOCK_TOKENS; - } - policy_us.push(started.elapsed().as_secs_f64() * 1e6); - assert!(s.bytes() <= s.config().budget_bytes); - lengths[session] += 4_096; - } - } - s.check_invariants(); - let longest = lengths.iter().max().copied().unwrap(); - let mean = |v: &[f64]| v.iter().sum::() / v.len() as f64; - let max = |v: &[f64]| v.iter().cloned().fold(0.0, f64::max); - eprintln!( - "scale: {} requests, longest prompt {longest}; reuse {:.1}%; lookup mean {:.0} us max {:.0} us; policy per request mean {:.0} us max {:.0} us; nodes {} blocks {} bytes {} MiB of {}; admitted {} rejected {} evicted {}", - match_us.len(), - 100.0 * reused as f64 / prompt_total as f64, - mean(&match_us), max(&match_us), mean(&policy_us), max(&policy_us), - s.node_count(), s.block_count(), s.bytes() >> 20, s.config().budget_bytes >> 20, - s.stats().admitted, s.stats().rejected, s.stats().evicted - ); - assert!(longest >= 170_000); - // the cache is smaller than the sum of the histories (12 x ~90k tokens on average = 15 GB of blocks alone): it must have chosen - assert!(s.stats().evicted > 0 || s.stats().rejected > 0); - // a lookup over a 180k-token prompt (hashing and comparing every token) is milliseconds even in a debug build - assert!(max(&match_us) < 200_000.0, "{} us", max(&match_us)); - assert!(max(&policy_us) < 2_000_000.0, "{} us", max(&policy_us)); - // sessions keep resuming close to their frontier: the hit rate stays high - assert!(reused as f64 / prompt_total as f64 > 0.5); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/prefix_cache/store/tests.rs b/crates/leleka-runtime/src/prefix_cache/store/tests.rs new file mode 100644 index 00000000..4e172a12 --- /dev/null +++ b/crates/leleka-runtime/src/prefix_cache/store/tests.rs @@ -0,0 +1,582 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::prefix_cache::hash::chain; + +#[derive(Debug)] +struct Payload(usize); +impl ByteSize for Payload { + fn byte_size(&self) -> usize { + self.0 + } +} +const G: usize = 8; +const STATE: usize = 100; +const BLOCK: usize = 30; + +fn store(budget: usize) -> PrefixStore { + PrefixStore::new(StoreConfig { block_tokens: G, budget_bytes: budget, max_nodes: 64, policy: PolicyParams::default() }) +} +fn tokens(session: i32, shared_blocks: usize, blocks: usize) -> Vec { + // `shared_blocks` identical leading blocks, then blocks private to `session` + let mut t = Vec::new(); + for j in 0..blocks { + for i in 0..G { + t.push(if j < shared_blocks { (j * G + i) as i32 } else { session * 10_000 + (j * G + i) as i32 }); + } + } + t +} +/// Insert the node at `blocks` of `t` the way the serving code does. `Exists` stands for "now cached". +fn put(s: &mut PrefixStore, t: &[i32], blocks: usize, frontier: bool) -> Consider { + let prefix = &t[..blocks * G]; + match s.consider(prefix, frontier, STATE, BLOCK) { + Consider::Admit(c) => { + let blocks_in: Vec<(usize, Payload)> = c.missing.iter().map(|j| (*j, Payload(BLOCK))).collect(); + s.commit(c, prefix, Payload(STATE), blocks_in).unwrap(); + s.check_invariants(); + Consider::Exists + } + other => other, + } +} + +#[test] +fn a_request_resumes_from_the_deepest_node_of_any_session() { + let mut s = store(10_000); + let a = tokens(1, 2, 5); + let b = tokens(2, 2, 5); + assert_eq!(put(&mut s, &a, 2, false), Consider::Exists); + assert_eq!(put(&mut s, &a, 5, true), Consider::Exists); + // session B shares the first two blocks only + let m = s.longest_match(&b, b.len()).unwrap(); + assert_eq!(m.tokens, 2 * G); + let m = s.longest_match(&a, a.len()).unwrap(); + assert_eq!(m.tokens, 5 * G); + // the limit keeps the last prompt token out of the cached part + assert_eq!(s.longest_match(&a, 5 * G - 1).unwrap().tokens, 2 * G); + assert_eq!(s.longest_match(&a, G - 1), None); + // an unrelated prompt matches nothing, and so does a prompt shorter than a block + assert_eq!(s.longest_match(&tokens(3, 0, 5), 40), None); + assert_eq!(s.longest_match(&a[..G - 1], G - 1), None); +} + +#[test] +fn common_prefixes_are_stored_once() { + let mut s = store(100_000); + let a = tokens(1, 4, 6); + let b = tokens(2, 4, 6); + put(&mut s, &a, 6, true); + let after_a = s.block_bytes(); + assert_eq!(after_a, 6 * BLOCK); + put(&mut s, &b, 6, true); + // B adds its two private blocks only + assert_eq!(s.block_bytes(), 8 * BLOCK); + assert_eq!(s.block_count(), 8); + assert_eq!(s.node_bytes(), 2 * STATE); + // the shared blocks are referenced by both nodes + let ma = s.longest_match(&a, a.len()).unwrap(); + let mb = s.longest_match(&b, b.len()).unwrap(); + assert_ne!(ma.key, mb.key); + assert_eq!(s.blocks_from(ma.key, 4).unwrap().len(), 2); + assert_eq!(s.blocks_from(ma.key, 0).unwrap().len(), 6); + s.check_invariants(); +} + +#[test] +fn a_node_with_descendants_is_a_branch_point_and_a_frontier_is_not() { + let mut s = store(100_000); + let a = tokens(1, 2, 5); + let b = tokens(2, 2, 5); + put(&mut s, &a, 2, false); + put(&mut s, &a, 5, true); + let shared = s.longest_match(&b, b.len()).unwrap(); + let own = s.longest_match(&a, a.len()).unwrap(); + assert!(s.is_branch_point(shared.key), "A's chain continues below the shared prefix"); + assert!(!s.is_branch_point(own.key)); + s.record_hit(&shared); + s.record_hit(&own); + assert_eq!(s.stats().shared_hits, 1); + assert_eq!(s.stats().hits, 2); + // once B has built its own chain the shared node has two branches below it + put(&mut s, &b, 5, true); + assert!(s.is_branch_point(shared.key)); + assert!(!s.is_branch_point(0xdead)); +} + +/// Insert a tail node (a checkpoint between two grid points) the way the serving code does. +fn put_tail(s: &mut PrefixStore, t: &[i32], len: usize) -> Consider { + let prefix = &t[..len]; + match s.consider_tail(prefix, true, STATE, BLOCK) { + Consider::Admit(c) => { + let blocks_in: Vec<(usize, Payload)> = c.missing.iter().map(|j| (*j, Payload(BLOCK))).collect(); + s.commit_tail(c, prefix, Payload(STATE), blocks_in, Payload(BLOCK / 2)).unwrap(); + s.check_invariants(); + Consider::Exists + } + other => other, + } +} + +/// Insert a tail node that leaves the tail ending at `keep` standing (the decode-end checkpoint of a request). +fn put_tail_keeping(s: &mut PrefixStore, t: &[i32], len: usize, keep: usize) { + let prefix = &t[..len]; + match s.consider_tail(prefix, true, STATE, BLOCK) { + Consider::Admit(c) => { + let blocks_in: Vec<(usize, Payload)> = c.missing.iter().map(|j| (*j, Payload(BLOCK))).collect(); + s.commit_tail_keeping(c, prefix, Payload(STATE), blocks_in, Payload(BLOCK / 2), Some(keep)).unwrap(); + s.check_invariants(); + } + other => panic!("not admitted: {other:?}"), + } +} + +#[test] +fn the_prompt_end_checkpoint_survives_the_decode_end_checkpoint_of_its_request() { + let mut s = store(100_000); + let a = tokens(1, 2, 8); + put(&mut s, &a, 3, true); + // the prompt ended 5 tokens after the third grid point, the decode added 4 more + assert_eq!(put_tail(&mut s, &a, 3 * G + 5), Consider::Exists); + let before = s.node_count(); + put_tail_keeping(&mut s, &a, 3 * G + 9, 3 * G + 5); + assert_eq!(s.node_count(), before + 1, "the decode end is added and the prompt end stays"); + // the next prompt resends the prompt but not the reply: it continues from the prompt end + let mut next = a[..3 * G + 5].to_vec(); + next.extend_from_slice(&[900, 901, 902]); + let m = s.longest_match(&next, next.len()).unwrap(); + assert_eq!(m.tokens, 3 * G + 5); + // the next request's own prompt-end checkpoint supersedes the earlier prompt end as before + assert_eq!(put_tail(&mut s, &next, 3 * G + 7), Consider::Exists); + let m = s.longest_match(&next, next.len()).unwrap(); + assert_eq!(m.tokens, 3 * G + 7); +} + +#[test] +fn a_checkpoint_between_two_grid_points_is_matched_exactly_and_supersedes_the_one_before_it() { + let mut s = store(100_000); + let a = tokens(1, 2, 8); + put(&mut s, &a, 3, true); + // the request ended 5 tokens after the third grid point + assert_eq!(put_tail(&mut s, &a, 3 * G + 5), Consider::Exists); + let m = s.longest_match(&a, a.len()).unwrap(); + assert_eq!(m.tokens, 3 * G + 5, "the tail node is deeper than the grid node under it"); + assert_eq!(s.node_tokens(m.key), Some(3 * G + 5)); + let (_, first, len) = s.tail_of(m.key).unwrap(); + assert_eq!((first, len), (3 * G, 5)); + assert_eq!(s.blocks_from(m.key, 2).unwrap().len(), 1, "its full blocks are the grid node's"); + // the limit keeps it out when the prompt is too short to resume from it + assert_eq!(s.longest_match(&a, 3 * G + 4).unwrap().tokens, 3 * G); + // tokens that differ inside the tail do not match + let mut other = a.clone(); + other[3 * G + 2] += 1; + assert_eq!(s.longest_match(&other, other.len()).unwrap().tokens, 3 * G); + // the next request of the session ends later: its node supersedes the first one + let nodes = s.node_count(); + assert_eq!(put_tail(&mut s, &a, 3 * G + 7), Consider::Exists); + assert_eq!(s.node_count(), nodes, "one added, one superseded"); + assert_eq!(s.longest_match(&a, a.len()).unwrap().tokens, 3 * G + 7); + // a tail that starts a new block after a later grid point supersedes it too + put(&mut s, &a, 4, true); + assert_eq!(put_tail(&mut s, &a, 4 * G + 3), Consider::Exists); + assert_eq!(s.longest_match(&a, a.len()).unwrap().tokens, 4 * G + 3); + assert_eq!(s.longest_match(&a, 4 * G + 2).unwrap().tokens, 4 * G, "the older tails are gone, the grid nodes remain"); + // summaries and router queries only know grid nodes + assert!(s.heads().iter().all(|h| h.1 % G == 0)); + assert_eq!(s.heads_by_value().len(), s.heads().len()); + assert_eq!(s.prefix_match(&crate::prefix_cache::hash::chain(&a, G)), 4 * G); + s.check_invariants(); +} + +#[test] +fn evicting_a_tail_node_removes_it_from_the_index_and_frees_its_tail() { + let mut s = store(100_000); + let a = tokens(1, 0, 6); + put(&mut s, &a, 2, false); + put_tail(&mut s, &a, 2 * G + 6); + let m = s.longest_match(&a, a.len()).unwrap(); + assert_eq!(m.tokens, 2 * G + 6); + let before = s.bytes(); + s.evict(m.key); + s.check_invariants(); + assert_eq!(s.bytes(), before - STATE - BLOCK / 2); + assert_eq!(s.longest_match(&a, a.len()).unwrap().tokens, 2 * G); + assert!(s.tail_of(m.key).is_none()); +} + +#[test] +fn a_tail_node_competes_by_value_like_any_other_and_a_budget_squeeze_keeps_the_newest_frontier() { + // room for about three single-block nodes + let mut s = store(3 * (STATE + BLOCK) + 10); + for session in 1..=6 { + s.tick(10); + let t = tokens(session, 0, 2); + put_tail(&mut s, &t, G + 3); + assert!(s.bytes() <= s.config().budget_bytes); + s.check_invariants(); + } + let newest = tokens(6, 0, 2); + assert_eq!(s.longest_match(&newest, newest.len()).unwrap().tokens, G + 3); +} + +const MINUTE: u64 = 60_000; + +#[test] +fn a_session_is_kept_for_the_retention_time_and_dropped_after_it() { + let mut s = store(100_000); + let a = tokens(1, 0, 4); + s.tick_at(a.len(), 0); + put(&mut s, &a, 4, true); + // 59 minutes idle: still there + s.set_now(59 * MINUTE); + assert_eq!(s.expire(), 0); + assert!(s.longest_match(&a, a.len() + 1).is_some()); + // a request that uses it renews the clock + s.tick_at(a.len(), 59 * MINUTE); + let m = s.longest_match(&a, a.len()).unwrap(); + s.record_hit(&m); + s.set_now(100 * MINUTE); + assert_eq!(s.expire(), 0, "41 minutes since the last use"); + // 61 minutes without a request: gone, with its blocks + s.set_now(121 * MINUTE); + assert_eq!(s.expire(), 1); + assert_eq!((s.node_count(), s.block_count(), s.bytes()), (0, 0, 0)); + assert_eq!((s.stats().expired, s.stats().evicted), (1, 1)); + s.check_invariants(); +} + +#[test] +fn retention_zero_never_expires() { + let mut s = PrefixStore::::new(StoreConfig { block_tokens: G, budget_bytes: 100_000, max_nodes: 64, policy: PolicyParams { retention_ms: 0, ..PolicyParams::default() } }); + let a = tokens(1, 0, 2); + put(&mut s, &a, 2, true); + s.set_now(1_000_000 * MINUTE); + assert_eq!(s.expire(), 0); + assert_eq!(s.node_count(), 1); +} + +#[test] +fn when_the_budget_runs_out_the_session_idle_longest_is_displaced_first() { + // room for two 3-block sessions (3 blocks + state = 190 bytes each), not three + let mut s = store(2 * (3 * BLOCK + STATE) + 20); + let (a, b, c) = (tokens(1, 0, 3), tokens(2, 0, 3), tokens(3, 0, 3)); + s.tick_at(a.len(), 0); + put(&mut s, &a, 3, true); + s.tick_at(b.len(), 30 * MINUTE); + put(&mut s, &b, 3, true); + // A has been idle for 40 minutes, B for 10: C displaces A, not B + s.tick_at(c.len(), 40 * MINUTE); + assert_eq!(put(&mut s, &c, 3, true), Consider::Exists); + assert!(s.longest_match(&a, a.len() + 1).is_none(), "the oldest session was displaced"); + assert!(s.longest_match(&b, b.len() + 1).is_some(), "the newer session stays"); + assert!(s.longest_match(&c, c.len() + 1).is_some()); + s.check_invariants(); +} + +#[test] +fn an_existing_node_is_only_touched() { + let mut s = store(10_000); + let a = tokens(1, 0, 3); + put(&mut s, &a, 3, true); + let before = (s.bytes(), s.stats().admitted); + assert_eq!(s.consider(&a, true, STATE, BLOCK), Consider::Exists); + assert_eq!((s.bytes(), s.stats().admitted), before); + assert_eq!(s.stats().already_cached, 1); +} + +#[test] +fn eviction_frees_a_block_only_when_no_node_covers_it() { + let mut s = store(100_000); + let a = tokens(1, 4, 6); + let b = tokens(2, 4, 6); + put(&mut s, &a, 6, true); + put(&mut s, &b, 6, true); + let ma = s.longest_match(&a, a.len()).unwrap(); + s.evict(ma.key); + s.check_invariants(); + // the four shared blocks survive for B, A's two private ones are gone + assert_eq!(s.block_count(), 6); + assert_eq!(s.longest_match(&a, a.len()), None); + assert_eq!(s.longest_match(&b, b.len()).unwrap().tokens, 6 * G); + let mb = s.longest_match(&b, b.len()).unwrap(); + s.evict(mb.key); + assert_eq!((s.block_count(), s.bytes()), (0, 0)); +} + +#[test] +fn a_full_store_evicts_the_least_valuable_entry_for_a_more_valuable_one() { + // room for about two single-block nodes + let mut s = store(2 * (STATE + BLOCK) + 10); + let old = tokens(1, 0, 1); + let other = tokens(2, 0, 1); + put(&mut s, &old, 1, true); + put(&mut s, &other, 1, true); + for _ in 0..200 { + s.tick(10); + } + // `old` idles for 200 requests while `other` is used again and again + for _ in 0..3 { + s.tick(10); + let m = s.longest_match(&other, other.len() + 1).unwrap(); + s.record_hit_as(&m, false); + } + let fresh = tokens(3, 0, 1); + assert_eq!(put(&mut s, &fresh, 1, true), Consider::Exists, "a new frontier beats an idle one"); + assert!(s.longest_match(&old, 100).is_none(), "the idle entry went"); + assert!(s.longest_match(&other, 100).is_some(), "the used entry stayed"); + assert!(s.longest_match(&fresh, 100).is_some()); + assert_eq!(s.stats().evicted, 1); + assert!(s.bytes() <= s.config().budget_bytes); +} + +#[test] +fn a_low_value_candidate_does_not_evict_a_hot_entry() { + let mut s = store(STATE + BLOCK + 10); + let hot = tokens(1, 0, 1); + put(&mut s, &hot, 1, true); + for _ in 0..4 { + s.tick(10); + let m = s.longest_match(&hot, 100).unwrap(); + s.record_hit_as(&m, true); + } + // an interior (non-frontier) candidate of another prompt is worth far less than the shared, used root + let cold = tokens(2, 0, 1); + assert_eq!(s.consider(&cold, false, STATE, BLOCK), Consider::Rejected(Reject::NotWorth)); + assert!(s.longest_match(&hot, 100).is_some()); + assert_eq!(s.stats().rejected, 1); + assert_eq!(s.stats().evicted, 0); +} + +#[test] +fn an_entry_bigger_than_the_budget_is_refused_up_front() { + let mut s = store(100); + let a = tokens(1, 0, 2); + assert_eq!(s.consider(&a, true, STATE, BLOCK), Consider::Rejected(Reject::TooLarge)); + assert_eq!(s.bytes(), 0); +} + +#[test] +fn a_hit_by_another_session_makes_a_shared_root_outlive_private_leaves() { + // budget for the shared root chain + 3 private frontier leaves + let mut s = store(STATE * 5 + BLOCK * 8); + let root = tokens(0, 2, 2); + put(&mut s, &root, 2, false); + // sessions branch off the root, one after the other; every new session hits the root + for session in 1..=6 { + s.tick(100); + let t = tokens(session, 2, 4); + let m = s.longest_match(&t, t.len()).unwrap(); + assert!(m.tokens >= 2 * G); + s.record_hit_as(&m, true); + put(&mut s, &t, 4, true); + s.check_invariants(); + assert!(s.bytes() <= s.config().budget_bytes); + } + // the root survives all the churn, the oldest private leaves went + assert_eq!(s.longest_match(&root, root.len()).map(|m| m.tokens), Some(2 * G)); + assert!(s.longest_match(&tokens(1, 2, 4), 100).map(|m| m.tokens) == Some(2 * G), "session 1's leaf was evicted"); + assert_eq!(s.longest_match(&tokens(6, 2, 4), 100).map(|m| m.tokens), Some(4 * G), "the newest leaf stays"); +} + +#[test] +fn thinning_a_chain_keeps_the_deepest_node_and_the_blocks_it_needs() { + let mut s = store(6 * STATE + 12 * BLOCK); + let long = tokens(1, 0, 12); + for k in 1..=12 { + s.tick(100); + put(&mut s, &long, k, k == 12); + assert!(s.bytes() <= s.config().budget_bytes); + } + s.check_invariants(); + // the frontier is cached with its whole chain of blocks + let m = s.longest_match(&long, long.len()).unwrap(); + assert_eq!(m.tokens, 12 * G); + assert_eq!(s.blocks_from(m.key, 0).unwrap().len(), 12); + assert!(s.node_count() <= 6, "{} nodes", s.node_count()); +} + +#[test] +fn the_budget_is_enforced_again_when_the_real_payload_is_bigger_than_the_estimate() { + let mut s = store(STATE + BLOCK + 10); + let a = tokens(1, 0, 1); + match s.consider(&a, true, STATE, BLOCK) { + Consider::Admit(c) => { + s.commit(c, &a, Payload(STATE * 3), vec![(0, Payload(BLOCK))]).unwrap(); + } + other => panic!("{other:?}"), + } + assert_eq!(s.bytes(), 0, "the oversized node was dropped at once"); + assert_eq!(s.stats().rejected_after_build, 1); + s.check_invariants(); +} + +#[test] +fn commit_refuses_blocks_that_are_not_the_candidates() { + let mut s = store(10_000); + let a = tokens(1, 0, 2); + let Consider::Admit(c) = s.consider(&a, true, STATE, BLOCK) else { panic!() }; + assert_eq!(c.missing, vec![0, 1]); + assert_eq!(s.commit(c, &a, Payload(STATE), vec![(0, Payload(BLOCK))]), Err(Reject::Mismatch)); + assert_eq!(s.bytes(), 0); +} + +#[test] +fn a_colliding_block_is_never_cached_or_matched() { + let mut s = store(10_000); + let a = tokens(1, 0, 1); + put(&mut s, &a, 1, true); + // forge a block under a's chain value that holds other tokens + let h = chain(&a, G)[0]; + s.blocks.get_mut(&h).unwrap().tokens = vec![9; G].into(); + assert_eq!(s.longest_match(&a, 100), None); + assert_eq!(s.consider(&a, true, STATE, BLOCK), Consider::Rejected(Reject::Collision)); +} + +#[test] +fn the_node_cap_makes_room_by_value() { + let mut s = PrefixStore::::new(StoreConfig { + block_tokens: G, + budget_bytes: 1 << 20, + max_nodes: 2, + policy: PolicyParams::default(), + }); + for session in 1..=4 { + s.tick(10); + put(&mut s, &tokens(session, 0, 1), 1, true); + assert!(s.node_count() <= 2); + } + s.check_invariants(); + assert!(s.longest_match(&tokens(4, 0, 1), 100).is_some()); + assert!(s.longest_match(&tokens(1, 0, 1), 100).is_none()); +} + +#[test] +fn prefix_match_reports_the_deepest_known_chain_value() { + let mut s = store(100_000); + let a = tokens(1, 3, 6); + put(&mut s, &a, 3, false); + put(&mut s, &a, 6, true); + let c = chain(&a, G); + assert_eq!(s.prefix_match(&c), 6 * G); + assert_eq!(s.prefix_match(&c[..4]), 3 * G); + assert_eq!(s.prefix_match(&c[..2]), 0); + let other = chain(&tokens(2, 3, 6), G); + assert_eq!(s.prefix_match(&other), 3 * G); + assert_eq!(s.prefix_match(&[]), 0); + assert_eq!(s.heads().iter().map(|h| h.1).collect::>(), vec![6 * G, 3 * G]); + assert_eq!(s.heads_by_value().len(), 2); +} + +#[test] +fn shrinking_the_budget_evicts_down_to_it() { + let mut s = store(100_000); + for session in 1..=5 { + s.tick(10); + put(&mut s, &tokens(session, 0, 2), 2, true); + } + assert_eq!(s.node_count(), 5); + s.set_budget(2 * (STATE + 2 * BLOCK)); + assert!(s.bytes() <= 2 * (STATE + 2 * BLOCK)); + assert_eq!(s.node_count(), 2); + s.check_invariants(); + s.clear(); + assert_eq!((s.bytes(), s.node_count(), s.block_count()), (0, 0, 0)); +} + +#[test] +fn a_long_agent_session_costs_a_sparse_chain_not_a_node_per_block() { + // one session growing 1..=40 blocks, frontier each time; budget for ~8 states + let mut s = store(8 * STATE + 40 * BLOCK); + let t = tokens(1, 0, 40); + for k in 1..=40 { + s.tick(100); + if let Some(m) = s.longest_match(&t, k * G) { + s.record_hit_as(&m, false); + } + put(&mut s, &t, k, true); + assert!(s.bytes() <= s.config().budget_bytes); + } + s.check_invariants(); + let m = s.longest_match(&t, t.len()).unwrap(); + assert_eq!(m.tokens, 40 * G, "the frontier is always kept"); + assert!(s.node_count() <= 8); + // the surviving ancestors are spread, not clustered at the tail only + let depths: Vec = s.heads().iter().map(|h| h.1 / G).collect(); + assert!(depths.iter().any(|d| *d < 39), "{depths:?}"); +} + +/// The pool at the production size, model-free: 12 agent sessions behind one runtime, an 8k shared system prompt, histories +/// growing by 4k tokens per request up to 180k, interleaved round robin, 2048-token blocks, the sizes a real node and block have +/// (127 MB of state, 29 MB per block) against a 13 GB budget. Checks the budget, the hit rate, the cost of the policy and of a +/// lookup over a 180k-token prompt. +#[test] +#[ignore = "scale simulation, seconds in release: cargo test --release -p leleka-runtime --lib -- --ignored twelve_sessions"] +fn twelve_sessions_growing_to_180k_tokens_stay_inside_the_budget_and_the_lookup_stays_fast() { + const BLOCK_TOKENS: usize = 2048; + const STATE_BYTES: usize = 127 << 20; + const BLOCK_BYTES: usize = 29 << 20; + let mut s = PrefixStore::::new(StoreConfig { + block_tokens: BLOCK_TOKENS, + budget_bytes: 13 << 30, + max_nodes: 1024, + policy: PolicyParams::default(), + }); + let token = |session: i32, i: usize| -> i32 { + if i < 4 * BLOCK_TOKENS { (i as i32 * 31) % 247_000 + 1 } else { ((i64::from(session) * 1_000_003 + i as i64 * 7919) % 247_000 + 1) as i32 } + }; + let sessions = 12; + let mut lengths = vec![8_192usize; sessions]; + let (mut match_us, mut policy_us) = (Vec::new(), Vec::new()); + let (mut reused, mut prompt_total) = (0usize, 0usize); + for _round in 0..43 { + for session in 0..sessions { + let n = lengths[session]; + let prompt: Vec = (0..n).map(|i| token(session as i32, i)).collect(); + s.tick(n); + let limit = n - 1; + let started = std::time::Instant::now(); + let hit = s.longest_match(&prompt, limit); + match_us.push(started.elapsed().as_secs_f64() * 1e6); + let resume = hit.map_or(0, |m| m.tokens); + match hit { + Some(m) => s.record_hit(&m), + None => s.record_miss(), + } + reused += resume; + prompt_total += limit; + let last_grid = limit / BLOCK_TOKENS * BLOCK_TOKENS; + let started = std::time::Instant::now(); + let mut end = (resume / BLOCK_TOKENS + 1) * BLOCK_TOKENS; + while end <= last_grid { + if let Consider::Admit(c) = s.consider(&prompt[..end], end == last_grid, STATE_BYTES, BLOCK_BYTES) { + let blocks = c.missing.iter().map(|j| (*j, Payload(BLOCK_BYTES))).collect(); + s.commit(c, &prompt[..end], Payload(STATE_BYTES), blocks).unwrap(); + } + end += BLOCK_TOKENS; + } + policy_us.push(started.elapsed().as_secs_f64() * 1e6); + assert!(s.bytes() <= s.config().budget_bytes); + lengths[session] += 4_096; + } + } + s.check_invariants(); + let longest = lengths.iter().max().copied().unwrap(); + let mean = |v: &[f64]| v.iter().sum::() / v.len() as f64; + let max = |v: &[f64]| v.iter().cloned().fold(0.0, f64::max); + eprintln!( + "scale: {} requests, longest prompt {longest}; reuse {:.1}%; lookup mean {:.0} us max {:.0} us; policy per request mean {:.0} us max {:.0} us; nodes {} blocks {} bytes {} MiB of {}; admitted {} rejected {} evicted {}", + match_us.len(), + 100.0 * reused as f64 / prompt_total as f64, + mean(&match_us), max(&match_us), mean(&policy_us), max(&policy_us), + s.node_count(), s.block_count(), s.bytes() >> 20, s.config().budget_bytes >> 20, + s.stats().admitted, s.stats().rejected, s.stats().evicted + ); + assert!(longest >= 170_000); + // the cache is smaller than the sum of the histories (12 x ~90k tokens on average = 15 GB of blocks alone): it must have chosen + assert!(s.stats().evicted > 0 || s.stats().rejected > 0); + // a lookup over a 180k-token prompt (hashing and comparing every token) is milliseconds even in a debug build + assert!(max(&match_us) < 200_000.0, "{} us", max(&match_us)); + assert!(max(&policy_us) < 2_000_000.0, "{} us", max(&policy_us)); + // sessions keep resuming close to their frontier: the hit rate stays high + assert!(reused as f64 / prompt_total as f64 > 0.5); +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor.rs b/crates/leleka-runtime/src/qwen_forward/executor.rs index b41d3210..dd00767f 100644 --- a/crates/leleka-runtime/src/qwen_forward/executor.rs +++ b/crates/leleka-runtime/src/qwen_forward/executor.rs @@ -1105,197 +1105,4 @@ fn validate_descriptors( } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn topology_validation_requires_the_exact_contiguous_closed_sequence() { - assert_eq!( - validate_descriptors( - 3, - [ - (0, BoundLayerKind::Gdn), - (1, BoundLayerKind::Qsa), - (2, BoundLayerKind::Gdn), - ] - .into_iter(), - ), - Ok(Dimension::new(3).unwrap()) - ); - assert_eq!( - validate_descriptors( - 2, - [(0, BoundLayerKind::Gdn), (0, BoundLayerKind::Qsa)].into_iter(), - ), - Err(Error::InvalidLayer) - ); - assert_eq!( - validate_descriptors( - 2, - [(0, BoundLayerKind::Gdn), (2, BoundLayerKind::Qsa)].into_iter(), - ), - Err(Error::InvalidLayer) - ); - assert_eq!( - validate_descriptors( - 1, - [(0, BoundLayerKind::Qsa), (1, BoundLayerKind::Gdn)].into_iter() - ), - Err(Error::InvalidDimension) - ); - assert_eq!( - validate_descriptors(0, std::iter::empty()), - Err(Error::InvalidDimension) - ); - } - - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - #[test] - #[ignore = "requires the two exact pinned IQ3_S GGUF shards and an available NVIDIA GPU"] - fn pinned_artifact_refuses_missing_output_before_layers_without_state_commit() { - use crate::model_binding::qwen4exp_input::ModelBinding; - use leleka_cuda_driver::Driver; - use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact}; - use std::{env, path::PathBuf, rc::Rc}; - - const SHARD0_SHA256: &str = - "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; - const SHARD1_SHA256: &str = - "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"; - - // Paths are supplied only by the operator for this ignored test; the - // artifact identities remain fixed in source and cannot be overridden. - let shard0_path = env::var_os("LELEKA_STRA169_IQ3S_SHARD0") - .map(PathBuf::from) - .unwrap_or_else(|| panic!("missing pinned shard 0 test path")); - let shard1_path = env::var_os("LELEKA_STRA169_IQ3S_SHARD1") - .map(PathBuf::from) - .unwrap_or_else(|| panic!("missing pinned shard 1 test path")); - - let shard0 = VerifiedGgufFile::open(&shard0_path, SHARD0_SHA256) - .unwrap_or_else(|_| panic!("pinned shard 0 verification failed")); - let shard1 = VerifiedGgufFile::open(&shard1_path, SHARD1_SHA256) - .unwrap_or_else(|_| panic!("pinned shard 1 verification failed")); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1) - .unwrap_or_else(|error| panic!("pinned Qwen artifact binding failed: {error}")); - let binding = ModelBinding::from_artifact(artifact) - .unwrap_or_else(|_| panic!("pinned runtime binding failed")); - - let driver = Driver::load().unwrap_or_else(|_| panic!("CUDA driver load failed")); - let device = driver - .device(0) - .unwrap_or_else(|_| panic!("CUDA device selection failed")); - let context = device - .create_context(64 * 1024 * 1024) - .unwrap_or_else(|_| panic!("CUDA context creation failed")); - let context = Rc::new(context); - let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); - - let token = TokenId::new(0, Dimension::new(248_320).unwrap()).unwrap(); - let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(); - let identity = binding.identity(); - assert_eq!( - QwenForward::step(&binding, token, position, &mut session), - Err(Error::Unsupported(Stage::Output)) - ); - - // Verify rollback in a no-GPU transaction at the same position. The - // deliberate error keeps this inspection transaction unpublished. - let state_probe = session.transact(token, position, &identity, |txn| { - assert_eq!(txn.input_predecessors()?, [-1, -1]); - let layers = Dimension::new(u64::from(binding.layer_count()))?; - for descriptor in binding.ordered_layers() { - let layer = LayerId::new(u64::from(descriptor.index()), layers)?; - match descriptor.kind() { - BoundLayerKind::Gdn => assert_eq!(txn.gdn_prior(layer)?.next_position(), 0), - BoundLayerKind::Qsa => assert_eq!(txn.qsa_prior(layer)?.next_position(), 0), - } - } - assert_eq!(txn.ple_prior()?.next_position(), 0); - Err(Error::NonFinite) - }); - assert_eq!(state_probe, Err(Error::NonFinite)); - } - - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - #[test] - #[ignore = "requires exact pinned shards, qualified QSA assets and an available NVIDIA GPU"] - fn pinned_artifact_two_tokens_finish_all_layers_and_commit_state() { - use crate::model_binding::qwen4exp_input::ModelBinding; - use leleka_cuda_driver::Driver; - use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact}; - use std::{env, path::PathBuf, rc::Rc}; - - let path = |name| { - env::var_os(name) - .map(PathBuf::from) - .expect("missing pinned test path") - }; - // Neither the supplied path nor the test can override the model identity. - let shard0 = VerifiedGgufFile::open( - &path("LELEKA_STRA169_IQ3S_SHARD0"), - "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3", - ) - .expect("pinned shard 0 verification failed"); - let shard1 = VerifiedGgufFile::open( - &path("LELEKA_STRA169_IQ3S_SHARD1"), - "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113", - ) - .expect("pinned shard 1 verification failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1) - .unwrap_or_else(|error| panic!("pinned artifact binding failed: {error}")); - let binding = ModelBinding::from_artifact(artifact).expect("runtime binding failed"); - eprintln!("integration: exact artifact and all role descriptors bound"); - - let driver = Driver::load().expect("CUDA driver load failed"); - let device = driver.device(0).expect("CUDA device selection failed"); - let context = Rc::new( - device - .create_context(1024 * 1024 * 1024) - .expect("CUDA context creation failed"), - ); - let output = - OutputStage::load(&binding, context.as_ref()).expect("output head load failed"); - let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); - let vocabulary = Dimension::new(248_320).unwrap(); - let context_length = crate::qwen_forward::contract::position_dimension(); - - // Synthetic public token IDs, never a captured user request. A finite - // bounded result proves composition only, not independent model parity. - for (position, id) in [0, 1].into_iter().enumerate() { - let token = TokenId::new(id, vocabulary).unwrap(); - let position = Position::new(position as u64, context_length).unwrap(); - let greedy = - QwenForward::step_with_output(&binding, token, position, &mut session, &output) - .unwrap_or_else(|error| { - panic!("full forward at {} failed: {error:?}", position.get()) - }); - assert!(greedy.get() < 248_320); - eprintln!( - "integration: 48 layers and finite head completed at {}, greedy={}", - position.get(), - greedy.get() - ); - } - let identity = binding.identity(); - let inspected = session.transact( - TokenId::new(1, vocabulary).unwrap(), - Position::new(2, context_length).unwrap(), - &identity, - |txn| { - assert_eq!(txn.input_predecessors()?, [0, 1]); - assert_eq!(txn.ple_prior()?.next_position(), 2); - let layers = Dimension::new(u64::from(binding.layer_count()))?; - for descriptor in binding.ordered_layers() { - let layer = LayerId::new(u64::from(descriptor.index()), layers)?; - match descriptor.kind() { - BoundLayerKind::Gdn => assert_eq!(txn.gdn_prior(layer)?.next_position(), 2), - BoundLayerKind::Qsa => assert_eq!(txn.qsa_prior(layer)?.next_position(), 2), - } - } - Err(Error::NonFinite) // Never publish the inspection transaction. - }, - ); - assert_eq!(inspected, Err(Error::NonFinite)); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/executor/tests.rs b/crates/leleka-runtime/src/qwen_forward/executor/tests.rs new file mode 100644 index 00000000..79f4ceb8 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/executor/tests.rs @@ -0,0 +1,194 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn topology_validation_requires_the_exact_contiguous_closed_sequence() { + assert_eq!( + validate_descriptors( + 3, + [ + (0, BoundLayerKind::Gdn), + (1, BoundLayerKind::Qsa), + (2, BoundLayerKind::Gdn), + ] + .into_iter(), + ), + Ok(Dimension::new(3).unwrap()) + ); + assert_eq!( + validate_descriptors( + 2, + [(0, BoundLayerKind::Gdn), (0, BoundLayerKind::Qsa)].into_iter(), + ), + Err(Error::InvalidLayer) + ); + assert_eq!( + validate_descriptors( + 2, + [(0, BoundLayerKind::Gdn), (2, BoundLayerKind::Qsa)].into_iter(), + ), + Err(Error::InvalidLayer) + ); + assert_eq!( + validate_descriptors( + 1, + [(0, BoundLayerKind::Qsa), (1, BoundLayerKind::Gdn)].into_iter() + ), + Err(Error::InvalidDimension) + ); + assert_eq!( + validate_descriptors(0, std::iter::empty()), + Err(Error::InvalidDimension) + ); +} + +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[test] +#[ignore = "requires the two exact pinned IQ3_S GGUF shards and an available NVIDIA GPU"] +fn pinned_artifact_refuses_missing_output_before_layers_without_state_commit() { + use crate::model_binding::qwen4exp_input::ModelBinding; + use leleka_cuda_driver::Driver; + use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact}; + use std::{env, path::PathBuf, rc::Rc}; + + const SHARD0_SHA256: &str = + "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; + const SHARD1_SHA256: &str = + "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"; + + // Paths are supplied only by the operator for this ignored test; the + // artifact identities remain fixed in source and cannot be overridden. + let shard0_path = env::var_os("LELEKA_STRA169_IQ3S_SHARD0") + .map(PathBuf::from) + .unwrap_or_else(|| panic!("missing pinned shard 0 test path")); + let shard1_path = env::var_os("LELEKA_STRA169_IQ3S_SHARD1") + .map(PathBuf::from) + .unwrap_or_else(|| panic!("missing pinned shard 1 test path")); + + let shard0 = VerifiedGgufFile::open(&shard0_path, SHARD0_SHA256) + .unwrap_or_else(|_| panic!("pinned shard 0 verification failed")); + let shard1 = VerifiedGgufFile::open(&shard1_path, SHARD1_SHA256) + .unwrap_or_else(|_| panic!("pinned shard 1 verification failed")); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1) + .unwrap_or_else(|error| panic!("pinned Qwen artifact binding failed: {error}")); + let binding = ModelBinding::from_artifact(artifact) + .unwrap_or_else(|_| panic!("pinned runtime binding failed")); + + let driver = Driver::load().unwrap_or_else(|_| panic!("CUDA driver load failed")); + let device = driver + .device(0) + .unwrap_or_else(|_| panic!("CUDA device selection failed")); + let context = device + .create_context(64 * 1024 * 1024) + .unwrap_or_else(|_| panic!("CUDA context creation failed")); + let context = Rc::new(context); + let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); + + let token = TokenId::new(0, Dimension::new(248_320).unwrap()).unwrap(); + let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(); + let identity = binding.identity(); + assert_eq!( + QwenForward::step(&binding, token, position, &mut session), + Err(Error::Unsupported(Stage::Output)) + ); + + // Verify rollback in a no-GPU transaction at the same position. The + // deliberate error keeps this inspection transaction unpublished. + let state_probe = session.transact(token, position, &identity, |txn| { + assert_eq!(txn.input_predecessors()?, [-1, -1]); + let layers = Dimension::new(u64::from(binding.layer_count()))?; + for descriptor in binding.ordered_layers() { + let layer = LayerId::new(u64::from(descriptor.index()), layers)?; + match descriptor.kind() { + BoundLayerKind::Gdn => assert_eq!(txn.gdn_prior(layer)?.next_position(), 0), + BoundLayerKind::Qsa => assert_eq!(txn.qsa_prior(layer)?.next_position(), 0), + } + } + assert_eq!(txn.ple_prior()?.next_position(), 0); + Err(Error::NonFinite) + }); + assert_eq!(state_probe, Err(Error::NonFinite)); +} + +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[test] +#[ignore = "requires exact pinned shards, qualified QSA assets and an available NVIDIA GPU"] +fn pinned_artifact_two_tokens_finish_all_layers_and_commit_state() { + use crate::model_binding::qwen4exp_input::ModelBinding; + use leleka_cuda_driver::Driver; + use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact}; + use std::{env, path::PathBuf, rc::Rc}; + + let path = |name| { + env::var_os(name) + .map(PathBuf::from) + .expect("missing pinned test path") + }; + // Neither the supplied path nor the test can override the model identity. + let shard0 = VerifiedGgufFile::open( + &path("LELEKA_STRA169_IQ3S_SHARD0"), + "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3", + ) + .expect("pinned shard 0 verification failed"); + let shard1 = VerifiedGgufFile::open( + &path("LELEKA_STRA169_IQ3S_SHARD1"), + "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113", + ) + .expect("pinned shard 1 verification failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1) + .unwrap_or_else(|error| panic!("pinned artifact binding failed: {error}")); + let binding = ModelBinding::from_artifact(artifact).expect("runtime binding failed"); + eprintln!("integration: exact artifact and all role descriptors bound"); + + let driver = Driver::load().expect("CUDA driver load failed"); + let device = driver.device(0).expect("CUDA device selection failed"); + let context = Rc::new( + device + .create_context(1024 * 1024 * 1024) + .expect("CUDA context creation failed"), + ); + let output = + OutputStage::load(&binding, context.as_ref()).expect("output head load failed"); + let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); + let vocabulary = Dimension::new(248_320).unwrap(); + let context_length = crate::qwen_forward::contract::position_dimension(); + + // Synthetic public token IDs, never a captured user request. A finite + // bounded result proves composition only, not independent model parity. + for (position, id) in [0, 1].into_iter().enumerate() { + let token = TokenId::new(id, vocabulary).unwrap(); + let position = Position::new(position as u64, context_length).unwrap(); + let greedy = + QwenForward::step_with_output(&binding, token, position, &mut session, &output) + .unwrap_or_else(|error| { + panic!("full forward at {} failed: {error:?}", position.get()) + }); + assert!(greedy.get() < 248_320); + eprintln!( + "integration: 48 layers and finite head completed at {}, greedy={}", + position.get(), + greedy.get() + ); + } + let identity = binding.identity(); + let inspected = session.transact( + TokenId::new(1, vocabulary).unwrap(), + Position::new(2, context_length).unwrap(), + &identity, + |txn| { + assert_eq!(txn.input_predecessors()?, [0, 1]); + assert_eq!(txn.ple_prior()?.next_position(), 2); + let layers = Dimension::new(u64::from(binding.layer_count()))?; + for descriptor in binding.ordered_layers() { + let layer = LayerId::new(u64::from(descriptor.index()), layers)?; + match descriptor.kind() { + BoundLayerKind::Gdn => assert_eq!(txn.gdn_prior(layer)?.next_position(), 2), + BoundLayerKind::Qsa => assert_eq!(txn.qsa_prior(layer)?.next_position(), 2), + } + } + Err(Error::NonFinite) // Never publish the inspection transaction. + }, + ); + assert_eq!(inspected, Err(Error::NonFinite)); +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_expert.rs b/crates/leleka-runtime/src/qwen_forward/moe_expert.rs index 5de4832d..5e138734 100644 --- a/crates/leleka-runtime/src/qwen_forward/moe_expert.rs +++ b/crates/leleka-runtime/src/qwen_forward/moe_expert.rs @@ -1076,58 +1076,4 @@ fn driver_error(error: DriverError) -> Error {if crate::bringup_trace_enabled()| #[path = "moe_activation_reuse_gpu.rs"] mod moe_activation_reuse_gpu; #[cfg(test)] -mod tests { - use super::*; - #[test] - fn completed_tiles_keep_all_rows_and_late_failure_withholds_candidate() { - let values = collect_rows(N, |first, count| { - Ok((first..first + count) - .map(|i| i as f32) - .collect::>() - .into_boxed_slice()) - }) - .unwrap(); - assert_eq!(values[0], 0.0); - assert_eq!(values[639], 639.0); - assert_eq!(values[2559], 2559.0); - for error in [ - Error::InputRead, - Error::InputAllocation, - Error::CudaExecution, - ] { - let mut calls = 0; - let result = collect_rows(N, |first, count| { - calls += 1; - if first == 2496 { - Err(error) - } else { - Ok(vec![1.0; count].into_boxed_slice()) - } - }); - assert_eq!(result, Err(error)); - assert_eq!(calls, 40); - } - assert_eq!( - collect_rows(639, |_, _| unreachable!()), - Err(Error::InvalidDimension) - ); - } - #[test] - fn nonfinite_last_expert_output_refuses_and_signedzero_is_retained() { - for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - let result = collect_rows(N, |first, count| { - let mut values = vec![-0.0; count]; - if first == 2496 { - values[63] = bad; - } - Ok(values.into_boxed_slice()) - }); - assert_eq!(result, Err(Error::NonFinite)); - } - let zeros = collect_rows(FF, |_, count| Ok(vec![-0.0; count].into_boxed_slice())).unwrap(); - assert!(zeros.iter().all(|v| v.to_bits() == 0x80000000)); - assert_eq!(admit_budget(1, DEVICE_PEAK + 1), Ok(())); - assert_eq!(admit_budget(1, DEVICE_PEAK), Err(Error::InputAllocation)); - assert_eq!(admit_budget(usize::MAX, usize::MAX), Err(Error::Overflow)); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/moe_expert/tests.rs b/crates/leleka-runtime/src/qwen_forward/moe_expert/tests.rs new file mode 100644 index 00000000..27c48869 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_expert/tests.rs @@ -0,0 +1,55 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +#[test] +fn completed_tiles_keep_all_rows_and_late_failure_withholds_candidate() { + let values = collect_rows(N, |first, count| { + Ok((first..first + count) + .map(|i| i as f32) + .collect::>() + .into_boxed_slice()) + }) + .unwrap(); + assert_eq!(values[0], 0.0); + assert_eq!(values[639], 639.0); + assert_eq!(values[2559], 2559.0); + for error in [ + Error::InputRead, + Error::InputAllocation, + Error::CudaExecution, + ] { + let mut calls = 0; + let result = collect_rows(N, |first, count| { + calls += 1; + if first == 2496 { + Err(error) + } else { + Ok(vec![1.0; count].into_boxed_slice()) + } + }); + assert_eq!(result, Err(error)); + assert_eq!(calls, 40); + } + assert_eq!( + collect_rows(639, |_, _| unreachable!()), + Err(Error::InvalidDimension) + ); +} +#[test] +fn nonfinite_last_expert_output_refuses_and_signedzero_is_retained() { + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let result = collect_rows(N, |first, count| { + let mut values = vec![-0.0; count]; + if first == 2496 { + values[63] = bad; + } + Ok(values.into_boxed_slice()) + }); + assert_eq!(result, Err(Error::NonFinite)); + } + let zeros = collect_rows(FF, |_, count| Ok(vec![-0.0; count].into_boxed_slice())).unwrap(); + assert!(zeros.iter().all(|v| v.to_bits() == 0x80000000)); + assert_eq!(admit_budget(1, DEVICE_PEAK + 1), Ok(())); + assert_eq!(admit_budget(1, DEVICE_PEAK), Err(Error::InputAllocation)); + assert_eq!(admit_budget(usize::MAX, usize::MAX), Err(Error::Overflow)); +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_prefill_batch.rs b/crates/leleka-runtime/src/qwen_forward/moe_prefill_batch.rs index c5c21b87..5200e518 100644 --- a/crates/leleka-runtime/src/qwen_forward/moe_prefill_batch.rs +++ b/crates/leleka-runtime/src/qwen_forward/moe_prefill_batch.rs @@ -733,103 +733,4 @@ impl MoePrefillStage { } #[cfg(test)] -mod tests { - use super::*; - - fn descending() -> ([i32; SELECTED], [f32; SELECTED]) { - ( - std::array::from_fn(|i| (i * 7) as i32), - std::array::from_fn(|i| 0.2 - i as f32 * 0.01), - ) - } - - #[test] - fn a_route_row_needs_distinct_in_range_ids_and_finite_ordered_unit_weights() { - let (ids, weights) = descending(); - assert!(validate_route_row(&ids, &weights).is_ok()); - // Equal weights are valid (distinct probabilities may round together). - assert!(validate_route_row(&ids, &[0.1; SELECTED]).is_ok()); - let mut duplicate = ids; - duplicate[3] = duplicate[1]; - assert_eq!( - validate_route_row(&duplicate, &weights), - Err(Error::InvalidExpert) - ); - let mut high = ids; - high[0] = EXPERTS as i32; - assert_eq!( - validate_route_row(&high, &weights), - Err(Error::InvalidExpert) - ); - let mut negative = ids; - negative[0] = -1; - assert_eq!( - validate_route_row(&negative, &weights), - Err(Error::InvalidExpert) - ); - let mut nan = weights; - nan[2] = f32::NAN; - assert_eq!(validate_route_row(&ids, &nan), Err(Error::NonFinite)); - let mut over = weights; - over[0] = 1.5; - assert_eq!( - validate_route_row(&ids, &over), - Err(Error::InvalidDimension) - ); - let mut rising = weights; - rising.swap(0, 9); - assert_eq!( - validate_route_row(&ids, &rising), - Err(Error::InvalidDimension) - ); - } - - #[test] - fn shared_formats_are_the_six_real_native_kinds() { - let key = |raw_kind| MoeWeightDescriptor { - layer: 0, - expert: None, - role: 0, - raw_kind, - columns: MIXED, - rows: FF, - bytes: 0, - }; - for (raw, format) in [ - (12, GdnNativeFormat::Q4K), - (13, GdnNativeFormat::Q5K), - (14, GdnNativeFormat::Q6K), - (23, GdnNativeFormat::Iq4Xs), - ] { - assert_eq!(gate_up_format(key(raw)).unwrap(), format); - } - for (raw, format) in [(8, GdnNativeFormat::Q8_0), (20, GdnNativeFormat::Iq4Nl)] { - assert_eq!(down_format(key(raw)).unwrap(), format); - } - assert!(gate_up_format(key(8)).is_err()); - assert!(down_format(key(12)).is_err()); - } - - #[test] - fn device_bytes_follow_the_prompt_path_buffer_set() { - let high = device_bytes(64, MoeBf16Profile::HighOnly, false).unwrap(); - let low = device_bytes(64, MoeBf16Profile::HighPlusLow, false).unwrap(); - assert_eq!(low - high, 64 * MIXED * 2); - let combined = device_bytes(64, MoeBf16Profile::HighOnly, true).unwrap(); - assert_eq!(combined - high, 64 * MIXED * 4); - // 64 rows: mixed 655,360 + images 2 x 327,680 + logits 131,072 + ids/weights 2 x 2,560 - // + sgate/sup 2 x 163,840 + H 81,920 + shared 655,360 + sg 256. - assert_eq!( - high, - 655_360 + 2 * 327_680 + 131_072 + 2 * 2_560 + 2 * 163_840 + 81_920 + 655_360 + 256 - ); - } - - #[test] - fn f32_staging_is_little_endian() { - assert_eq!( - f32_bytes(&[1.0, -2.0]).unwrap(), - [0, 0, 128, 63, 0, 0, 0, 192] - ); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/moe_prefill_batch/tests.rs b/crates/leleka-runtime/src/qwen_forward/moe_prefill_batch/tests.rs new file mode 100644 index 00000000..3e604eaf --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_prefill_batch/tests.rs @@ -0,0 +1,100 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn descending() -> ([i32; SELECTED], [f32; SELECTED]) { + ( + std::array::from_fn(|i| (i * 7) as i32), + std::array::from_fn(|i| 0.2 - i as f32 * 0.01), + ) +} + +#[test] +fn a_route_row_needs_distinct_in_range_ids_and_finite_ordered_unit_weights() { + let (ids, weights) = descending(); + assert!(validate_route_row(&ids, &weights).is_ok()); + // Equal weights are valid (distinct probabilities may round together). + assert!(validate_route_row(&ids, &[0.1; SELECTED]).is_ok()); + let mut duplicate = ids; + duplicate[3] = duplicate[1]; + assert_eq!( + validate_route_row(&duplicate, &weights), + Err(Error::InvalidExpert) + ); + let mut high = ids; + high[0] = EXPERTS as i32; + assert_eq!( + validate_route_row(&high, &weights), + Err(Error::InvalidExpert) + ); + let mut negative = ids; + negative[0] = -1; + assert_eq!( + validate_route_row(&negative, &weights), + Err(Error::InvalidExpert) + ); + let mut nan = weights; + nan[2] = f32::NAN; + assert_eq!(validate_route_row(&ids, &nan), Err(Error::NonFinite)); + let mut over = weights; + over[0] = 1.5; + assert_eq!( + validate_route_row(&ids, &over), + Err(Error::InvalidDimension) + ); + let mut rising = weights; + rising.swap(0, 9); + assert_eq!( + validate_route_row(&ids, &rising), + Err(Error::InvalidDimension) + ); +} + +#[test] +fn shared_formats_are_the_six_real_native_kinds() { + let key = |raw_kind| MoeWeightDescriptor { + layer: 0, + expert: None, + role: 0, + raw_kind, + columns: MIXED, + rows: FF, + bytes: 0, + }; + for (raw, format) in [ + (12, GdnNativeFormat::Q4K), + (13, GdnNativeFormat::Q5K), + (14, GdnNativeFormat::Q6K), + (23, GdnNativeFormat::Iq4Xs), + ] { + assert_eq!(gate_up_format(key(raw)).unwrap(), format); + } + for (raw, format) in [(8, GdnNativeFormat::Q8_0), (20, GdnNativeFormat::Iq4Nl)] { + assert_eq!(down_format(key(raw)).unwrap(), format); + } + assert!(gate_up_format(key(8)).is_err()); + assert!(down_format(key(12)).is_err()); +} + +#[test] +fn device_bytes_follow_the_prompt_path_buffer_set() { + let high = device_bytes(64, MoeBf16Profile::HighOnly, false).unwrap(); + let low = device_bytes(64, MoeBf16Profile::HighPlusLow, false).unwrap(); + assert_eq!(low - high, 64 * MIXED * 2); + let combined = device_bytes(64, MoeBf16Profile::HighOnly, true).unwrap(); + assert_eq!(combined - high, 64 * MIXED * 4); + // 64 rows: mixed 655,360 + images 2 x 327,680 + logits 131,072 + ids/weights 2 x 2,560 + // + sgate/sup 2 x 163,840 + H 81,920 + shared 655,360 + sg 256. + assert_eq!( + high, + 655_360 + 2 * 327_680 + 131_072 + 2 * 2_560 + 2 * 163_840 + 81_920 + 655_360 + 256 + ); +} + +#[test] +fn f32_staging_is_little_endian() { + assert_eq!( + f32_bytes(&[1.0, -2.0]).unwrap(), + [0, 0, 128, 63, 0, 0, 0, 192] + ); +} diff --git a/crates/leleka-runtime/src/qwen_forward/mtp_attention.rs b/crates/leleka-runtime/src/qwen_forward/mtp_attention.rs index 4708a988..cc83a4c3 100644 --- a/crates/leleka-runtime/src/qwen_forward/mtp_attention.rs +++ b/crates/leleka-runtime/src/qwen_forward/mtp_attention.rs @@ -683,51 +683,4 @@ fn apply_gate(context: &Context<'_>, values: &[f32], gate: &[f32]) -> Result Result<()> { Ok(()) } #[cfg(test)] -mod tests { - use super::*; - fn fixture(rows: usize, blocks: usize, salt: u8) -> Vec { - let mut bytes = vec![0; rows * blocks * 18]; - for row in 0..rows { - for block in 0..blocks { - let at = (row * blocks + block) * 18; - // Independent byte labels, including signedzero/subnormal scales. - let half = [0x8000u16, 0x0001, 0x3c00, 0xbc00][block % 4]; - bytes[at..at + 2].copy_from_slice(&half.to_le_bytes()); - for lane in 0..16 { - bytes[at + 2 + lane] = salt - .wrapping_add(row as u8) - .wrapping_add((block * 3 + lane) as u8); - } - } - } - bytes - } - #[test] - fn mtp_experts_new_gate_up_tiles_preserve_every_label() { - let gate = fixture(16, 40, 11); - let up = fixture(16, 40, 97); - let tile = gate_up_tile(&gate, &up).unwrap(); - assert_eq!((tile.codes.len(), tile.scales.len()), (20480, 2560)); - for row in 0..16 { - for (kind, source) in [&gate, &up].into_iter().enumerate() { - for block in 0..40 { - let input = (row * 40 + block) * 18; - let packed = (2 * row + kind) * 40 + block; - assert_eq!( - &tile.scales[packed * 2..packed * 2 + 2], - &source[input..input + 2] - ); - assert_eq!( - &tile.codes[packed * 16..packed * 16 + 16], - &source[input + 2..input + 18] - ); - } - } - } - } - #[test] - fn mtp_experts_new_down_tiles_preserve_every_label() { - let rows = fixture(64, 10, 37); - let tile = down_tile(&rows).unwrap(); - assert_eq!((tile.codes.len(), tile.scales.len()), (10240, 1280)); - for block in 0..640 { - assert_eq!( - &tile.scales[block * 2..block * 2 + 2], - &rows[block * 18..block * 18 + 2] - ); - assert_eq!( - &tile.codes[block * 16..block * 16 + 16], - &rows[block * 18 + 2..block * 18 + 18] - ); - } - } - #[test] - fn mtp_experts_new_adapter_refuses_shape_and_nonfinite_scales() { - let gate = fixture(16, 40, 3); - assert!(matches!( - gate_up_tile(&gate[..gate.len() - 1], &gate), - Err(Error::InvalidDimension) - )); - assert!(matches!(down_tile(&[0; 1]), Err(Error::InvalidDimension))); - for raw in [0x7c00u16, 0xfc00, 0x7e00] { - let mut bad = gate.clone(); - let last = bad.len() - 18; - bad[last..last + 2].copy_from_slice(&raw.to_le_bytes()); - assert!(matches!(gate_up_tile(&bad, &gate), Err(Error::NonFinite))); - } - } - #[test] - fn mtp_experts_new_route_refuses_duplicate_range_and_weights() { - let ids = [511, 0, 31, 7, 9, 255, 256, 3, 4, 5]; - let weights = [0.1; K]; - assert_eq!( - validate_route(ids, &weights).unwrap(), - ids.map(|id| id as u32) - ); - for (slot, value) in [(9, -1), (9, 512), (9, 511)] { - let mut bad = ids; - bad[slot] = value; - assert_eq!(validate_route(bad, &weights), Err(Error::InvalidExpert)); - } - for value in [f32::NAN, f32::INFINITY, -0.01, 1.01] { - let mut bad = weights; - bad[9] = value; - assert_eq!(validate_route(ids, &bad), Err(Error::NonFinite)); - } - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/mtp_experts/tests.rs b/crates/leleka-runtime/src/qwen_forward/mtp_experts/tests.rs new file mode 100644 index 00000000..5b4faaec --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/mtp_experts/tests.rs @@ -0,0 +1,93 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +fn fixture(rows: usize, blocks: usize, salt: u8) -> Vec { + let mut bytes = vec![0; rows * blocks * 18]; + for row in 0..rows { + for block in 0..blocks { + let at = (row * blocks + block) * 18; + // Independent byte labels, including signedzero/subnormal scales. + let half = [0x8000u16, 0x0001, 0x3c00, 0xbc00][block % 4]; + bytes[at..at + 2].copy_from_slice(&half.to_le_bytes()); + for lane in 0..16 { + bytes[at + 2 + lane] = salt + .wrapping_add(row as u8) + .wrapping_add((block * 3 + lane) as u8); + } + } + } + bytes +} +#[test] +fn mtp_experts_new_gate_up_tiles_preserve_every_label() { + let gate = fixture(16, 40, 11); + let up = fixture(16, 40, 97); + let tile = gate_up_tile(&gate, &up).unwrap(); + assert_eq!((tile.codes.len(), tile.scales.len()), (20480, 2560)); + for row in 0..16 { + for (kind, source) in [&gate, &up].into_iter().enumerate() { + for block in 0..40 { + let input = (row * 40 + block) * 18; + let packed = (2 * row + kind) * 40 + block; + assert_eq!( + &tile.scales[packed * 2..packed * 2 + 2], + &source[input..input + 2] + ); + assert_eq!( + &tile.codes[packed * 16..packed * 16 + 16], + &source[input + 2..input + 18] + ); + } + } + } +} +#[test] +fn mtp_experts_new_down_tiles_preserve_every_label() { + let rows = fixture(64, 10, 37); + let tile = down_tile(&rows).unwrap(); + assert_eq!((tile.codes.len(), tile.scales.len()), (10240, 1280)); + for block in 0..640 { + assert_eq!( + &tile.scales[block * 2..block * 2 + 2], + &rows[block * 18..block * 18 + 2] + ); + assert_eq!( + &tile.codes[block * 16..block * 16 + 16], + &rows[block * 18 + 2..block * 18 + 18] + ); + } +} +#[test] +fn mtp_experts_new_adapter_refuses_shape_and_nonfinite_scales() { + let gate = fixture(16, 40, 3); + assert!(matches!( + gate_up_tile(&gate[..gate.len() - 1], &gate), + Err(Error::InvalidDimension) + )); + assert!(matches!(down_tile(&[0; 1]), Err(Error::InvalidDimension))); + for raw in [0x7c00u16, 0xfc00, 0x7e00] { + let mut bad = gate.clone(); + let last = bad.len() - 18; + bad[last..last + 2].copy_from_slice(&raw.to_le_bytes()); + assert!(matches!(gate_up_tile(&bad, &gate), Err(Error::NonFinite))); + } +} +#[test] +fn mtp_experts_new_route_refuses_duplicate_range_and_weights() { + let ids = [511, 0, 31, 7, 9, 255, 256, 3, 4, 5]; + let weights = [0.1; K]; + assert_eq!( + validate_route(ids, &weights).unwrap(), + ids.map(|id| id as u32) + ); + for (slot, value) in [(9, -1), (9, 512), (9, 511)] { + let mut bad = ids; + bad[slot] = value; + assert_eq!(validate_route(bad, &weights), Err(Error::InvalidExpert)); + } + for value in [f32::NAN, f32::INFINITY, -0.01, 1.01] { + let mut bad = weights; + bad[9] = value; + assert_eq!(validate_route(ids, &bad), Err(Error::NonFinite)); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/mtp_state.rs b/crates/leleka-runtime/src/qwen_forward/mtp_state.rs index 638d87ff..ada01223 100644 --- a/crates/leleka-runtime/src/qwen_forward/mtp_state.rs +++ b/crates/leleka-runtime/src/qwen_forward/mtp_state.rs @@ -527,287 +527,5 @@ impl Drop for MtpCheckpoint { } #[cfg(test)] -mod tests { - use super::*; - use crate::qwen_forward::session::QwenSession; - fn draft() -> (MtpSession, MtpFrame) { - let binding = BindingIdentity::test_identity(); - let target = QwenSession::test_session(binding.clone()); - let epoch = Rc::new(Cell::new(0)); - let frame = MtpFrame { - binding: binding.clone(), - token: TokenId::new(1, Dimension::new(248320).unwrap()).unwrap(), - position: Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(), - origin: target.target_origin().unwrap(), - epoch: Rc::clone(&epoch), - generation: 0, - depth: 0, - }; - let draft = MtpSession { - binding: binding.clone(), - epoch: Rc::clone(&epoch), - next_position: 0, - kv: DenseKv::empty(binding, epoch), - residual: None, - target_owner: None, - retained: Rc::new(Cell::new(0)), - }; - (draft, frame) - } - fn pending(draft: &MtpSession, frame: &MtpFrame) -> DenseKv { - draft - .kv - .append( - frame, - vec![0; HALF_ROW].into_boxed_slice(), - vec![0; HALF_ROW].into_boxed_slice(), - ) - .unwrap() - } - // Metadata/lineage tests only: these synthetic sessions do not certify a - // real target producer, CUDA completion or numerical model equivalence. - #[test] - fn first_seed_restore_keeps_real_snapshot_and_original_rollback() { - for extra_prediction in [false, true] { - let (mut draft, frame) = draft(); - let mut original = draft.checkpoint().unwrap(); - let initial_cells = Rc::clone(&original.kv.cells); - let admitted = draft.first_seed_host_charge().unwrap(); - let first = pending(&draft, &frame); - draft.commit(&frame, first, vec![1.0; 10240].into_boxed_slice()).unwrap(); - let seed = draft.checkpoint_first_seed(admitted).unwrap(); - let seed_cells = Rc::clone(&seed.kv.cells); - let seed_residual = Rc::clone(seed.residual.as_ref().unwrap()); - if extra_prediction { - let mut next = frame.clone(); - next.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(); - next.depth = 1; - let tail = pending(&draft, &next); - draft.commit(&next, tail, vec![2.0; 10240].into_boxed_slice()).unwrap(); - } - draft.restore_first_seed_checked(&frame, &seed, &mut original).unwrap(); - assert_eq!(draft.next_position, 1); - assert_eq!(draft.epoch.get(), 1); - assert_eq!(original.generation, 1); - assert!(Rc::ptr_eq(&draft.kv.cells, &seed_cells)); - assert!(Rc::ptr_eq(draft.residual.as_ref().unwrap(), &seed_residual)); - let mut restored_frame = frame.clone(); - restored_frame.generation = 1; - assert!(draft.kv.ring_validate(&restored_frame).is_ok()); - let (keys, values) = draft.kv.window(&restored_frame).unwrap(); - assert_eq!(keys.as_ref(), &[0; HALF_ROW]); - assert_eq!(values.as_ref(), &[0; HALF_ROW]); - assert_eq!(draft.kv.produced.as_ref().unwrap().token, frame.token); - // Seed/other old snapshots remain stale; only coupled original is reminted. - assert_eq!(draft.restore(&seed), Err(Error::IdentityMismatch)); - draft.restore(&original).unwrap(); - assert_eq!(draft.next_position, 0); - assert!(Rc::ptr_eq(&draft.kv.cells, &initial_cells)); - assert!(draft.residual.is_none()); - assert!(draft.target_owner.is_none()); - drop(seed); - drop(original); - assert_eq!(draft.retained.get(), 0); - } - } - - #[test] - fn first_seed_coupled_refusal_never_remints_or_mutates() { - for fault in 0..11 { - let (mut draft, frame) = draft(); - let mut original = draft.checkpoint().unwrap(); - let first = pending(&draft, &frame); - draft.commit(&frame, first, vec![0.0; 10240].into_boxed_slice()).unwrap(); - let mut seed = draft.checkpoint().unwrap(); - let real_retained = Rc::clone(&seed.retained); - let mut expected = frame.clone(); - match fault { - 0 => original.generation = 1, - 1 => seed.retained = Rc::new(Cell::new(1)), - 2 => seed.kv.parent = Weak::new(), - 3 => expected.token = TokenId::new(2, Dimension::new(248320).unwrap()).unwrap(), - 4 => original.binding = BindingIdentity::test_identity(), - 5 => seed.next_position = 2, - 6 => { - let unrelated = pending(&MtpSession { - binding: draft.binding.clone(), epoch: Rc::clone(&draft.epoch), - next_position: 0, kv: original.kv.clone(), residual: None, - target_owner: None, retained: Rc::clone(&draft.retained), - }, &frame); - draft.kv = unrelated; - } - 7 => { - draft.epoch.set(u64::MAX); - original.generation = u64::MAX; - seed.generation = u64::MAX; - expected.generation = u64::MAX; - seed.kv.produced.as_mut().unwrap().generation = u64::MAX; - draft.kv.produced.as_mut().unwrap().generation = u64::MAX; - } - 8 => seed.epoch = Rc::new(Cell::new(0)), - 9 => expected.origin = QwenSession::test_session(frame.binding.clone()).target_origin().unwrap(), - 10 => { - let mut invalid = vec![0.0; 10240]; - invalid[10239] = f32::NAN; - seed.residual = Some(Rc::new(invalid.into_boxed_slice())); - draft.residual = seed.residual.clone(); - } - _ => unreachable!(), - } - let cells = Rc::clone(&draft.kv.cells); - let residual = Rc::clone(draft.residual.as_ref().unwrap()); - let generation = draft.epoch.get(); - let original_generation = original.generation; - let result = draft.restore_first_seed_checked(&expected, &seed, &mut original); - let expected_error = match fault { - 7 => Error::Overflow, - 10 => Error::NonFinite, - _ => Error::IdentityMismatch, - }; - assert_eq!(result, Err(expected_error)); - assert_eq!(draft.epoch.get(), generation); - assert_eq!(original.generation, original_generation); - assert_eq!(draft.next_position, 1); - assert!(Rc::ptr_eq(&draft.kv.cells, &cells)); - assert!(Rc::ptr_eq(draft.residual.as_ref().unwrap(), &residual)); - seed.retained = real_retained; - } - } - - #[test] - fn first_seed_actual_capacity_and_existing_five_checkpoint_cap() { - let (mut draft, frame) = draft(); - let admitted = draft.first_seed_host_charge().unwrap(); - let first = pending(&draft, &frame); - draft.commit(&frame, first, vec![0.0; 10240].into_boxed_slice()).unwrap(); - let actual = first_seed_retained_charge(draft.kv.cells.capacity()).unwrap(); - assert!(actual <= admitted); - assert!(matches!(draft.checkpoint_first_seed(actual - 1), Err(Error::InputAllocation))); - assert_eq!(draft.retained.get(), 0); - let mut retained = Vec::new(); - for _ in 0..5 { retained.push(draft.checkpoint_first_seed(actual).unwrap()); } - assert!(matches!(draft.checkpoint_first_seed(actual), Err(Error::InputAllocation))); - assert_eq!(draft.retained.get(), 5); - drop(retained); - assert_eq!(draft.retained.get(), 0); - assert_eq!(first_seed_retained_charge(usize::MAX), Err(Error::Overflow)); - } - - #[test] - fn ring_requires_exact_parent_epoch_and_branch() { - let (mut draft, frame) = draft(); - let first = pending(&draft, &frame); - assert!(first.ring_same(&first.clone(), &frame).unwrap()); - draft - .commit(&frame, first.clone(), vec![0.0; 10240].into_boxed_slice()) - .unwrap(); - let mut next_frame = frame.clone(); - next_frame.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(); - let next = pending(&draft, &next_frame); - assert!(next.ring_append(&first, &next_frame).unwrap()); - let branch = pending(&draft, &next_frame); - assert!(!branch.ring_same(&next, &next_frame).unwrap()); - assert!(!branch.ring_append(&next, &next_frame).unwrap()); - let mut unrelated = first.clone(); - unrelated.owner = Rc::new(Cell::new(0)); - assert!(!next.ring_append(&unrelated, &next_frame).unwrap()); - draft.epoch.set(1); - assert_eq!( - next.ring_validate(&next_frame), - Err(Error::IdentityMismatch) - ); - next_frame.generation = 1; - assert_eq!( - next.ring_validate(&next_frame), - Err(Error::IdentityMismatch) - ); - } - #[test] - fn ring_restore_requires_reload_for_old_numerical_mirror() { - let (mut draft, frame) = draft(); - let first = pending(&draft, &frame); - draft - .commit(&frame, first.clone(), vec![0.0; 10240].into_boxed_slice()) - .unwrap(); - let checkpoint = draft.checkpoint().unwrap(); - let mut next_frame = frame.clone(); - next_frame.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(); - let second = pending(&draft, &next_frame); - draft - .commit(&next_frame, second, vec![0.0; 10240].into_boxed_slice()) - .unwrap(); - draft.restore(&checkpoint).unwrap(); - next_frame.generation = draft.epoch.get(); - let restored = pending(&draft, &next_frame); - assert!(restored.ring_validate(&next_frame).is_ok()); - assert!(!restored.ring_append(&first, &next_frame).unwrap()); - assert!(!restored.ring_same(&first, &next_frame).unwrap()); - } - #[test] - fn ring_parent_is_weak_and_half_cell_refuses_nonfinite() { - let (draft, frame) = draft(); - let initial = Rc::downgrade(&draft.kv.cells); - let first = pending(&draft, &frame); - assert!(first.parent.upgrade().is_some()); - drop(draft); - assert!(initial.upgrade().is_none()); - assert!(first.parent.upgrade().is_none()); - let mut bad = vec![0_u8; HALF_ROW]; - bad[1] = 0x7c; - assert_eq!(validate_half(&bad), Err(Error::NonFinite)); - } - #[test] - fn mtp_new_pending_token_epoch_and_residual_refuse_atomically() { - let (mut draft, frame) = draft(); - let stale = pending(&draft, &frame); - let mut wrong = frame.clone(); - wrong.token = TokenId::new(2, Dimension::new(248320).unwrap()).unwrap(); - assert_eq!( - draft.commit(&wrong, stale.clone(), vec![0.0; 10240].into_boxed_slice()), - Err(Error::IdentityMismatch) - ); - assert_eq!(draft.next_position, 0); - let initial = draft.checkpoint().unwrap(); - draft.restore(&initial).unwrap(); - wrong.generation = 1; - assert_eq!( - draft.commit(&wrong, stale, vec![0.0; 10240].into_boxed_slice()), - Err(Error::IdentityMismatch) - ); - let fresh = pending(&draft, &wrong); - let mut invalid = vec![0.0; 10240]; - invalid[10239] = f32::NAN; - assert_eq!( - draft.commit(&wrong, fresh.clone(), invalid.into_boxed_slice()), - Err(Error::NonFinite) - ); - assert_eq!(draft.next_position, 0); - assert!(draft.residual.is_none()); - draft - .commit(&wrong, fresh, vec![0.0; 10240].into_boxed_slice()) - .unwrap(); - assert_eq!(draft.next_position, 1); - assert_eq!(draft.residual.as_ref().unwrap().len(), 10240); - } - #[test] - fn mtp_new_checkpoint_cap_and_current_target_prefix() { - let (draft, frame) = draft(); - let identity = frame.binding.clone(); - let mut target = QwenSession::test_session(identity); - let mut other = frame.clone(); - other.origin = target.target_origin().unwrap(); - assert!(!other.same(&frame)); - let prior = target.checkpoint().unwrap(); - let old = other.clone(); - target.restore_checkpoint(&prior).unwrap(); - other.origin = target.target_origin().unwrap(); - assert!(!other.same(&old)); - let mut retained = Vec::new(); - for _ in 0..5 { - retained.push(draft.checkpoint().unwrap()); - } - assert!(matches!(draft.checkpoint(), Err(Error::InputAllocation))); - retained.pop(); - assert!(draft.checkpoint().is_ok()); - } -} +#[path = "mtp_state/tests.rs"] +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/mtp_state/tests.rs b/crates/leleka-runtime/src/qwen_forward/mtp_state/tests.rs new file mode 100644 index 00000000..84828581 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/mtp_state/tests.rs @@ -0,0 +1,284 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::qwen_forward::session::QwenSession; +fn draft() -> (MtpSession, MtpFrame) { + let binding = BindingIdentity::test_identity(); + let target = QwenSession::test_session(binding.clone()); + let epoch = Rc::new(Cell::new(0)); + let frame = MtpFrame { + binding: binding.clone(), + token: TokenId::new(1, Dimension::new(248320).unwrap()).unwrap(), + position: Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(), + origin: target.target_origin().unwrap(), + epoch: Rc::clone(&epoch), + generation: 0, + depth: 0, + }; + let draft = MtpSession { + binding: binding.clone(), + epoch: Rc::clone(&epoch), + next_position: 0, + kv: DenseKv::empty(binding, epoch), + residual: None, + target_owner: None, + retained: Rc::new(Cell::new(0)), + }; + (draft, frame) +} +fn pending(draft: &MtpSession, frame: &MtpFrame) -> DenseKv { + draft + .kv + .append( + frame, + vec![0; HALF_ROW].into_boxed_slice(), + vec![0; HALF_ROW].into_boxed_slice(), + ) + .unwrap() +} +// Metadata/lineage tests only: these synthetic sessions do not certify a +// real target producer, CUDA completion or numerical model equivalence. +#[test] +fn first_seed_restore_keeps_real_snapshot_and_original_rollback() { + for extra_prediction in [false, true] { + let (mut draft, frame) = draft(); + let mut original = draft.checkpoint().unwrap(); + let initial_cells = Rc::clone(&original.kv.cells); + let admitted = draft.first_seed_host_charge().unwrap(); + let first = pending(&draft, &frame); + draft.commit(&frame, first, vec![1.0; 10240].into_boxed_slice()).unwrap(); + let seed = draft.checkpoint_first_seed(admitted).unwrap(); + let seed_cells = Rc::clone(&seed.kv.cells); + let seed_residual = Rc::clone(seed.residual.as_ref().unwrap()); + if extra_prediction { + let mut next = frame.clone(); + next.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(); + next.depth = 1; + let tail = pending(&draft, &next); + draft.commit(&next, tail, vec![2.0; 10240].into_boxed_slice()).unwrap(); + } + draft.restore_first_seed_checked(&frame, &seed, &mut original).unwrap(); + assert_eq!(draft.next_position, 1); + assert_eq!(draft.epoch.get(), 1); + assert_eq!(original.generation, 1); + assert!(Rc::ptr_eq(&draft.kv.cells, &seed_cells)); + assert!(Rc::ptr_eq(draft.residual.as_ref().unwrap(), &seed_residual)); + let mut restored_frame = frame.clone(); + restored_frame.generation = 1; + assert!(draft.kv.ring_validate(&restored_frame).is_ok()); + let (keys, values) = draft.kv.window(&restored_frame).unwrap(); + assert_eq!(keys.as_ref(), &[0; HALF_ROW]); + assert_eq!(values.as_ref(), &[0; HALF_ROW]); + assert_eq!(draft.kv.produced.as_ref().unwrap().token, frame.token); + // Seed/other old snapshots remain stale; only coupled original is reminted. + assert_eq!(draft.restore(&seed), Err(Error::IdentityMismatch)); + draft.restore(&original).unwrap(); + assert_eq!(draft.next_position, 0); + assert!(Rc::ptr_eq(&draft.kv.cells, &initial_cells)); + assert!(draft.residual.is_none()); + assert!(draft.target_owner.is_none()); + drop(seed); + drop(original); + assert_eq!(draft.retained.get(), 0); + } +} + +#[test] +fn first_seed_coupled_refusal_never_remints_or_mutates() { + for fault in 0..11 { + let (mut draft, frame) = draft(); + let mut original = draft.checkpoint().unwrap(); + let first = pending(&draft, &frame); + draft.commit(&frame, first, vec![0.0; 10240].into_boxed_slice()).unwrap(); + let mut seed = draft.checkpoint().unwrap(); + let real_retained = Rc::clone(&seed.retained); + let mut expected = frame.clone(); + match fault { + 0 => original.generation = 1, + 1 => seed.retained = Rc::new(Cell::new(1)), + 2 => seed.kv.parent = Weak::new(), + 3 => expected.token = TokenId::new(2, Dimension::new(248320).unwrap()).unwrap(), + 4 => original.binding = BindingIdentity::test_identity(), + 5 => seed.next_position = 2, + 6 => { + let unrelated = pending(&MtpSession { + binding: draft.binding.clone(), epoch: Rc::clone(&draft.epoch), + next_position: 0, kv: original.kv.clone(), residual: None, + target_owner: None, retained: Rc::clone(&draft.retained), + }, &frame); + draft.kv = unrelated; + } + 7 => { + draft.epoch.set(u64::MAX); + original.generation = u64::MAX; + seed.generation = u64::MAX; + expected.generation = u64::MAX; + seed.kv.produced.as_mut().unwrap().generation = u64::MAX; + draft.kv.produced.as_mut().unwrap().generation = u64::MAX; + } + 8 => seed.epoch = Rc::new(Cell::new(0)), + 9 => expected.origin = QwenSession::test_session(frame.binding.clone()).target_origin().unwrap(), + 10 => { + let mut invalid = vec![0.0; 10240]; + invalid[10239] = f32::NAN; + seed.residual = Some(Rc::new(invalid.into_boxed_slice())); + draft.residual = seed.residual.clone(); + } + _ => unreachable!(), + } + let cells = Rc::clone(&draft.kv.cells); + let residual = Rc::clone(draft.residual.as_ref().unwrap()); + let generation = draft.epoch.get(); + let original_generation = original.generation; + let result = draft.restore_first_seed_checked(&expected, &seed, &mut original); + let expected_error = match fault { + 7 => Error::Overflow, + 10 => Error::NonFinite, + _ => Error::IdentityMismatch, + }; + assert_eq!(result, Err(expected_error)); + assert_eq!(draft.epoch.get(), generation); + assert_eq!(original.generation, original_generation); + assert_eq!(draft.next_position, 1); + assert!(Rc::ptr_eq(&draft.kv.cells, &cells)); + assert!(Rc::ptr_eq(draft.residual.as_ref().unwrap(), &residual)); + seed.retained = real_retained; + } +} + +#[test] +fn first_seed_actual_capacity_and_existing_five_checkpoint_cap() { + let (mut draft, frame) = draft(); + let admitted = draft.first_seed_host_charge().unwrap(); + let first = pending(&draft, &frame); + draft.commit(&frame, first, vec![0.0; 10240].into_boxed_slice()).unwrap(); + let actual = first_seed_retained_charge(draft.kv.cells.capacity()).unwrap(); + assert!(actual <= admitted); + assert!(matches!(draft.checkpoint_first_seed(actual - 1), Err(Error::InputAllocation))); + assert_eq!(draft.retained.get(), 0); + let mut retained = Vec::new(); + for _ in 0..5 { retained.push(draft.checkpoint_first_seed(actual).unwrap()); } + assert!(matches!(draft.checkpoint_first_seed(actual), Err(Error::InputAllocation))); + assert_eq!(draft.retained.get(), 5); + drop(retained); + assert_eq!(draft.retained.get(), 0); + assert_eq!(first_seed_retained_charge(usize::MAX), Err(Error::Overflow)); +} + +#[test] +fn ring_requires_exact_parent_epoch_and_branch() { + let (mut draft, frame) = draft(); + let first = pending(&draft, &frame); + assert!(first.ring_same(&first.clone(), &frame).unwrap()); + draft + .commit(&frame, first.clone(), vec![0.0; 10240].into_boxed_slice()) + .unwrap(); + let mut next_frame = frame.clone(); + next_frame.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(); + let next = pending(&draft, &next_frame); + assert!(next.ring_append(&first, &next_frame).unwrap()); + let branch = pending(&draft, &next_frame); + assert!(!branch.ring_same(&next, &next_frame).unwrap()); + assert!(!branch.ring_append(&next, &next_frame).unwrap()); + let mut unrelated = first.clone(); + unrelated.owner = Rc::new(Cell::new(0)); + assert!(!next.ring_append(&unrelated, &next_frame).unwrap()); + draft.epoch.set(1); + assert_eq!( + next.ring_validate(&next_frame), + Err(Error::IdentityMismatch) + ); + next_frame.generation = 1; + assert_eq!( + next.ring_validate(&next_frame), + Err(Error::IdentityMismatch) + ); +} +#[test] +fn ring_restore_requires_reload_for_old_numerical_mirror() { + let (mut draft, frame) = draft(); + let first = pending(&draft, &frame); + draft + .commit(&frame, first.clone(), vec![0.0; 10240].into_boxed_slice()) + .unwrap(); + let checkpoint = draft.checkpoint().unwrap(); + let mut next_frame = frame.clone(); + next_frame.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(); + let second = pending(&draft, &next_frame); + draft + .commit(&next_frame, second, vec![0.0; 10240].into_boxed_slice()) + .unwrap(); + draft.restore(&checkpoint).unwrap(); + next_frame.generation = draft.epoch.get(); + let restored = pending(&draft, &next_frame); + assert!(restored.ring_validate(&next_frame).is_ok()); + assert!(!restored.ring_append(&first, &next_frame).unwrap()); + assert!(!restored.ring_same(&first, &next_frame).unwrap()); +} +#[test] +fn ring_parent_is_weak_and_half_cell_refuses_nonfinite() { + let (draft, frame) = draft(); + let initial = Rc::downgrade(&draft.kv.cells); + let first = pending(&draft, &frame); + assert!(first.parent.upgrade().is_some()); + drop(draft); + assert!(initial.upgrade().is_none()); + assert!(first.parent.upgrade().is_none()); + let mut bad = vec![0_u8; HALF_ROW]; + bad[1] = 0x7c; + assert_eq!(validate_half(&bad), Err(Error::NonFinite)); +} +#[test] +fn mtp_new_pending_token_epoch_and_residual_refuse_atomically() { + let (mut draft, frame) = draft(); + let stale = pending(&draft, &frame); + let mut wrong = frame.clone(); + wrong.token = TokenId::new(2, Dimension::new(248320).unwrap()).unwrap(); + assert_eq!( + draft.commit(&wrong, stale.clone(), vec![0.0; 10240].into_boxed_slice()), + Err(Error::IdentityMismatch) + ); + assert_eq!(draft.next_position, 0); + let initial = draft.checkpoint().unwrap(); + draft.restore(&initial).unwrap(); + wrong.generation = 1; + assert_eq!( + draft.commit(&wrong, stale, vec![0.0; 10240].into_boxed_slice()), + Err(Error::IdentityMismatch) + ); + let fresh = pending(&draft, &wrong); + let mut invalid = vec![0.0; 10240]; + invalid[10239] = f32::NAN; + assert_eq!( + draft.commit(&wrong, fresh.clone(), invalid.into_boxed_slice()), + Err(Error::NonFinite) + ); + assert_eq!(draft.next_position, 0); + assert!(draft.residual.is_none()); + draft + .commit(&wrong, fresh, vec![0.0; 10240].into_boxed_slice()) + .unwrap(); + assert_eq!(draft.next_position, 1); + assert_eq!(draft.residual.as_ref().unwrap().len(), 10240); +} +#[test] +fn mtp_new_checkpoint_cap_and_current_target_prefix() { + let (draft, frame) = draft(); + let identity = frame.binding.clone(); + let mut target = QwenSession::test_session(identity); + let mut other = frame.clone(); + other.origin = target.target_origin().unwrap(); + assert!(!other.same(&frame)); + let prior = target.checkpoint().unwrap(); + let old = other.clone(); + target.restore_checkpoint(&prior).unwrap(); + other.origin = target.target_origin().unwrap(); + assert!(!other.same(&old)); + let mut retained = Vec::new(); + for _ in 0..5 { + retained.push(draft.checkpoint().unwrap()); + } + assert!(matches!(draft.checkpoint(), Err(Error::InputAllocation))); + retained.pop(); + assert!(draft.checkpoint().is_ok()); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_config.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_config.rs index f73f37b2..577b0c64 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_config.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_config.rs @@ -322,144 +322,4 @@ pub(in crate::qwen_forward) fn prefill_layout_options( } #[cfg(test)] -mod tests { - use super::*; - #[test] - fn the_pack_expert_bank_is_needed_only_without_an_rt_directory() { - // pack-driven draft (no RT directory): the pack's experts are the draft layer's experts - assert!(mtp_pack_experts_needed(false)); - // RT-directory draft (the product): it streams its own experts; the default environment holds no second copy - if !legacy_footprint() { - assert!(!mtp_pack_experts_needed(true)); - } - } - #[test] - fn the_legacy_footprint_switch_is_off_unless_asked_for() { - assert!(!legacy_footprint_from(None)); - assert!(!legacy_footprint_from(Some(""))); - assert!(!legacy_footprint_from(Some("0"))); - assert!(!legacy_footprint_from(Some("off"))); - assert!(legacy_footprint_from(Some("1"))); - assert!(legacy_footprint_from(Some(" on "))); - } - - use leleka_context::rope_scaling::RopeKernelArgs; - - fn blobs() -> ExpertBlobSizes { - ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap() - } - - #[test] - fn blob_sizes_are_whole_sixteen_byte_units_and_track_the_maxima() { - let sizes = blobs(); - assert_eq!(sizes.blob_bytes(0), Some(2_300_000)); - assert_eq!(sizes.blob_bytes(47), Some((700_000 + 4096 * 47 + 700_000 + 900_000 + 15) & !15)); - assert_eq!(sizes.blob_bytes(48), None); - assert_eq!(sizes.max_blob(), sizes.blob_bytes(47).unwrap()); - assert_eq!(sizes.gate_up_max(), 700_000 + 4096 * 47 + 700_000); - assert_eq!(sizes.down_max(), 900_000); - assert!((0..48).all(|l| sizes.blob_bytes(l).unwrap() % 16 == 0)); - assert!(sizes.layout().is_ok()); - let mut zero = [1usize; 48]; - zero[3] = 0; - assert_eq!(ExpertBlobSizes::from_layer_bytes(zero, [1; 48], [1; 48]).err(), Some(Error::InvalidDimension)); - assert_eq!(ExpertBlobSizes::from_layer_bytes([usize::MAX; 48], [1; 48], [1; 48]).err(), Some(Error::Overflow)); - } - - #[test] - fn theta_scale_is_powf_of_the_frequency_base_over_the_rotation_width() { - let identity = RopeConstants::from_parts(1e7, RopeKernelArgs::default()); - assert_eq!(identity.theta_scale, 1e7f32.powf(-2.0 / 64.0)); - assert_eq!((identity.freq_scale, identity.corr_low, identity.corr_high), (1.0, 0.0, 0.0)); - assert_eq!((identity.ext_factor, identity.magnitude), (0.0, 1.0)); - let scaled = RopeConstants::from_parts( - 1e7, - RopeKernelArgs { freq_scale: 0.5, corr_low: 3.0, corr_high: 40.0, ext_factor: 1.0, attn_factor: 1.07 }, - ); - let kv = scaled.draft_kv(); - assert_eq!(kv.theta_scale, scaled.theta_scale); - assert_eq!((kv.freq_scale, kv.corr_low, kv.corr_high, kv.ext_factor, kv.mscale), (0.5, 3.0, 40.0, 1.0, 1.07)); - assert!(!kv.disabled && !kv.hybrid && !kv.q4 && !kv.rotated && !kv.alternate_f16); - assert!(!kv.rope_table_enabled && !kv.multimodal_positions && kv.mode == 0); - let rope = scaled.verify_rope(); - assert_eq!((rope.theta_scale, rope.magnitude), (scaled.theta_scale, 1.07)); - assert!(rope.positions.is_none() && rope.angles.is_none()); - } - - #[test] - fn mtp_policies_stay_inside_the_closed_profile_and_share_one_kv_policy() { - let rope = RopeConstants::from_parts(1e7, RopeKernelArgs::default()); - let full = mtp_full_policy(&rope); - let scalar = mtp_scalar_policy(&rope); - assert!(full.native_router && full.native_combine && full.native_shared_scalar && full.native_final_gr); - assert!(!full.old_grouped_s2 && !full.fp32_final_gr && full.coupled_j.is_none() && full.legacy_router_mode == 0); - assert!(full.gr == OriginalMtpGrVariant::Plain && scalar.gr == OriginalMtpGrVariant::Plain); - assert!(!scalar.per_group_sync); - assert_eq!(full.kv.theta_scale, scalar.kv.theta_scale); - } - - #[test] - fn sampler_path_follows_the_two_environment_flags_with_old_taking_precedence() { - let env = |pairs: &'static [(&'static str, &'static str)]| { - move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| (*v).to_owned()) - }; - assert_eq!(sampler_path(env(&[])), SamplerPath::Split); - assert_eq!(sampler_path(env(&[("STRATA_SAMPLER_ONE_BLOCK", "1")])), SamplerPath::OneBlock); - assert_eq!(sampler_path(env(&[("STRATA_OLD_SAMPLER", "1"), ("STRATA_SAMPLER_ONE_BLOCK", "1")])), SamplerPath::Old); - assert_eq!(sampler_path(env(&[("STRATA_OLD_SAMPLER", "0")])), SamplerPath::Split); - assert_eq!(sampler_path(env(&[("STRATA_OLD_SAMPLER", "")])), SamplerPath::Split); - } - - #[test] - fn request_params_map_field_for_field() { - let reference = leleka_sampler_ref::chain::SamplerParams { - top_k: 33, - top_p: 0.8, - min_p: 0.05, - temperature: 0.7, - min_keep: 2, - penalty_last_n: 64, - penalty_repeat: 1.1, - penalty_freq: 0.2, - penalty_present: -0.3, - seed: 99, - counter: 7, - greedy: false, - }; - let driver = driver_sampler_params(&reference); - assert_eq!((driver.top_k, driver.top_p, driver.min_p, driver.temperature), (33, 0.8, 0.05, 0.7)); - assert_eq!((driver.min_keep, driver.penalty_last_n, driver.penalty_repeat), (2, 64, 1.1)); - assert_eq!((driver.penalty_freq, driver.penalty_present, driver.seed, driver.counter), (0.2, -0.3, 99, 7)); - assert!(!driver.greedy); - assert!(driver.validate().is_ok()); - let greedy = greedy_params(5); - assert!(greedy.greedy && greedy.temperature == 0.0 && greedy.seed == 5); - assert!(greedy.validate().is_ok()); - } - - #[test] - fn geometry_and_prefill_carve_close_for_the_selected_capacities_and_contexts() { - for max_t in [2usize, 6, 8] { - for cells in [262_144usize, 524_288] { - let g = verify_geometry(max_t, cells, &blobs()).unwrap(); - assert_eq!((g.max_t, g.max_cells, g.vocabulary), (max_t, cells, 248_320)); - assert!(g.max_expert_blob >= 2_000_000); - } - } - assert!(verify_geometry(1, 262_144, &blobs()).is_err(), "Verifier::init refuses a one-row window"); - assert!(verify_geometry(9, 262_144, &blobs()).is_err()); - for capacity in [256usize, 1024, 8192] { - let options = prefill_layout_options(capacity, 262_144, &blobs()); - let layout = options.carve().expect("carve"); - assert_eq!(layout.capacity, capacity); - // the four INT8 staging runs the resident QSA transport requires, byte for byte - let runs = leleka_cuda_driver::serving_context().geometry.stage_runs().unwrap(); - let want = [("kv_k_q", runs[0]), ("kv_v_q", runs[1]), ("kv_k_scale", runs[2]), ("kv_v_scale", runs[3])]; - for (name, bytes) in want { - let span = layout.span(leleka_cuda_driver::PrefillPhase::Common, name).expect(name); - assert_eq!(span.bytes, bytes, "{name}"); - } - assert!(layout.separately_owned_bytes == 0); - } - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_config/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_config/tests.rs new file mode 100644 index 00000000..2bf077a0 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_config/tests.rs @@ -0,0 +1,141 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +#[test] +fn the_pack_expert_bank_is_needed_only_without_an_rt_directory() { + // pack-driven draft (no RT directory): the pack's experts are the draft layer's experts + assert!(mtp_pack_experts_needed(false)); + // RT-directory draft (the product): it streams its own experts; the default environment holds no second copy + if !legacy_footprint() { + assert!(!mtp_pack_experts_needed(true)); + } +} +#[test] +fn the_legacy_footprint_switch_is_off_unless_asked_for() { + assert!(!legacy_footprint_from(None)); + assert!(!legacy_footprint_from(Some(""))); + assert!(!legacy_footprint_from(Some("0"))); + assert!(!legacy_footprint_from(Some("off"))); + assert!(legacy_footprint_from(Some("1"))); + assert!(legacy_footprint_from(Some(" on "))); +} + +use leleka_context::rope_scaling::RopeKernelArgs; + +fn blobs() -> ExpertBlobSizes { + ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap() +} + +#[test] +fn blob_sizes_are_whole_sixteen_byte_units_and_track_the_maxima() { + let sizes = blobs(); + assert_eq!(sizes.blob_bytes(0), Some(2_300_000)); + assert_eq!(sizes.blob_bytes(47), Some((700_000 + 4096 * 47 + 700_000 + 900_000 + 15) & !15)); + assert_eq!(sizes.blob_bytes(48), None); + assert_eq!(sizes.max_blob(), sizes.blob_bytes(47).unwrap()); + assert_eq!(sizes.gate_up_max(), 700_000 + 4096 * 47 + 700_000); + assert_eq!(sizes.down_max(), 900_000); + assert!((0..48).all(|l| sizes.blob_bytes(l).unwrap() % 16 == 0)); + assert!(sizes.layout().is_ok()); + let mut zero = [1usize; 48]; + zero[3] = 0; + assert_eq!(ExpertBlobSizes::from_layer_bytes(zero, [1; 48], [1; 48]).err(), Some(Error::InvalidDimension)); + assert_eq!(ExpertBlobSizes::from_layer_bytes([usize::MAX; 48], [1; 48], [1; 48]).err(), Some(Error::Overflow)); +} + +#[test] +fn theta_scale_is_powf_of_the_frequency_base_over_the_rotation_width() { + let identity = RopeConstants::from_parts(1e7, RopeKernelArgs::default()); + assert_eq!(identity.theta_scale, 1e7f32.powf(-2.0 / 64.0)); + assert_eq!((identity.freq_scale, identity.corr_low, identity.corr_high), (1.0, 0.0, 0.0)); + assert_eq!((identity.ext_factor, identity.magnitude), (0.0, 1.0)); + let scaled = RopeConstants::from_parts( + 1e7, + RopeKernelArgs { freq_scale: 0.5, corr_low: 3.0, corr_high: 40.0, ext_factor: 1.0, attn_factor: 1.07 }, + ); + let kv = scaled.draft_kv(); + assert_eq!(kv.theta_scale, scaled.theta_scale); + assert_eq!((kv.freq_scale, kv.corr_low, kv.corr_high, kv.ext_factor, kv.mscale), (0.5, 3.0, 40.0, 1.0, 1.07)); + assert!(!kv.disabled && !kv.hybrid && !kv.q4 && !kv.rotated && !kv.alternate_f16); + assert!(!kv.rope_table_enabled && !kv.multimodal_positions && kv.mode == 0); + let rope = scaled.verify_rope(); + assert_eq!((rope.theta_scale, rope.magnitude), (scaled.theta_scale, 1.07)); + assert!(rope.positions.is_none() && rope.angles.is_none()); +} + +#[test] +fn mtp_policies_stay_inside_the_closed_profile_and_share_one_kv_policy() { + let rope = RopeConstants::from_parts(1e7, RopeKernelArgs::default()); + let full = mtp_full_policy(&rope); + let scalar = mtp_scalar_policy(&rope); + assert!(full.native_router && full.native_combine && full.native_shared_scalar && full.native_final_gr); + assert!(!full.old_grouped_s2 && !full.fp32_final_gr && full.coupled_j.is_none() && full.legacy_router_mode == 0); + assert!(full.gr == OriginalMtpGrVariant::Plain && scalar.gr == OriginalMtpGrVariant::Plain); + assert!(!scalar.per_group_sync); + assert_eq!(full.kv.theta_scale, scalar.kv.theta_scale); +} + +#[test] +fn sampler_path_follows_the_two_environment_flags_with_old_taking_precedence() { + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| (*v).to_owned()) + }; + assert_eq!(sampler_path(env(&[])), SamplerPath::Split); + assert_eq!(sampler_path(env(&[("STRATA_SAMPLER_ONE_BLOCK", "1")])), SamplerPath::OneBlock); + assert_eq!(sampler_path(env(&[("STRATA_OLD_SAMPLER", "1"), ("STRATA_SAMPLER_ONE_BLOCK", "1")])), SamplerPath::Old); + assert_eq!(sampler_path(env(&[("STRATA_OLD_SAMPLER", "0")])), SamplerPath::Split); + assert_eq!(sampler_path(env(&[("STRATA_OLD_SAMPLER", "")])), SamplerPath::Split); +} + +#[test] +fn request_params_map_field_for_field() { + let reference = leleka_sampler_ref::chain::SamplerParams { + top_k: 33, + top_p: 0.8, + min_p: 0.05, + temperature: 0.7, + min_keep: 2, + penalty_last_n: 64, + penalty_repeat: 1.1, + penalty_freq: 0.2, + penalty_present: -0.3, + seed: 99, + counter: 7, + greedy: false, + }; + let driver = driver_sampler_params(&reference); + assert_eq!((driver.top_k, driver.top_p, driver.min_p, driver.temperature), (33, 0.8, 0.05, 0.7)); + assert_eq!((driver.min_keep, driver.penalty_last_n, driver.penalty_repeat), (2, 64, 1.1)); + assert_eq!((driver.penalty_freq, driver.penalty_present, driver.seed, driver.counter), (0.2, -0.3, 99, 7)); + assert!(!driver.greedy); + assert!(driver.validate().is_ok()); + let greedy = greedy_params(5); + assert!(greedy.greedy && greedy.temperature == 0.0 && greedy.seed == 5); + assert!(greedy.validate().is_ok()); +} + +#[test] +fn geometry_and_prefill_carve_close_for_the_selected_capacities_and_contexts() { + for max_t in [2usize, 6, 8] { + for cells in [262_144usize, 524_288] { + let g = verify_geometry(max_t, cells, &blobs()).unwrap(); + assert_eq!((g.max_t, g.max_cells, g.vocabulary), (max_t, cells, 248_320)); + assert!(g.max_expert_blob >= 2_000_000); + } + } + assert!(verify_geometry(1, 262_144, &blobs()).is_err(), "Verifier::init refuses a one-row window"); + assert!(verify_geometry(9, 262_144, &blobs()).is_err()); + for capacity in [256usize, 1024, 8192] { + let options = prefill_layout_options(capacity, 262_144, &blobs()); + let layout = options.carve().expect("carve"); + assert_eq!(layout.capacity, capacity); + // the four INT8 staging runs the resident QSA transport requires, byte for byte + let runs = leleka_cuda_driver::serving_context().geometry.stage_runs().unwrap(); + let want = [("kv_k_q", runs[0]), ("kv_v_q", runs[1]), ("kv_k_scale", runs[2]), ("kv_v_scale", runs[3])]; + for (name, bytes) in want { + let span = layout.span(leleka_cuda_driver::PrefillPhase::Common, name).expect(name); + assert_eq!(span.bytes, bytes, "{name}"); + } + assert!(layout.separately_owned_bytes == 0); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_conversation.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_conversation.rs index 20d051b0..fae6abd3 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_conversation.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_conversation.rs @@ -323,340 +323,5 @@ fn operator_line(line: &str) { } #[cfg(test)] -mod tests { - use super::*; - use crate::backend::original_prompt::{PromptPath, PromptPlan}; - - /// A device whose state is the token list it holds; points are copies of it. A restore is only possible - /// to a point that is a prefix of what the device holds (the positional-cell rule). - #[derive(Default)] - struct Fake { - held: Vec, - draft_at: Option, - log: Vec, - fail_restore: bool, - settled: bool, - } - impl ResumeDevice for Fake { - type Point = (Vec, usize); - fn zero(&mut self) -> Result<(), Error> { - self.log.push("zero".into()); - self.held.clear(); - self.draft_at = Some(0); - self.settled = true; - Ok(()) - } - fn position(&self) -> Result { - Ok(self.held.len() as u64) - } - fn save(&mut self) -> Result { - self.log.push(format!("save {}", self.held.len())); - Ok((self.held.clone(), self.draft_at.ok_or(Error::IdentityMismatch)?)) - } - fn point_position(point: &Self::Point) -> u64 { - point.0.len() as u64 - } - fn restore(&mut self, point: &Self::Point) -> Result<(), Error> { - self.log.push(format!("restore {}", point.0.len())); - if self.fail_restore || !self.held.starts_with(&point.0) { - return Err(Error::IdentityMismatch); - } - self.held = point.0.clone(); - self.draft_at = None; - self.settled = true; - Ok(()) - } - fn restore_draft(&mut self, point: &Self::Point, resume: usize) -> Result<(), Error> { - self.log.push(format!("draft {resume}")); - if point.1 != resume || self.held.len() != resume { - return Err(Error::IdentityMismatch); - } - self.draft_at = Some(point.1); - Ok(()) - } - fn live_in_step(&self) -> bool { - self.settled && self.draft_at == Some(self.held.len()) - } - } - - fn config() -> ConversationConfig { - ConversationConfig { reread_checkpoints: false, prompt_cache_root: 8, ..ConversationConfig::original() } - } - - /// One request against the fake: begin, read the plan's batched chunks (the device then holds them), - /// and finish as a decode that committed `reply` (live only when `live`). - fn serve(c: &mut ServeConversation<(Vec, usize)>, d: &mut Fake, prompt: &[i32], reply: &[i32], live: bool) -> RequestStart { - let start = c.begin(d, prompt).unwrap(); - assert_eq!(d.held.len(), start.read_from); - let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); - let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); - let plan = PromptPlan::new(&tokens, start.resume, start.reread_to, None, options, 256).unwrap(); - for action in plan { - if action.path == PromptPath::FinalSeed { - break; - } - assert_eq!(d.held.len(), action.first); - d.held.extend_from_slice(&prompt[action.first..action.first + action.count]); - d.draft_at = Some(d.held.len()); - c.after_action(d, prompt, &action).unwrap(); - } - assert_eq!(d.held.len(), prompt.len() - 1); - // decode: the last prompt token and the reply join the session; the ring lags unless `live` - d.held.push(prompt[prompt.len() - 1]); - d.held.extend_from_slice(reply); - d.settled = live; - d.draft_at = live.then_some(d.held.len()); - if live { - c.note_live(d.held.clone()); - } - c.finish(true); - start - } - - fn chat(system: usize, turns: &[usize]) -> Vec { - let t = TURN_TOKEN as i32; - let mut ids = vec![1]; - ids.extend((0..system).map(|i| 1000 + i as i32)); - for (k, &n) in turns.iter().enumerate() { - ids.push(t); - ids.extend((0..n).map(|i| 5000 + (k * 100 + i) as i32)); - } - ids.extend([t, 77, 10]); - ids - } - - #[test] - fn a_request_that_extends_the_previous_one_resumes_at_its_last_turn_and_reads_only_the_suffix() { - let mut c = ServeConversation::new(config()); - let mut d = Fake::default(); - let first = chat(20, &[5]); - let start = serve(&mut c, &mut d, &first, &[42, 43], false); - assert_eq!((start.resume, start.read_from), (0, 0)); - assert_eq!(d.log[0], "zero"); - // root (first turn boundary, >= 8 tokens in) and the last turn boundary were checkpointed - let root = 21; - let turn = first.len() - 3; - assert_eq!(c.checkpoint_lengths(), vec![root, turn]); - // the second request carries the first prompt, the reply and a new user turn - let mut second = first.clone(); - second.extend([42, 43]); - second.extend(chat(0, &[4])[1..].iter().copied()); - d.log.clear(); - let start = serve(&mut c, &mut d, &second, &[44], false); - assert_eq!((start.resume, start.from_live, start.read_from), (turn, false, turn)); - assert_eq!(d.log[..2], [format!("restore {turn}"), format!("draft {turn}")]); - assert!(c.checkpoint_lengths().contains(&root), "the root is kept"); - } - - #[test] - fn a_settled_in_step_session_continues_live_without_a_restore() { - let mut c = ServeConversation::new(config()); - let mut d = Fake::default(); - let first = chat(20, &[5]); - serve(&mut c, &mut d, &first, &[42, 43], true); - let held = d.held.clone(); - let mut second = held.clone(); - second.extend([7, 8, 9]); - d.log.clear(); - let start = serve(&mut c, &mut d, &second, &[1], false); - assert_eq!((start.resume, start.from_live), (held.len(), true)); - assert!(d.log.iter().all(|l| !l.starts_with("restore") && l != "zero"), "{:?}", d.log); - } - - /// Read the first `chunks` batched chunks of the plan of `prompt` after `begin` (the device then holds them, the ring in step). - fn read_chunks(c: &mut ServeConversation<(Vec, usize)>, d: &mut Fake, prompt: &[i32], start: &RequestStart, chunks: usize) { - let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); - let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); - let plan = PromptPlan::new(&tokens, start.resume, start.reread_to, None, options, 256).unwrap(); - for action in plan.take(chunks) { - assert_eq!(d.held.len(), action.first); - d.held.extend_from_slice(&prompt[action.first..action.first + action.count]); - d.draft_at = Some(d.held.len()); - c.after_action(d, prompt, &action).unwrap(); - } - } - - /// Upstream 41cf05a0 `8824e217` (generate.cpp #1620): a request cancelled between two prompt windows lost the conversation - /// it had restored. Here the request's start clears the live claim; a cancel in the prompt must give back what the - /// session holds (the restored tokens plus the published chunks), and the conversation's next request continues from it. - #[test] - fn a_request_cancelled_between_prompt_chunks_leaves_its_conversation_live() { - let mut c = ServeConversation::new(config()); - let mut d = Fake::default(); - let first = chat(20, &[5]); - serve(&mut c, &mut d, &first, &[42, 43], true); - let held = d.held.clone(); - let mut second = held.clone(); - second.extend((0..700).map(|i| 6000 + i)); - second.push(10); - // before: cancelled after two chunks and the claim was gone, so the next request restored the last checkpoint - let start = c.begin(&mut d, &second).unwrap(); - assert_eq!((start.resume, start.from_live), (held.len(), true)); - read_chunks(&mut c, &mut d, &second, &start, 2); - let reached = d.held.len(); - assert_eq!(reached, held.len() + 512); - let (mut lost, mut lost_d) = (ServeConversation::new(config()), Fake::default()); - { - // the same state without the fix: the cancel finishes with nothing noted - serve(&mut lost, &mut lost_d, &first, &[42, 43], true); - let s = lost.begin(&mut lost_d, &second).unwrap(); - read_chunks(&mut lost, &mut lost_d, &second, &s, 2); - lost.finish(true); - let mut third = second[..reached].to_vec(); - third.extend([1, 2, 3]); - let s = lost.begin(&mut lost_d, &third).unwrap(); - assert!(!s.from_live && s.resume < reached, "without the claim the request restores a checkpoint: {s:?}"); - } - assert!(c.note_cancelled_prefill(&second, d.position().unwrap(), d.live_in_step())); - c.finish(true); - let mut third = second[..reached].to_vec(); - third.extend([1, 2, 3]); - d.log.clear(); - let start = c.begin(&mut d, &third).unwrap(); - assert_eq!((start.resume, start.from_live, start.read_from), (reached, true, reached)); - assert!(d.log.iter().all(|l| !l.starts_with("restore") && l != "zero"), "{:?}", d.log); - // the checkpoints the request took before the cancel are kept as prefixes of the live tokens - assert!(c.checkpoint_lengths().iter().all(|&l| l <= reached)); - } - - #[test] - fn a_cancel_before_the_first_chunk_keeps_the_restored_session_and_a_session_that_is_not_in_step_keeps_nothing() { - let mut c = ServeConversation::new(config()); - let mut d = Fake::default(); - let first = chat(20, &[5]); - serve(&mut c, &mut d, &first, &[42, 43], true); - let held = d.held.clone(); - let mut second = held.clone(); - second.extend((0..300).map(|i| 6000 + i)); - second.push(10); - // cancelled before the first chunk: the session stands exactly where the request found it - let start = c.begin(&mut d, &second).unwrap(); - assert_eq!(start.resume, held.len()); - assert!(c.note_cancelled_prefill(&second, d.position().unwrap(), d.live_in_step())); - c.finish(true); - let start = c.begin(&mut d, &second).unwrap(); - assert_eq!((start.resume, start.from_live), (held.len(), true)); - // the draft ring does not stand at the session's position: nothing is claimed (the next request restores a checkpoint) - read_chunks(&mut c, &mut d, &second, &start, 1); - d.draft_at = Some(held.len()); - assert!(!d.live_in_step()); - assert!(!c.note_cancelled_prefill(&second, d.position().unwrap(), d.live_in_step())); - c.finish(true); - let start = c.begin(&mut d, &second).unwrap(); - assert!(!start.from_live && start.resume < held.len() + 256, "{start:?}"); - // never a claim for a position that is not a prompt prefix: zero, the whole prompt, or a request that was not placed - assert!(!c.note_cancelled_prefill(&second, 0, true)); - assert!(!c.note_cancelled_prefill(&second, second.len() as u64, true)); - assert!(!c.note_cancelled_prefill(&second, u64::MAX, true)); - c.finish(true); - assert!(!c.note_cancelled_prefill(&second, 10, true), "no request in progress"); - } - - /// Upstream 41cf05a0 `aece46db`: a prompt of one token is entirely the first verify input; nothing is read, restored or - /// checkpointed, whatever the cache holds (the buffer is zeroed for it, which drops the cells the old checkpoints name). - #[test] - fn a_one_token_prompt_starts_empty_reads_nothing_and_checkpoints_nothing() { - let mut c = ServeConversation::new(config()); - let mut d = Fake::default(); - let first = chat(20, &[5]); - serve(&mut c, &mut d, &first, &[42, 43], true); - let chain = c.checkpoint_lengths(); - assert!(!chain.is_empty()); - let start = c.begin(&mut d, &[first[0]]).unwrap(); - assert_eq!((start.resume, start.from_live, start.read_from), (0, false, 0)); - assert_eq!(d.log.last().map(String::as_str), Some("zero")); - assert_eq!(d.held.len(), 0); - // the plan of a 1-token prompt is the final seed alone: no chunk, no checkpoint - let tokens = [first[0] as u32]; - let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); - let plan = PromptPlan::new(&tokens, 0, None, None, options, 256).unwrap(); - assert!(plan.into_iter().all(|a| a.path == PromptPath::FinalSeed)); - c.finish(true); - // the buffer was zeroed for it, so the displaced conversation's checkpoints (cells that are gone) are dropped with it - assert!(c.checkpoint_lengths().is_empty()); - } - - #[test] - fn an_unrelated_prompt_starts_empty_and_a_shared_system_prompt_reuses_the_root() { - let mut c = ServeConversation::new(config()); - let mut d = Fake::default(); - serve(&mut c, &mut d, &chat(20, &[5]), &[42], false); - // same system prompt, another chat (its first user turn differs at once): the root checkpoint - let mut other = chat(20, &[9, 3]); - other[22] = 9999; - d.log.clear(); - let start = serve(&mut c, &mut d, &other, &[1], false); - assert_eq!(start.resume, 21); - assert_eq!(d.log[0], "restore 21"); - // nothing in common: the empty prompt, and the chain is rebuilt from scratch - let mut unrelated = chat(3, &[2]); - unrelated[0] = 2; - d.log.clear(); - let start = serve(&mut c, &mut d, &unrelated, &[1], false); - assert_eq!(start.resume, 0); - assert_eq!(d.log[0], "zero"); - assert!(c.checkpoint_lengths().iter().all(|&l| l < unrelated.len())); - } - - #[test] - fn a_failed_request_drops_every_checkpoint_and_a_failed_restore_is_an_error_for_the_caller() { - let mut c = ServeConversation::new(config()); - let mut d = Fake::default(); - let first = chat(20, &[5]); - serve(&mut c, &mut d, &first, &[42], false); - let mut second = first.clone(); - second.extend([42, 9, 9]); - d.fail_restore = true; - assert!(c.begin(&mut d, &second).is_err()); - c.invalidate(); - assert!(c.checkpoint_lengths().is_empty()); - d.fail_restore = false; - let start = serve(&mut c, &mut d, &second, &[1], false); - assert_eq!(start.resume, 0, "after an invalidation the next request reads from the start"); - // a request that fails mid-way leaves nothing to resume from - c.begin(&mut d, &second).unwrap(); - c.finish(false); - assert!(c.checkpoint_lengths().is_empty()); - } - - #[test] - fn the_chain_is_bounded_and_the_saved_points_follow_it() { - let mut c = ServeConversation::new(ConversationConfig { prompt_cache: 2, ..config() }); - let mut d = Fake::default(); - let mut prompt = chat(20, &[5]); - for k in 0..5 { - serve(&mut c, &mut d, &prompt, &[40 + k], false); - assert!(c.checkpoint_lengths().len() <= 2); - assert_eq!(c.saved.len(), c.checkpoint_lengths().len()); - prompt.extend([40 + k]); - prompt.extend(chat(0, &[3])[1..].iter().copied()); - } - } - - #[test] - fn reread_mode_reads_the_checkpoint_again_instead_of_restoring_it() { - let mut c = ServeConversation::new(ConversationConfig { reread_checkpoints: true, ..config() }); - let mut d = Fake::default(); - let first = chat(20, &[5]); - serve(&mut c, &mut d, &first, &[42], false); - let mut second = first.clone(); - second.extend([42, 9, 9]); - d.log.clear(); - let start = serve(&mut c, &mut d, &second, &[1], false); - assert_eq!((start.read_from, start.reread_to), (0, Some(first.len() - 3))); - assert_eq!(d.log[0], "zero"); - assert!(d.log.iter().all(|l| !l.starts_with("restore"))); - } - - #[test] - fn the_config_follows_the_original_defaults_and_refuses_nonsense() { - let o = ConversationConfig::original(); - assert_eq!((o.prompt_cache, o.prompt_cache_every, o.prompt_cache_root, o.turn_token), (6, 16_384, 2048, Some(248_045))); - assert!(o.validate().is_ok()); - assert!(ConversationConfig { prompt_cache: 0, ..o.clone() }.validate().is_err()); - assert!(ConversationConfig { turn_token: Some(248_320), ..o.clone() }.validate().is_err()); - let plan = o.plan_options(PromptOptions { prompt_cache: false, turn_token: None, root_min: 0, ..PromptOptions::original_mode17(4096) }); - assert!(plan.prompt_cache && plan.turn_token == Some(248_045) && plan.root_min == 2048); - assert_eq!(o.options().conversation_cache_bytes, 0, "parking stays off"); - } -} +#[path = "original_serve_conversation/tests.rs"] +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_conversation/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_conversation/tests.rs new file mode 100644 index 00000000..2080d6c7 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_conversation/tests.rs @@ -0,0 +1,337 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::backend::original_prompt::{PromptPath, PromptPlan}; + +/// A device whose state is the token list it holds; points are copies of it. A restore is only possible +/// to a point that is a prefix of what the device holds (the positional-cell rule). +#[derive(Default)] +struct Fake { + held: Vec, + draft_at: Option, + log: Vec, + fail_restore: bool, + settled: bool, +} +impl ResumeDevice for Fake { + type Point = (Vec, usize); + fn zero(&mut self) -> Result<(), Error> { + self.log.push("zero".into()); + self.held.clear(); + self.draft_at = Some(0); + self.settled = true; + Ok(()) + } + fn position(&self) -> Result { + Ok(self.held.len() as u64) + } + fn save(&mut self) -> Result { + self.log.push(format!("save {}", self.held.len())); + Ok((self.held.clone(), self.draft_at.ok_or(Error::IdentityMismatch)?)) + } + fn point_position(point: &Self::Point) -> u64 { + point.0.len() as u64 + } + fn restore(&mut self, point: &Self::Point) -> Result<(), Error> { + self.log.push(format!("restore {}", point.0.len())); + if self.fail_restore || !self.held.starts_with(&point.0) { + return Err(Error::IdentityMismatch); + } + self.held = point.0.clone(); + self.draft_at = None; + self.settled = true; + Ok(()) + } + fn restore_draft(&mut self, point: &Self::Point, resume: usize) -> Result<(), Error> { + self.log.push(format!("draft {resume}")); + if point.1 != resume || self.held.len() != resume { + return Err(Error::IdentityMismatch); + } + self.draft_at = Some(point.1); + Ok(()) + } + fn live_in_step(&self) -> bool { + self.settled && self.draft_at == Some(self.held.len()) + } +} + +fn config() -> ConversationConfig { + ConversationConfig { reread_checkpoints: false, prompt_cache_root: 8, ..ConversationConfig::original() } +} + +/// One request against the fake: begin, read the plan's batched chunks (the device then holds them), +/// and finish as a decode that committed `reply` (live only when `live`). +fn serve(c: &mut ServeConversation<(Vec, usize)>, d: &mut Fake, prompt: &[i32], reply: &[i32], live: bool) -> RequestStart { + let start = c.begin(d, prompt).unwrap(); + assert_eq!(d.held.len(), start.read_from); + let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); + let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); + let plan = PromptPlan::new(&tokens, start.resume, start.reread_to, None, options, 256).unwrap(); + for action in plan { + if action.path == PromptPath::FinalSeed { + break; + } + assert_eq!(d.held.len(), action.first); + d.held.extend_from_slice(&prompt[action.first..action.first + action.count]); + d.draft_at = Some(d.held.len()); + c.after_action(d, prompt, &action).unwrap(); + } + assert_eq!(d.held.len(), prompt.len() - 1); + // decode: the last prompt token and the reply join the session; the ring lags unless `live` + d.held.push(prompt[prompt.len() - 1]); + d.held.extend_from_slice(reply); + d.settled = live; + d.draft_at = live.then_some(d.held.len()); + if live { + c.note_live(d.held.clone()); + } + c.finish(true); + start +} + +fn chat(system: usize, turns: &[usize]) -> Vec { + let t = TURN_TOKEN as i32; + let mut ids = vec![1]; + ids.extend((0..system).map(|i| 1000 + i as i32)); + for (k, &n) in turns.iter().enumerate() { + ids.push(t); + ids.extend((0..n).map(|i| 5000 + (k * 100 + i) as i32)); + } + ids.extend([t, 77, 10]); + ids +} + +#[test] +fn a_request_that_extends_the_previous_one_resumes_at_its_last_turn_and_reads_only_the_suffix() { + let mut c = ServeConversation::new(config()); + let mut d = Fake::default(); + let first = chat(20, &[5]); + let start = serve(&mut c, &mut d, &first, &[42, 43], false); + assert_eq!((start.resume, start.read_from), (0, 0)); + assert_eq!(d.log[0], "zero"); + // root (first turn boundary, >= 8 tokens in) and the last turn boundary were checkpointed + let root = 21; + let turn = first.len() - 3; + assert_eq!(c.checkpoint_lengths(), vec![root, turn]); + // the second request carries the first prompt, the reply and a new user turn + let mut second = first.clone(); + second.extend([42, 43]); + second.extend(chat(0, &[4])[1..].iter().copied()); + d.log.clear(); + let start = serve(&mut c, &mut d, &second, &[44], false); + assert_eq!((start.resume, start.from_live, start.read_from), (turn, false, turn)); + assert_eq!(d.log[..2], [format!("restore {turn}"), format!("draft {turn}")]); + assert!(c.checkpoint_lengths().contains(&root), "the root is kept"); +} + +#[test] +fn a_settled_in_step_session_continues_live_without_a_restore() { + let mut c = ServeConversation::new(config()); + let mut d = Fake::default(); + let first = chat(20, &[5]); + serve(&mut c, &mut d, &first, &[42, 43], true); + let held = d.held.clone(); + let mut second = held.clone(); + second.extend([7, 8, 9]); + d.log.clear(); + let start = serve(&mut c, &mut d, &second, &[1], false); + assert_eq!((start.resume, start.from_live), (held.len(), true)); + assert!(d.log.iter().all(|l| !l.starts_with("restore") && l != "zero"), "{:?}", d.log); +} + +/// Read the first `chunks` batched chunks of the plan of `prompt` after `begin` (the device then holds them, the ring in step). +fn read_chunks(c: &mut ServeConversation<(Vec, usize)>, d: &mut Fake, prompt: &[i32], start: &RequestStart, chunks: usize) { + let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); + let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); + let plan = PromptPlan::new(&tokens, start.resume, start.reread_to, None, options, 256).unwrap(); + for action in plan.take(chunks) { + assert_eq!(d.held.len(), action.first); + d.held.extend_from_slice(&prompt[action.first..action.first + action.count]); + d.draft_at = Some(d.held.len()); + c.after_action(d, prompt, &action).unwrap(); + } +} + +/// Upstream 41cf05a0 `8824e217` (generate.cpp #1620): a request cancelled between two prompt windows lost the conversation +/// it had restored. Here the request's start clears the live claim; a cancel in the prompt must give back what the +/// session holds (the restored tokens plus the published chunks), and the conversation's next request continues from it. +#[test] +fn a_request_cancelled_between_prompt_chunks_leaves_its_conversation_live() { + let mut c = ServeConversation::new(config()); + let mut d = Fake::default(); + let first = chat(20, &[5]); + serve(&mut c, &mut d, &first, &[42, 43], true); + let held = d.held.clone(); + let mut second = held.clone(); + second.extend((0..700).map(|i| 6000 + i)); + second.push(10); + // before: cancelled after two chunks and the claim was gone, so the next request restored the last checkpoint + let start = c.begin(&mut d, &second).unwrap(); + assert_eq!((start.resume, start.from_live), (held.len(), true)); + read_chunks(&mut c, &mut d, &second, &start, 2); + let reached = d.held.len(); + assert_eq!(reached, held.len() + 512); + let (mut lost, mut lost_d) = (ServeConversation::new(config()), Fake::default()); + { + // the same state without the fix: the cancel finishes with nothing noted + serve(&mut lost, &mut lost_d, &first, &[42, 43], true); + let s = lost.begin(&mut lost_d, &second).unwrap(); + read_chunks(&mut lost, &mut lost_d, &second, &s, 2); + lost.finish(true); + let mut third = second[..reached].to_vec(); + third.extend([1, 2, 3]); + let s = lost.begin(&mut lost_d, &third).unwrap(); + assert!(!s.from_live && s.resume < reached, "without the claim the request restores a checkpoint: {s:?}"); + } + assert!(c.note_cancelled_prefill(&second, d.position().unwrap(), d.live_in_step())); + c.finish(true); + let mut third = second[..reached].to_vec(); + third.extend([1, 2, 3]); + d.log.clear(); + let start = c.begin(&mut d, &third).unwrap(); + assert_eq!((start.resume, start.from_live, start.read_from), (reached, true, reached)); + assert!(d.log.iter().all(|l| !l.starts_with("restore") && l != "zero"), "{:?}", d.log); + // the checkpoints the request took before the cancel are kept as prefixes of the live tokens + assert!(c.checkpoint_lengths().iter().all(|&l| l <= reached)); +} + +#[test] +fn a_cancel_before_the_first_chunk_keeps_the_restored_session_and_a_session_that_is_not_in_step_keeps_nothing() { + let mut c = ServeConversation::new(config()); + let mut d = Fake::default(); + let first = chat(20, &[5]); + serve(&mut c, &mut d, &first, &[42, 43], true); + let held = d.held.clone(); + let mut second = held.clone(); + second.extend((0..300).map(|i| 6000 + i)); + second.push(10); + // cancelled before the first chunk: the session stands exactly where the request found it + let start = c.begin(&mut d, &second).unwrap(); + assert_eq!(start.resume, held.len()); + assert!(c.note_cancelled_prefill(&second, d.position().unwrap(), d.live_in_step())); + c.finish(true); + let start = c.begin(&mut d, &second).unwrap(); + assert_eq!((start.resume, start.from_live), (held.len(), true)); + // the draft ring does not stand at the session's position: nothing is claimed (the next request restores a checkpoint) + read_chunks(&mut c, &mut d, &second, &start, 1); + d.draft_at = Some(held.len()); + assert!(!d.live_in_step()); + assert!(!c.note_cancelled_prefill(&second, d.position().unwrap(), d.live_in_step())); + c.finish(true); + let start = c.begin(&mut d, &second).unwrap(); + assert!(!start.from_live && start.resume < held.len() + 256, "{start:?}"); + // never a claim for a position that is not a prompt prefix: zero, the whole prompt, or a request that was not placed + assert!(!c.note_cancelled_prefill(&second, 0, true)); + assert!(!c.note_cancelled_prefill(&second, second.len() as u64, true)); + assert!(!c.note_cancelled_prefill(&second, u64::MAX, true)); + c.finish(true); + assert!(!c.note_cancelled_prefill(&second, 10, true), "no request in progress"); +} + +/// Upstream 41cf05a0 `aece46db`: a prompt of one token is entirely the first verify input; nothing is read, restored or +/// checkpointed, whatever the cache holds (the buffer is zeroed for it, which drops the cells the old checkpoints name). +#[test] +fn a_one_token_prompt_starts_empty_reads_nothing_and_checkpoints_nothing() { + let mut c = ServeConversation::new(config()); + let mut d = Fake::default(); + let first = chat(20, &[5]); + serve(&mut c, &mut d, &first, &[42, 43], true); + let chain = c.checkpoint_lengths(); + assert!(!chain.is_empty()); + let start = c.begin(&mut d, &[first[0]]).unwrap(); + assert_eq!((start.resume, start.from_live, start.read_from), (0, false, 0)); + assert_eq!(d.log.last().map(String::as_str), Some("zero")); + assert_eq!(d.held.len(), 0); + // the plan of a 1-token prompt is the final seed alone: no chunk, no checkpoint + let tokens = [first[0] as u32]; + let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); + let plan = PromptPlan::new(&tokens, 0, None, None, options, 256).unwrap(); + assert!(plan.into_iter().all(|a| a.path == PromptPath::FinalSeed)); + c.finish(true); + // the buffer was zeroed for it, so the displaced conversation's checkpoints (cells that are gone) are dropped with it + assert!(c.checkpoint_lengths().is_empty()); +} + +#[test] +fn an_unrelated_prompt_starts_empty_and_a_shared_system_prompt_reuses_the_root() { + let mut c = ServeConversation::new(config()); + let mut d = Fake::default(); + serve(&mut c, &mut d, &chat(20, &[5]), &[42], false); + // same system prompt, another chat (its first user turn differs at once): the root checkpoint + let mut other = chat(20, &[9, 3]); + other[22] = 9999; + d.log.clear(); + let start = serve(&mut c, &mut d, &other, &[1], false); + assert_eq!(start.resume, 21); + assert_eq!(d.log[0], "restore 21"); + // nothing in common: the empty prompt, and the chain is rebuilt from scratch + let mut unrelated = chat(3, &[2]); + unrelated[0] = 2; + d.log.clear(); + let start = serve(&mut c, &mut d, &unrelated, &[1], false); + assert_eq!(start.resume, 0); + assert_eq!(d.log[0], "zero"); + assert!(c.checkpoint_lengths().iter().all(|&l| l < unrelated.len())); +} + +#[test] +fn a_failed_request_drops_every_checkpoint_and_a_failed_restore_is_an_error_for_the_caller() { + let mut c = ServeConversation::new(config()); + let mut d = Fake::default(); + let first = chat(20, &[5]); + serve(&mut c, &mut d, &first, &[42], false); + let mut second = first.clone(); + second.extend([42, 9, 9]); + d.fail_restore = true; + assert!(c.begin(&mut d, &second).is_err()); + c.invalidate(); + assert!(c.checkpoint_lengths().is_empty()); + d.fail_restore = false; + let start = serve(&mut c, &mut d, &second, &[1], false); + assert_eq!(start.resume, 0, "after an invalidation the next request reads from the start"); + // a request that fails mid-way leaves nothing to resume from + c.begin(&mut d, &second).unwrap(); + c.finish(false); + assert!(c.checkpoint_lengths().is_empty()); +} + +#[test] +fn the_chain_is_bounded_and_the_saved_points_follow_it() { + let mut c = ServeConversation::new(ConversationConfig { prompt_cache: 2, ..config() }); + let mut d = Fake::default(); + let mut prompt = chat(20, &[5]); + for k in 0..5 { + serve(&mut c, &mut d, &prompt, &[40 + k], false); + assert!(c.checkpoint_lengths().len() <= 2); + assert_eq!(c.saved.len(), c.checkpoint_lengths().len()); + prompt.extend([40 + k]); + prompt.extend(chat(0, &[3])[1..].iter().copied()); + } +} + +#[test] +fn reread_mode_reads_the_checkpoint_again_instead_of_restoring_it() { + let mut c = ServeConversation::new(ConversationConfig { reread_checkpoints: true, ..config() }); + let mut d = Fake::default(); + let first = chat(20, &[5]); + serve(&mut c, &mut d, &first, &[42], false); + let mut second = first.clone(); + second.extend([42, 9, 9]); + d.log.clear(); + let start = serve(&mut c, &mut d, &second, &[1], false); + assert_eq!((start.read_from, start.reread_to), (0, Some(first.len() - 3))); + assert_eq!(d.log[0], "zero"); + assert!(d.log.iter().all(|l| !l.starts_with("restore"))); +} + +#[test] +fn the_config_follows_the_original_defaults_and_refuses_nonsense() { + let o = ConversationConfig::original(); + assert_eq!((o.prompt_cache, o.prompt_cache_every, o.prompt_cache_root, o.turn_token), (6, 16_384, 2048, Some(248_045))); + assert!(o.validate().is_ok()); + assert!(ConversationConfig { prompt_cache: 0, ..o.clone() }.validate().is_err()); + assert!(ConversationConfig { turn_token: Some(248_320), ..o.clone() }.validate().is_err()); + let plan = o.plan_options(PromptOptions { prompt_cache: false, turn_token: None, root_min: 0, ..PromptOptions::original_mode17(4096) }); + assert!(plan.prompt_cache && plan.turn_token == Some(248_045) && plan.root_min == 2048); + assert_eq!(o.options().conversation_cache_bytes, 0, "parking stays off"); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs index 68e95563..42a75e80 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs @@ -555,671 +555,4 @@ impl OriginalServePort for TracePort

{ } #[cfg(test)] -mod tests { - use super::*; - use super::super::original_spec_controller::{NanGuard,OriginalSpecController,SpecConfig,SpecError}; - use super::super::original_spec_draft::DraftPreparation; - use std::cell::RefCell; - - const VOCAB:u32=1000; - fn model(x:i32)->i32 {(x*5+1)%997} - - #[derive(Default)] - struct World { - /// committed target tokens (the session prefix), including the current input. - committed:Vec,events:Vec,commit_waits:usize, - fail:Option<&'static str>,fail_restore:Option<&'static str>, - /// tokens the "MTP" drafts: chain of the model, shifted by `skew` to force rejections - skew:i32,sampler_cell:i64, - /// the highest cell (+1) a verify window row or a draft touched - max_end:i64, - } - struct Win {inputs:Vec,outputs:Vec,position:i64} - struct Fake {w:Rc>,pending_commit:Option,pending_position:i64} - impl Fake { - fn new(prompt:&[i32])->(Self,Rc>) { - let w=Rc::new(RefCell::new(World{committed:prompt.to_vec(),..Default::default()})); - (Self{w:Rc::clone(&w),pending_commit:None,pending_position:0},w) - } - fn log(&self,s:impl Into) {self.w.borrow_mut().events.push(s.into());} - fn fails(&self,what:&str)->bool {self.w.borrow().fail==Some(what)} - } - impl OriginalServePort for Fake { - type Window=Win;type Seed=i32;type TargetCheckpoint=(Vec,i64);type DraftCheckpoint=i64;type Adaptive=u64; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { - let w=self.w.borrow(); - if w.committed.len() as i64!=position+1||&w.committed[..consumed.len()]!=consumed||w.committed[position as usize]!=input {return Err(Error::IdentityMismatch);} - Ok(()) - } - fn checkpoint_target(&self)->Result { - if self.pending_commit.is_some() {return Err(Error::CudaExecution);} - let w=self.w.borrow();Ok((w.committed.clone(),w.sampler_cell)) - } - fn checkpoint_draft(&self)->Result {self.log("ckpt-draft");Ok(self.w.borrow().committed.len() as i64)} - fn restore_target(&mut self,c:&Self::TargetCheckpoint)->Result<()> { - self.log("restore-target"); - if self.w.borrow().fail_restore==Some("target") {return Err(Error::CudaExecution);} - let mut w=self.w.borrow_mut();w.committed=c.0.clone();w.sampler_cell=c.1;Ok(()) - } - fn restore_draft(&mut self,_:&i64)->Result<()> { - self.log("restore-draft"); - if self.w.borrow().fail_restore==Some("draft") {return Err(Error::CudaExecution);}Ok(()) - } - fn apply_pending(&mut self)->Result<()> {self.log("apply-pending");Ok(())} - fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { - self.log(format!("run t={} consumed={}",inputs.len(),consumed.len())); - if self.fails("run") {return Err(Error::CudaExecution);} - // the window must see the committed branch (async commit already published) - let outputs:Vec=inputs.iter().map(|&x|model(x)).collect(); - self.w.borrow_mut().sampler_cell=position+inputs.len() as i64; - {let mut w=self.w.borrow_mut();w.max_end=w.max_end.max(position+inputs.len() as i64);} - Ok(Win{inputs:inputs.to_vec(),outputs,position}) - } - fn validate_window(&self,w:&Win,position:i64,inputs:&[i32])->Result<()> { - if self.fails("validate") {return Err(Error::NonFinite);} - if w.position!=position||w.inputs!=inputs {return Err(Error::IdentityMismatch);}Ok(()) - } - fn window_outputs<'a>(&self,w:&'a Win)->&'a[i32] {if self.fails("short") {&w.outputs[..1]} else {&w.outputs}} - fn commit_window(&mut self,w:&mut Win,keep:usize)->Result<()> { - self.log(format!("commit keep={keep}")); - if self.fails("commit") {return Err(Error::CudaExecution);} - self.pending_commit=Some(keep);self.pending_position=w.position; - // the published prefix is visible only after wait_commit - Ok(()) - } - fn wait_commit(&mut self)->Result<()> { - if self.pending_commit.take().is_some() { - self.log("wait-commit");self.w.borrow_mut().commit_waits+=1; - if self.fails("wait") {return Err(Error::CudaExecution);} - } - Ok(()) - } - fn drain_window(&mut self,_:Win)->Result<()> {self.log("drain-window");if self.fails("drain") {Err(Error::CudaExecution)} else {Ok(())}} - fn discard_window(&mut self)->Result<()> {self.log("discard-window");if self.fails("discard") {Err(Error::CudaExecution)} else {Ok(())}} - fn begin_adaptation(&mut self,r:u64)->Result {self.log(format!("begin-adapt {r}"));if self.fails("begin") {Err(Error::CudaExecution)} else {Ok(r)}} - fn join_adaptation(&mut self,r:u64)->Result<()> {self.log(format!("join-adapt {r}"));if self.fails("join") {Err(Error::CudaExecution)} else {Ok(())}} - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.log(format!("history {} {next}",consumed.len()));Ok(())} - fn draft_committed(&mut self,w:&Win,position:i64,a:usize,outputs:&[i32],max_drafts:usize,min_p:f32,_coupled:bool)->Result { - self.log(format!("draft a={a}")); - if self.fails("draft") {return Err(Error::CudaExecution);} - let skew=self.w.borrow().skew; - let mut ids=vec![(model(outputs[a])+skew).rem_euclid(997)];let mut probs=vec![0.9f32]; - while ids.len()=min_p { - let last=*ids.last().unwrap();ids.push(model(last));probs.push(0.9); - } - let _=w; - {let mut wd=self.w.borrow_mut();wd.max_end=wd.max_end.max(position+a as i64+ids.len() as i64);} - Ok(DraftCompletion{ids,probabilities:probs,first_cell:position+a as i64,accepted_row:a}) - } - fn drain_draft(&mut self)->Result<()> {self.log("drain-draft");Ok(())} - fn draft_first(&mut self,_:&i32,_t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,_c:bool)->Result { - self.log("draft-first"); - let mut ids=vec![model(token)];let mut probs=vec![0.9f32]; - while ids.len()=min_p {let l=*ids.last().unwrap();ids.push(model(l));probs.push(0.9);} - Ok(DraftCompletion{ids,probabilities:probs,first_cell:cell,accepted_row:0}) - } - fn drain_first(&mut self)->Result<()> {self.log("drain-first");Ok(())} - } - - fn engine(prompt:&[i32],max_t:usize)->(OriginalServeEngine,Rc>) { - let (f,w)=Fake::new(prompt); - (OriginalServeEngine::new(f,VOCAB,max_t,max_t-1).unwrap(),w) - } - fn events(w:&Rc>)->Vec {w.borrow().events.clone()} - fn idx(e:&[String],needle:&str)->usize {e.iter().position(|s|s.starts_with(needle)).unwrap_or_else(||panic!("missing {needle} in {e:?}"))} - fn prompt() -> Vec {vec![11,model(11),model(model(11))]} - - /// Drive one window by hand the way the controller does (verify, commit). - fn verify_commit(e:&mut OriginalServeEngine,p:i64,inputs:&[i32],consumed:&[i32],keep:usize)->ServedWindow { - e.apply_pending().unwrap(); - let mut v=e.verify(p,inputs,consumed).unwrap(); - e.commit_verified(&mut v,keep).unwrap();v - } - - #[test] - fn constructor_validates_dimensions() { - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,0,4,3).is_err()); - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,VOCAB,0,0).is_err()); - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,VOCAB,4,4).is_err()); - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,VOCAB,4,3).is_ok()); - } - - #[test] - fn verify_returns_all_t_outputs_and_requires_a_drained_window() { - let p=prompt();let (mut e,w)=engine(&p,4); - let consumed=&p[..2];let input=p[2]; - let mut v=e.verify(2,&[input],consumed).unwrap(); - assert_eq!(e.outputs(&v),&[model(input)]); - e.validate_verified(&v,2,&[input]).unwrap(); - assert_eq!(e.validate_verified(&v,3,&[input]),Err(Error::IdentityMismatch)); - assert_eq!(e.validate_verified(&v,2,&[input+1]),Err(Error::IdentityMismatch)); - // a second window while one is live is refused before anything runs - let runs=events(&w).iter().filter(|s|s.starts_with("run")).count(); - assert_eq!(e.verify(2,&[input],consumed).err(),Some(Error::IdentityMismatch)); - assert_eq!(events(&w).iter().filter(|s|s.starts_with("run")).count(),runs); - e.commit_verified(&mut v,1).unwrap(); - assert_eq!(v.committed_rows(),Some(1)); - e.drain_verified(v).unwrap(); - e.wait_commit().unwrap(); - } - - #[test] - fn out_of_range_tokens_never_reach_the_port() { - let p=prompt();let (mut e,w)=engine(&p,4); - assert_eq!(e.verify(2,&[VOCAB as i32],&p[..2]).err(),Some(Error::InvalidToken)); - assert_eq!(e.verify(2,&[5],&[-1]).err(),Some(Error::InvalidToken)); - assert!(!events(&w).iter().any(|s|s.starts_with("run"))); - assert_eq!(e.verify(2,&[],&p[..2]).err(),Some(Error::IdentityMismatch)); - assert_eq!(e.verify(2,&[1,2,3,4,5],&p[..2]).err(),Some(Error::IdentityMismatch)); - } - - #[test] - fn a_short_or_invalid_window_is_drained_not_leaked() { - let p=prompt();let (mut e,w)=engine(&p,4); - w.borrow_mut().fail=Some("short"); - assert_eq!(e.verify(2,&[p[2],model(p[2])],&p[..2]).err(),Some(Error::IdentityMismatch)); - assert!(events(&w).iter().any(|s|s=="drain-window")); - w.borrow_mut().fail=Some("validate"); - assert_eq!(e.verify(2,&[p[2]],&p[..2]).err(),Some(Error::NonFinite)); - w.borrow_mut().fail=None; - // nothing left live: a clean window works again - let v=e.verify(2,&[p[2]],&p[..2]).unwrap();e.drain_verified(v).unwrap(); - assert!(!e.is_poisoned()); - } - - #[test] - fn commit_checks_the_accepted_prefix_and_only_once() { - let p=prompt();let (mut e,_)=engine(&p,4); - let a=p[2];let good=model(a); - let mut v=e.verify(2,&[a,good,good+1],&p[..2]).unwrap(); - // row 2's input (good+1) != output 1 (model(good)) so keep=3 is not a legal prefix - assert_eq!(e.commit_verified(&mut v,3),Err(Error::IdentityMismatch)); - assert_eq!(e.commit_verified(&mut v,0),Err(Error::IdentityMismatch)); - assert_eq!(e.commit_verified(&mut v,4),Err(Error::IdentityMismatch)); - e.commit_verified(&mut v,2).unwrap(); - assert_eq!(e.commit_verified(&mut v,2),Err(Error::IdentityMismatch)); - e.drain_verified(v).unwrap();e.wait_commit().unwrap(); - } - - #[test] - fn commit_is_asynchronous_and_the_window_drain_waits_for_its_event() { - let p=prompt();let (mut e,w)=engine(&p,4); - let v=verify_commit(&mut e,2,&[p[2]],&p[..2],1); - assert!(e.commit_pending()); - // checkpoints and validation refuse to read the session mid-commit - assert_eq!(e.checkpoint_target().err(),Some(Error::IdentityMismatch)); - assert_eq!(e.checkpoint_draft().err(),Some(Error::IdentityMismatch)); - assert_eq!(e.validate_current(&p[..2],p[2],2),Err(Error::IdentityMismatch)); - assert_eq!(w.borrow().commit_waits,0); - // the draft (event-dependent) runs before the drain; the drain waits + publishes - e.drain_verified(v).unwrap(); - assert_eq!(w.borrow().commit_waits,1); - assert!(!e.commit_pending()); - let ev=events(&w); - assert!(idx(&ev,"wait-commit")(Vec,Vec) { - let p=prompt_long(); - let (f,w)=Fake::new(&p[..p.len()-1]); - // Fake's committed prefix tracks tokens through the current input - w.borrow_mut().committed=p.clone();w.borrow_mut().skew=skew; - let mut e=OriginalServeEngine::new(f,VOCAB,max_t,max_t-1).unwrap(); - let mut c=OriginalSpecController::new(SpecConfig::new(max_t,0,4096,VOCAB,0,false).unwrap()).unwrap(); - c.begin_request(&p,max_new,0.0,&[]).unwrap(); - e.set_min_p(0.0).unwrap(); - let mut out=Vec::new(); - while !c.finished() { - // the fake's committed list must follow what the controller commits - let round=match c.verify_commit(&mut e,||false) {Ok(Some(r))=>r,Ok(None)=>break,Err(err)=>panic!("{err:?}")}; - out.extend_from_slice(round.tokens()); - w.borrow_mut().committed.extend_from_slice(round.tokens()); - c.finish_round(&mut e,round,||1.0,||false).unwrap(); - } - c.finish_request(&mut e).unwrap(); - let ev=events(&w);(out,ev) - } - fn prompt_long()->Vec {let mut v=vec![11];for i in 1..40 {v.push(model(v[i-1]));}v} - - #[test] - fn controller_over_the_engine_emits_the_greedy_continuation() { - let (out,ev)=run_request(0,4,20); - let mut expect=Vec::new();let mut x=*prompt_long().last().unwrap(); - for _ in 0..out.len() {x=model(x);expect.push(x);} - assert_eq!(out,expect); - assert!(out.len()>=20); - // every verify was followed by a commit, a drain, and (while unfinished) a draft - assert!(ev.iter().filter(|s|s.starts_with("commit keep=")).count()>=4); - assert_eq!(ev.iter().filter(|s|s.starts_with("run ")).count(),ev.iter().filter(|s|s.starts_with("commit keep=")).count()); - assert_eq!(ev.iter().filter(|s|*s=="drain-window").count(),ev.iter().filter(|s|s.starts_with("run ")).count()); - } - - #[test] - fn controller_over_the_engine_survives_rejected_drafts() { - let (out,ev)=run_request(3,4,12); - let mut expect=Vec::new();let mut x=*prompt_long().last().unwrap(); - for _ in 0..out.len() {x=model(x);expect.push(x);} - assert_eq!(out,expect,"rejected drafts must never change the greedy text"); - assert!(ev.iter().any(|s|s=="commit keep=1")); - } - - #[test] - fn controller_both_restores_run_when_the_verifier_fails() { - let p=prompt_long(); - let (f,w)=Fake::new(&p); - let mut e=OriginalServeEngine::new(f,VOCAB,4,3).unwrap(); - let mut c=OriginalSpecController::new(SpecConfig::new(4,0,4096,VOCAB,0,false).unwrap()).unwrap(); - c.begin_request(&p,8,0.0,&[]).unwrap(); - w.borrow_mut().fail=Some("run"); - let err=c.verify_commit(&mut e,||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); - let ev=events(&w); - assert!(ev.iter().any(|s|s=="restore-target")&&ev.iter().any(|s|s=="restore-draft")); - assert!(!c.is_failed()); - } - - #[test] - fn preparation_drives_the_engine_through_after_verified() { - let p=prompt();let (mut e,_)=engine(&p,4); - let a=p[2]; - let mut v=e.verify(2,&[a],&p[..2]).unwrap(); - let outs=e.outputs(&v).to_vec();e.commit_verified(&mut v,1).unwrap(); - let prep=DraftPreparation::new(4,3,VOCAB).unwrap(); - let batch=prep.after_verified(&mut e,&v,2,0,&outs,&p[..3],&mut crate::qwen_forward::token_memo::PrefixMemo::new(),0.0,false).unwrap(); - assert_eq!(batch.produced(),3); - assert_eq!(batch.ids()[0],model(outs[0])); - e.drain_verified(v).unwrap(); - } - - #[test] - fn the_adaptive_window_is_selected_by_the_explicit_switch_then_by_a_fixed_spec_then_by_the_default() { - let w=OriginalServeSettings::adaptive_wanted; - assert!(w(Some("on"),false)&&w(Some("1"),true)&&w(Some("yes"),true)); - assert!(!w(Some("off"),false)&&!w(Some("0"),false)&&!w(Some("no"),false)); - assert_eq!(w(None,false),ADAPTIVE_DEFAULT); - assert!(!w(None,true),"a fixed LELEKA_SPEC keeps the fixed window"); - } - - #[test] - fn a_window_cap_narrows_every_bound_and_leaves_the_rest() { - let mut wide=OriginalServeSettings::mode17(4096,VOCAB,true); - wide.max_t=8;wide.mtp_max_t=8; - wide.adaptive=Some(AdaptiveConfig::new(8,7)); - for cap in 2..=8 { - let s=wide.with_window_cap(cap); - assert_eq!((s.max_t,s.mtp_max_t),(cap,cap),"cap {cap}"); - assert_eq!(s.max_drafts(),cap-1); - let a=s.adaptive.unwrap(); - assert_eq!((a.max_t,a.max_drafts),(cap,cap-1)); - // unchanged: everything that is not a width - assert_eq!((s.max_context,s.vocabulary,s.suffix_min_match,s.coupled),(wide.max_context,wide.vocabulary,wide.suffix_min_match,wide.coupled)); - assert_eq!(s.nan_guard,wide.nan_guard); - // the controller and the engine accept it - let c=s.controller().unwrap(); - assert!(c.finished()&&!c.is_failed()); - let (f,_)=Fake::new(&prompt_long()); - assert!(OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_drafts()).is_ok(),"cap {cap}"); - } - // a cap above the settings changes nothing; a fixed window narrower than the cap keeps its own width - assert_eq!(wide.with_window_cap(8),wide); - let fixed=OriginalServeSettings::mode17(4096,VOCAB,false); - assert_eq!(fixed.with_window_cap(8),fixed); - let narrow=fixed.with_window_cap(3); - assert_eq!((narrow.max_t,narrow.mtp_max_t,narrow.max_drafts()),(3,3,2)); - assert!(narrow.adaptive.is_none()); - } - - #[test] - fn mode17_settings_follow_generate_defaults() { - let s=OriginalServeSettings::mode17(4096,VOCAB,false); - assert_eq!((s.max_t,s.mtp_max_t,s.suffix_min_match),(6,4,3)); - assert_eq!(s.max_drafts(),3); - // the drafter is loaded at the verify width (6), not at its own window width (4): suffix windows are 6 rows wide - assert_eq!(s.mtp_load_t(),6); - assert!(s.mtp_load_t()>=s.max_t&&s.max_drafts()bool,fail_emit_after:Option) - ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine) { - let (r,out,c,e,_)=serve_in(p,max_new,eos,cancel,fail_emit_after,4096);(r,out,c,e) - } - fn serve_in(p:&[i32],max_new:usize,eos:&[i32],mut cancel:impl FnMut()->bool,fail_emit_after:Option,max_context:i64) - ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine,Rc>) { - let (f,w)=Fake::new(p); - let s=OriginalServeSettings{max_t:4,mtp_max_t:0,max_context,vocabulary:VOCAB,suffix_min_match:0,coupled:false,adaptive:None,nan_guard:NanGuard::off(),request_min_p:None}; - let mut e=OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_t-1).unwrap(); - let mut c=s.controller().unwrap(); - let mut out=Vec::new(); - let wc=Rc::clone(&w); - let r=serve_request(&mut c,&mut e,p,max_new,0.0,eos,|t|{ - if fail_emit_after.is_some_and(|n|out.len()>=n) {return Err(Error::InputRead);} - out.extend_from_slice(t);wc.borrow_mut().committed.extend_from_slice(t);Ok(()) - },&mut cancel,||0.0); - (r,out,c,e,w) - } - - /// Upstream 41cf05a0 `e85567b6`: through the real engine (plan, cap and cross-check of the chain), a request that runs to the - /// context's end never touches a cell past it, whatever the distance of the last windows to it. - #[test] - fn serve_request_to_the_context_end_stays_inside_the_cells_and_ends_as_context() { - let p=prompt_long(); - for k in 1..=9i64 { - let max_context=p.len() as i64-1+k; - let (r,out,c,e,w)=serve_in(&p,1000,&[],||false,None,max_context); - let r=r.unwrap_or_else(|err|panic!("k {k}: {err:?}")); - assert_eq!(r.stop,ServeStop::Context,"k {k}"); - assert_eq!(out.len() as i64,k,"k {k}: one token per row that fits"); - let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} - assert!(w.borrow().max_end<=max_context,"k {k}: touched cell {} of {max_context}",w.borrow().max_end); - assert!(c.finished()&&!c.is_failed()&&!e.is_poisoned()&&!e.commit_pending(),"k {k}"); - } - } - - #[test] - fn serve_request_emits_the_greedy_text_and_reports_the_stop() { - let p=prompt_long(); - let (r,out,mut c,_e)=serve(&p,10,&[],||false,None); - let r=r.unwrap(); - assert_eq!(r.stop,ServeStop::Length); - assert!(r.produced>=10&&r.rounds>=1); - assert_eq!(out.len(),r.produced); - let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} - // the controller is reusable for the next request - assert!(c.begin_request(&p,1,0.0,&[]).is_ok()); - } - - /// Upstream 41cf05a0 `aece46db`: a 1-token prompt (position 0 is the first verify input) speculates like any other. - #[test] - fn serve_request_with_a_one_token_prompt_speculates() { - let p=vec![11]; - let (r,out,_c,e)=serve(&p,30,&[],||false,None); - let r=r.unwrap(); - assert_eq!((r.stop,r.produced),(ServeStop::Length,out.len())); - assert!(out.len()>=30); - let mut x=11;for &t in &out {x=model(x);assert_eq!(t,x);} - assert!(r.rounds3},None); - assert_eq!(r.err(),Some(SpecError::Cancelled)); - assert!(c.finished(),"a cancelled request is closed"); - assert!(!e.commit_pending()); - } - - #[test] - fn serve_request_a_failed_emit_still_finishes_the_round_and_closes_the_request() { - let p=prompt_long(); - let (r,out,c,e)=serve(&p,50,&[],||false,Some(1)); - assert_eq!(r.err(),Some(SpecError::Forward(Error::InputRead))); - assert!(!out.is_empty()); - assert!(c.finished()&&!e.commit_pending()); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_engine/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_engine/tests.rs new file mode 100644 index 00000000..78b948f9 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_engine/tests.rs @@ -0,0 +1,668 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use super::super::original_spec_controller::{NanGuard,OriginalSpecController,SpecConfig,SpecError}; +use super::super::original_spec_draft::DraftPreparation; +use std::cell::RefCell; + +const VOCAB:u32=1000; +fn model(x:i32)->i32 {(x*5+1)%997} + +#[derive(Default)] +struct World { + /// committed target tokens (the session prefix), including the current input. + committed:Vec,events:Vec,commit_waits:usize, + fail:Option<&'static str>,fail_restore:Option<&'static str>, + /// tokens the "MTP" drafts: chain of the model, shifted by `skew` to force rejections + skew:i32,sampler_cell:i64, + /// the highest cell (+1) a verify window row or a draft touched + max_end:i64, +} +struct Win {inputs:Vec,outputs:Vec,position:i64} +struct Fake {w:Rc>,pending_commit:Option,pending_position:i64} +impl Fake { + fn new(prompt:&[i32])->(Self,Rc>) { + let w=Rc::new(RefCell::new(World{committed:prompt.to_vec(),..Default::default()})); + (Self{w:Rc::clone(&w),pending_commit:None,pending_position:0},w) + } + fn log(&self,s:impl Into) {self.w.borrow_mut().events.push(s.into());} + fn fails(&self,what:&str)->bool {self.w.borrow().fail==Some(what)} +} +impl OriginalServePort for Fake { + type Window=Win;type Seed=i32;type TargetCheckpoint=(Vec,i64);type DraftCheckpoint=i64;type Adaptive=u64; + fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { + let w=self.w.borrow(); + if w.committed.len() as i64!=position+1||&w.committed[..consumed.len()]!=consumed||w.committed[position as usize]!=input {return Err(Error::IdentityMismatch);} + Ok(()) + } + fn checkpoint_target(&self)->Result { + if self.pending_commit.is_some() {return Err(Error::CudaExecution);} + let w=self.w.borrow();Ok((w.committed.clone(),w.sampler_cell)) + } + fn checkpoint_draft(&self)->Result {self.log("ckpt-draft");Ok(self.w.borrow().committed.len() as i64)} + fn restore_target(&mut self,c:&Self::TargetCheckpoint)->Result<()> { + self.log("restore-target"); + if self.w.borrow().fail_restore==Some("target") {return Err(Error::CudaExecution);} + let mut w=self.w.borrow_mut();w.committed=c.0.clone();w.sampler_cell=c.1;Ok(()) + } + fn restore_draft(&mut self,_:&i64)->Result<()> { + self.log("restore-draft"); + if self.w.borrow().fail_restore==Some("draft") {return Err(Error::CudaExecution);}Ok(()) + } + fn apply_pending(&mut self)->Result<()> {self.log("apply-pending");Ok(())} + fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { + self.log(format!("run t={} consumed={}",inputs.len(),consumed.len())); + if self.fails("run") {return Err(Error::CudaExecution);} + // the window must see the committed branch (async commit already published) + let outputs:Vec=inputs.iter().map(|&x|model(x)).collect(); + self.w.borrow_mut().sampler_cell=position+inputs.len() as i64; + {let mut w=self.w.borrow_mut();w.max_end=w.max_end.max(position+inputs.len() as i64);} + Ok(Win{inputs:inputs.to_vec(),outputs,position}) + } + fn validate_window(&self,w:&Win,position:i64,inputs:&[i32])->Result<()> { + if self.fails("validate") {return Err(Error::NonFinite);} + if w.position!=position||w.inputs!=inputs {return Err(Error::IdentityMismatch);}Ok(()) + } + fn window_outputs<'a>(&self,w:&'a Win)->&'a[i32] {if self.fails("short") {&w.outputs[..1]} else {&w.outputs}} + fn commit_window(&mut self,w:&mut Win,keep:usize)->Result<()> { + self.log(format!("commit keep={keep}")); + if self.fails("commit") {return Err(Error::CudaExecution);} + self.pending_commit=Some(keep);self.pending_position=w.position; + // the published prefix is visible only after wait_commit + Ok(()) + } + fn wait_commit(&mut self)->Result<()> { + if self.pending_commit.take().is_some() { + self.log("wait-commit");self.w.borrow_mut().commit_waits+=1; + if self.fails("wait") {return Err(Error::CudaExecution);} + } + Ok(()) + } + fn drain_window(&mut self,_:Win)->Result<()> {self.log("drain-window");if self.fails("drain") {Err(Error::CudaExecution)} else {Ok(())}} + fn discard_window(&mut self)->Result<()> {self.log("discard-window");if self.fails("discard") {Err(Error::CudaExecution)} else {Ok(())}} + fn begin_adaptation(&mut self,r:u64)->Result {self.log(format!("begin-adapt {r}"));if self.fails("begin") {Err(Error::CudaExecution)} else {Ok(r)}} + fn join_adaptation(&mut self,r:u64)->Result<()> {self.log(format!("join-adapt {r}"));if self.fails("join") {Err(Error::CudaExecution)} else {Ok(())}} + fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.log(format!("history {} {next}",consumed.len()));Ok(())} + fn draft_committed(&mut self,w:&Win,position:i64,a:usize,outputs:&[i32],max_drafts:usize,min_p:f32,_coupled:bool)->Result { + self.log(format!("draft a={a}")); + if self.fails("draft") {return Err(Error::CudaExecution);} + let skew=self.w.borrow().skew; + let mut ids=vec![(model(outputs[a])+skew).rem_euclid(997)];let mut probs=vec![0.9f32]; + while ids.len()=min_p { + let last=*ids.last().unwrap();ids.push(model(last));probs.push(0.9); + } + let _=w; + {let mut wd=self.w.borrow_mut();wd.max_end=wd.max_end.max(position+a as i64+ids.len() as i64);} + Ok(DraftCompletion{ids,probabilities:probs,first_cell:position+a as i64,accepted_row:a}) + } + fn drain_draft(&mut self)->Result<()> {self.log("drain-draft");Ok(())} + fn draft_first(&mut self,_:&i32,_t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,_c:bool)->Result { + self.log("draft-first"); + let mut ids=vec![model(token)];let mut probs=vec![0.9f32]; + while ids.len()=min_p {let l=*ids.last().unwrap();ids.push(model(l));probs.push(0.9);} + Ok(DraftCompletion{ids,probabilities:probs,first_cell:cell,accepted_row:0}) + } + fn drain_first(&mut self)->Result<()> {self.log("drain-first");Ok(())} +} + +fn engine(prompt:&[i32],max_t:usize)->(OriginalServeEngine,Rc>) { + let (f,w)=Fake::new(prompt); + (OriginalServeEngine::new(f,VOCAB,max_t,max_t-1).unwrap(),w) +} +fn events(w:&Rc>)->Vec {w.borrow().events.clone()} +fn idx(e:&[String],needle:&str)->usize {e.iter().position(|s|s.starts_with(needle)).unwrap_or_else(||panic!("missing {needle} in {e:?}"))} +fn prompt() -> Vec {vec![11,model(11),model(model(11))]} + +/// Drive one window by hand the way the controller does (verify, commit). +fn verify_commit(e:&mut OriginalServeEngine,p:i64,inputs:&[i32],consumed:&[i32],keep:usize)->ServedWindow { + e.apply_pending().unwrap(); + let mut v=e.verify(p,inputs,consumed).unwrap(); + e.commit_verified(&mut v,keep).unwrap();v +} + +#[test] +fn constructor_validates_dimensions() { + let (f,_)=Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f,0,4,3).is_err()); + let (f,_)=Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f,VOCAB,0,0).is_err()); + let (f,_)=Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f,VOCAB,4,4).is_err()); + let (f,_)=Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f,VOCAB,4,3).is_ok()); +} + +#[test] +fn verify_returns_all_t_outputs_and_requires_a_drained_window() { + let p=prompt();let (mut e,w)=engine(&p,4); + let consumed=&p[..2];let input=p[2]; + let mut v=e.verify(2,&[input],consumed).unwrap(); + assert_eq!(e.outputs(&v),&[model(input)]); + e.validate_verified(&v,2,&[input]).unwrap(); + assert_eq!(e.validate_verified(&v,3,&[input]),Err(Error::IdentityMismatch)); + assert_eq!(e.validate_verified(&v,2,&[input+1]),Err(Error::IdentityMismatch)); + // a second window while one is live is refused before anything runs + let runs=events(&w).iter().filter(|s|s.starts_with("run")).count(); + assert_eq!(e.verify(2,&[input],consumed).err(),Some(Error::IdentityMismatch)); + assert_eq!(events(&w).iter().filter(|s|s.starts_with("run")).count(),runs); + e.commit_verified(&mut v,1).unwrap(); + assert_eq!(v.committed_rows(),Some(1)); + e.drain_verified(v).unwrap(); + e.wait_commit().unwrap(); +} + +#[test] +fn out_of_range_tokens_never_reach_the_port() { + let p=prompt();let (mut e,w)=engine(&p,4); + assert_eq!(e.verify(2,&[VOCAB as i32],&p[..2]).err(),Some(Error::InvalidToken)); + assert_eq!(e.verify(2,&[5],&[-1]).err(),Some(Error::InvalidToken)); + assert!(!events(&w).iter().any(|s|s.starts_with("run"))); + assert_eq!(e.verify(2,&[],&p[..2]).err(),Some(Error::IdentityMismatch)); + assert_eq!(e.verify(2,&[1,2,3,4,5],&p[..2]).err(),Some(Error::IdentityMismatch)); +} + +#[test] +fn a_short_or_invalid_window_is_drained_not_leaked() { + let p=prompt();let (mut e,w)=engine(&p,4); + w.borrow_mut().fail=Some("short"); + assert_eq!(e.verify(2,&[p[2],model(p[2])],&p[..2]).err(),Some(Error::IdentityMismatch)); + assert!(events(&w).iter().any(|s|s=="drain-window")); + w.borrow_mut().fail=Some("validate"); + assert_eq!(e.verify(2,&[p[2]],&p[..2]).err(),Some(Error::NonFinite)); + w.borrow_mut().fail=None; + // nothing left live: a clean window works again + let v=e.verify(2,&[p[2]],&p[..2]).unwrap();e.drain_verified(v).unwrap(); + assert!(!e.is_poisoned()); +} + +#[test] +fn commit_checks_the_accepted_prefix_and_only_once() { + let p=prompt();let (mut e,_)=engine(&p,4); + let a=p[2];let good=model(a); + let mut v=e.verify(2,&[a,good,good+1],&p[..2]).unwrap(); + // row 2's input (good+1) != output 1 (model(good)) so keep=3 is not a legal prefix + assert_eq!(e.commit_verified(&mut v,3),Err(Error::IdentityMismatch)); + assert_eq!(e.commit_verified(&mut v,0),Err(Error::IdentityMismatch)); + assert_eq!(e.commit_verified(&mut v,4),Err(Error::IdentityMismatch)); + e.commit_verified(&mut v,2).unwrap(); + assert_eq!(e.commit_verified(&mut v,2),Err(Error::IdentityMismatch)); + e.drain_verified(v).unwrap();e.wait_commit().unwrap(); +} + +#[test] +fn commit_is_asynchronous_and_the_window_drain_waits_for_its_event() { + let p=prompt();let (mut e,w)=engine(&p,4); + let v=verify_commit(&mut e,2,&[p[2]],&p[..2],1); + assert!(e.commit_pending()); + // checkpoints and validation refuse to read the session mid-commit + assert_eq!(e.checkpoint_target().err(),Some(Error::IdentityMismatch)); + assert_eq!(e.checkpoint_draft().err(),Some(Error::IdentityMismatch)); + assert_eq!(e.validate_current(&p[..2],p[2],2),Err(Error::IdentityMismatch)); + assert_eq!(w.borrow().commit_waits,0); + // the draft (event-dependent) runs before the drain; the drain waits + publishes + e.drain_verified(v).unwrap(); + assert_eq!(w.borrow().commit_waits,1); + assert!(!e.commit_pending()); + let ev=events(&w); + assert!(idx(&ev,"wait-commit")(Vec,Vec) { + let p=prompt_long(); + let (f,w)=Fake::new(&p[..p.len()-1]); + // Fake's committed prefix tracks tokens through the current input + w.borrow_mut().committed=p.clone();w.borrow_mut().skew=skew; + let mut e=OriginalServeEngine::new(f,VOCAB,max_t,max_t-1).unwrap(); + let mut c=OriginalSpecController::new(SpecConfig::new(max_t,0,4096,VOCAB,0,false).unwrap()).unwrap(); + c.begin_request(&p,max_new,0.0,&[]).unwrap(); + e.set_min_p(0.0).unwrap(); + let mut out=Vec::new(); + while !c.finished() { + // the fake's committed list must follow what the controller commits + let round=match c.verify_commit(&mut e,||false) {Ok(Some(r))=>r,Ok(None)=>break,Err(err)=>panic!("{err:?}")}; + out.extend_from_slice(round.tokens()); + w.borrow_mut().committed.extend_from_slice(round.tokens()); + c.finish_round(&mut e,round,||1.0,||false).unwrap(); + } + c.finish_request(&mut e).unwrap(); + let ev=events(&w);(out,ev) +} +fn prompt_long()->Vec {let mut v=vec![11];for i in 1..40 {v.push(model(v[i-1]));}v} + +#[test] +fn controller_over_the_engine_emits_the_greedy_continuation() { + let (out,ev)=run_request(0,4,20); + let mut expect=Vec::new();let mut x=*prompt_long().last().unwrap(); + for _ in 0..out.len() {x=model(x);expect.push(x);} + assert_eq!(out,expect); + assert!(out.len()>=20); + // every verify was followed by a commit, a drain, and (while unfinished) a draft + assert!(ev.iter().filter(|s|s.starts_with("commit keep=")).count()>=4); + assert_eq!(ev.iter().filter(|s|s.starts_with("run ")).count(),ev.iter().filter(|s|s.starts_with("commit keep=")).count()); + assert_eq!(ev.iter().filter(|s|*s=="drain-window").count(),ev.iter().filter(|s|s.starts_with("run ")).count()); +} + +#[test] +fn controller_over_the_engine_survives_rejected_drafts() { + let (out,ev)=run_request(3,4,12); + let mut expect=Vec::new();let mut x=*prompt_long().last().unwrap(); + for _ in 0..out.len() {x=model(x);expect.push(x);} + assert_eq!(out,expect,"rejected drafts must never change the greedy text"); + assert!(ev.iter().any(|s|s=="commit keep=1")); +} + +#[test] +fn controller_both_restores_run_when_the_verifier_fails() { + let p=prompt_long(); + let (f,w)=Fake::new(&p); + let mut e=OriginalServeEngine::new(f,VOCAB,4,3).unwrap(); + let mut c=OriginalSpecController::new(SpecConfig::new(4,0,4096,VOCAB,0,false).unwrap()).unwrap(); + c.begin_request(&p,8,0.0,&[]).unwrap(); + w.borrow_mut().fail=Some("run"); + let err=c.verify_commit(&mut e,||false).err().unwrap(); + assert_eq!(err,SpecError::Forward(Error::CudaExecution)); + let ev=events(&w); + assert!(ev.iter().any(|s|s=="restore-target")&&ev.iter().any(|s|s=="restore-draft")); + assert!(!c.is_failed()); +} + +#[test] +fn preparation_drives_the_engine_through_after_verified() { + let p=prompt();let (mut e,_)=engine(&p,4); + let a=p[2]; + let mut v=e.verify(2,&[a],&p[..2]).unwrap(); + let outs=e.outputs(&v).to_vec();e.commit_verified(&mut v,1).unwrap(); + let prep=DraftPreparation::new(4,3,VOCAB).unwrap(); + let batch=prep.after_verified(&mut e,&v,2,0,&outs,&p[..3],&mut crate::qwen_forward::token_memo::PrefixMemo::new(),0.0,false).unwrap(); + assert_eq!(batch.produced(),3); + assert_eq!(batch.ids()[0],model(outs[0])); + e.drain_verified(v).unwrap(); +} + +#[test] +fn the_adaptive_window_is_selected_by_the_explicit_switch_then_by_a_fixed_spec_then_by_the_default() { + let w=OriginalServeSettings::adaptive_wanted; + assert!(w(Some("on"),false)&&w(Some("1"),true)&&w(Some("yes"),true)); + assert!(!w(Some("off"),false)&&!w(Some("0"),false)&&!w(Some("no"),false)); + assert_eq!(w(None,false),ADAPTIVE_DEFAULT); + assert!(!w(None,true),"a fixed LELEKA_SPEC keeps the fixed window"); +} + +#[test] +fn a_window_cap_narrows_every_bound_and_leaves_the_rest() { + let mut wide=OriginalServeSettings::mode17(4096,VOCAB,true); + wide.max_t=8;wide.mtp_max_t=8; + wide.adaptive=Some(AdaptiveConfig::new(8,7)); + for cap in 2..=8 { + let s=wide.with_window_cap(cap); + assert_eq!((s.max_t,s.mtp_max_t),(cap,cap),"cap {cap}"); + assert_eq!(s.max_drafts(),cap-1); + let a=s.adaptive.unwrap(); + assert_eq!((a.max_t,a.max_drafts),(cap,cap-1)); + // unchanged: everything that is not a width + assert_eq!((s.max_context,s.vocabulary,s.suffix_min_match,s.coupled),(wide.max_context,wide.vocabulary,wide.suffix_min_match,wide.coupled)); + assert_eq!(s.nan_guard,wide.nan_guard); + // the controller and the engine accept it + let c=s.controller().unwrap(); + assert!(c.finished()&&!c.is_failed()); + let (f,_)=Fake::new(&prompt_long()); + assert!(OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_drafts()).is_ok(),"cap {cap}"); + } + // a cap above the settings changes nothing; a fixed window narrower than the cap keeps its own width + assert_eq!(wide.with_window_cap(8),wide); + let fixed=OriginalServeSettings::mode17(4096,VOCAB,false); + assert_eq!(fixed.with_window_cap(8),fixed); + let narrow=fixed.with_window_cap(3); + assert_eq!((narrow.max_t,narrow.mtp_max_t,narrow.max_drafts()),(3,3,2)); + assert!(narrow.adaptive.is_none()); +} + +#[test] +fn mode17_settings_follow_generate_defaults() { + let s=OriginalServeSettings::mode17(4096,VOCAB,false); + assert_eq!((s.max_t,s.mtp_max_t,s.suffix_min_match),(6,4,3)); + assert_eq!(s.max_drafts(),3); + // the drafter is loaded at the verify width (6), not at its own window width (4): suffix windows are 6 rows wide + assert_eq!(s.mtp_load_t(),6); + assert!(s.mtp_load_t()>=s.max_t&&s.max_drafts()bool,fail_emit_after:Option) + ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine) { + let (r,out,c,e,_)=serve_in(p,max_new,eos,cancel,fail_emit_after,4096);(r,out,c,e) +} +fn serve_in(p:&[i32],max_new:usize,eos:&[i32],mut cancel:impl FnMut()->bool,fail_emit_after:Option,max_context:i64) + ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine,Rc>) { + let (f,w)=Fake::new(p); + let s=OriginalServeSettings{max_t:4,mtp_max_t:0,max_context,vocabulary:VOCAB,suffix_min_match:0,coupled:false,adaptive:None,nan_guard:NanGuard::off(),request_min_p:None}; + let mut e=OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_t-1).unwrap(); + let mut c=s.controller().unwrap(); + let mut out=Vec::new(); + let wc=Rc::clone(&w); + let r=serve_request(&mut c,&mut e,p,max_new,0.0,eos,|t|{ + if fail_emit_after.is_some_and(|n|out.len()>=n) {return Err(Error::InputRead);} + out.extend_from_slice(t);wc.borrow_mut().committed.extend_from_slice(t);Ok(()) + },&mut cancel,||0.0); + (r,out,c,e,w) +} + +/// Upstream 41cf05a0 `e85567b6`: through the real engine (plan, cap and cross-check of the chain), a request that runs to the +/// context's end never touches a cell past it, whatever the distance of the last windows to it. +#[test] +fn serve_request_to_the_context_end_stays_inside_the_cells_and_ends_as_context() { + let p=prompt_long(); + for k in 1..=9i64 { + let max_context=p.len() as i64-1+k; + let (r,out,c,e,w)=serve_in(&p,1000,&[],||false,None,max_context); + let r=r.unwrap_or_else(|err|panic!("k {k}: {err:?}")); + assert_eq!(r.stop,ServeStop::Context,"k {k}"); + assert_eq!(out.len() as i64,k,"k {k}: one token per row that fits"); + let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} + assert!(w.borrow().max_end<=max_context,"k {k}: touched cell {} of {max_context}",w.borrow().max_end); + assert!(c.finished()&&!c.is_failed()&&!e.is_poisoned()&&!e.commit_pending(),"k {k}"); + } +} + +#[test] +fn serve_request_emits_the_greedy_text_and_reports_the_stop() { + let p=prompt_long(); + let (r,out,mut c,_e)=serve(&p,10,&[],||false,None); + let r=r.unwrap(); + assert_eq!(r.stop,ServeStop::Length); + assert!(r.produced>=10&&r.rounds>=1); + assert_eq!(out.len(),r.produced); + let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} + // the controller is reusable for the next request + assert!(c.begin_request(&p,1,0.0,&[]).is_ok()); +} + +/// Upstream 41cf05a0 `aece46db`: a 1-token prompt (position 0 is the first verify input) speculates like any other. +#[test] +fn serve_request_with_a_one_token_prompt_speculates() { + let p=vec![11]; + let (r,out,_c,e)=serve(&p,30,&[],||false,None); + let r=r.unwrap(); + assert_eq!((r.stop,r.produced),(ServeStop::Length,out.len())); + assert!(out.len()>=30); + let mut x=11;for &t in &out {x=model(x);assert_eq!(t,x);} + assert!(r.rounds3},None); + assert_eq!(r.err(),Some(SpecError::Cancelled)); + assert!(c.finished(),"a cancelled request is closed"); + assert!(!e.commit_pending()); +} + +#[test] +fn serve_request_a_failed_emit_still_finishes_the_round_and_closes_the_request() { + let p=prompt_long(); + let (r,out,c,e)=serve(&p,50,&[],||false,Some(1)); + assert_eq!(r.err(),Some(SpecError::Forward(Error::InputRead))); + assert!(!out.is_empty()); + assert!(c.finished()&&!e.commit_pending()); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs index 4e0c5a59..a7c596ed 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_host.rs @@ -588,40 +588,4 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { } #[cfg(test)] -mod tests { - use super::*; - - fn greedy() -> SamplerParams { - crate::qwen_forward::original_serve_config::greedy_params(1) - } - - #[test] - fn a_greedy_request_without_penalties_does_not_enable_the_sampling_head() { - let sampling = RequestSampling::new(greedy(), SamplerPath::Split).unwrap(); - assert!(!sampling.enabled()); - let mut penalized = greedy(); - penalized.penalty_last_n = 64; - assert!(RequestSampling::new(penalized, SamplerPath::Split).unwrap().enabled()); - let mut stochastic = SamplerParams::default(); - stochastic.temperature = 0.7; - stochastic.greedy = false; - assert!(RequestSampling::new(stochastic, SamplerPath::OneBlock).unwrap().enabled()); - } - - #[test] - fn invalid_sampler_parameters_are_refused_before_any_window() { - let mut bad = greedy(); - bad.top_p = 1.5; - assert!(RequestSampling::new(bad, SamplerPath::Split).is_err()); - let mut nan = greedy(); - nan.temperature = f32::NAN; - assert!(RequestSampling::new(nan, SamplerPath::Split).is_err()); - } - - #[test] - fn the_host_outcome_names_the_four_things_the_stack_decides_on() { - let outcome = HostOutcome { failed: false, dirty: true, state_lag: true, position: 9 }; - assert!(outcome.dirty && outcome.state_lag && !outcome.failed); - assert_eq!(outcome.position, 9); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_host/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_host/tests.rs new file mode 100644 index 00000000..7780f44e --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_host/tests.rs @@ -0,0 +1,37 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn greedy() -> SamplerParams { + crate::qwen_forward::original_serve_config::greedy_params(1) +} + +#[test] +fn a_greedy_request_without_penalties_does_not_enable_the_sampling_head() { + let sampling = RequestSampling::new(greedy(), SamplerPath::Split).unwrap(); + assert!(!sampling.enabled()); + let mut penalized = greedy(); + penalized.penalty_last_n = 64; + assert!(RequestSampling::new(penalized, SamplerPath::Split).unwrap().enabled()); + let mut stochastic = SamplerParams::default(); + stochastic.temperature = 0.7; + stochastic.greedy = false; + assert!(RequestSampling::new(stochastic, SamplerPath::OneBlock).unwrap().enabled()); +} + +#[test] +fn invalid_sampler_parameters_are_refused_before_any_window() { + let mut bad = greedy(); + bad.top_p = 1.5; + assert!(RequestSampling::new(bad, SamplerPath::Split).is_err()); + let mut nan = greedy(); + nan.temperature = f32::NAN; + assert!(RequestSampling::new(nan, SamplerPath::Split).is_err()); +} + +#[test] +fn the_host_outcome_names_the_four_things_the_stack_decides_on() { + let outcome = HostOutcome { failed: false, dirty: true, state_lag: true, position: 9 }; + assert!(outcome.dirty && outcome.state_lag && !outcome.failed); + assert_eq!(outcome.position, 9); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs index 16fa104b..5f048d89 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs @@ -850,101 +850,4 @@ fn selection(ids: &[i32], row: usize) -> Result<[u32; TOP_K]> { } #[cfg(test)] -mod tests { - use super::*; - - fn ids(rows: &[[i32; TOP_K]]) -> Vec { - rows.iter().flatten().copied().collect() - } - - #[test] - fn every_pair_is_planned_exactly_once_and_experts_keep_first_use_order() { - let a = [5, 1, 9, 2, 3, 4, 6, 7, 8, 0]; - let b = [9, 5, 11, 12, 13, 14, 15, 16, 17, 18]; - let plan = plan_experts(&ids(&[a, b]), 2).unwrap(); - assert_eq!(plan[0], ExpertJob { expert: 5, pairs: vec![(0, 0), (1, 1)] }); - assert_eq!(plan[1], ExpertJob { expert: 1, pairs: vec![(0, 1)] }); - assert_eq!(plan[2], ExpertJob { expert: 9, pairs: vec![(0, 2), (1, 0)] }); - let total: usize = plan.iter().map(|j| j.pairs.len()).sum(); - assert_eq!(total, 20); - let mut all: Vec<_> = plan.iter().flat_map(|j| j.pairs.iter().copied()).collect(); - all.sort_unstable(); - all.dedup(); - assert_eq!(all.len(), 20); - // distinct experts: 10 + 8 new in row 1 (9 and 5 shared) - assert_eq!(plan.len(), 18); - } - - #[test] - fn a_mask_leaves_the_gpu_entries_out_but_still_validates_them() { - let a = [5, 1, 9, 2, 3, 4, 6, 7, 8, 0]; - let b = [9, 5, 11, 12, 13, 14, 15, 16, 17, 18]; - let mut include = vec![true; 20]; - // expert 5 on the GPU in both rows, expert 9 only in row 0 - include[0] = false; - include[11] = false; - include[2] = false; - let plan = plan_experts_where(&ids(&[a, b]), 2, Some(&include)).unwrap(); - assert!(plan.iter().all(|j| j.expert != 5)); - assert_eq!(plan.iter().find(|j| j.expert == 9).unwrap().pairs, vec![(1, 0)]); - assert_eq!(plan.iter().map(|j| j.pairs.len()).sum::(), 17); - // a repeat is refused even inside a masked entry - let mut bad = a; - bad[1] = 5; - assert_eq!(plan_experts_where(&ids(&[bad]), 1, Some(&[false; 10])), Err(Error::InvalidExpert)); - assert_eq!(plan_experts_where(&ids(&[a]), 1, Some(&[true; 9])), Err(Error::InvalidDimension)); - } - - #[test] - fn invalid_router_output_is_refused_not_repaired() { - let good = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - assert_eq!(plan_experts(&ids(&[good]), 0), Err(Error::InvalidDimension)); - assert_eq!(plan_experts(&good, 2), Err(Error::InvalidDimension)); - assert_eq!(plan_experts(&vec![0; 90], 9), Err(Error::InvalidDimension)); - let mut out_of_range = good; - out_of_range[3] = 512; - assert_eq!(plan_experts(&ids(&[out_of_range]), 1), Err(Error::InvalidExpert)); - out_of_range[3] = -1; - assert_eq!(plan_experts(&ids(&[out_of_range]), 1), Err(Error::InvalidExpert)); - let mut repeated = good; - repeated[9] = 0; - assert_eq!(plan_experts(&ids(&[repeated]), 1), Err(Error::InvalidExpert)); - } - - #[test] - fn scatter_writes_each_slot_at_the_documented_offset_and_nothing_else() { - let rows = 3; - let mut out = vec![-1.0f32; rows * TOP_K * HIDDEN]; - let job = ExpertJob { expert: 7, pairs: vec![(0, 4), (2, 9)] }; - let mut values = vec![0.0f32; 2 * HIDDEN]; - values[..HIDDEN].fill(1.0); - values[HIDDEN..].fill(2.0); - scatter(&mut out, &job, &values).unwrap(); - for row in 0..rows { - for slot in 0..TOP_K { - let at = output_offset(row, slot); - let want = match (row, slot) { - (0, 4) => 1.0, - (2, 9) => 2.0, - _ => -1.0, - }; - assert!(out[at..at + HIDDEN].iter().all(|&v| v == want), "slot ({row},{slot})"); - } - } - assert_eq!(output_offset(1, 3), (TOP_K + 3) * HIDDEN); - // wrong value count / out-of-window pair - assert_eq!(scatter(&mut out, &job, &values[..HIDDEN]), Err(Error::InvalidDimension)); - let far = ExpertJob { expert: 1, pairs: vec![(rows, 0)] }; - assert_eq!(scatter(&mut out, &far, &values[..HIDDEN]), Err(Error::InvalidDimension)); - } - - #[test] - fn selection_rejects_negative_ids_and_short_rows() { - let good = ids(&[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]); - assert_eq!(selection(&good, 0), Ok([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])); - assert_eq!(selection(&good, 1), Err(Error::InvalidDimension)); - let mut bad = good.clone(); - bad[2] = -3; - assert_eq!(selection(&bad, 0), Err(Error::InvalidExpert)); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_pool/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_pool/tests.rs new file mode 100644 index 00000000..4df3fb00 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_pool/tests.rs @@ -0,0 +1,98 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn ids(rows: &[[i32; TOP_K]]) -> Vec { + rows.iter().flatten().copied().collect() +} + +#[test] +fn every_pair_is_planned_exactly_once_and_experts_keep_first_use_order() { + let a = [5, 1, 9, 2, 3, 4, 6, 7, 8, 0]; + let b = [9, 5, 11, 12, 13, 14, 15, 16, 17, 18]; + let plan = plan_experts(&ids(&[a, b]), 2).unwrap(); + assert_eq!(plan[0], ExpertJob { expert: 5, pairs: vec![(0, 0), (1, 1)] }); + assert_eq!(plan[1], ExpertJob { expert: 1, pairs: vec![(0, 1)] }); + assert_eq!(plan[2], ExpertJob { expert: 9, pairs: vec![(0, 2), (1, 0)] }); + let total: usize = plan.iter().map(|j| j.pairs.len()).sum(); + assert_eq!(total, 20); + let mut all: Vec<_> = plan.iter().flat_map(|j| j.pairs.iter().copied()).collect(); + all.sort_unstable(); + all.dedup(); + assert_eq!(all.len(), 20); + // distinct experts: 10 + 8 new in row 1 (9 and 5 shared) + assert_eq!(plan.len(), 18); +} + +#[test] +fn a_mask_leaves_the_gpu_entries_out_but_still_validates_them() { + let a = [5, 1, 9, 2, 3, 4, 6, 7, 8, 0]; + let b = [9, 5, 11, 12, 13, 14, 15, 16, 17, 18]; + let mut include = vec![true; 20]; + // expert 5 on the GPU in both rows, expert 9 only in row 0 + include[0] = false; + include[11] = false; + include[2] = false; + let plan = plan_experts_where(&ids(&[a, b]), 2, Some(&include)).unwrap(); + assert!(plan.iter().all(|j| j.expert != 5)); + assert_eq!(plan.iter().find(|j| j.expert == 9).unwrap().pairs, vec![(1, 0)]); + assert_eq!(plan.iter().map(|j| j.pairs.len()).sum::(), 17); + // a repeat is refused even inside a masked entry + let mut bad = a; + bad[1] = 5; + assert_eq!(plan_experts_where(&ids(&[bad]), 1, Some(&[false; 10])), Err(Error::InvalidExpert)); + assert_eq!(plan_experts_where(&ids(&[a]), 1, Some(&[true; 9])), Err(Error::InvalidDimension)); +} + +#[test] +fn invalid_router_output_is_refused_not_repaired() { + let good = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + assert_eq!(plan_experts(&ids(&[good]), 0), Err(Error::InvalidDimension)); + assert_eq!(plan_experts(&good, 2), Err(Error::InvalidDimension)); + assert_eq!(plan_experts(&vec![0; 90], 9), Err(Error::InvalidDimension)); + let mut out_of_range = good; + out_of_range[3] = 512; + assert_eq!(plan_experts(&ids(&[out_of_range]), 1), Err(Error::InvalidExpert)); + out_of_range[3] = -1; + assert_eq!(plan_experts(&ids(&[out_of_range]), 1), Err(Error::InvalidExpert)); + let mut repeated = good; + repeated[9] = 0; + assert_eq!(plan_experts(&ids(&[repeated]), 1), Err(Error::InvalidExpert)); +} + +#[test] +fn scatter_writes_each_slot_at_the_documented_offset_and_nothing_else() { + let rows = 3; + let mut out = vec![-1.0f32; rows * TOP_K * HIDDEN]; + let job = ExpertJob { expert: 7, pairs: vec![(0, 4), (2, 9)] }; + let mut values = vec![0.0f32; 2 * HIDDEN]; + values[..HIDDEN].fill(1.0); + values[HIDDEN..].fill(2.0); + scatter(&mut out, &job, &values).unwrap(); + for row in 0..rows { + for slot in 0..TOP_K { + let at = output_offset(row, slot); + let want = match (row, slot) { + (0, 4) => 1.0, + (2, 9) => 2.0, + _ => -1.0, + }; + assert!(out[at..at + HIDDEN].iter().all(|&v| v == want), "slot ({row},{slot})"); + } + } + assert_eq!(output_offset(1, 3), (TOP_K + 3) * HIDDEN); + // wrong value count / out-of-window pair + assert_eq!(scatter(&mut out, &job, &values[..HIDDEN]), Err(Error::InvalidDimension)); + let far = ExpertJob { expert: 1, pairs: vec![(rows, 0)] }; + assert_eq!(scatter(&mut out, &far, &values[..HIDDEN]), Err(Error::InvalidDimension)); +} + +#[test] +fn selection_rejects_negative_ids_and_short_rows() { + let good = ids(&[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]); + assert_eq!(selection(&good, 0), Ok([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])); + assert_eq!(selection(&good, 1), Err(Error::InvalidDimension)); + let mut bad = good.clone(); + bad[2] = -3; + assert_eq!(selection(&bad, 0), Err(Error::InvalidExpert)); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs index ca24eb6d..c9971207 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs @@ -634,677 +634,5 @@ impl PrefixServe { } #[cfg(test)] -mod tests { - use super::*; - use crate::backend::original_prompt::{PromptOptions, PromptPath, PromptPlan}; - - const G: usize = 256; - - /// A payload with a size. - struct Bytes(usize); - impl ByteSize for Bytes { - fn byte_size(&self) -> usize { - self.0 - } - } - /// The state a fake device parks: where the session stood, and a digest of the tokens it had read. - struct State { - position: u64, - digest: u64, - } - impl ByteSize for State { - fn byte_size(&self) -> usize { - 100 - } - } - struct Block { - cells: Vec, - } - impl ByteSize for Block { - fn byte_size(&self) -> usize { - self.cells.len() * 4 - } - } - - /// A device whose positional buffer is a token per cell and whose recurrent state is a digest of every token - /// read in order, so a restore that mixes up cells or states is visible as soon as it is used. - struct Fake { - cells: Vec, - position: u64, - digest: u64, - log: Vec, - fail_import: bool, - available: Option, - } - impl Fake { - fn new() -> Self { - Self { cells: vec![-1; 1 << 16], position: 0, digest: 0, log: Vec::new(), fail_import: false, available: Some(1 << 40) } - } - fn read(&mut self, tokens: &[i32], first: usize) { - assert_eq!(first as u64, self.position, "chunks are contiguous"); - for (i, &t) in tokens.iter().enumerate() { - self.cells[first + i] = t; - self.digest = self.digest.wrapping_mul(1_000_003).wrapping_add(t as u64 + 7); - } - self.position += tokens.len() as u64; - } - } - impl PrefixDevice for Fake { - type State = State; - type Block = Block; - fn position(&self) -> Result { - Ok(self.position) - } - fn estimate(&self, block_tokens: usize) -> (usize, usize) { - (100, block_tokens * 4) - } - fn park_state(&mut self) -> Result { - Ok(State { position: self.position, digest: self.digest }) - } - fn park_block(&mut self, first: usize, tokens: usize) -> Result { - assert!((first + tokens) as u64 <= self.position, "only cells the session has read"); - Ok(Block { cells: self.cells[first..first + tokens].to_vec() }) - } - fn park_tail(&mut self, first: usize, tokens: usize) -> Result { - assert!((first + tokens) as u64 <= self.position, "only cells the session has read"); - Ok(Block { cells: self.cells[first..first + tokens].to_vec() }) - } - fn import(&mut self, state: &State, blocks: &[(usize, &Block)]) -> Result<(), Error> { - if self.fail_import { - return Err(Error::CudaExecution); - } - for (j, block) in blocks { - self.cells[j * G..j * G + block.cells.len()].copy_from_slice(&block.cells); - } - self.log.push(format!("import {} blocks={}", state.position, blocks.len())); - self.position = state.position; - self.digest = state.digest; - Ok(()) - } - fn restore_draft(&mut self, _: &State, resume: usize) -> Result<(), Error> { - self.log.push(format!("draft {resume}")); - Ok(()) - } - fn available_memory(&self) -> Option { - self.available - } - } - - fn cfg() -> PrefixConfig { - PrefixConfig { block_tokens: G, ..PrefixConfig::auto() } - } - fn serve() -> PrefixServe { - PrefixServe::new(cfg(), 1024, 1 << 30, "test") - } - - /// One request against the fake: begin, read the plan's chunks on the grid, finish. Returns (start, digest the - /// session holds at the end of the prefill = a function of all tokens read). - fn request(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], stop_after_chunks: Option) -> (Option, u64) { - let start = s.begin(d, prompt).unwrap(); - let resume = match &start { - Some(st) => st.resume, - None => { - // the caller resets the owners; the cells stay where they are - d.position = 0; - d.digest = 0; - 0 - } - }; - let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); - // like the stack: a request that resumed between two grid points reads the way a full read of its own would - let grid = if resume % s.block_tokens() == 0 { s.block_tokens() } else { 0 }; - let options = PromptOptions { grid, prompt_cache: false, turn_token: None, root_min: 0, force_batched: true, ..PromptOptions::original_mode17(1 << 16) }; - let mut chunks = 0; - for action in PromptPlan::new(&tokens, resume, None, None, options, 1024).unwrap() { - if action.path == PromptPath::FinalSeed { - break; - } - if stop_after_chunks == Some(chunks) { - // cancelled before this chunk - s.finish(true); - return (start, d.digest); - } - s.before_chunk(action.first); - // a chunk interrupted half way would have written part of its cells: model it by a failing chunk - d.read(&prompt[action.first..action.first + action.count], action.first); - s.after_chunk(d, prompt, action.first + action.count).unwrap(); - chunks += 1; - } - assert_eq!(d.position as usize, prompt.len() - 1); - // the invariant that matters: the cells the session reads are this prompt's - assert_eq!(&d.cells[..prompt.len() - 1], &prompt[..prompt.len() - 1]); - s.after_prefill(d, prompt).unwrap(); - s.finish(true); - (start, d.digest) - } - - /// An agent turn: `request`, then the decode of `reply` (the session consumes the last prompt token and every reply token but the - /// last, which is the pending input) and the request-end checkpoint of `TailMode::Reply`. Returns (start, digest after the - /// prefill, the consumed tokens). - fn turn(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], reply: &[i32]) -> (Option, u64, Vec) { - let start = s.begin(d, prompt).unwrap(); - let resume = match &start { - Some(st) => st.resume, - None => { - d.position = 0; - d.digest = 0; - 0 - } - }; - let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); - let grid = if resume % s.block_tokens() == 0 { s.block_tokens() } else { 0 }; - let options = PromptOptions { grid, prompt_cache: false, turn_token: None, root_min: 0, force_batched: true, ..PromptOptions::original_mode17(1 << 16) }; - for action in PromptPlan::new(&tokens, resume, None, None, options, 1024).unwrap() { - if action.path == PromptPath::FinalSeed { - break; - } - s.before_chunk(action.first); - d.read(&prompt[action.first..action.first + action.count], action.first); - s.after_chunk(d, prompt, action.first + action.count).unwrap(); - } - s.after_prefill(d, prompt).unwrap(); - let digest = d.digest; - let mut consumed = prompt[..prompt.len() - 1].to_vec(); - let decoded: Vec = std::iter::once(prompt[prompt.len() - 1]).chain(reply[..reply.len() - 1].iter().copied()).collect(); - d.read(&decoded, consumed.len()); - consumed.extend_from_slice(&decoded); - s.after_decode(d, &consumed).unwrap(); - s.finish(true); - (start, digest, consumed) - } - - /// A token that depends on the stream `seed` and the position `i` (ids stay inside the vocabulary). - fn tok(seed: i32, i: usize) -> i32 { - ((i64::from(seed) * 1_000_003 + i as i64 * 7919) % 247_000 + 1) as i32 - } - fn doc(seed: i32, blocks: usize, extra: usize) -> Vec { - (0..blocks * G + extra).map(|i| tok(seed, i)).collect() - } - /// `shared` leading blocks from a common system prompt, then the session's own tokens. - fn session(id: i32, shared: usize, total: usize, extra: usize) -> Vec { - let mut t = doc(0, shared, 0); - t.extend((shared * G..total * G + extra).map(|i| tok(id, i))); - t - } - fn full_digest(prompt: &[i32]) -> u64 { - let mut d = Fake::new(); - d.read(&prompt[..prompt.len() - 1], 0); - d.digest - } - - #[test] - fn a_second_session_with_the_same_system_prompt_resumes_from_the_shared_blocks_and_ends_in_the_full_reads_state() { - let mut s = serve(); - let mut d = Fake::new(); - let a = session(1, 4, 8, 50); - let b = session(2, 4, 8, 50); - let (start, digest) = request(&mut s, &mut d, &a, None); - assert_eq!(start, None); - assert_eq!(digest, full_digest(&a)); - // A's checkpoints: every grid point of its prompt was admitted (room is plentiful) - assert_eq!(s.node_count(), 8); - assert_eq!(s.block_count(), 8); - // B reads the same system prompt: resumes at 4 blocks, building on A's blocks - d.log.clear(); - let (start, digest) = request(&mut s, &mut d, &b, None); - let start = start.unwrap(); - assert_eq!((start.resume, start.switched, start.branch), (4 * G, true, true)); - assert_eq!(start.copied_tokens, 0, "the buffer held A, whose first four blocks are the shared prompt: nothing to write back"); - assert_eq!(digest, full_digest(&b), "the resumed read ends in exactly the full read's state"); - assert_eq!(s.stats().hits, 1); - assert_eq!(s.stats().shared_hits, 1); - // B's own blocks were added, the shared four were not stored again - assert_eq!(s.block_count(), 12); - } - - #[test] - fn interleaved_sessions_each_resume_from_their_own_deepest_checkpoint() { - let mut s = serve(); - let mut d = Fake::new(); - let mut prompts = [session(1, 4, 6, 10), session(2, 4, 6, 10), session(3, 4, 6, 10)]; - let mut last_len = [0usize; 3]; - for turn in 0..4 { - for (i, p) in prompts.iter_mut().enumerate() { - let (start, digest) = request(&mut s, &mut d, p, None); - assert_eq!(digest, full_digest(p), "turn {turn} session {i}"); - let resume = start.map_or(0, |st| st.resume); - let expected = match (turn, i) { - (0, 0) => 0, - (0, _) => 4 * G, // the shared system prompt - // the session's own deepest checkpoint: the grid point at or below its previous prefill end - _ => (last_len[i] - 1) / G * G, - }; - assert_eq!(resume, expected, "turn {turn} session {i}"); - last_len[i] = p.len(); - // the agent appends a tool result: one more block and a bit - p.extend(doc(1000 + (i as i32 + 1) * 10 + turn, 1, 30)); - } - } - // sharing: the system prompt's four blocks exist once per cached chain, not once per session - assert!(s.stats().shared_hits >= 2); - assert!(s.stats().hits >= 11); - } - - #[test] - fn a_miss_resets_the_owners_so_nothing_is_claimed_even_if_the_request_is_cancelled_before_its_first_chunk() { - let mut s = serve(); - let mut d = Fake::new(); - let a = session(1, 0, 4, 10); - request(&mut s, &mut d, &a, None); - assert_eq!(s.live_tokens(), a.len() - 1); - // another session misses: the owners are reset (the empty-prompt rollback rewrites the first index row), then the - // request is cancelled before it read anything - let b = session(2, 0, 4, 10); - assert_eq!(s.begin(&mut d, &b).unwrap(), None); - assert_eq!(s.live_tokens(), 0); - s.finish(true); - // A comes back: it resumes from its checkpoints and every cell is written back (none is claimed from the buffer) - let (start, digest) = request(&mut s, &mut d, &a, None); - let start = start.unwrap(); - assert_eq!((start.resume, start.copied_tokens), (4 * G, 4 * G)); - assert_eq!(digest, full_digest(&a)); - } - - fn tail_serve(mode: TailMode) -> PrefixServe { - PrefixServe::new(PrefixConfig { tail: mode, ..cfg() }, 1024, 1 << 30, "test") - } - - #[test] - fn a_checkpoint_at_the_end_of_the_prefill_lets_the_next_turn_resume_at_the_exact_position() { - let mut grid_only = tail_serve(TailMode::Off); - let mut tail = tail_serve(TailMode::Prompt); - let (mut dg, mut dt) = (Fake::new(), Fake::new()); - let first = session(1, 0, 4, 10); - request(&mut grid_only, &mut dg, &first, None); - request(&mut tail, &mut dt, &first, None); - // the next turn: the same history, a reply of 300 tokens and the new ones - let mut second = first.clone(); - second.extend(doc(77, 1, 44)); - let (g_start, g_digest) = request(&mut grid_only, &mut dg, &second, None); - let (t_start, t_digest) = request(&mut tail, &mut dt, &second, None); - let (g_start, t_start) = (g_start.unwrap(), t_start.unwrap()); - assert_eq!(g_start.resume, 4 * G, "grid only: the last grid point"); - assert_eq!(t_start.resume, first.len() - 1, "the tail node: exactly where the previous prefill ended"); - assert_eq!(t_start.copied_tokens, 0, "the same session: its cells are in the buffer"); - assert_eq!(g_digest, full_digest(&second)); - assert_eq!(t_digest, full_digest(&second), "the state at the cut continues like a full read"); - // a third turn resumes from the newest tail, and the one before is superseded - let mut third = second.clone(); - third.extend(doc(78, 0, 90)); - let (start, digest) = request(&mut tail, &mut dt, &third, None); - assert_eq!(start.unwrap().resume, second.len() - 1); - assert_eq!(digest, full_digest(&third)); - } - - #[test] - fn a_request_end_checkpoint_survives_another_session_and_is_written_back_with_its_tail() { - let mut s = tail_serve(TailMode::Prompt); - let mut d = Fake::new(); - let a = session(1, 1, 5, 17); - let b = session(2, 1, 5, 40); - request(&mut s, &mut d, &a, None); - request(&mut s, &mut d, &b, None); - // A comes back extended: the buffer holds B; the node's last full blocks and its tail (16 tokens) are written back - let mut a2 = a.clone(); - a2.extend(doc(5, 0, 120)); - let (start, digest) = request(&mut s, &mut d, &a2, None); - let start = start.unwrap(); - assert_eq!(start.resume, a.len() - 1); - assert!(start.switched); - assert_eq!(start.copied_tokens, 4 * G + 16, "four full blocks after the shared one, and the 16 cells of the tail"); - assert_eq!(digest, full_digest(&a2)); - } - - #[test] - fn a_checkpoint_at_the_end_of_the_decode_makes_the_next_turn_read_only_the_new_tokens() { - let mut s = tail_serve(TailMode::Reply); - let mut d = Fake::new(); - let first = session(1, 0, 4, 12); - let reply = doc(33, 0, 300); - let (start, _, consumed) = turn(&mut s, &mut d, &first, &reply); - assert!(start.is_none()); - assert_eq!(consumed.len(), first.len() + reply.len() - 1); - // the next prompt: the history, the reply token for token, then 60 new tokens - let mut second = first.clone(); - second.extend(reply.iter().copied()); - second.extend(doc(34, 0, 60)); - let (start, digest, consumed2) = turn(&mut s, &mut d, &second, &doc(35, 0, 100)); - let start = start.unwrap(); - assert_eq!(start.resume, consumed.len(), "the end of the previous decode"); - assert_eq!(start.copied_tokens, 0); - assert_eq!(digest, full_digest(&second)); - // another session comes in between; the first returns and the decode-end node is written back from host memory - let other = session(2, 0, 3, 5); - turn(&mut s, &mut d, &other, &doc(36, 0, 50)); - let mut third = second.clone(); - third.extend(doc(35, 0, 100)); - third.extend(doc(37, 0, 20)); - let (start, digest, _) = turn(&mut s, &mut d, &third, &doc(38, 0, 30)); - let start = start.unwrap(); - assert_eq!(start.resume, consumed2.len()); - assert!(start.switched && start.copied_tokens > 0); - assert_eq!(digest, full_digest(&third)); - } - - #[test] - fn tail_checkpoints_are_off_by_default_and_never_taken_at_a_grid_point_or_below_one_block() { - let mut s = serve(); - let mut d = Fake::new(); - let a = session(1, 0, 4, 10); - request(&mut s, &mut d, &a, None); - assert_eq!(s.node_count(), 4, "grid nodes only"); - let mut p = tail_serve(TailMode::Prompt); - let mut d = Fake::new(); - // n - 1 is a multiple of the block: the grid node is the checkpoint - let aligned = session(1, 0, 4, 1); - request(&mut p, &mut d, &aligned, None); - assert_eq!(p.node_count(), 4); - // less than one block: nothing to hang a tail on - let short = session(3, 0, 0, 100); - request(&mut p, &mut d, &short, None); - assert_eq!(p.node_count(), 4); - } - - #[test] - fn the_same_session_continuing_copies_no_cells() { - let mut s = serve(); - let mut d = Fake::new(); - let mut p = session(1, 0, 6, 10); - request(&mut s, &mut d, &p, None); - p.extend(doc(777, 1, 40)); - let (start, digest) = request(&mut s, &mut d, &p, None); - let start = start.unwrap(); - assert_eq!((start.resume, start.switched, start.branch, start.copied_tokens), (6 * G, false, false, 0)); - assert_eq!(digest, full_digest(&p)); - } - - #[test] - fn switching_to_another_session_and_back_writes_back_only_what_the_buffer_lost() { - let mut s = serve(); - let mut d = Fake::new(); - let a = session(1, 2, 8, 10); - let b = session(2, 2, 8, 10); - request(&mut s, &mut d, &a, None); - request(&mut s, &mut d, &b, None); - // A again: the buffer holds B; the first 2 blocks are shared, so only A's later cells are written back - let (start, digest) = request(&mut s, &mut d, &a, None); - let start = start.unwrap(); - assert_eq!(start.resume, 8 * G); - assert!(start.switched); - assert_eq!(start.copied_tokens, 6 * G, "blocks 2..8; the two shared blocks were in the buffer"); - assert_eq!(digest, full_digest(&a)); - } - - #[test] - fn a_cancelled_prefill_never_claims_cells_it_did_not_finish() { - let mut s = serve(); - let mut d = Fake::new(); - let a = session(1, 0, 8, 10); - // cancelled after 3 of 8 chunks - request(&mut s, &mut d, &a, Some(3)); - assert_eq!(s.live_tokens(), 3 * G); - assert_eq!(s.node_count(), 3, "the checkpoints of the finished chunks are good"); - // the buffer gets scribbled over by a different request, then A is retried - let b = session(2, 0, 8, 10); - request(&mut s, &mut d, &b, Some(1)); - let (start, digest) = request(&mut s, &mut d, &a, None); - let start = start.unwrap(); - assert_eq!(start.resume, 3 * G); - assert_eq!(digest, full_digest(&a), "restored from the 3-block checkpoint, finished, and equal to a full read"); - } - - /// Upstream 41cf05a0 `8824e217`: a request cancelled before its first window lost the conversation it had restored. Here the - /// restore is the request's own `begin`: after a cancel right behind it the store still has every node, the buffer is claimed - /// up to the restored point (the import wrote exactly those cells) and the retry of the same session needs no copy. - #[test] - fn a_request_cancelled_right_after_restoring_its_session_keeps_it() { - let mut s = serve(); - let mut d = Fake::new(); - let mut a = session(1, 0, 6, 10); - request(&mut s, &mut d, &a, None); - let nodes = s.node_count(); - // another session scribbles over the buffer, then A's next turn restores its checkpoint and is cancelled before reading - let b = session(2, 0, 6, 10); - request(&mut s, &mut d, &b, None); - a.extend(doc(777, 1, 40)); - let (start, _) = request(&mut s, &mut d, &a, Some(0)); - let start = start.unwrap(); - assert_eq!(start.resume, 6 * G); - assert!(start.switched && start.copied_tokens > 0, "the buffer held B: A's cells were written back"); - assert_eq!(s.live_tokens(), 6 * G, "the restore is claimed"); - assert!(s.node_count() >= nodes, "no node was lost to the cancel"); - // the retry resumes at the same point and copies nothing: the claim was honest - let (start, digest) = request(&mut s, &mut d, &a, None); - let start = start.unwrap(); - assert_eq!((start.resume, start.switched, start.copied_tokens), (6 * G, false, 0)); - assert_eq!(digest, full_digest(&a)); - } - - /// Upstream 41cf05a0 `940011da`: a full cache dropped the snapshot instead of evicting. Three sessions into a store with room - /// for about two chains: the newest is cached (the session idle longest pays for it), the store stays inside its budget, and - /// every later resume is exact. - #[test] - fn a_full_store_evicts_the_session_idle_longest_so_the_newest_request_is_cached() { - let mut s = PrefixServe::new(cfg(), 1024, 9 * 100 + 9 * 1024, "test"); - let mut d = Fake::new(); - let (a, b, c) = (session(1, 0, 4, 10), session(2, 0, 4, 10), session(3, 0, 4, 10)); - for p in [&a, &b, &c] { - let (_, digest) = request(&mut s, &mut d, p, None); - assert_eq!(digest, full_digest(p)); - assert!(s.bytes() <= s.budget_bytes(), "{} > {}", s.bytes(), s.budget_bytes()); - } - assert!(s.stats().evicted > 0, "the store was full, so something went"); - let deepest = |p: &[i32], s: &PrefixServe| s.store().longest_match(p, p.len() - 1).map_or(0, |m| m.tokens); - assert_eq!(deepest(&c, &s), 4 * G, "the newest request's deepest checkpoint is cached, not dropped"); - assert!(deepest(&a, &s) < 4 * G, "the session idle longest gave way"); - // whatever was evicted, every session resumes to exactly the full read's state - for p in [&a, &b, &c, &a] { - let (_, digest) = request(&mut s, &mut d, p, None); - assert_eq!(digest, full_digest(p)); - assert!(s.bytes() <= s.budget_bytes()); - } - } - - /// Upstream 41cf05a0 `aece46db` (a 1-token prompt with `--spec`): the prompt has no token to read (the single token is the first - /// verify input), so nothing is looked up, read or checkpointed and no claim is made on the buffer. - #[test] - fn a_one_token_prompt_reads_nothing_and_claims_nothing() { - let mut s = serve(); - let mut d = Fake::new(); - let long = session(1, 0, 4, 10); - request(&mut s, &mut d, &long, None); - let nodes = s.node_count(); - let one = [4242]; - assert_eq!(s.begin(&mut d, &one).unwrap(), None, "no checkpoint is a prefix of a one-token prompt"); - assert_eq!(s.live_tokens(), 0, "the owners are reset: no cell is claimed"); - assert_eq!(s.after_prefill(&mut d, &one).unwrap(), ChunkOutcome::Nothing); - s.finish(true); - assert_eq!(s.node_count(), nodes, "the other session's checkpoints are untouched"); - // and it does not break the session that was cached - let (start, digest) = request(&mut s, &mut d, &long, None); - assert_eq!(start.unwrap().resume, 4 * G); - assert_eq!(digest, full_digest(&long)); - } - - #[test] - fn a_failed_import_is_an_error_for_the_caller_and_invalidate_forgets_everything() { - let mut s = serve(); - let mut d = Fake::new(); - let a = session(1, 0, 4, 10); - request(&mut s, &mut d, &a, None); - let mut longer = a.clone(); - longer.extend(doc(555, 2, 0)); - d.fail_import = true; - assert!(s.begin(&mut d, &longer).is_err()); - s.invalidate(); - d.fail_import = false; - assert_eq!((s.node_count(), s.block_count(), s.live_tokens()), (0, 0, 0)); - let (start, digest) = request(&mut s, &mut d, &longer, None); - assert_eq!(start, None); - assert_eq!(digest, full_digest(&longer)); - // a lost owner (finish(false)) forgets too - s.finish(false); - assert_eq!(s.node_count(), 0); - } - - #[test] - fn the_budget_bounds_the_store_and_the_newest_frontier_survives() { - // room for ~3 states and 6 blocks of 256 tokens (1 KiB each here) - let mut s = PrefixServe::new(cfg(), 1024, 3 * 100 + 9 * 1024, "test"); - let mut d = Fake::new(); - let mut p = session(1, 0, 4, 10); - for turn in 0..6 { - let (_, digest) = request(&mut s, &mut d, &p, None); - assert_eq!(digest, full_digest(&p)); - assert!(s.bytes() <= s.budget_bytes(), "turn {turn}: {} > {}", s.bytes(), s.budget_bytes()); - p.extend(doc(turn + 3000, 1, 5)); - } - assert!(s.stats().evicted + s.stats().rejected > 0, "the budget forced choices"); - // the last request's deepest checkpoint is cached - let last = (p.len() - (G + 5) - 1) / G * G; - let hit = s.store().longest_match(&p, p.len() - 1).unwrap(); - assert_eq!(hit.tokens, last); - } - - fn governor() -> leleka_memory::Governor { - let mut cfg = leleka_memory::GovernorConfig::new(leleka_memory::Policy::for_host(121 << 30, false)); - cfg.log = false; - leleka_memory::Governor::new(cfg, std::sync::Arc::new(leleka_memory::FakeProc::default())) - } - - #[test] - fn a_memory_shed_evicts_to_the_target_and_the_configured_budget_comes_back() { - let g = governor(); - let mut s = PrefixServe::new(cfg(), 1024, 1 << 30, "test"); - let mut d = Fake::new(); - let prompts: Vec> = (1..=4).map(|i| session(i, 2, 6, 10)).collect(); - for p in &prompts { - request(&mut s, &mut d, p, None); - } - let full = s.bytes(); - assert!(full > 0 && s.node_count() > 0); - // shed to a quarter: evicted down to the target, bookkeeping intact - let freed = s.apply_shed(Some(full as u64 / 4), &g); - assert!(freed > 0 && s.bytes() <= full / 4, "{} > {}", s.bytes(), full / 4); - s.store().check_invariants(); - // a request after the shed is still exact: whatever was evicted is read again - let (_, digest) = request(&mut s, &mut d, &prompts[0], None); - assert_eq!(digest, full_digest(&prompts[0])); - assert!(s.bytes() <= s.budget_bytes(), "the shed budget bounds the store"); - // everything goes at reject; the next request reads from 0 and is exact - s.apply_shed(Some(0), &g); - assert_eq!((s.bytes(), s.node_count(), s.block_count()), (0, 0, 0)); - let (start, digest) = request(&mut s, &mut d, &prompts[1], None); - assert_eq!(start, None); - assert_eq!(digest, full_digest(&prompts[1])); - assert_eq!(s.bytes(), 0, "nothing is admitted while the budget is zero"); - // pressure over: the configured budget is restored and the cache refills - assert_eq!(s.apply_shed(None, &g), 0); - assert_eq!(s.budget_bytes(), 1 << 30); - request(&mut s, &mut d, &prompts[2], None); - assert!(s.bytes() > 0); - // a directive that asks for more than the configured budget never raises it - s.apply_shed(Some(u64::MAX), &g); - assert_eq!(s.budget_bytes(), 1 << 30); - s.store().check_invariants(); - } - - #[test] - fn churn_under_random_shed_directives_keeps_every_resume_exact_and_the_store_inside_its_budget() { - let g = governor(); - let budget = 2 * 100 + 12 * 1024; - let mut s = PrefixServe::new(cfg(), 1024, budget as u64, "test"); - let mut d = Fake::new(); - let mut prompts: Vec> = (1..=5).map(|i| session(i, 2, 4, 10)).collect(); - let mut x = 0x2545_f491_4f6c_dd1du64; - let mut next = move || { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x - }; - let mut shed_events = 0; - for turn in 0..300 { - let who = (next() % 5) as usize; - match next() % 8 { - 0 => { - s.apply_shed(Some(next() % (budget as u64 + 1)), &g); - shed_events += 1; - } - 1 => { - s.apply_shed(None, &g); - } - 2 if s.bytes() > 0 => { - s.apply_shed(Some(0), &g); - shed_events += 1; - } - _ => {} - } - let p = &mut prompts[who]; - if p.len() < 40 * G { - p.extend(doc(turn + 7000, 1, 3)); - } - let (_, digest) = request(&mut s, &mut d, p, if next() % 9 == 0 { Some(1) } else { None }); - // a cancelled request ends mid-prefill: its digest is a partial read, only complete ones are compared - if digest == full_digest(p) { - assert!(s.bytes() <= s.budget_bytes(), "turn {turn}: {} > {}", s.bytes(), s.budget_bytes()); - } - s.store().check_invariants(); - assert!(s.bytes() <= budget, "turn {turn}: the store outgrew its configured budget"); - } - assert!(shed_events > 20, "the schedule exercised shedding"); - assert!(s.stats().evicted > 0); - } - - #[test] - fn low_host_memory_skips_the_checkpoint_instead_of_building_it() { - let mut s = serve(); - let mut d = Fake::new(); - d.available = Some(1 << 20); // below the 3 GiB floor - let a = session(1, 0, 3, 10); - let start = s.begin(&mut d, &a).unwrap(); - assert_eq!(start, None); - d.read(&a[..G], 0); - s.before_chunk(0); - assert_eq!(s.after_chunk(&mut d, &a, G).unwrap(), ChunkOutcome::LowMemory); - assert_eq!(s.node_count(), 0); - d.available = None; - assert_eq!(s.after_chunk(&mut d, &a, G).unwrap(), ChunkOutcome::LowMemory, "unknown telemetry fails closed"); - } - - #[test] - fn the_pool_queries_see_the_cached_prefixes() { - let mut s = serve(); - let mut d = Fake::new(); - let a = session(1, 3, 6, 10); - request(&mut s, &mut d, &a, None); - let chain = crate::prefix_cache::chain(&a, G); - let m = s.prefix_match(&chain); - assert_eq!((m.cached_tokens as usize, m.block_tokens as usize), (6 * G, G)); - // another session that shares 3 blocks - let other = crate::prefix_cache::chain(&session(2, 3, 6, 10), G); - assert_eq!(s.prefix_match(&other).cached_tokens as usize, 3 * G); - let summary = s.summary(100); - assert_eq!(summary.namespace, m.namespace); - assert_eq!(summary.match_tokens(&chain) as usize, 6 * G); - assert!(s.describe().contains("nodes=6")); - } - - #[test] - fn config_resolution_follows_the_operator() { - let cfg = PrefixConfig::auto(); - assert_eq!(cfg.resolved_block(8192), 8192); - assert_eq!(cfg.resolved_block(1024), 1024); - assert_eq!(PrefixConfig { block_tokens: 2048, ..PrefixConfig::auto() }.resolved_block(8192), 2048); - assert!(cfg.validate(1024).is_ok()); - assert!(PrefixConfig { block_tokens: 300, ..PrefixConfig::auto() }.validate(1024).is_err()); - assert!(PrefixConfig { block_tokens: 4096, ..PrefixConfig::auto() }.validate(2048).is_err()); - assert_eq!(PrefixConfig { budget: PrefixBudget::Off, ..PrefixConfig::auto() }.resolve_budget(Some(1 << 40)), 0); - assert_eq!(PrefixConfig { budget: PrefixBudget::Bytes(5), ..PrefixConfig::auto() }.resolve_budget(None), 5); - assert_eq!(PrefixConfig::auto().resolve_budget(None), 0); - assert!(PrefixConfig::auto().resolve_budget(Some(80 << 30)) > (30 << 30)); - // the 5090 server after the expert source: a few GiB, not nothing - let server = PrefixConfig::auto().resolve_budget(Some(14 << 30)); - assert!(server >= (7 << 30) && server <= (8 << 30), "{server}"); - } -} +#[path = "original_serve_prefix/tests.rs"] +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs new file mode 100644 index 00000000..7057ab06 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs @@ -0,0 +1,674 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::backend::original_prompt::{PromptOptions, PromptPath, PromptPlan}; + +const G: usize = 256; + +/// A payload with a size. +struct Bytes(usize); +impl ByteSize for Bytes { + fn byte_size(&self) -> usize { + self.0 + } +} +/// The state a fake device parks: where the session stood, and a digest of the tokens it had read. +struct State { + position: u64, + digest: u64, +} +impl ByteSize for State { + fn byte_size(&self) -> usize { + 100 + } +} +struct Block { + cells: Vec, +} +impl ByteSize for Block { + fn byte_size(&self) -> usize { + self.cells.len() * 4 + } +} + +/// A device whose positional buffer is a token per cell and whose recurrent state is a digest of every token +/// read in order, so a restore that mixes up cells or states is visible as soon as it is used. +struct Fake { + cells: Vec, + position: u64, + digest: u64, + log: Vec, + fail_import: bool, + available: Option, +} +impl Fake { + fn new() -> Self { + Self { cells: vec![-1; 1 << 16], position: 0, digest: 0, log: Vec::new(), fail_import: false, available: Some(1 << 40) } + } + fn read(&mut self, tokens: &[i32], first: usize) { + assert_eq!(first as u64, self.position, "chunks are contiguous"); + for (i, &t) in tokens.iter().enumerate() { + self.cells[first + i] = t; + self.digest = self.digest.wrapping_mul(1_000_003).wrapping_add(t as u64 + 7); + } + self.position += tokens.len() as u64; + } +} +impl PrefixDevice for Fake { + type State = State; + type Block = Block; + fn position(&self) -> Result { + Ok(self.position) + } + fn estimate(&self, block_tokens: usize) -> (usize, usize) { + (100, block_tokens * 4) + } + fn park_state(&mut self) -> Result { + Ok(State { position: self.position, digest: self.digest }) + } + fn park_block(&mut self, first: usize, tokens: usize) -> Result { + assert!((first + tokens) as u64 <= self.position, "only cells the session has read"); + Ok(Block { cells: self.cells[first..first + tokens].to_vec() }) + } + fn park_tail(&mut self, first: usize, tokens: usize) -> Result { + assert!((first + tokens) as u64 <= self.position, "only cells the session has read"); + Ok(Block { cells: self.cells[first..first + tokens].to_vec() }) + } + fn import(&mut self, state: &State, blocks: &[(usize, &Block)]) -> Result<(), Error> { + if self.fail_import { + return Err(Error::CudaExecution); + } + for (j, block) in blocks { + self.cells[j * G..j * G + block.cells.len()].copy_from_slice(&block.cells); + } + self.log.push(format!("import {} blocks={}", state.position, blocks.len())); + self.position = state.position; + self.digest = state.digest; + Ok(()) + } + fn restore_draft(&mut self, _: &State, resume: usize) -> Result<(), Error> { + self.log.push(format!("draft {resume}")); + Ok(()) + } + fn available_memory(&self) -> Option { + self.available + } +} + +fn cfg() -> PrefixConfig { + PrefixConfig { block_tokens: G, ..PrefixConfig::auto() } +} +fn serve() -> PrefixServe { + PrefixServe::new(cfg(), 1024, 1 << 30, "test") +} + +/// One request against the fake: begin, read the plan's chunks on the grid, finish. Returns (start, digest the +/// session holds at the end of the prefill = a function of all tokens read). +fn request(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], stop_after_chunks: Option) -> (Option, u64) { + let start = s.begin(d, prompt).unwrap(); + let resume = match &start { + Some(st) => st.resume, + None => { + // the caller resets the owners; the cells stay where they are + d.position = 0; + d.digest = 0; + 0 + } + }; + let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); + // like the stack: a request that resumed between two grid points reads the way a full read of its own would + let grid = if resume % s.block_tokens() == 0 { s.block_tokens() } else { 0 }; + let options = PromptOptions { grid, prompt_cache: false, turn_token: None, root_min: 0, force_batched: true, ..PromptOptions::original_mode17(1 << 16) }; + let mut chunks = 0; + for action in PromptPlan::new(&tokens, resume, None, None, options, 1024).unwrap() { + if action.path == PromptPath::FinalSeed { + break; + } + if stop_after_chunks == Some(chunks) { + // cancelled before this chunk + s.finish(true); + return (start, d.digest); + } + s.before_chunk(action.first); + // a chunk interrupted half way would have written part of its cells: model it by a failing chunk + d.read(&prompt[action.first..action.first + action.count], action.first); + s.after_chunk(d, prompt, action.first + action.count).unwrap(); + chunks += 1; + } + assert_eq!(d.position as usize, prompt.len() - 1); + // the invariant that matters: the cells the session reads are this prompt's + assert_eq!(&d.cells[..prompt.len() - 1], &prompt[..prompt.len() - 1]); + s.after_prefill(d, prompt).unwrap(); + s.finish(true); + (start, d.digest) +} + +/// An agent turn: `request`, then the decode of `reply` (the session consumes the last prompt token and every reply token but the +/// last, which is the pending input) and the request-end checkpoint of `TailMode::Reply`. Returns (start, digest after the +/// prefill, the consumed tokens). +fn turn(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], reply: &[i32]) -> (Option, u64, Vec) { + let start = s.begin(d, prompt).unwrap(); + let resume = match &start { + Some(st) => st.resume, + None => { + d.position = 0; + d.digest = 0; + 0 + } + }; + let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); + let grid = if resume % s.block_tokens() == 0 { s.block_tokens() } else { 0 }; + let options = PromptOptions { grid, prompt_cache: false, turn_token: None, root_min: 0, force_batched: true, ..PromptOptions::original_mode17(1 << 16) }; + for action in PromptPlan::new(&tokens, resume, None, None, options, 1024).unwrap() { + if action.path == PromptPath::FinalSeed { + break; + } + s.before_chunk(action.first); + d.read(&prompt[action.first..action.first + action.count], action.first); + s.after_chunk(d, prompt, action.first + action.count).unwrap(); + } + s.after_prefill(d, prompt).unwrap(); + let digest = d.digest; + let mut consumed = prompt[..prompt.len() - 1].to_vec(); + let decoded: Vec = std::iter::once(prompt[prompt.len() - 1]).chain(reply[..reply.len() - 1].iter().copied()).collect(); + d.read(&decoded, consumed.len()); + consumed.extend_from_slice(&decoded); + s.after_decode(d, &consumed).unwrap(); + s.finish(true); + (start, digest, consumed) +} + +/// A token that depends on the stream `seed` and the position `i` (ids stay inside the vocabulary). +fn tok(seed: i32, i: usize) -> i32 { + ((i64::from(seed) * 1_000_003 + i as i64 * 7919) % 247_000 + 1) as i32 +} +fn doc(seed: i32, blocks: usize, extra: usize) -> Vec { + (0..blocks * G + extra).map(|i| tok(seed, i)).collect() +} +/// `shared` leading blocks from a common system prompt, then the session's own tokens. +fn session(id: i32, shared: usize, total: usize, extra: usize) -> Vec { + let mut t = doc(0, shared, 0); + t.extend((shared * G..total * G + extra).map(|i| tok(id, i))); + t +} +fn full_digest(prompt: &[i32]) -> u64 { + let mut d = Fake::new(); + d.read(&prompt[..prompt.len() - 1], 0); + d.digest +} + +#[test] +fn a_second_session_with_the_same_system_prompt_resumes_from_the_shared_blocks_and_ends_in_the_full_reads_state() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 4, 8, 50); + let b = session(2, 4, 8, 50); + let (start, digest) = request(&mut s, &mut d, &a, None); + assert_eq!(start, None); + assert_eq!(digest, full_digest(&a)); + // A's checkpoints: every grid point of its prompt was admitted (room is plentiful) + assert_eq!(s.node_count(), 8); + assert_eq!(s.block_count(), 8); + // B reads the same system prompt: resumes at 4 blocks, building on A's blocks + d.log.clear(); + let (start, digest) = request(&mut s, &mut d, &b, None); + let start = start.unwrap(); + assert_eq!((start.resume, start.switched, start.branch), (4 * G, true, true)); + assert_eq!(start.copied_tokens, 0, "the buffer held A, whose first four blocks are the shared prompt: nothing to write back"); + assert_eq!(digest, full_digest(&b), "the resumed read ends in exactly the full read's state"); + assert_eq!(s.stats().hits, 1); + assert_eq!(s.stats().shared_hits, 1); + // B's own blocks were added, the shared four were not stored again + assert_eq!(s.block_count(), 12); +} + +#[test] +fn interleaved_sessions_each_resume_from_their_own_deepest_checkpoint() { + let mut s = serve(); + let mut d = Fake::new(); + let mut prompts = [session(1, 4, 6, 10), session(2, 4, 6, 10), session(3, 4, 6, 10)]; + let mut last_len = [0usize; 3]; + for turn in 0..4 { + for (i, p) in prompts.iter_mut().enumerate() { + let (start, digest) = request(&mut s, &mut d, p, None); + assert_eq!(digest, full_digest(p), "turn {turn} session {i}"); + let resume = start.map_or(0, |st| st.resume); + let expected = match (turn, i) { + (0, 0) => 0, + (0, _) => 4 * G, // the shared system prompt + // the session's own deepest checkpoint: the grid point at or below its previous prefill end + _ => (last_len[i] - 1) / G * G, + }; + assert_eq!(resume, expected, "turn {turn} session {i}"); + last_len[i] = p.len(); + // the agent appends a tool result: one more block and a bit + p.extend(doc(1000 + (i as i32 + 1) * 10 + turn, 1, 30)); + } + } + // sharing: the system prompt's four blocks exist once per cached chain, not once per session + assert!(s.stats().shared_hits >= 2); + assert!(s.stats().hits >= 11); +} + +#[test] +fn a_miss_resets_the_owners_so_nothing_is_claimed_even_if_the_request_is_cancelled_before_its_first_chunk() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 0, 4, 10); + request(&mut s, &mut d, &a, None); + assert_eq!(s.live_tokens(), a.len() - 1); + // another session misses: the owners are reset (the empty-prompt rollback rewrites the first index row), then the + // request is cancelled before it read anything + let b = session(2, 0, 4, 10); + assert_eq!(s.begin(&mut d, &b).unwrap(), None); + assert_eq!(s.live_tokens(), 0); + s.finish(true); + // A comes back: it resumes from its checkpoints and every cell is written back (none is claimed from the buffer) + let (start, digest) = request(&mut s, &mut d, &a, None); + let start = start.unwrap(); + assert_eq!((start.resume, start.copied_tokens), (4 * G, 4 * G)); + assert_eq!(digest, full_digest(&a)); +} + +fn tail_serve(mode: TailMode) -> PrefixServe { + PrefixServe::new(PrefixConfig { tail: mode, ..cfg() }, 1024, 1 << 30, "test") +} + +#[test] +fn a_checkpoint_at_the_end_of_the_prefill_lets_the_next_turn_resume_at_the_exact_position() { + let mut grid_only = tail_serve(TailMode::Off); + let mut tail = tail_serve(TailMode::Prompt); + let (mut dg, mut dt) = (Fake::new(), Fake::new()); + let first = session(1, 0, 4, 10); + request(&mut grid_only, &mut dg, &first, None); + request(&mut tail, &mut dt, &first, None); + // the next turn: the same history, a reply of 300 tokens and the new ones + let mut second = first.clone(); + second.extend(doc(77, 1, 44)); + let (g_start, g_digest) = request(&mut grid_only, &mut dg, &second, None); + let (t_start, t_digest) = request(&mut tail, &mut dt, &second, None); + let (g_start, t_start) = (g_start.unwrap(), t_start.unwrap()); + assert_eq!(g_start.resume, 4 * G, "grid only: the last grid point"); + assert_eq!(t_start.resume, first.len() - 1, "the tail node: exactly where the previous prefill ended"); + assert_eq!(t_start.copied_tokens, 0, "the same session: its cells are in the buffer"); + assert_eq!(g_digest, full_digest(&second)); + assert_eq!(t_digest, full_digest(&second), "the state at the cut continues like a full read"); + // a third turn resumes from the newest tail, and the one before is superseded + let mut third = second.clone(); + third.extend(doc(78, 0, 90)); + let (start, digest) = request(&mut tail, &mut dt, &third, None); + assert_eq!(start.unwrap().resume, second.len() - 1); + assert_eq!(digest, full_digest(&third)); +} + +#[test] +fn a_request_end_checkpoint_survives_another_session_and_is_written_back_with_its_tail() { + let mut s = tail_serve(TailMode::Prompt); + let mut d = Fake::new(); + let a = session(1, 1, 5, 17); + let b = session(2, 1, 5, 40); + request(&mut s, &mut d, &a, None); + request(&mut s, &mut d, &b, None); + // A comes back extended: the buffer holds B; the node's last full blocks and its tail (16 tokens) are written back + let mut a2 = a.clone(); + a2.extend(doc(5, 0, 120)); + let (start, digest) = request(&mut s, &mut d, &a2, None); + let start = start.unwrap(); + assert_eq!(start.resume, a.len() - 1); + assert!(start.switched); + assert_eq!(start.copied_tokens, 4 * G + 16, "four full blocks after the shared one, and the 16 cells of the tail"); + assert_eq!(digest, full_digest(&a2)); +} + +#[test] +fn a_checkpoint_at_the_end_of_the_decode_makes_the_next_turn_read_only_the_new_tokens() { + let mut s = tail_serve(TailMode::Reply); + let mut d = Fake::new(); + let first = session(1, 0, 4, 12); + let reply = doc(33, 0, 300); + let (start, _, consumed) = turn(&mut s, &mut d, &first, &reply); + assert!(start.is_none()); + assert_eq!(consumed.len(), first.len() + reply.len() - 1); + // the next prompt: the history, the reply token for token, then 60 new tokens + let mut second = first.clone(); + second.extend(reply.iter().copied()); + second.extend(doc(34, 0, 60)); + let (start, digest, consumed2) = turn(&mut s, &mut d, &second, &doc(35, 0, 100)); + let start = start.unwrap(); + assert_eq!(start.resume, consumed.len(), "the end of the previous decode"); + assert_eq!(start.copied_tokens, 0); + assert_eq!(digest, full_digest(&second)); + // another session comes in between; the first returns and the decode-end node is written back from host memory + let other = session(2, 0, 3, 5); + turn(&mut s, &mut d, &other, &doc(36, 0, 50)); + let mut third = second.clone(); + third.extend(doc(35, 0, 100)); + third.extend(doc(37, 0, 20)); + let (start, digest, _) = turn(&mut s, &mut d, &third, &doc(38, 0, 30)); + let start = start.unwrap(); + assert_eq!(start.resume, consumed2.len()); + assert!(start.switched && start.copied_tokens > 0); + assert_eq!(digest, full_digest(&third)); +} + +#[test] +fn tail_checkpoints_are_off_by_default_and_never_taken_at_a_grid_point_or_below_one_block() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 0, 4, 10); + request(&mut s, &mut d, &a, None); + assert_eq!(s.node_count(), 4, "grid nodes only"); + let mut p = tail_serve(TailMode::Prompt); + let mut d = Fake::new(); + // n - 1 is a multiple of the block: the grid node is the checkpoint + let aligned = session(1, 0, 4, 1); + request(&mut p, &mut d, &aligned, None); + assert_eq!(p.node_count(), 4); + // less than one block: nothing to hang a tail on + let short = session(3, 0, 0, 100); + request(&mut p, &mut d, &short, None); + assert_eq!(p.node_count(), 4); +} + +#[test] +fn the_same_session_continuing_copies_no_cells() { + let mut s = serve(); + let mut d = Fake::new(); + let mut p = session(1, 0, 6, 10); + request(&mut s, &mut d, &p, None); + p.extend(doc(777, 1, 40)); + let (start, digest) = request(&mut s, &mut d, &p, None); + let start = start.unwrap(); + assert_eq!((start.resume, start.switched, start.branch, start.copied_tokens), (6 * G, false, false, 0)); + assert_eq!(digest, full_digest(&p)); +} + +#[test] +fn switching_to_another_session_and_back_writes_back_only_what_the_buffer_lost() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 2, 8, 10); + let b = session(2, 2, 8, 10); + request(&mut s, &mut d, &a, None); + request(&mut s, &mut d, &b, None); + // A again: the buffer holds B; the first 2 blocks are shared, so only A's later cells are written back + let (start, digest) = request(&mut s, &mut d, &a, None); + let start = start.unwrap(); + assert_eq!(start.resume, 8 * G); + assert!(start.switched); + assert_eq!(start.copied_tokens, 6 * G, "blocks 2..8; the two shared blocks were in the buffer"); + assert_eq!(digest, full_digest(&a)); +} + +#[test] +fn a_cancelled_prefill_never_claims_cells_it_did_not_finish() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 0, 8, 10); + // cancelled after 3 of 8 chunks + request(&mut s, &mut d, &a, Some(3)); + assert_eq!(s.live_tokens(), 3 * G); + assert_eq!(s.node_count(), 3, "the checkpoints of the finished chunks are good"); + // the buffer gets scribbled over by a different request, then A is retried + let b = session(2, 0, 8, 10); + request(&mut s, &mut d, &b, Some(1)); + let (start, digest) = request(&mut s, &mut d, &a, None); + let start = start.unwrap(); + assert_eq!(start.resume, 3 * G); + assert_eq!(digest, full_digest(&a), "restored from the 3-block checkpoint, finished, and equal to a full read"); +} + +/// Upstream 41cf05a0 `8824e217`: a request cancelled before its first window lost the conversation it had restored. Here the +/// restore is the request's own `begin`: after a cancel right behind it the store still has every node, the buffer is claimed +/// up to the restored point (the import wrote exactly those cells) and the retry of the same session needs no copy. +#[test] +fn a_request_cancelled_right_after_restoring_its_session_keeps_it() { + let mut s = serve(); + let mut d = Fake::new(); + let mut a = session(1, 0, 6, 10); + request(&mut s, &mut d, &a, None); + let nodes = s.node_count(); + // another session scribbles over the buffer, then A's next turn restores its checkpoint and is cancelled before reading + let b = session(2, 0, 6, 10); + request(&mut s, &mut d, &b, None); + a.extend(doc(777, 1, 40)); + let (start, _) = request(&mut s, &mut d, &a, Some(0)); + let start = start.unwrap(); + assert_eq!(start.resume, 6 * G); + assert!(start.switched && start.copied_tokens > 0, "the buffer held B: A's cells were written back"); + assert_eq!(s.live_tokens(), 6 * G, "the restore is claimed"); + assert!(s.node_count() >= nodes, "no node was lost to the cancel"); + // the retry resumes at the same point and copies nothing: the claim was honest + let (start, digest) = request(&mut s, &mut d, &a, None); + let start = start.unwrap(); + assert_eq!((start.resume, start.switched, start.copied_tokens), (6 * G, false, 0)); + assert_eq!(digest, full_digest(&a)); +} + +/// Upstream 41cf05a0 `940011da`: a full cache dropped the snapshot instead of evicting. Three sessions into a store with room +/// for about two chains: the newest is cached (the session idle longest pays for it), the store stays inside its budget, and +/// every later resume is exact. +#[test] +fn a_full_store_evicts_the_session_idle_longest_so_the_newest_request_is_cached() { + let mut s = PrefixServe::new(cfg(), 1024, 9 * 100 + 9 * 1024, "test"); + let mut d = Fake::new(); + let (a, b, c) = (session(1, 0, 4, 10), session(2, 0, 4, 10), session(3, 0, 4, 10)); + for p in [&a, &b, &c] { + let (_, digest) = request(&mut s, &mut d, p, None); + assert_eq!(digest, full_digest(p)); + assert!(s.bytes() <= s.budget_bytes(), "{} > {}", s.bytes(), s.budget_bytes()); + } + assert!(s.stats().evicted > 0, "the store was full, so something went"); + let deepest = |p: &[i32], s: &PrefixServe| s.store().longest_match(p, p.len() - 1).map_or(0, |m| m.tokens); + assert_eq!(deepest(&c, &s), 4 * G, "the newest request's deepest checkpoint is cached, not dropped"); + assert!(deepest(&a, &s) < 4 * G, "the session idle longest gave way"); + // whatever was evicted, every session resumes to exactly the full read's state + for p in [&a, &b, &c, &a] { + let (_, digest) = request(&mut s, &mut d, p, None); + assert_eq!(digest, full_digest(p)); + assert!(s.bytes() <= s.budget_bytes()); + } +} + +/// Upstream 41cf05a0 `aece46db` (a 1-token prompt with `--spec`): the prompt has no token to read (the single token is the first +/// verify input), so nothing is looked up, read or checkpointed and no claim is made on the buffer. +#[test] +fn a_one_token_prompt_reads_nothing_and_claims_nothing() { + let mut s = serve(); + let mut d = Fake::new(); + let long = session(1, 0, 4, 10); + request(&mut s, &mut d, &long, None); + let nodes = s.node_count(); + let one = [4242]; + assert_eq!(s.begin(&mut d, &one).unwrap(), None, "no checkpoint is a prefix of a one-token prompt"); + assert_eq!(s.live_tokens(), 0, "the owners are reset: no cell is claimed"); + assert_eq!(s.after_prefill(&mut d, &one).unwrap(), ChunkOutcome::Nothing); + s.finish(true); + assert_eq!(s.node_count(), nodes, "the other session's checkpoints are untouched"); + // and it does not break the session that was cached + let (start, digest) = request(&mut s, &mut d, &long, None); + assert_eq!(start.unwrap().resume, 4 * G); + assert_eq!(digest, full_digest(&long)); +} + +#[test] +fn a_failed_import_is_an_error_for_the_caller_and_invalidate_forgets_everything() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 0, 4, 10); + request(&mut s, &mut d, &a, None); + let mut longer = a.clone(); + longer.extend(doc(555, 2, 0)); + d.fail_import = true; + assert!(s.begin(&mut d, &longer).is_err()); + s.invalidate(); + d.fail_import = false; + assert_eq!((s.node_count(), s.block_count(), s.live_tokens()), (0, 0, 0)); + let (start, digest) = request(&mut s, &mut d, &longer, None); + assert_eq!(start, None); + assert_eq!(digest, full_digest(&longer)); + // a lost owner (finish(false)) forgets too + s.finish(false); + assert_eq!(s.node_count(), 0); +} + +#[test] +fn the_budget_bounds_the_store_and_the_newest_frontier_survives() { + // room for ~3 states and 6 blocks of 256 tokens (1 KiB each here) + let mut s = PrefixServe::new(cfg(), 1024, 3 * 100 + 9 * 1024, "test"); + let mut d = Fake::new(); + let mut p = session(1, 0, 4, 10); + for turn in 0..6 { + let (_, digest) = request(&mut s, &mut d, &p, None); + assert_eq!(digest, full_digest(&p)); + assert!(s.bytes() <= s.budget_bytes(), "turn {turn}: {} > {}", s.bytes(), s.budget_bytes()); + p.extend(doc(turn + 3000, 1, 5)); + } + assert!(s.stats().evicted + s.stats().rejected > 0, "the budget forced choices"); + // the last request's deepest checkpoint is cached + let last = (p.len() - (G + 5) - 1) / G * G; + let hit = s.store().longest_match(&p, p.len() - 1).unwrap(); + assert_eq!(hit.tokens, last); +} + +fn governor() -> leleka_memory::Governor { + let mut cfg = leleka_memory::GovernorConfig::new(leleka_memory::Policy::for_host(121 << 30, false)); + cfg.log = false; + leleka_memory::Governor::new(cfg, std::sync::Arc::new(leleka_memory::FakeProc::default())) +} + +#[test] +fn a_memory_shed_evicts_to_the_target_and_the_configured_budget_comes_back() { + let g = governor(); + let mut s = PrefixServe::new(cfg(), 1024, 1 << 30, "test"); + let mut d = Fake::new(); + let prompts: Vec> = (1..=4).map(|i| session(i, 2, 6, 10)).collect(); + for p in &prompts { + request(&mut s, &mut d, p, None); + } + let full = s.bytes(); + assert!(full > 0 && s.node_count() > 0); + // shed to a quarter: evicted down to the target, bookkeeping intact + let freed = s.apply_shed(Some(full as u64 / 4), &g); + assert!(freed > 0 && s.bytes() <= full / 4, "{} > {}", s.bytes(), full / 4); + s.store().check_invariants(); + // a request after the shed is still exact: whatever was evicted is read again + let (_, digest) = request(&mut s, &mut d, &prompts[0], None); + assert_eq!(digest, full_digest(&prompts[0])); + assert!(s.bytes() <= s.budget_bytes(), "the shed budget bounds the store"); + // everything goes at reject; the next request reads from 0 and is exact + s.apply_shed(Some(0), &g); + assert_eq!((s.bytes(), s.node_count(), s.block_count()), (0, 0, 0)); + let (start, digest) = request(&mut s, &mut d, &prompts[1], None); + assert_eq!(start, None); + assert_eq!(digest, full_digest(&prompts[1])); + assert_eq!(s.bytes(), 0, "nothing is admitted while the budget is zero"); + // pressure over: the configured budget is restored and the cache refills + assert_eq!(s.apply_shed(None, &g), 0); + assert_eq!(s.budget_bytes(), 1 << 30); + request(&mut s, &mut d, &prompts[2], None); + assert!(s.bytes() > 0); + // a directive that asks for more than the configured budget never raises it + s.apply_shed(Some(u64::MAX), &g); + assert_eq!(s.budget_bytes(), 1 << 30); + s.store().check_invariants(); +} + +#[test] +fn churn_under_random_shed_directives_keeps_every_resume_exact_and_the_store_inside_its_budget() { + let g = governor(); + let budget = 2 * 100 + 12 * 1024; + let mut s = PrefixServe::new(cfg(), 1024, budget as u64, "test"); + let mut d = Fake::new(); + let mut prompts: Vec> = (1..=5).map(|i| session(i, 2, 4, 10)).collect(); + let mut x = 0x2545_f491_4f6c_dd1du64; + let mut next = move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + }; + let mut shed_events = 0; + for turn in 0..300 { + let who = (next() % 5) as usize; + match next() % 8 { + 0 => { + s.apply_shed(Some(next() % (budget as u64 + 1)), &g); + shed_events += 1; + } + 1 => { + s.apply_shed(None, &g); + } + 2 if s.bytes() > 0 => { + s.apply_shed(Some(0), &g); + shed_events += 1; + } + _ => {} + } + let p = &mut prompts[who]; + if p.len() < 40 * G { + p.extend(doc(turn + 7000, 1, 3)); + } + let (_, digest) = request(&mut s, &mut d, p, if next() % 9 == 0 { Some(1) } else { None }); + // a cancelled request ends mid-prefill: its digest is a partial read, only complete ones are compared + if digest == full_digest(p) { + assert!(s.bytes() <= s.budget_bytes(), "turn {turn}: {} > {}", s.bytes(), s.budget_bytes()); + } + s.store().check_invariants(); + assert!(s.bytes() <= budget, "turn {turn}: the store outgrew its configured budget"); + } + assert!(shed_events > 20, "the schedule exercised shedding"); + assert!(s.stats().evicted > 0); +} + +#[test] +fn low_host_memory_skips_the_checkpoint_instead_of_building_it() { + let mut s = serve(); + let mut d = Fake::new(); + d.available = Some(1 << 20); // below the 3 GiB floor + let a = session(1, 0, 3, 10); + let start = s.begin(&mut d, &a).unwrap(); + assert_eq!(start, None); + d.read(&a[..G], 0); + s.before_chunk(0); + assert_eq!(s.after_chunk(&mut d, &a, G).unwrap(), ChunkOutcome::LowMemory); + assert_eq!(s.node_count(), 0); + d.available = None; + assert_eq!(s.after_chunk(&mut d, &a, G).unwrap(), ChunkOutcome::LowMemory, "unknown telemetry fails closed"); +} + +#[test] +fn the_pool_queries_see_the_cached_prefixes() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 3, 6, 10); + request(&mut s, &mut d, &a, None); + let chain = crate::prefix_cache::chain(&a, G); + let m = s.prefix_match(&chain); + assert_eq!((m.cached_tokens as usize, m.block_tokens as usize), (6 * G, G)); + // another session that shares 3 blocks + let other = crate::prefix_cache::chain(&session(2, 3, 6, 10), G); + assert_eq!(s.prefix_match(&other).cached_tokens as usize, 3 * G); + let summary = s.summary(100); + assert_eq!(summary.namespace, m.namespace); + assert_eq!(summary.match_tokens(&chain) as usize, 6 * G); + assert!(s.describe().contains("nodes=6")); +} + +#[test] +fn config_resolution_follows_the_operator() { + let cfg = PrefixConfig::auto(); + assert_eq!(cfg.resolved_block(8192), 8192); + assert_eq!(cfg.resolved_block(1024), 1024); + assert_eq!(PrefixConfig { block_tokens: 2048, ..PrefixConfig::auto() }.resolved_block(8192), 2048); + assert!(cfg.validate(1024).is_ok()); + assert!(PrefixConfig { block_tokens: 300, ..PrefixConfig::auto() }.validate(1024).is_err()); + assert!(PrefixConfig { block_tokens: 4096, ..PrefixConfig::auto() }.validate(2048).is_err()); + assert_eq!(PrefixConfig { budget: PrefixBudget::Off, ..PrefixConfig::auto() }.resolve_budget(Some(1 << 40)), 0); + assert_eq!(PrefixConfig { budget: PrefixBudget::Bytes(5), ..PrefixConfig::auto() }.resolve_budget(None), 5); + assert_eq!(PrefixConfig::auto().resolve_budget(None), 0); + assert!(PrefixConfig::auto().resolve_budget(Some(80 << 30)) > (30 << 30)); + // the 5090 server after the expert source: a few GiB, not nothing + let server = PrefixConfig::auto().resolve_budget(Some(14 << 30)); + assert!(server >= (7 << 30) && server <= (8 << 30), "{server}"); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs index 9ab865bf..e0a9a63d 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs @@ -1266,325 +1266,4 @@ pub(in crate::qwen_forward) fn refill_defer_enabled() -> bool { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn adapt_decay_outside_zero_to_one_falls_back_to_the_default_with_a_line() { - // unset: the default, no line - assert_eq!(adapt_decay(None), (0.7, None)); - // inside 0..=1 (both ends included): taken as given - for (text, want) in [("0", 0.0), ("0.25", 0.25), (" 0.9 ", 0.9), ("1", 1.0), ("1.0", 1.0)] { - assert_eq!(adapt_decay(Some(text)), (want, None), "{text}"); - } - // above 1 (counts grow without end), below 0 (counts flip sign), not finite, not a number: default plus a line naming the knob - for text in ["1.0001", "2", "1e30", "-0.1", "-1", "inf", "-inf", "NaN", "", "fast"] { - let (value, line) = adapt_decay(Some(text)); - assert_eq!(value, 0.7, "{text}"); - assert!(line.is_some_and(|l| l.contains("LELEKA_ADAPT_DECAY")), "{text}"); - } - // the decayed usage of a value in range stays finite however many adaptations ran; one above 1 would not - let mut kept = 8.0_f32; - let mut grown = 8.0_f32; - for _ in 0..1000 { - kept *= adapt_decay(Some("0.9")).0; - grown *= 1.5; - } - assert!(kept.is_finite() && kept < 8.0); - assert!(grown.is_infinite()); - } - - #[test] - fn the_default_reserves_keep_more_free_vram_at_decode_than_vanilla_runs_with() { - let config = ExpertTierConfig::off(); - // 700 + 300 less the 514 MiB verifier assembly - assert_eq!(config.decode_headroom_mib(), 486); - assert!(config.decode_headroom_mib() >= VANILLA_FREE_FLOOR_MIB as isize); - // the opt-in 130 MiB is the vanilla floor to the MiB (700 + 130 - 514 = 316) - let tight = ExpertTierConfig { decode_reserve_mib: 130, ..ExpertTierConfig::off() }; - assert_eq!(tight.decode_headroom_mib(), 316); - assert!(tight.decode_headroom_mib() >= VANILLA_FREE_FLOOR_MIB as isize); - } - - #[test] - fn a_reserve_below_the_verifier_assembly_reports_a_negative_headroom() { - let config = ExpertTierConfig { reserve_mib: 100, decode_reserve_mib: 100, ..ExpertTierConfig::off() }; - assert_eq!(config.decode_headroom_mib(), 200 - VERIFIER_ASSEMBLY_MIB as isize); - assert!(config.decode_headroom_mib() < 0); - } - - #[test] - fn the_selection_based_ranking_picks_the_reference_swaps_in_the_same_order() { - // xorshift: deterministic usage with many ties (small integer counts) and a random resident set per layer - let mut x = 0x9e3779b97f4a7c15u64; - let mut next = move || { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x - }; - for case in 0..40 { - let skew = 1 + case % 7; - let usage: Vec = (0..LAYERS * EXPERTS).map(|_| ((next() % 11) as f32 / skew as f32).floor() + if next() % 5 == 0 { 0.5 } else { 0.0 }).collect(); - let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % (2 + (case % 4) as u64) != 0).collect(); - let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; - for max_swaps in [1usize, 5, 96, 4096] { - let fast = choose_swaps(&usage, resident, max_swaps); - let slow = choose_swaps_reference(&usage, resident, max_swaps); - assert_eq!(fast.len(), slow.len(), "case {case} max {max_swaps}"); - for (a, b) in fast.iter().zip(&slow) { - assert_eq!((a.layer, a.incoming, a.outgoing, a.gain.to_bits()), (b.layer, b.incoming, b.outgoing, b.gain.to_bits()), "case {case} max {max_swaps}"); - } - } - } - } - - #[test] - #[ignore = "timing probe: cargo test --release -p leleka-runtime --lib choose_swaps_timing -- --ignored --nocapture"] - fn choose_swaps_timing() { - let mut x = 0x2545f4914f6cdd1du64; - let mut next = move || { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x - }; - let usage: Vec = (0..LAYERS * EXPERTS).map(|_| if next() % 6 == 0 { (next() % 9) as f32 } else { 0.0 }).collect(); - let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % 100 < 46).collect(); - let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; - let time = |f: &dyn Fn() -> usize| { - let t = std::time::Instant::now(); - let mut n = 0; - for _ in 0..200 { - n += f(); - } - (t.elapsed().as_secs_f64() * 1e6 / 200.0, n) - }; - let (fast, a) = time(&|| choose_swaps(&usage, resident, 96).len()); - let (slow, b) = time(&|| choose_swaps_reference(&usage, resident, 96).len()); - eprintln!("choose_swaps: new {fast:.0} us, reference {slow:.0} us per call ({a} {b})"); - } - - use super::*; - - fn row(ids: [i32; 10]) -> Vec { - ids.to_vec() - } - - #[test] - fn residents_are_vram_groups_in_routing_order_and_the_rest_is_the_cpus_without_pcie() { - let mut ids = row([5, 1, 9, 2, 3, 4, 6, 7, 8, 0]); - ids.extend(row([9, 5, 11, 12, 13, 14, 15, 16, 17, 18])); - let resident = |e: u32| match e { - 9 => Some(40), - 5 => Some(7), - 17 => Some(3), - _ => None, - }; - let s = split_group(&ids, 10, 80, resident, 0, 16).unwrap(); - // first use order: 5 (entries 0, 11), 9 (2, 10), 17 (18) - assert_eq!(s.plan.vram(), &[(7, vec![0, 11]), (40, vec![2, 10]), (3, vec![18])]); - assert!(s.plan.pcie().is_empty() && s.pcie_experts.is_empty()); - for (i, &kind) in s.kinds.iter().enumerate() { - let want = if [0, 11, 2, 10, 18].contains(&i) { 0 } else { -1 }; - assert_eq!(kind, want, "entry {i}"); - } - assert_eq!(s.plan.entries(), 5); - } - - #[test] - fn the_pcie_share_is_the_last_misses_in_routing_order_capped_by_staging() { - // 10 distinct misses, pcie_frac 0.55 -> pcie_num 141, m = 10 * 141 >> 8 = 5 - let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); - let none = |_: u32| None; - let s = split_group(&ids, 10, 40, none, 141, 16).unwrap(); - assert_eq!(s.pcie_experts, vec![15, 16, 17, 18, 19]); - assert_eq!(s.plan.pcie(), &[vec![5], vec![6], vec![7], vec![8], vec![9]]); - assert_eq!(s.kinds, vec![-1, -1, -1, -1, -1, 1, 1, 1, 1, 1]); - // staging holds 3: the first three of the selected tail - let s = split_group(&ids, 10, 40, none, 141, 3).unwrap(); - assert_eq!(s.pcie_experts, vec![15, 16, 17]); - assert_eq!(s.kinds.iter().filter(|&&k| k == 1).count(), 3); - // pcie_num 256: every miss; 0: none - assert_eq!(split_group(&ids, 10, 40, none, 256, 16).unwrap().pcie_experts.len(), 10); - assert!(split_group(&ids, 10, 40, none, 0, 16).unwrap().plan.is_empty()); - } - - #[test] - fn a_restricted_pcie_share_takes_only_eligible_misses_and_never_more_than_the_unrestricted_one() { - // 10 misses, share 141/256 -> m = 5 of all misses; only 11, 14, 16, 17 may be staged - let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); - let none = |_: u32| None; - let ok = |e: u32| matches!(e, 11 | 14 | 16 | 17); - let s = split_group_pcie(&ids, 10, 40, none, 141, 16, 0, ok).unwrap(); - assert_eq!(s.pcie_experts, vec![11, 14, 16, 17], "capped by the eligible misses, routing order"); - assert_eq!(s.kinds, vec![-1, 1, -1, -1, 1, -1, 1, 1, -1, -1]); - // a smaller share takes the last eligible misses - let s = split_group_pcie(&ids, 10, 40, none, 64, 16, 0, ok).unwrap(); // m = 10 * 64 >> 8 = 2 - assert_eq!(s.pcie_experts, vec![16, 17]); - // nothing eligible, nothing staged; and the unrestricted split is the old one - assert!(split_group_pcie(&ids, 10, 40, none, 256, 16, 0, |_| false).unwrap().plan.pcie().is_empty()); - let all = split_group_pcie(&ids, 10, 40, none, 141, 16, 0, |_| true).unwrap(); - let old = split_group(&ids, 10, 40, none, 141, 16).unwrap(); - assert_eq!((all.pcie_experts, all.kinds), (old.pcie_experts, old.kinds)); - // residents and skipped experts are not eligible misses - let resident = |e: u32| (e == 11).then_some(2usize); - let s = split_group_pcie(&ids, 10, 40, resident, 256, 16, 0, ok).unwrap(); - assert_eq!(s.pcie_experts, vec![14, 16, 17]); - } - - #[test] - fn a_resident_expert_never_counts_as_a_miss_for_the_pcie_rank() { - // 1 and 3 resident; the misses are 2, 4, 20..=25 - let padded = row([1, 2, 3, 4, 20, 21, 22, 23, 24, 25]); - let resident = |e: u32| (e == 1 || e == 3).then_some(e as usize); - let s = split_group(&padded, 10, 40, resident, 128, 16).unwrap(); - // 8 misses (2, 4, 20..=25), m = 8 * 128 >> 8 = 4: the last four misses in routing order - assert_eq!(s.pcie_experts, vec![22, 23, 24, 25]); - assert_eq!(s.plan.vram().len(), 2); - } - - #[test] - fn the_tail_skip_drops_missed_experts_every_token_routes_at_or_below_the_rank() { - // row 0 ranks: 12 at 6, 30 at 7, 31 at 8, 40 (resident) at 9; row 1 ranks: 15 at 7, 12 at 8, 30 at 9 - let mut ids = row([1, 2, 3, 4, 5, 6, 12, 30, 31, 40]); - ids.extend(row([7, 8, 9, 10, 11, 13, 14, 15, 12, 30])); - let resident = |e: u32| (e == 40).then_some(3usize); - let off = split_group_tail(&ids, 10, 20, resident, 0, 16, 0).unwrap(); - assert_eq!(off.skipped_experts, 0); - assert!(off.kinds.iter().all(|&k| k != -2)); - let on = split_group_tail(&ids, 10, 20, resident, 0, 16, 7).unwrap(); - // 30: best rank min(7, 9) = 7 -> skipped (entries 7 and 19); 31: rank 8 -> skipped (entry 8); 15: rank 7 -> skipped (entry 17); - // 12: best rank min(6, 8) = 6 < 7 -> kept in both rows (entries 6 and 18) - assert_eq!(on.skipped_experts, 3); - assert_eq!(on.kinds.iter().enumerate().filter(|&(_, &k)| k == -2).map(|(i, _)| i).collect::>(), vec![7, 8, 17, 19]); - assert_eq!((on.kinds[6], on.kinds[18]), (-1, -1)); - assert_eq!(on.kinds[9], 0, "a resident expert is never skipped"); - // everything else is exactly what the skip-off split produced - for i in 0..20 { - if on.kinds[i] != -2 { - assert_eq!(on.kinds[i], off.kinds[i], "entry {i}"); - } - } - assert_eq!(on.plan.vram(), off.plan.vram()); - // rank 8: only expert 31 (rank 8 in its only row); rank 9: nothing (the rank-9 entries are resident 40 and 30, best rank 7) - assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 8).unwrap().skipped_experts, 1); - assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 9).unwrap().skipped_experts, 0); - } - - #[test] - fn the_tail_skip_shrinks_the_miss_count_before_the_pcie_share_is_taken() { - // ten misses, rank 7..9 are three experts: 7 misses remain, pcie_num 141 -> m = 7 * 141 >> 8 = 3 (instead of 5 of ten) - let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); - let none = |_: u32| None; - let s = split_group_tail(&ids, 10, 40, none, 141, 16, 7).unwrap(); - assert_eq!(s.skipped_experts, 3); - assert_eq!(s.kinds, vec![-1, -1, -1, -1, 1, 1, 1, -2, -2, -2]); - assert_eq!(s.pcie_experts, vec![14, 15, 16]); - // a rank past the last slot skips nothing - let off = split_group_tail(&ids, 10, 40, none, 141, 16, 10).unwrap(); - assert_eq!(off.skipped_experts, 0); - } - - #[test] - fn the_tail_skip_leaves_invalid_ids_to_the_cpu_check() { - let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]); - let s = split_group_tail(&ids, 10, 40, |_| None, 0, 16, 1).unwrap(); - assert_eq!(s.kinds[0], -1, "an out-of-range id is never a skip: the CPU path reports it"); - } - - #[test] - fn out_of_range_ids_stay_with_the_cpu_and_oversized_groups_are_refused() { - let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]); - let s = split_group(&ids, 10, 40, |_| Some(1), 256, 16).unwrap(); - assert_eq!(s.kinds[0], -1); - assert!(split_group(&ids, 10, 5, |_| None, 0, 16).is_err()); - assert!(split_group(&vec![0; 130], 10, 200, |_| None, 0, 16).is_err()); - assert!(split_group(&ids[..9], 10, 40, |_| None, 0, 16).is_err()); - } - - #[test] - fn swaps_take_the_most_routed_misses_over_the_least_routed_residents() { - let mut usage = vec![0.0f32; LAYERS * EXPERTS]; - // layer 2: residents 0 (5.0), 1 (0.5), 2 (3.0); candidates 10 (9.0), 11 (2.5), 12 (1.9: below 2) - for (e, u) in [(0, 5.0), (1, 0.5), (2, 3.0), (10, 9.0), (11, 2.5), (12, 1.9)] { - usage[2 * EXPERTS + e] = u; - } - // layer 7: resident 4 (0.0), candidate 30 (2.0: the least count a candidate may have) - usage[7 * EXPERTS + 30] = 2.0; - let resident = |l: usize, e: usize| (l == 2 && e < 3) || (l == 7 && e == 4); - let swaps = choose_swaps(&usage, resident, 96); - // layer 2 pairs: (10, 1) gain 8.5; (11, 2): 2.5 < 3.0 + 1.5 stops; layer 7: (30, 4) gain 2.0 - assert_eq!(swaps.len(), 2); - assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (2, 10, 1)); - assert_eq!((swaps[1].layer, swaps[1].incoming, swaps[1].outgoing), (7, 30, 4)); - assert_eq!(choose_swaps(&usage, resident, 1).len(), 1); - // no resident in a layer: no swap there (a native pack's cache only changes through its profile) - assert!(choose_swaps(&usage, |_, _| false, 96).is_empty()); - } - - #[test] - fn the_lag_controller_lowers_the_share_when_the_copies_land_last_and_probes_up_when_they_land_first() { - let mut c = PcieLag { num: 141, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; - // the PCIe leg finishes 200 us after the CPU leg on average: the share drops by 10 - c.lag_us = 200.0 * 48.0; - c.groups = 48; - c.round(); - assert_eq!(c.pcie_num(), 131); - // too few measured groups: nothing moves - c.lag_us = 9999.0; - c.groups = 3; - c.round(); - assert_eq!(c.pcie_num(), 131); - // copies always first: after three quiet rounds the share rises by 3 - let mut c = PcieLag { num: 100, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; - for _ in 0..3 { - c.groups = 20; - c.round(); - } - assert_eq!(c.pcie_num(), 103); - // the share stays inside its bounds - let mut c = PcieLag { num: PcieLag::MIN, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; - c.lag_us = 1e6; - c.groups = 10; - c.round(); - assert_eq!(c.pcie_num(), PcieLag::MIN); - } - - #[test] - fn the_pcie_mode_auto_is_dma_and_the_kernel_needs_device_aliases() { - // auto: DMA staging (this port's default; generate.cpp's is the copy kernel), the kernel only on request - assert_eq!(PcieMode::Auto.graph_mode(false, true), Some(0)); - assert_eq!(PcieMode::Auto.graph_mode(true, true), Some(0)); - assert_eq!(PcieMode::Auto.graph_mode(false, false), Some(0)); - assert_eq!(PcieMode::Kernel.graph_mode(false, true), Some(2)); - assert_eq!(PcieMode::Kernel.graph_mode(true, true), None); - assert_eq!(PcieMode::Dma.graph_mode(false, true), Some(0)); - assert_eq!(ExpertTierConfig::off().pcie_mode, PcieMode::Auto); - } - - #[test] - fn the_configuration_is_off_by_default_and_refuses_what_it_cannot_honour() { - let off = ExpertTierConfig::off(); - assert!(!off.enabled() && off.validate().is_ok() && off.pcie_num() == 115); - // the prompt-routing seed is an opt-in experiment - assert_eq!((off.seed_swaps, off.seed_keep, off.seed_usage, off.seed_decay), (0, 0.0, 0.0, 1.0)); - assert!(ExpertTierConfig { seed_keep: -1.0, ..off.clone() }.validate().is_err()); - let with_profile = ExpertTierConfig { profile: Some("p.bin".into()), ..off.clone() }; - assert!(with_profile.enabled()); - assert_eq!(with_profile.effective_slots(), -1); - assert_eq!(ExpertTierConfig { slots: 2048, ..off.clone() }.effective_slots(), 2048); - assert_eq!(ExpertTierConfig { pcie_frac: 0.55, ..off.clone() }.pcie_num(), 141); - // the default share needs a pinned source; an operator's share applies to a pageable bank too - assert_eq!(off.pcie_num_for(false), 115); - assert_eq!(off.pcie_num_for(true), 0); - assert_eq!(ExpertTierConfig { pcie_frac: 0.3, pcie_frac_set: true, ..off.clone() }.pcie_num_for(true), 77); - assert_eq!(ExpertTierConfig { pcie_frac: 1.0, ..off.clone() }.pcie_num(), 256); - assert!(ExpertTierConfig { slots: -2, ..off.clone() }.validate().is_err()); - assert!(ExpertTierConfig { pcie_frac: 1.5, ..off.clone() }.validate().is_err()); - assert!(ExpertTierConfig { pcie_frac: f64::NAN, ..off.clone() }.validate().is_err()); - assert!(!ExpertTierConfig { adapt_every: 0, ..off.clone() }.adaptive()); - assert!(ResidencyState::new(&ExpertTierConfig { adapt_swaps: 0, ..off.clone() }).usage.is_empty()); - assert_eq!(ResidencyState::new(&off).usage.len(), LAYERS * EXPERTS); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency/tests.rs new file mode 100644 index 00000000..d1e74e45 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency/tests.rs @@ -0,0 +1,322 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn adapt_decay_outside_zero_to_one_falls_back_to_the_default_with_a_line() { + // unset: the default, no line + assert_eq!(adapt_decay(None), (0.7, None)); + // inside 0..=1 (both ends included): taken as given + for (text, want) in [("0", 0.0), ("0.25", 0.25), (" 0.9 ", 0.9), ("1", 1.0), ("1.0", 1.0)] { + assert_eq!(adapt_decay(Some(text)), (want, None), "{text}"); + } + // above 1 (counts grow without end), below 0 (counts flip sign), not finite, not a number: default plus a line naming the knob + for text in ["1.0001", "2", "1e30", "-0.1", "-1", "inf", "-inf", "NaN", "", "fast"] { + let (value, line) = adapt_decay(Some(text)); + assert_eq!(value, 0.7, "{text}"); + assert!(line.is_some_and(|l| l.contains("LELEKA_ADAPT_DECAY")), "{text}"); + } + // the decayed usage of a value in range stays finite however many adaptations ran; one above 1 would not + let mut kept = 8.0_f32; + let mut grown = 8.0_f32; + for _ in 0..1000 { + kept *= adapt_decay(Some("0.9")).0; + grown *= 1.5; + } + assert!(kept.is_finite() && kept < 8.0); + assert!(grown.is_infinite()); +} + +#[test] +fn the_default_reserves_keep_more_free_vram_at_decode_than_vanilla_runs_with() { + let config = ExpertTierConfig::off(); + // 700 + 300 less the 514 MiB verifier assembly + assert_eq!(config.decode_headroom_mib(), 486); + assert!(config.decode_headroom_mib() >= VANILLA_FREE_FLOOR_MIB as isize); + // the opt-in 130 MiB is the vanilla floor to the MiB (700 + 130 - 514 = 316) + let tight = ExpertTierConfig { decode_reserve_mib: 130, ..ExpertTierConfig::off() }; + assert_eq!(tight.decode_headroom_mib(), 316); + assert!(tight.decode_headroom_mib() >= VANILLA_FREE_FLOOR_MIB as isize); +} + +#[test] +fn a_reserve_below_the_verifier_assembly_reports_a_negative_headroom() { + let config = ExpertTierConfig { reserve_mib: 100, decode_reserve_mib: 100, ..ExpertTierConfig::off() }; + assert_eq!(config.decode_headroom_mib(), 200 - VERIFIER_ASSEMBLY_MIB as isize); + assert!(config.decode_headroom_mib() < 0); +} + +#[test] +fn the_selection_based_ranking_picks_the_reference_swaps_in_the_same_order() { + // xorshift: deterministic usage with many ties (small integer counts) and a random resident set per layer + let mut x = 0x9e3779b97f4a7c15u64; + let mut next = move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + }; + for case in 0..40 { + let skew = 1 + case % 7; + let usage: Vec = (0..LAYERS * EXPERTS).map(|_| ((next() % 11) as f32 / skew as f32).floor() + if next() % 5 == 0 { 0.5 } else { 0.0 }).collect(); + let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % (2 + (case % 4) as u64) != 0).collect(); + let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; + for max_swaps in [1usize, 5, 96, 4096] { + let fast = choose_swaps(&usage, resident, max_swaps); + let slow = choose_swaps_reference(&usage, resident, max_swaps); + assert_eq!(fast.len(), slow.len(), "case {case} max {max_swaps}"); + for (a, b) in fast.iter().zip(&slow) { + assert_eq!((a.layer, a.incoming, a.outgoing, a.gain.to_bits()), (b.layer, b.incoming, b.outgoing, b.gain.to_bits()), "case {case} max {max_swaps}"); + } + } + } +} + +#[test] +#[ignore = "timing probe: cargo test --release -p leleka-runtime --lib choose_swaps_timing -- --ignored --nocapture"] +fn choose_swaps_timing() { + let mut x = 0x2545f4914f6cdd1du64; + let mut next = move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + }; + let usage: Vec = (0..LAYERS * EXPERTS).map(|_| if next() % 6 == 0 { (next() % 9) as f32 } else { 0.0 }).collect(); + let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % 100 < 46).collect(); + let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; + let time = |f: &dyn Fn() -> usize| { + let t = std::time::Instant::now(); + let mut n = 0; + for _ in 0..200 { + n += f(); + } + (t.elapsed().as_secs_f64() * 1e6 / 200.0, n) + }; + let (fast, a) = time(&|| choose_swaps(&usage, resident, 96).len()); + let (slow, b) = time(&|| choose_swaps_reference(&usage, resident, 96).len()); + eprintln!("choose_swaps: new {fast:.0} us, reference {slow:.0} us per call ({a} {b})"); +} + +use super::*; + +fn row(ids: [i32; 10]) -> Vec { + ids.to_vec() +} + +#[test] +fn residents_are_vram_groups_in_routing_order_and_the_rest_is_the_cpus_without_pcie() { + let mut ids = row([5, 1, 9, 2, 3, 4, 6, 7, 8, 0]); + ids.extend(row([9, 5, 11, 12, 13, 14, 15, 16, 17, 18])); + let resident = |e: u32| match e { + 9 => Some(40), + 5 => Some(7), + 17 => Some(3), + _ => None, + }; + let s = split_group(&ids, 10, 80, resident, 0, 16).unwrap(); + // first use order: 5 (entries 0, 11), 9 (2, 10), 17 (18) + assert_eq!(s.plan.vram(), &[(7, vec![0, 11]), (40, vec![2, 10]), (3, vec![18])]); + assert!(s.plan.pcie().is_empty() && s.pcie_experts.is_empty()); + for (i, &kind) in s.kinds.iter().enumerate() { + let want = if [0, 11, 2, 10, 18].contains(&i) { 0 } else { -1 }; + assert_eq!(kind, want, "entry {i}"); + } + assert_eq!(s.plan.entries(), 5); +} + +#[test] +fn the_pcie_share_is_the_last_misses_in_routing_order_capped_by_staging() { + // 10 distinct misses, pcie_frac 0.55 -> pcie_num 141, m = 10 * 141 >> 8 = 5 + let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); + let none = |_: u32| None; + let s = split_group(&ids, 10, 40, none, 141, 16).unwrap(); + assert_eq!(s.pcie_experts, vec![15, 16, 17, 18, 19]); + assert_eq!(s.plan.pcie(), &[vec![5], vec![6], vec![7], vec![8], vec![9]]); + assert_eq!(s.kinds, vec![-1, -1, -1, -1, -1, 1, 1, 1, 1, 1]); + // staging holds 3: the first three of the selected tail + let s = split_group(&ids, 10, 40, none, 141, 3).unwrap(); + assert_eq!(s.pcie_experts, vec![15, 16, 17]); + assert_eq!(s.kinds.iter().filter(|&&k| k == 1).count(), 3); + // pcie_num 256: every miss; 0: none + assert_eq!(split_group(&ids, 10, 40, none, 256, 16).unwrap().pcie_experts.len(), 10); + assert!(split_group(&ids, 10, 40, none, 0, 16).unwrap().plan.is_empty()); +} + +#[test] +fn a_restricted_pcie_share_takes_only_eligible_misses_and_never_more_than_the_unrestricted_one() { + // 10 misses, share 141/256 -> m = 5 of all misses; only 11, 14, 16, 17 may be staged + let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); + let none = |_: u32| None; + let ok = |e: u32| matches!(e, 11 | 14 | 16 | 17); + let s = split_group_pcie(&ids, 10, 40, none, 141, 16, 0, ok).unwrap(); + assert_eq!(s.pcie_experts, vec![11, 14, 16, 17], "capped by the eligible misses, routing order"); + assert_eq!(s.kinds, vec![-1, 1, -1, -1, 1, -1, 1, 1, -1, -1]); + // a smaller share takes the last eligible misses + let s = split_group_pcie(&ids, 10, 40, none, 64, 16, 0, ok).unwrap(); // m = 10 * 64 >> 8 = 2 + assert_eq!(s.pcie_experts, vec![16, 17]); + // nothing eligible, nothing staged; and the unrestricted split is the old one + assert!(split_group_pcie(&ids, 10, 40, none, 256, 16, 0, |_| false).unwrap().plan.pcie().is_empty()); + let all = split_group_pcie(&ids, 10, 40, none, 141, 16, 0, |_| true).unwrap(); + let old = split_group(&ids, 10, 40, none, 141, 16).unwrap(); + assert_eq!((all.pcie_experts, all.kinds), (old.pcie_experts, old.kinds)); + // residents and skipped experts are not eligible misses + let resident = |e: u32| (e == 11).then_some(2usize); + let s = split_group_pcie(&ids, 10, 40, resident, 256, 16, 0, ok).unwrap(); + assert_eq!(s.pcie_experts, vec![14, 16, 17]); +} + +#[test] +fn a_resident_expert_never_counts_as_a_miss_for_the_pcie_rank() { + // 1 and 3 resident; the misses are 2, 4, 20..=25 + let padded = row([1, 2, 3, 4, 20, 21, 22, 23, 24, 25]); + let resident = |e: u32| (e == 1 || e == 3).then_some(e as usize); + let s = split_group(&padded, 10, 40, resident, 128, 16).unwrap(); + // 8 misses (2, 4, 20..=25), m = 8 * 128 >> 8 = 4: the last four misses in routing order + assert_eq!(s.pcie_experts, vec![22, 23, 24, 25]); + assert_eq!(s.plan.vram().len(), 2); +} + +#[test] +fn the_tail_skip_drops_missed_experts_every_token_routes_at_or_below_the_rank() { + // row 0 ranks: 12 at 6, 30 at 7, 31 at 8, 40 (resident) at 9; row 1 ranks: 15 at 7, 12 at 8, 30 at 9 + let mut ids = row([1, 2, 3, 4, 5, 6, 12, 30, 31, 40]); + ids.extend(row([7, 8, 9, 10, 11, 13, 14, 15, 12, 30])); + let resident = |e: u32| (e == 40).then_some(3usize); + let off = split_group_tail(&ids, 10, 20, resident, 0, 16, 0).unwrap(); + assert_eq!(off.skipped_experts, 0); + assert!(off.kinds.iter().all(|&k| k != -2)); + let on = split_group_tail(&ids, 10, 20, resident, 0, 16, 7).unwrap(); + // 30: best rank min(7, 9) = 7 -> skipped (entries 7 and 19); 31: rank 8 -> skipped (entry 8); 15: rank 7 -> skipped (entry 17); + // 12: best rank min(6, 8) = 6 < 7 -> kept in both rows (entries 6 and 18) + assert_eq!(on.skipped_experts, 3); + assert_eq!(on.kinds.iter().enumerate().filter(|&(_, &k)| k == -2).map(|(i, _)| i).collect::>(), vec![7, 8, 17, 19]); + assert_eq!((on.kinds[6], on.kinds[18]), (-1, -1)); + assert_eq!(on.kinds[9], 0, "a resident expert is never skipped"); + // everything else is exactly what the skip-off split produced + for i in 0..20 { + if on.kinds[i] != -2 { + assert_eq!(on.kinds[i], off.kinds[i], "entry {i}"); + } + } + assert_eq!(on.plan.vram(), off.plan.vram()); + // rank 8: only expert 31 (rank 8 in its only row); rank 9: nothing (the rank-9 entries are resident 40 and 30, best rank 7) + assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 8).unwrap().skipped_experts, 1); + assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 9).unwrap().skipped_experts, 0); +} + +#[test] +fn the_tail_skip_shrinks_the_miss_count_before_the_pcie_share_is_taken() { + // ten misses, rank 7..9 are three experts: 7 misses remain, pcie_num 141 -> m = 7 * 141 >> 8 = 3 (instead of 5 of ten) + let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); + let none = |_: u32| None; + let s = split_group_tail(&ids, 10, 40, none, 141, 16, 7).unwrap(); + assert_eq!(s.skipped_experts, 3); + assert_eq!(s.kinds, vec![-1, -1, -1, -1, 1, 1, 1, -2, -2, -2]); + assert_eq!(s.pcie_experts, vec![14, 15, 16]); + // a rank past the last slot skips nothing + let off = split_group_tail(&ids, 10, 40, none, 141, 16, 10).unwrap(); + assert_eq!(off.skipped_experts, 0); +} + +#[test] +fn the_tail_skip_leaves_invalid_ids_to_the_cpu_check() { + let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + let s = split_group_tail(&ids, 10, 40, |_| None, 0, 16, 1).unwrap(); + assert_eq!(s.kinds[0], -1, "an out-of-range id is never a skip: the CPU path reports it"); +} + +#[test] +fn out_of_range_ids_stay_with_the_cpu_and_oversized_groups_are_refused() { + let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + let s = split_group(&ids, 10, 40, |_| Some(1), 256, 16).unwrap(); + assert_eq!(s.kinds[0], -1); + assert!(split_group(&ids, 10, 5, |_| None, 0, 16).is_err()); + assert!(split_group(&vec![0; 130], 10, 200, |_| None, 0, 16).is_err()); + assert!(split_group(&ids[..9], 10, 40, |_| None, 0, 16).is_err()); +} + +#[test] +fn swaps_take_the_most_routed_misses_over_the_least_routed_residents() { + let mut usage = vec![0.0f32; LAYERS * EXPERTS]; + // layer 2: residents 0 (5.0), 1 (0.5), 2 (3.0); candidates 10 (9.0), 11 (2.5), 12 (1.9: below 2) + for (e, u) in [(0, 5.0), (1, 0.5), (2, 3.0), (10, 9.0), (11, 2.5), (12, 1.9)] { + usage[2 * EXPERTS + e] = u; + } + // layer 7: resident 4 (0.0), candidate 30 (2.0: the least count a candidate may have) + usage[7 * EXPERTS + 30] = 2.0; + let resident = |l: usize, e: usize| (l == 2 && e < 3) || (l == 7 && e == 4); + let swaps = choose_swaps(&usage, resident, 96); + // layer 2 pairs: (10, 1) gain 8.5; (11, 2): 2.5 < 3.0 + 1.5 stops; layer 7: (30, 4) gain 2.0 + assert_eq!(swaps.len(), 2); + assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (2, 10, 1)); + assert_eq!((swaps[1].layer, swaps[1].incoming, swaps[1].outgoing), (7, 30, 4)); + assert_eq!(choose_swaps(&usage, resident, 1).len(), 1); + // no resident in a layer: no swap there (a native pack's cache only changes through its profile) + assert!(choose_swaps(&usage, |_, _| false, 96).is_empty()); +} + +#[test] +fn the_lag_controller_lowers_the_share_when_the_copies_land_last_and_probes_up_when_they_land_first() { + let mut c = PcieLag { num: 141, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; + // the PCIe leg finishes 200 us after the CPU leg on average: the share drops by 10 + c.lag_us = 200.0 * 48.0; + c.groups = 48; + c.round(); + assert_eq!(c.pcie_num(), 131); + // too few measured groups: nothing moves + c.lag_us = 9999.0; + c.groups = 3; + c.round(); + assert_eq!(c.pcie_num(), 131); + // copies always first: after three quiet rounds the share rises by 3 + let mut c = PcieLag { num: 100, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; + for _ in 0..3 { + c.groups = 20; + c.round(); + } + assert_eq!(c.pcie_num(), 103); + // the share stays inside its bounds + let mut c = PcieLag { num: PcieLag::MIN, lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }; + c.lag_us = 1e6; + c.groups = 10; + c.round(); + assert_eq!(c.pcie_num(), PcieLag::MIN); +} + +#[test] +fn the_pcie_mode_auto_is_dma_and_the_kernel_needs_device_aliases() { + // auto: DMA staging (this port's default; generate.cpp's is the copy kernel), the kernel only on request + assert_eq!(PcieMode::Auto.graph_mode(false, true), Some(0)); + assert_eq!(PcieMode::Auto.graph_mode(true, true), Some(0)); + assert_eq!(PcieMode::Auto.graph_mode(false, false), Some(0)); + assert_eq!(PcieMode::Kernel.graph_mode(false, true), Some(2)); + assert_eq!(PcieMode::Kernel.graph_mode(true, true), None); + assert_eq!(PcieMode::Dma.graph_mode(false, true), Some(0)); + assert_eq!(ExpertTierConfig::off().pcie_mode, PcieMode::Auto); +} + +#[test] +fn the_configuration_is_off_by_default_and_refuses_what_it_cannot_honour() { + let off = ExpertTierConfig::off(); + assert!(!off.enabled() && off.validate().is_ok() && off.pcie_num() == 115); + // the prompt-routing seed is an opt-in experiment + assert_eq!((off.seed_swaps, off.seed_keep, off.seed_usage, off.seed_decay), (0, 0.0, 0.0, 1.0)); + assert!(ExpertTierConfig { seed_keep: -1.0, ..off.clone() }.validate().is_err()); + let with_profile = ExpertTierConfig { profile: Some("p.bin".into()), ..off.clone() }; + assert!(with_profile.enabled()); + assert_eq!(with_profile.effective_slots(), -1); + assert_eq!(ExpertTierConfig { slots: 2048, ..off.clone() }.effective_slots(), 2048); + assert_eq!(ExpertTierConfig { pcie_frac: 0.55, ..off.clone() }.pcie_num(), 141); + // the default share needs a pinned source; an operator's share applies to a pageable bank too + assert_eq!(off.pcie_num_for(false), 115); + assert_eq!(off.pcie_num_for(true), 0); + assert_eq!(ExpertTierConfig { pcie_frac: 0.3, pcie_frac_set: true, ..off.clone() }.pcie_num_for(true), 77); + assert_eq!(ExpertTierConfig { pcie_frac: 1.0, ..off.clone() }.pcie_num(), 256); + assert!(ExpertTierConfig { slots: -2, ..off.clone() }.validate().is_err()); + assert!(ExpertTierConfig { pcie_frac: 1.5, ..off.clone() }.validate().is_err()); + assert!(ExpertTierConfig { pcie_frac: f64::NAN, ..off.clone() }.validate().is_err()); + assert!(!ExpertTierConfig { adapt_every: 0, ..off.clone() }.adaptive()); + assert!(ResidencyState::new(&ExpertTierConfig { adapt_swaps: 0, ..off.clone() }).usage.is_empty()); + assert_eq!(ResidencyState::new(&off).usage.len(), LAYERS * EXPERTS); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index ec26c8de..4a5de33d 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -1978,74 +1978,4 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_chunk_borrows_the_smallest_rung_that_holds_it() { - let blobs = ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap(); - let layout = prefill_layout_options(8192, 262_144, &blobs); - let tiers: Vec = [(512usize, 600usize), (2048, 900)] - .into_iter() - .map(|(rows, slots)| LoanTier { rows, layout: PrefillLayoutOptions { capacity: rows, ..layout }, slots }) - .collect(); - assert_eq!(tier_for(&tiers, 1).map(|t| t.rows), Some(512)); - assert_eq!(tier_for(&tiers, 512).map(|t| t.rows), Some(512)); - assert_eq!(tier_for(&tiers, 513).map(|t| t.rows), Some(2048)); - assert_eq!(tier_for(&tiers, 2048).map(|t| t.slots), Some(900)); - assert!(tier_for(&tiers, 2049).is_none(), "above the ladder the chunk borrows the full loan"); - assert!(tier_for(&[], 100).is_none()); - // the arena of a smaller rung is smaller - assert!(prefill_bytes(tiers[0].layout).unwrap() < prefill_bytes(tiers[1].layout).unwrap()); - assert!(prefill_bytes(tiers[1].layout).unwrap() < prefill_bytes(layout).unwrap()); - } - - #[test] - fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_rules() { - let config = StackConfig::new(4096); - assert!(ADMITTED_CAPACITIES.contains(&config.capacity)); - for capacity in [256usize, 1024, 8192] { - assert!(StackConfig { capacity, ..config.clone() }.validate().is_ok(), "{capacity}"); - } - for capacity in [0usize, 255, 300, 16384, 32768] { - assert!(StackConfig { capacity, ..config.clone() }.validate().is_err(), "{capacity}"); - } - assert!(StackConfig { max_context: 0, ..config.clone() }.validate().is_err()); - assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate().is_err()); - assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate().is_err()); - assert!(StackConfig { max_context: i64::MAX, ..config }.validate().is_err()); - } - - #[test] - fn the_conversation_cache_is_on_by_default_with_the_original_settings() { - let config = StackConfig::new(4096); - let conversation = config.conversation.as_ref().expect("--prompt-cache 6 is the default, as in the Original"); - assert_eq!((conversation.prompt_cache, conversation.prompt_cache_every, conversation.prompt_cache_root), (6, 16_384, 2048)); - assert_eq!(conversation.turn_token, Some(TURN_TOKEN)); - assert!(config.validate().is_ok()); - assert!(StackConfig { conversation: None, ..config }.validate().is_ok(), "the cache can be turned off"); - } - - #[test] - fn kv_defaults_to_the_production_int8_window_and_refuses_unported_formats() { - let config = StackConfig::new(4096); - assert_eq!((config.kv_format, config.kv_resident), (KvFormat::Int8, 32_768)); - assert_eq!(config.kv_footprint().map(|f| f.resident_pages), Some(8192)); - for kv_resident in [0usize, 1, 20_480, 40_000, 262_144] { - assert!(StackConfig { kv_resident, ..config.clone() }.validate().is_ok(), "{kv_resident}"); - } - assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate().is_err()); - for kv_format in [KvFormat::Fp16, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { - assert_eq!( - StackConfig { kv_format, ..config.clone() }.validate(), - Err(Error::Unsupported(crate::qwen_forward::contract::Stage::Session)) - ); - } - } - - #[test] - fn plan_errors_keep_their_class() { - assert_eq!(plan_error(PlanError::InvalidInput), Error::InvalidDimension); - assert_eq!(plan_error(PlanError::Overflow), Error::Overflow); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/tests.rs new file mode 100644 index 00000000..57b81916 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/tests.rs @@ -0,0 +1,71 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn a_chunk_borrows_the_smallest_rung_that_holds_it() { + let blobs = ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap(); + let layout = prefill_layout_options(8192, 262_144, &blobs); + let tiers: Vec = [(512usize, 600usize), (2048, 900)] + .into_iter() + .map(|(rows, slots)| LoanTier { rows, layout: PrefillLayoutOptions { capacity: rows, ..layout }, slots }) + .collect(); + assert_eq!(tier_for(&tiers, 1).map(|t| t.rows), Some(512)); + assert_eq!(tier_for(&tiers, 512).map(|t| t.rows), Some(512)); + assert_eq!(tier_for(&tiers, 513).map(|t| t.rows), Some(2048)); + assert_eq!(tier_for(&tiers, 2048).map(|t| t.slots), Some(900)); + assert!(tier_for(&tiers, 2049).is_none(), "above the ladder the chunk borrows the full loan"); + assert!(tier_for(&[], 100).is_none()); + // the arena of a smaller rung is smaller + assert!(prefill_bytes(tiers[0].layout).unwrap() < prefill_bytes(tiers[1].layout).unwrap()); + assert!(prefill_bytes(tiers[1].layout).unwrap() < prefill_bytes(layout).unwrap()); +} + +#[test] +fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_rules() { + let config = StackConfig::new(4096); + assert!(ADMITTED_CAPACITIES.contains(&config.capacity)); + for capacity in [256usize, 1024, 8192] { + assert!(StackConfig { capacity, ..config.clone() }.validate().is_ok(), "{capacity}"); + } + for capacity in [0usize, 255, 300, 16384, 32768] { + assert!(StackConfig { capacity, ..config.clone() }.validate().is_err(), "{capacity}"); + } + assert!(StackConfig { max_context: 0, ..config.clone() }.validate().is_err()); + assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate().is_err()); + assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate().is_err()); + assert!(StackConfig { max_context: i64::MAX, ..config }.validate().is_err()); +} + +#[test] +fn the_conversation_cache_is_on_by_default_with_the_original_settings() { + let config = StackConfig::new(4096); + let conversation = config.conversation.as_ref().expect("--prompt-cache 6 is the default, as in the Original"); + assert_eq!((conversation.prompt_cache, conversation.prompt_cache_every, conversation.prompt_cache_root), (6, 16_384, 2048)); + assert_eq!(conversation.turn_token, Some(TURN_TOKEN)); + assert!(config.validate().is_ok()); + assert!(StackConfig { conversation: None, ..config }.validate().is_ok(), "the cache can be turned off"); +} + +#[test] +fn kv_defaults_to_the_production_int8_window_and_refuses_unported_formats() { + let config = StackConfig::new(4096); + assert_eq!((config.kv_format, config.kv_resident), (KvFormat::Int8, 32_768)); + assert_eq!(config.kv_footprint().map(|f| f.resident_pages), Some(8192)); + for kv_resident in [0usize, 1, 20_480, 40_000, 262_144] { + assert!(StackConfig { kv_resident, ..config.clone() }.validate().is_ok(), "{kv_resident}"); + } + assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate().is_err()); + for kv_format in [KvFormat::Fp16, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { + assert_eq!( + StackConfig { kv_format, ..config.clone() }.validate(), + Err(Error::Unsupported(crate::qwen_forward::contract::Stage::Session)) + ); + } +} + +#[test] +fn plan_errors_keep_their_class() { + assert_eq!(plan_error(PlanError::InvalidInput), Error::InvalidDimension); + assert_eq!(plan_error(PlanError::Overflow), Error::Overflow); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs index 18141f0c..1200c138 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs @@ -385,92 +385,4 @@ fn recover<'a, 'ctx>(qsa: Rc>, slots: [usize; } #[cfg(test)] -mod tests { - use super::*; - use leleka_cuda_driver::Error as D; - - #[test] - fn a_graph_out_of_memory_names_the_widest_window_worth_recording() { - // window T=6 of 8 did not fit: 1..=5 were recorded and fit - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 6 }, 8), Some(5)); - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 3 }, 8), Some(2)); - // the commit graph (window 0) is recorded after every window: the widest window goes - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 8), Some(7)); - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 4), Some(3)); - // nothing wide enough is left (a width of one is no speculation), and a window past max_t is clamped - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 2 }, 8), None); - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 1 }, 8), None); - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 2), None); - assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 9 }, 4), Some(3)); - // every other failure, including a plain out-of-memory the driver did not classify, is not retried - for other in [D::HostAllocation, D::ContextPoisoned, D::InvalidQwenShape, D::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }] { - assert_eq!(window_cap_after(&other, 8), None, "{other:?}"); - } - assert!(ServeFailure::from(D::GraphOutOfMemory { window: 6 }).describe().contains("T=6")); - } - - #[test] - fn the_assembly_is_repeated_with_narrower_windows_until_one_fits() { - // 8 and 6 do not fit, 5 does - let mut tried = Vec::new(); - let mut notes = Vec::new(); - let (used, outcome) = assemble_with_window_fallback( - 8, - |t| { - tried.push(t); - match t { - 8 => Err(("oom at 8", window_cap_after(&D::GraphOutOfMemory { window: 7 }, t))), - 6 => Err(("oom at 6", window_cap_after(&D::GraphOutOfMemory { window: 0 }, t))), - t => Ok(t * 10), - } - }, - |failed, next| notes.push((failed, next)), - ); - assert_eq!((used, outcome), (5, Ok(50))); - assert_eq!(tried, [8, 6, 5]); - assert_eq!(notes, [(8, 6), (6, 5)]); - // it fits at once: one attempt, nothing noted - let mut calls = 0; - let (used, outcome) = assemble_with_window_fallback::<_, &str>(8, |t| { calls += 1; Ok(t) }, |_, _| panic!("no retry")); - assert_eq!((used, outcome, calls), (8, Ok(8), 1)); - } - - #[test] - fn the_fallback_stops_at_the_floor_on_any_other_failure_and_never_loops() { - // nothing fits down to the floor: the last failure comes back, with the width it was tried at - let (used, outcome) = assemble_with_window_fallback::<(), _>( - 8, - |t| Err((format!("oom at {t}"), window_cap_after(&D::GraphOutOfMemory { window: t }, t))), - |_, _| {}, - ); - assert_eq!((used, outcome), (2, Err("oom at 2".to_string()))); - // a failure that is not an out-of-memory is returned at once, with no retry - let mut calls = 0; - let (used, outcome) = assemble_with_window_fallback::<(), _>(8, |_| { calls += 1; Err(("broken", None)) }, |_, _| panic!("no retry")); - assert_eq!((used, outcome, calls), (8, Err("broken"), 1)); - // a cap that does not narrow the window (a bug somewhere) is not followed - let (used, outcome) = assemble_with_window_fallback::<(), _>(4, |_| Err(("same", Some(4))), |_, _| panic!("no retry")); - assert_eq!((used, outcome), (4, Err("same"))); - } - - #[test] - fn driver_refusals_keep_their_words_and_a_stable_class() { - let unbound = leleka_cuda_driver::Error::InvalidDriverValue("Original verifier producer unbound: router"); - let failure = ServeFailure::from(unbound); - assert_eq!(failure.error, Error::Unsupported(Stage::Executor)); - assert_eq!(failure.detail.as_deref(), Some("Original verifier producer unbound: router")); - assert!(failure.describe().contains("router")); - let sealed = ServeFailure::from(leleka_cuda_driver::Error::UnsupportedQwenOperation); - assert_eq!(sealed.error, Error::Unsupported(Stage::Session)); - assert!(sealed.detail.as_deref().is_some_and(|d| d.contains("unsealed"))); - let plain = ServeFailure::from(leleka_cuda_driver::Error::ContextMismatch); - assert_eq!((plain.error, plain.detail), (Error::IdentityMismatch, None)); - assert_eq!(ServeFailure::from(Error::NonFinite).describe(), "NonFinite"); - } - - #[test] - fn the_ple_history_image_is_nine_slots_of_the_channel_width() { - assert_eq!(PLE_HISTORY_VALUES, 92_160); - assert_eq!(PLE_HISTORY_BYTES, 368_640); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_verifier/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_verifier/tests.rs new file mode 100644 index 00000000..ba6355a2 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_verifier/tests.rs @@ -0,0 +1,89 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use leleka_cuda_driver::Error as D; + +#[test] +fn a_graph_out_of_memory_names_the_widest_window_worth_recording() { + // window T=6 of 8 did not fit: 1..=5 were recorded and fit + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 6 }, 8), Some(5)); + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 3 }, 8), Some(2)); + // the commit graph (window 0) is recorded after every window: the widest window goes + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 8), Some(7)); + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 4), Some(3)); + // nothing wide enough is left (a width of one is no speculation), and a window past max_t is clamped + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 2 }, 8), None); + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 1 }, 8), None); + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 2), None); + assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 9 }, 4), Some(3)); + // every other failure, including a plain out-of-memory the driver did not classify, is not retried + for other in [D::HostAllocation, D::ContextPoisoned, D::InvalidQwenShape, D::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }] { + assert_eq!(window_cap_after(&other, 8), None, "{other:?}"); + } + assert!(ServeFailure::from(D::GraphOutOfMemory { window: 6 }).describe().contains("T=6")); +} + +#[test] +fn the_assembly_is_repeated_with_narrower_windows_until_one_fits() { + // 8 and 6 do not fit, 5 does + let mut tried = Vec::new(); + let mut notes = Vec::new(); + let (used, outcome) = assemble_with_window_fallback( + 8, + |t| { + tried.push(t); + match t { + 8 => Err(("oom at 8", window_cap_after(&D::GraphOutOfMemory { window: 7 }, t))), + 6 => Err(("oom at 6", window_cap_after(&D::GraphOutOfMemory { window: 0 }, t))), + t => Ok(t * 10), + } + }, + |failed, next| notes.push((failed, next)), + ); + assert_eq!((used, outcome), (5, Ok(50))); + assert_eq!(tried, [8, 6, 5]); + assert_eq!(notes, [(8, 6), (6, 5)]); + // it fits at once: one attempt, nothing noted + let mut calls = 0; + let (used, outcome) = assemble_with_window_fallback::<_, &str>(8, |t| { calls += 1; Ok(t) }, |_, _| panic!("no retry")); + assert_eq!((used, outcome, calls), (8, Ok(8), 1)); +} + +#[test] +fn the_fallback_stops_at_the_floor_on_any_other_failure_and_never_loops() { + // nothing fits down to the floor: the last failure comes back, with the width it was tried at + let (used, outcome) = assemble_with_window_fallback::<(), _>( + 8, + |t| Err((format!("oom at {t}"), window_cap_after(&D::GraphOutOfMemory { window: t }, t))), + |_, _| {}, + ); + assert_eq!((used, outcome), (2, Err("oom at 2".to_string()))); + // a failure that is not an out-of-memory is returned at once, with no retry + let mut calls = 0; + let (used, outcome) = assemble_with_window_fallback::<(), _>(8, |_| { calls += 1; Err(("broken", None)) }, |_, _| panic!("no retry")); + assert_eq!((used, outcome, calls), (8, Err("broken"), 1)); + // a cap that does not narrow the window (a bug somewhere) is not followed + let (used, outcome) = assemble_with_window_fallback::<(), _>(4, |_| Err(("same", Some(4))), |_, _| panic!("no retry")); + assert_eq!((used, outcome), (4, Err("same"))); +} + +#[test] +fn driver_refusals_keep_their_words_and_a_stable_class() { + let unbound = leleka_cuda_driver::Error::InvalidDriverValue("Original verifier producer unbound: router"); + let failure = ServeFailure::from(unbound); + assert_eq!(failure.error, Error::Unsupported(Stage::Executor)); + assert_eq!(failure.detail.as_deref(), Some("Original verifier producer unbound: router")); + assert!(failure.describe().contains("router")); + let sealed = ServeFailure::from(leleka_cuda_driver::Error::UnsupportedQwenOperation); + assert_eq!(sealed.error, Error::Unsupported(Stage::Session)); + assert!(sealed.detail.as_deref().is_some_and(|d| d.contains("unsealed"))); + let plain = ServeFailure::from(leleka_cuda_driver::Error::ContextMismatch); + assert_eq!((plain.error, plain.detail), (Error::IdentityMismatch, None)); + assert_eq!(ServeFailure::from(Error::NonFinite).describe(), "NonFinite"); +} + +#[test] +fn the_ple_history_image_is_nine_slots_of_the_channel_width() { + assert_eq!(PLE_HISTORY_VALUES, 92_160); + assert_eq!(PLE_HISTORY_BYTES, 368_640); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs b/crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs index 2665ac7e..0ea51a54 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs @@ -621,401 +621,4 @@ impl SpecStats { } #[cfg(test)] -mod tests { - use super::*; - - /// Deterministic generator for the synthetic traces. - struct Rng(u64); - impl Rng { - fn next(&mut self) -> f64 { - self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - ((self.0 >> 11) as f64) / ((1u64 << 53) as f64) - } - } - /// A synthetic content regime: draft probabilities are drawn from `[p_lo, p_hi]` and a draft with probability p is - /// accepted with probability `clamp(p * calib)`; a window of t rows costs `base + slope (t-1)` ms (+ noise). - #[derive(Clone, Copy)] - struct World { - p_lo: f64, - p_hi: f64, - calib: f64, - base: f64, - slope: f64, - suffix_q: f64, - suffix_len: usize, - suffix_match: usize, - } - const CODE_CHEAP: World = World { p_lo: 0.6, p_hi: 1.0, calib: 0.97, base: 30.0, slope: 2.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; - const CODE_COSTLY: World = World { p_lo: 0.6, p_hi: 1.0, calib: 0.97, base: 30.0, slope: 11.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; - const PROSE_CHEAP: World = World { p_lo: 0.15, p_hi: 0.9, calib: 0.85, base: 30.0, slope: 2.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; - const PROSE_COSTLY: World = World { p_lo: 0.15, p_hi: 0.9, calib: 0.85, base: 30.0, slope: 11.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; - const REPEAT: World = World { p_lo: 0.5, p_hi: 1.0, calib: 0.9, base: 30.0, slope: 3.0, suffix_q: 0.995, suffix_len: 7, suffix_match: 40 }; - - /// One policy-driven (`fixed == None`) or fixed-width round; returns (tokens, ms, t). - fn play(world: &World, rng: &mut Rng, policy: Option<&mut AdaptivePolicy>, fixed: Option) -> (usize, f64, usize) { - let max_t = 8; - let probs: Vec = (0..max_t - 1).map(|_| (world.p_lo + (world.p_hi - world.p_lo) * rng.next()) as f32).collect(); - let hits = |rng: &mut Rng, q: f64, n: usize| -> usize { - let mut a = 0; - while a < n && rng.next() < q { a += 1; } - a - }; - let accept_mtp = |rng: &mut Rng, rows: usize| -> usize { - let mut a = 0; - while a < rows && rng.next() < (probs[a] as f64 * world.calib).min(0.999) { a += 1; } - a - }; - let noise = 1.0 + 0.04 * (rng.next() - 0.5); - let cost = |t: usize| (world.base + world.slope * (t - 1) as f64) * noise; - match (policy, fixed) { - (Some(pol), _) => { - let offer = Offer { mtp_probs: &probs, suffix_k: world.suffix_len, suffix_match: world.suffix_match, suffix_agrees: true }; - let c = pol.choose(&offer); - let a = match c.origin { - Origin::Mtp => accept_mtp(rng, c.t - 1), - Origin::Suffix => hits(rng, world.suffix_q, c.t - 1), - }; - let ms = cost(c.t) + 0.45 * probs.len().min(4) as f64; - pol.observe(&c, a, ms, probs.len().min(4)); - (a + 1, ms, c.t) - } - (None, Some(t)) => { - let a = if world.suffix_len > 0 && world.suffix_q > 0.9 && t - 1 <= world.suffix_len { - hits(rng, world.suffix_q, t - 1) - } else { - accept_mtp(rng, t - 1) - }; - (a + 1, cost(t) + 0.45 * 3.0, t) - } - _ => unreachable!(), - } - } - fn fixed_rate(world: &World, t: usize) -> f64 { - let mut rng = Rng(7); - let (mut tok, mut ms) = (0usize, 0.0); - for _ in 0..4000 { - let (a, m, _) = play(world, &mut rng, None, Some(t)); - tok += a; ms += m; - } - tok as f64 / ms - } - fn best_fixed(world: &World) -> (usize, f64) { - (1..=8).map(|t| (t, fixed_rate(world, t))).fold((1, 0.0), |b, x| if x.1 > b.1 { x } else { b }) - } - fn adaptive_run(world_seq: &[(World, usize)], cfg: AdaptiveConfig) -> (f64, Vec) { - let mut pol = AdaptivePolicy::new(cfg); - let mut rng = Rng(11); - let (mut tok, mut ms) = (0usize, 0.0); - let mut mean_t = Vec::new(); - for (w, n) in world_seq { - let mut sum_t = 0usize; - let mut tail = 0usize; - for i in 0..*n { - let (a, m, t) = play(w, &mut rng, Some(&mut pol), None); - tok += a; ms += m; sum_t += t; - if i >= *n / 2 { tail += t; } - } - let _ = sum_t; - mean_t.push(tail as f64 / (*n - *n / 2) as f64); - } - (tok as f64 / ms, mean_t) - } - fn cfg() -> AdaptiveConfig { - AdaptiveConfig::new(8, 7) - } - - #[test] - fn stationary_regimes_reach_the_best_fixed_width() { - for w in [CODE_CHEAP, CODE_COSTLY, PROSE_CHEAP, PROSE_COSTLY] { - let (bt, best) = best_fixed(&w); - let (rate, _) = adaptive_run(&[(w, 4000)], cfg()); - assert!(rate >= 0.97 * best, "adaptive {rate:.5} vs best fixed t={bt} {best:.5}"); - for t in [3usize, 4, 6] { - assert!(rate >= 0.99 * fixed_rate(&w, t), "adaptive {rate:.5} vs fixed {t}"); - } - } - } - - #[test] - fn it_widens_when_rows_are_cheap_and_narrows_when_they_are_not() { - let (_, cheap) = adaptive_run(&[(CODE_CHEAP, 1500)], cfg()); - let (_, costly) = adaptive_run(&[(CODE_COSTLY, 1500)], cfg()); - assert!(cheap[0] > costly[0] + 1.5, "cheap {:.2} costly {:.2}", cheap[0], costly[0]); - assert!(cheap[0] >= 6.0, "cheap windows are wide: {:.2}", cheap[0]); - } - - #[test] - fn it_follows_a_change_of_content_and_of_cost() { - let seq = [(CODE_CHEAP, 800), (PROSE_COSTLY, 800), (CODE_CHEAP, 800), (CODE_COSTLY, 800)]; - let (rate, tail) = adaptive_run(&seq, cfg()); - assert!(tail[0] > tail[1] + 2.0 && tail[2] > tail[1] + 2.0 && tail[2] > tail[3] + 1.5, "{tail:?}"); - // against the oracle that knows each segment's best fixed width - let (mut tok, mut ms) = (0.0, 0.0); - for (w, n) in seq { - let (_, r) = best_fixed(&w); - tok += r * n as f64 * 1.0; - ms += n as f64; - } - let _ = (tok, ms); - let oracle: f64 = seq.iter().map(|(w, n)| best_fixed(w).1 * *n as f64).sum::() / seq.iter().map(|(_, n)| *n as f64).sum::(); - assert!(rate >= 0.93 * oracle, "adaptive {rate:.5} vs per-segment oracle {oracle:.5}"); - // and it beats every single fixed width over the whole sequence - let whole = |t: usize| -> f64 { - let mut rng = Rng(3); - let (mut tk, mut m) = (0usize, 0.0); - for (w, n) in seq { - for _ in 0..n { - let (a, c, _) = play(&w, &mut rng, None, Some(t)); - tk += a; m += c; - } - } - tk as f64 / m - }; - for t in 1..=8 { - assert!(rate >= whole(t) * 0.995, "fixed {t}: {:.5} vs adaptive {rate:.5}", whole(t)); - } - } - - #[test] - fn reaction_to_a_switch_takes_tens_of_rounds_not_hundreds() { - let mut pol = AdaptivePolicy::new(cfg()); - let mut rng = Rng(5); - for _ in 0..600 { play(&CODE_COSTLY, &mut rng, Some(&mut pol), None); } - let mut ts = Vec::new(); - for _ in 0..120 { ts.push(play(&CODE_CHEAP, &mut rng, Some(&mut pol), None).2); } - let late: f64 = ts[60..].iter().sum::() as f64 / 60.0; - assert!(late >= 5.5, "width 60..120 rounds after the cost dropped: {late:.2}"); - } - - #[test] - fn exploration_costs_little_and_is_the_only_way_to_learn_unseen_widths() { - let mut off = cfg(); - off.explore_period = 0; - let (on_rate, _) = adaptive_run(&[(CODE_CHEAP, 3000)], cfg()); - let (off_rate, _) = adaptive_run(&[(CODE_CHEAP, 3000)], off); - assert!(on_rate >= 0.97 * off_rate, "on {on_rate:.5} off {off_rate:.5}"); - let mut pol = AdaptivePolicy::new(cfg()); - let mut rng = Rng(9); - let mut explored = 0; - for _ in 0..400 { - let before = pol.since_explore; - let _ = before; - let probs = [0.9f32; 7]; - let c = pol.choose(&Offer { mtp_probs: &probs, suffix_k: 0, suffix_match: 0, suffix_agrees: false }); - explored += c.explored as usize; - pol.observe(&c, 3.min(c.t - 1), 40.0 + 2.0 * c.t as f64 + rng.next(), 3); - } - assert!(explored >= 4 && explored <= 60, "explored {explored} of 400"); - } - - #[test] - fn a_long_repeated_suffix_opens_the_widest_window() { - let (rate, tail) = adaptive_run(&[(REPEAT, 600)], cfg()); - assert!(tail[0] >= 7.5, "mean width {:.2}", tail[0]); - assert!(rate > fixed_rate(&REPEAT, 4) * 1.3, "rate {rate:.5} vs fixed-4 {:.5}", fixed_rate(&REPEAT, 4)); - } - - #[test] - fn a_suffix_that_keeps_missing_is_dropped() { - let mut pol = AdaptivePolicy::new(cfg()); - let mut rng = Rng(21); - let probs = [0.9f32, 0.9, 0.9, 0.9, 0.8, 0.8, 0.7]; - let mut suffix_late = 0; - for i in 0..600 { - // a stale short match that never continues, MTP is right 85 % of the time - let c = pol.choose(&Offer { mtp_probs: &probs, suffix_k: 5, suffix_match: 4, suffix_agrees: false }); - let a = match c.origin { - Origin::Suffix => 0, - Origin::Mtp => { let mut a = 0; while a < c.t - 1 && rng.next() < 0.85 { a += 1; } a } - }; - if i >= 300 && c.origin == Origin::Suffix && c.t > 1 { suffix_late += 1; } - pol.observe(&c, a, 40.0 + 3.0 * c.t as f64, 3); - } - assert!(suffix_late <= 20, "{suffix_late} late suffix rounds"); - } - - #[test] - fn unmeasured_widths_are_interpolated_from_the_measured_ones() { - let mut pol = AdaptivePolicy::new(cfg()); - for i in 0..200 { - let t = [2usize, 4, 6][i % 3]; - let c = Choice { origin: Origin::Mtp, t, expected: 2.0, rate: 0.04, explored: false, probs: [0.8; MAX_T], matched: 0, agrees: false }; - pol.observe(&c, 1, 30.0 + 5.0 * (t - 1) as f64 + 0.45 * 3.0, 3); - } - for t in [1usize, 3, 5, 7, 8] { - let want = 30.0 + 5.0 * (t - 1) as f64; - let got = pol.window_ms(t); - assert!((got - want).abs() <= 0.1 * want, "t={t}: {got:.1} vs {want:.1}"); - } - assert!((pol.row_slope_ms() - 5.0).abs() < 1.0); - } - - #[test] - fn the_calibration_follows_the_drafter() { - // a drafter that is right half as often as it claims: its 0.9 drafts must be believed less than 0.9 - let mut pol = AdaptivePolicy::new(cfg()); - let mut rng = Rng(2); - for _ in 0..800 { - let c = Choice { origin: Origin::Mtp, t: 4, expected: 2.0, rate: 0.04, explored: false, probs: [0.92; MAX_T], matched: 0, agrees: false }; - let mut a = 0; - while a < 3 && rng.next() < 0.45 { a += 1; } - pol.observe(&c, a, 40.0, 3); - } - let r = pol.mtp_rate(1, 0.92); - assert!((r - 0.45).abs() < 0.1, "calibrated rate {r:.3}"); - assert!(pol.mtp_rate(1, 0.6) < 0.8); - } - - #[test] - fn the_draft_plan_stays_inside_its_bounds_and_follows_the_cost() { - let mut cheap = AdaptivePolicy::new(cfg()); - let mut costly = AdaptivePolicy::new(cfg()); - let mut rng = Rng(4); - for _ in 0..500 { - play(&CODE_CHEAP, &mut rng, Some(&mut cheap), None); - play(&CODE_COSTLY, &mut rng, Some(&mut costly), None); - } - let (a, b) = (cheap.draft_plan(), costly.draft_plan()); - for p in [a, b] { - assert!((1..=7).contains(&p.max_drafts) && (0.10..=0.90).contains(&p.min_p), "{p:?}"); - } - assert!(a.max_drafts > b.max_drafts, "{a:?} {b:?}"); - assert!(a.min_p <= b.min_p, "{a:?} {b:?}"); - } - - #[test] - fn replay_arm_options_set_the_named_constants_and_refuse_the_unknown() { - let mut c = cfg(); - assert!(c.set_option("step", "0.3") && c.set_option("explore", "0") && c.set_option("margin", "0.05") && c.set_option("min_p_lo", "0.2")); - assert!(c.set_option("alpha", "0.2") && c.set_option("decay", "0.99") && c.set_option("bias", "0.1")); - assert_eq!((c.draft_step_ms, c.explore_period, c.margin, c.min_p_lo), (0.3, 0, 0.05, 0.2)); - assert_eq!((c.cost_alpha, c.decay, c.bias_rate), (0.2, 0.99, 0.1)); - let before = c; - assert!(!c.set_option("nope", "1") && !c.set_option("step", "fast")); - assert_eq!(c, before); - } - - /// The earlier rule, kept as the reference: the floor is the lower edge of the first bucket whose calibrated acceptance clears the bar. - fn legacy_plan(pol: &AdaptivePolicy) -> DraftPlan { - let max_drafts = ((pol.hold_t.ceil() as usize).max(2)).min(pol.cfg.max_drafts.max(1)); - let rate = if pol.rate_ewma > 0.0 { pol.rate_ewma } else { 0.04 }; - let a_req = (rate * (pol.row_slope_ms() + pol.cfg.draft_step_ms) / pol.survive_ewma.max(0.2)).clamp(0.0, 0.99); - let mut min_p = pol.cfg.min_p_hi; - for b in 0..P_BUCKETS { - let r = sigmoid(logit(pol.mtp_bucket[b].rate(P_PRIOR[b], N0_BUCKET)) + pol.bias_mtp); - if r >= a_req { - min_p = P_EDGES[b]; - break; - } - } - DraftPlan { max_drafts, min_p: min_p.clamp(pol.cfg.min_p_lo, pol.cfg.min_p_hi) } - } - - #[test] - fn the_default_draft_plan_is_the_earlier_rule_and_the_new_options_only_lower_or_smooth_the_floor() { - let mut rng = Rng(8); - for world in [CODE_CHEAP, CODE_COSTLY, PROSE_CHEAP, PROSE_COSTLY] { - let mut pol = AdaptivePolicy::new(cfg()); - let (mut cheaper, mut smooth, mut measured) = (cfg(), cfg(), cfg()); - cheaper.row_q = 0.5; - smooth.smooth_floor = true; - measured.measured_rate = true; - let (mut pc, mut ps, mut pm) = (AdaptivePolicy::new(cheaper), AdaptivePolicy::new(smooth), AdaptivePolicy::new(measured)); - for i in 0..600 { - let mut r2 = Rng(i + 3); - play(&world, &mut rng, Some(&mut pol), None); - play(&world, &mut r2, Some(&mut pc), None); - let mut r3 = Rng(i + 3); - play(&world, &mut r3, Some(&mut ps), None); - let mut r4 = Rng(i + 3); - play(&world, &mut r4, Some(&mut pm), None); - assert_eq!(pol.draft_plan(), legacy_plan(&pol), "round {i}"); - let l = legacy_plan(&pc); - assert!(pc.draft_plan().min_p <= l.min_p + 1e-6 && pc.draft_plan().max_drafts == l.max_drafts, "row_q 0.5 raised the floor at round {i}"); - let sp = ps.draft_plan().min_p; - assert!((0.10..=0.90).contains(&sp), "smooth floor {sp} out of bounds at round {i}"); - let pl = pm.draft_plan(); - assert!((0.10..=0.90).contains(&pl.min_p) && (1..=7).contains(&pl.max_drafts), "{pl:?}"); - } - } - } - - #[test] - fn the_default_ceiling_is_the_new_one_and_the_legacy_switch_restores_the_old_policy_exactly() { - let new = AdaptiveConfig::new(8, 7); - assert_eq!(new.min_p_hi, FLOOR_CEILING); - let legacy = new.with_policy(Some("legacy")); - assert_eq!(legacy.min_p_hi, 0.90); - // everything but the ceiling is the earlier policy's, field by field - let earlier = AdaptiveConfig { - max_t: 8, max_drafts: 7, margin: 0.02, explore_period: 32, min_p_lo: 0.10, min_p_hi: 0.90, draft_step_ms: 0.45, - cost_alpha: 0.12, decay: 0.995, bias_rate: 0.06, row_q: 1.0, smooth_floor: false, measured_rate: false, - }; - assert_eq!(legacy, earlier); - assert_eq!(new.with_policy(Some("v1")), earlier); - assert_eq!(new.with_policy(None), new); - assert_eq!(new.with_policy(Some("current")), new); - // a request that names a ceiling keeps it in both policies; one that does not gets the policy's - for (cfg, want) in [(new, FLOOR_CEILING), (legacy, 0.90)] { - let mut pol = AdaptivePolicy::new(cfg); - pol.begin_request(0.0); - assert_eq!(pol.cfg.min_p_hi, want); - pol.begin_request(0.7); - assert_eq!(pol.cfg.min_p_hi, 0.7); - pol.begin_request(0.0); - assert_eq!(pol.cfg.min_p_hi, want); - } - // the chain floor the plan asks for never exceeds the ceiling of the policy - let mut pol = AdaptivePolicy::new(new); - pol.begin_request(0.0); - let mut rng = Rng(5); - for _ in 0..600 { - play(&CODE_COSTLY, &mut rng, Some(&mut pol), None); - assert!(pol.draft_plan().min_p <= FLOOR_CEILING + 1e-6); - } - } - - #[test] - fn the_smooth_floor_moves_continuously_with_the_bar() { - // synthetic, calibrated tables: the floor must not jump by a bucket for a small change of the bar - let mut pol = AdaptivePolicy::new({ let mut c = cfg(); c.smooth_floor = true; c }); - for b in 0..P_BUCKETS { - let centre = if b + 1 < P_BUCKETS { 0.5 * (P_EDGES[b] + P_EDGES[b + 1]) as f64 } else { 0.975 }; - for _ in 0..400 { - pol.mtp_bucket[b].add(false, 1.0); - } - pol.mtp_bucket[b].ok = 400.0 * centre; - } - let mut last: Option = None; - for step in 0..30 { - pol.rate_ewma = 0.10 + 0.002 * step as f64; - pol.survive_ewma = 0.5; - let p = pol.draft_plan().min_p; - if let Some(l) = last { - assert!((p - l).abs() < 0.08, "floor jumped from {l} to {p} at step {step}"); - assert!(p >= l - 1e-6, "floor fell while the bar rose"); - } - last = Some(p); - } - } - - #[test] - fn a_trace_is_reproducible() { - let run = || { - let mut pol = AdaptivePolicy::new(cfg()); - let mut rng = Rng(1); - (0..300).map(|_| play(&PROSE_CHEAP, &mut rng, Some(&mut pol), None).2).collect::>() - }; - assert_eq!(run(), run()); - } - - #[test] - fn stats_line_reports_the_histograms() { - let mut s = SpecStats::default(); - s.record(4, 3, false, false, 50.0); - s.record(6, 0, true, true, 60.0); - let l = s.line(); - assert!(l.contains("rounds=2 tokens=5 tok_per_round=2.500") && l.contains("lookup_rounds=1 explored=1"), "{l}"); - assert!(l.contains("accepted=3/8"), "{l}"); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_spec_adaptive/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_spec_adaptive/tests.rs new file mode 100644 index 00000000..8a206bb2 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_spec_adaptive/tests.rs @@ -0,0 +1,398 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +/// Deterministic generator for the synthetic traces. +struct Rng(u64); +impl Rng { + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((self.0 >> 11) as f64) / ((1u64 << 53) as f64) + } +} +/// A synthetic content regime: draft probabilities are drawn from `[p_lo, p_hi]` and a draft with probability p is +/// accepted with probability `clamp(p * calib)`; a window of t rows costs `base + slope (t-1)` ms (+ noise). +#[derive(Clone, Copy)] +struct World { + p_lo: f64, + p_hi: f64, + calib: f64, + base: f64, + slope: f64, + suffix_q: f64, + suffix_len: usize, + suffix_match: usize, +} +const CODE_CHEAP: World = World { p_lo: 0.6, p_hi: 1.0, calib: 0.97, base: 30.0, slope: 2.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; +const CODE_COSTLY: World = World { p_lo: 0.6, p_hi: 1.0, calib: 0.97, base: 30.0, slope: 11.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; +const PROSE_CHEAP: World = World { p_lo: 0.15, p_hi: 0.9, calib: 0.85, base: 30.0, slope: 2.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; +const PROSE_COSTLY: World = World { p_lo: 0.15, p_hi: 0.9, calib: 0.85, base: 30.0, slope: 11.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; +const REPEAT: World = World { p_lo: 0.5, p_hi: 1.0, calib: 0.9, base: 30.0, slope: 3.0, suffix_q: 0.995, suffix_len: 7, suffix_match: 40 }; + +/// One policy-driven (`fixed == None`) or fixed-width round; returns (tokens, ms, t). +fn play(world: &World, rng: &mut Rng, policy: Option<&mut AdaptivePolicy>, fixed: Option) -> (usize, f64, usize) { + let max_t = 8; + let probs: Vec = (0..max_t - 1).map(|_| (world.p_lo + (world.p_hi - world.p_lo) * rng.next()) as f32).collect(); + let hits = |rng: &mut Rng, q: f64, n: usize| -> usize { + let mut a = 0; + while a < n && rng.next() < q { a += 1; } + a + }; + let accept_mtp = |rng: &mut Rng, rows: usize| -> usize { + let mut a = 0; + while a < rows && rng.next() < (probs[a] as f64 * world.calib).min(0.999) { a += 1; } + a + }; + let noise = 1.0 + 0.04 * (rng.next() - 0.5); + let cost = |t: usize| (world.base + world.slope * (t - 1) as f64) * noise; + match (policy, fixed) { + (Some(pol), _) => { + let offer = Offer { mtp_probs: &probs, suffix_k: world.suffix_len, suffix_match: world.suffix_match, suffix_agrees: true }; + let c = pol.choose(&offer); + let a = match c.origin { + Origin::Mtp => accept_mtp(rng, c.t - 1), + Origin::Suffix => hits(rng, world.suffix_q, c.t - 1), + }; + let ms = cost(c.t) + 0.45 * probs.len().min(4) as f64; + pol.observe(&c, a, ms, probs.len().min(4)); + (a + 1, ms, c.t) + } + (None, Some(t)) => { + let a = if world.suffix_len > 0 && world.suffix_q > 0.9 && t - 1 <= world.suffix_len { + hits(rng, world.suffix_q, t - 1) + } else { + accept_mtp(rng, t - 1) + }; + (a + 1, cost(t) + 0.45 * 3.0, t) + } + _ => unreachable!(), + } +} +fn fixed_rate(world: &World, t: usize) -> f64 { + let mut rng = Rng(7); + let (mut tok, mut ms) = (0usize, 0.0); + for _ in 0..4000 { + let (a, m, _) = play(world, &mut rng, None, Some(t)); + tok += a; ms += m; + } + tok as f64 / ms +} +fn best_fixed(world: &World) -> (usize, f64) { + (1..=8).map(|t| (t, fixed_rate(world, t))).fold((1, 0.0), |b, x| if x.1 > b.1 { x } else { b }) +} +fn adaptive_run(world_seq: &[(World, usize)], cfg: AdaptiveConfig) -> (f64, Vec) { + let mut pol = AdaptivePolicy::new(cfg); + let mut rng = Rng(11); + let (mut tok, mut ms) = (0usize, 0.0); + let mut mean_t = Vec::new(); + for (w, n) in world_seq { + let mut sum_t = 0usize; + let mut tail = 0usize; + for i in 0..*n { + let (a, m, t) = play(w, &mut rng, Some(&mut pol), None); + tok += a; ms += m; sum_t += t; + if i >= *n / 2 { tail += t; } + } + let _ = sum_t; + mean_t.push(tail as f64 / (*n - *n / 2) as f64); + } + (tok as f64 / ms, mean_t) +} +fn cfg() -> AdaptiveConfig { + AdaptiveConfig::new(8, 7) +} + +#[test] +fn stationary_regimes_reach_the_best_fixed_width() { + for w in [CODE_CHEAP, CODE_COSTLY, PROSE_CHEAP, PROSE_COSTLY] { + let (bt, best) = best_fixed(&w); + let (rate, _) = adaptive_run(&[(w, 4000)], cfg()); + assert!(rate >= 0.97 * best, "adaptive {rate:.5} vs best fixed t={bt} {best:.5}"); + for t in [3usize, 4, 6] { + assert!(rate >= 0.99 * fixed_rate(&w, t), "adaptive {rate:.5} vs fixed {t}"); + } + } +} + +#[test] +fn it_widens_when_rows_are_cheap_and_narrows_when_they_are_not() { + let (_, cheap) = adaptive_run(&[(CODE_CHEAP, 1500)], cfg()); + let (_, costly) = adaptive_run(&[(CODE_COSTLY, 1500)], cfg()); + assert!(cheap[0] > costly[0] + 1.5, "cheap {:.2} costly {:.2}", cheap[0], costly[0]); + assert!(cheap[0] >= 6.0, "cheap windows are wide: {:.2}", cheap[0]); +} + +#[test] +fn it_follows_a_change_of_content_and_of_cost() { + let seq = [(CODE_CHEAP, 800), (PROSE_COSTLY, 800), (CODE_CHEAP, 800), (CODE_COSTLY, 800)]; + let (rate, tail) = adaptive_run(&seq, cfg()); + assert!(tail[0] > tail[1] + 2.0 && tail[2] > tail[1] + 2.0 && tail[2] > tail[3] + 1.5, "{tail:?}"); + // against the oracle that knows each segment's best fixed width + let (mut tok, mut ms) = (0.0, 0.0); + for (w, n) in seq { + let (_, r) = best_fixed(&w); + tok += r * n as f64 * 1.0; + ms += n as f64; + } + let _ = (tok, ms); + let oracle: f64 = seq.iter().map(|(w, n)| best_fixed(w).1 * *n as f64).sum::() / seq.iter().map(|(_, n)| *n as f64).sum::(); + assert!(rate >= 0.93 * oracle, "adaptive {rate:.5} vs per-segment oracle {oracle:.5}"); + // and it beats every single fixed width over the whole sequence + let whole = |t: usize| -> f64 { + let mut rng = Rng(3); + let (mut tk, mut m) = (0usize, 0.0); + for (w, n) in seq { + for _ in 0..n { + let (a, c, _) = play(&w, &mut rng, None, Some(t)); + tk += a; m += c; + } + } + tk as f64 / m + }; + for t in 1..=8 { + assert!(rate >= whole(t) * 0.995, "fixed {t}: {:.5} vs adaptive {rate:.5}", whole(t)); + } +} + +#[test] +fn reaction_to_a_switch_takes_tens_of_rounds_not_hundreds() { + let mut pol = AdaptivePolicy::new(cfg()); + let mut rng = Rng(5); + for _ in 0..600 { play(&CODE_COSTLY, &mut rng, Some(&mut pol), None); } + let mut ts = Vec::new(); + for _ in 0..120 { ts.push(play(&CODE_CHEAP, &mut rng, Some(&mut pol), None).2); } + let late: f64 = ts[60..].iter().sum::() as f64 / 60.0; + assert!(late >= 5.5, "width 60..120 rounds after the cost dropped: {late:.2}"); +} + +#[test] +fn exploration_costs_little_and_is_the_only_way_to_learn_unseen_widths() { + let mut off = cfg(); + off.explore_period = 0; + let (on_rate, _) = adaptive_run(&[(CODE_CHEAP, 3000)], cfg()); + let (off_rate, _) = adaptive_run(&[(CODE_CHEAP, 3000)], off); + assert!(on_rate >= 0.97 * off_rate, "on {on_rate:.5} off {off_rate:.5}"); + let mut pol = AdaptivePolicy::new(cfg()); + let mut rng = Rng(9); + let mut explored = 0; + for _ in 0..400 { + let before = pol.since_explore; + let _ = before; + let probs = [0.9f32; 7]; + let c = pol.choose(&Offer { mtp_probs: &probs, suffix_k: 0, suffix_match: 0, suffix_agrees: false }); + explored += c.explored as usize; + pol.observe(&c, 3.min(c.t - 1), 40.0 + 2.0 * c.t as f64 + rng.next(), 3); + } + assert!(explored >= 4 && explored <= 60, "explored {explored} of 400"); +} + +#[test] +fn a_long_repeated_suffix_opens_the_widest_window() { + let (rate, tail) = adaptive_run(&[(REPEAT, 600)], cfg()); + assert!(tail[0] >= 7.5, "mean width {:.2}", tail[0]); + assert!(rate > fixed_rate(&REPEAT, 4) * 1.3, "rate {rate:.5} vs fixed-4 {:.5}", fixed_rate(&REPEAT, 4)); +} + +#[test] +fn a_suffix_that_keeps_missing_is_dropped() { + let mut pol = AdaptivePolicy::new(cfg()); + let mut rng = Rng(21); + let probs = [0.9f32, 0.9, 0.9, 0.9, 0.8, 0.8, 0.7]; + let mut suffix_late = 0; + for i in 0..600 { + // a stale short match that never continues, MTP is right 85 % of the time + let c = pol.choose(&Offer { mtp_probs: &probs, suffix_k: 5, suffix_match: 4, suffix_agrees: false }); + let a = match c.origin { + Origin::Suffix => 0, + Origin::Mtp => { let mut a = 0; while a < c.t - 1 && rng.next() < 0.85 { a += 1; } a } + }; + if i >= 300 && c.origin == Origin::Suffix && c.t > 1 { suffix_late += 1; } + pol.observe(&c, a, 40.0 + 3.0 * c.t as f64, 3); + } + assert!(suffix_late <= 20, "{suffix_late} late suffix rounds"); +} + +#[test] +fn unmeasured_widths_are_interpolated_from_the_measured_ones() { + let mut pol = AdaptivePolicy::new(cfg()); + for i in 0..200 { + let t = [2usize, 4, 6][i % 3]; + let c = Choice { origin: Origin::Mtp, t, expected: 2.0, rate: 0.04, explored: false, probs: [0.8; MAX_T], matched: 0, agrees: false }; + pol.observe(&c, 1, 30.0 + 5.0 * (t - 1) as f64 + 0.45 * 3.0, 3); + } + for t in [1usize, 3, 5, 7, 8] { + let want = 30.0 + 5.0 * (t - 1) as f64; + let got = pol.window_ms(t); + assert!((got - want).abs() <= 0.1 * want, "t={t}: {got:.1} vs {want:.1}"); + } + assert!((pol.row_slope_ms() - 5.0).abs() < 1.0); +} + +#[test] +fn the_calibration_follows_the_drafter() { + // a drafter that is right half as often as it claims: its 0.9 drafts must be believed less than 0.9 + let mut pol = AdaptivePolicy::new(cfg()); + let mut rng = Rng(2); + for _ in 0..800 { + let c = Choice { origin: Origin::Mtp, t: 4, expected: 2.0, rate: 0.04, explored: false, probs: [0.92; MAX_T], matched: 0, agrees: false }; + let mut a = 0; + while a < 3 && rng.next() < 0.45 { a += 1; } + pol.observe(&c, a, 40.0, 3); + } + let r = pol.mtp_rate(1, 0.92); + assert!((r - 0.45).abs() < 0.1, "calibrated rate {r:.3}"); + assert!(pol.mtp_rate(1, 0.6) < 0.8); +} + +#[test] +fn the_draft_plan_stays_inside_its_bounds_and_follows_the_cost() { + let mut cheap = AdaptivePolicy::new(cfg()); + let mut costly = AdaptivePolicy::new(cfg()); + let mut rng = Rng(4); + for _ in 0..500 { + play(&CODE_CHEAP, &mut rng, Some(&mut cheap), None); + play(&CODE_COSTLY, &mut rng, Some(&mut costly), None); + } + let (a, b) = (cheap.draft_plan(), costly.draft_plan()); + for p in [a, b] { + assert!((1..=7).contains(&p.max_drafts) && (0.10..=0.90).contains(&p.min_p), "{p:?}"); + } + assert!(a.max_drafts > b.max_drafts, "{a:?} {b:?}"); + assert!(a.min_p <= b.min_p, "{a:?} {b:?}"); +} + +#[test] +fn replay_arm_options_set_the_named_constants_and_refuse_the_unknown() { + let mut c = cfg(); + assert!(c.set_option("step", "0.3") && c.set_option("explore", "0") && c.set_option("margin", "0.05") && c.set_option("min_p_lo", "0.2")); + assert!(c.set_option("alpha", "0.2") && c.set_option("decay", "0.99") && c.set_option("bias", "0.1")); + assert_eq!((c.draft_step_ms, c.explore_period, c.margin, c.min_p_lo), (0.3, 0, 0.05, 0.2)); + assert_eq!((c.cost_alpha, c.decay, c.bias_rate), (0.2, 0.99, 0.1)); + let before = c; + assert!(!c.set_option("nope", "1") && !c.set_option("step", "fast")); + assert_eq!(c, before); +} + +/// The earlier rule, kept as the reference: the floor is the lower edge of the first bucket whose calibrated acceptance clears the bar. +fn legacy_plan(pol: &AdaptivePolicy) -> DraftPlan { + let max_drafts = ((pol.hold_t.ceil() as usize).max(2)).min(pol.cfg.max_drafts.max(1)); + let rate = if pol.rate_ewma > 0.0 { pol.rate_ewma } else { 0.04 }; + let a_req = (rate * (pol.row_slope_ms() + pol.cfg.draft_step_ms) / pol.survive_ewma.max(0.2)).clamp(0.0, 0.99); + let mut min_p = pol.cfg.min_p_hi; + for b in 0..P_BUCKETS { + let r = sigmoid(logit(pol.mtp_bucket[b].rate(P_PRIOR[b], N0_BUCKET)) + pol.bias_mtp); + if r >= a_req { + min_p = P_EDGES[b]; + break; + } + } + DraftPlan { max_drafts, min_p: min_p.clamp(pol.cfg.min_p_lo, pol.cfg.min_p_hi) } +} + +#[test] +fn the_default_draft_plan_is_the_earlier_rule_and_the_new_options_only_lower_or_smooth_the_floor() { + let mut rng = Rng(8); + for world in [CODE_CHEAP, CODE_COSTLY, PROSE_CHEAP, PROSE_COSTLY] { + let mut pol = AdaptivePolicy::new(cfg()); + let (mut cheaper, mut smooth, mut measured) = (cfg(), cfg(), cfg()); + cheaper.row_q = 0.5; + smooth.smooth_floor = true; + measured.measured_rate = true; + let (mut pc, mut ps, mut pm) = (AdaptivePolicy::new(cheaper), AdaptivePolicy::new(smooth), AdaptivePolicy::new(measured)); + for i in 0..600 { + let mut r2 = Rng(i + 3); + play(&world, &mut rng, Some(&mut pol), None); + play(&world, &mut r2, Some(&mut pc), None); + let mut r3 = Rng(i + 3); + play(&world, &mut r3, Some(&mut ps), None); + let mut r4 = Rng(i + 3); + play(&world, &mut r4, Some(&mut pm), None); + assert_eq!(pol.draft_plan(), legacy_plan(&pol), "round {i}"); + let l = legacy_plan(&pc); + assert!(pc.draft_plan().min_p <= l.min_p + 1e-6 && pc.draft_plan().max_drafts == l.max_drafts, "row_q 0.5 raised the floor at round {i}"); + let sp = ps.draft_plan().min_p; + assert!((0.10..=0.90).contains(&sp), "smooth floor {sp} out of bounds at round {i}"); + let pl = pm.draft_plan(); + assert!((0.10..=0.90).contains(&pl.min_p) && (1..=7).contains(&pl.max_drafts), "{pl:?}"); + } + } +} + +#[test] +fn the_default_ceiling_is_the_new_one_and_the_legacy_switch_restores_the_old_policy_exactly() { + let new = AdaptiveConfig::new(8, 7); + assert_eq!(new.min_p_hi, FLOOR_CEILING); + let legacy = new.with_policy(Some("legacy")); + assert_eq!(legacy.min_p_hi, 0.90); + // everything but the ceiling is the earlier policy's, field by field + let earlier = AdaptiveConfig { + max_t: 8, max_drafts: 7, margin: 0.02, explore_period: 32, min_p_lo: 0.10, min_p_hi: 0.90, draft_step_ms: 0.45, + cost_alpha: 0.12, decay: 0.995, bias_rate: 0.06, row_q: 1.0, smooth_floor: false, measured_rate: false, + }; + assert_eq!(legacy, earlier); + assert_eq!(new.with_policy(Some("v1")), earlier); + assert_eq!(new.with_policy(None), new); + assert_eq!(new.with_policy(Some("current")), new); + // a request that names a ceiling keeps it in both policies; one that does not gets the policy's + for (cfg, want) in [(new, FLOOR_CEILING), (legacy, 0.90)] { + let mut pol = AdaptivePolicy::new(cfg); + pol.begin_request(0.0); + assert_eq!(pol.cfg.min_p_hi, want); + pol.begin_request(0.7); + assert_eq!(pol.cfg.min_p_hi, 0.7); + pol.begin_request(0.0); + assert_eq!(pol.cfg.min_p_hi, want); + } + // the chain floor the plan asks for never exceeds the ceiling of the policy + let mut pol = AdaptivePolicy::new(new); + pol.begin_request(0.0); + let mut rng = Rng(5); + for _ in 0..600 { + play(&CODE_COSTLY, &mut rng, Some(&mut pol), None); + assert!(pol.draft_plan().min_p <= FLOOR_CEILING + 1e-6); + } +} + +#[test] +fn the_smooth_floor_moves_continuously_with_the_bar() { + // synthetic, calibrated tables: the floor must not jump by a bucket for a small change of the bar + let mut pol = AdaptivePolicy::new({ let mut c = cfg(); c.smooth_floor = true; c }); + for b in 0..P_BUCKETS { + let centre = if b + 1 < P_BUCKETS { 0.5 * (P_EDGES[b] + P_EDGES[b + 1]) as f64 } else { 0.975 }; + for _ in 0..400 { + pol.mtp_bucket[b].add(false, 1.0); + } + pol.mtp_bucket[b].ok = 400.0 * centre; + } + let mut last: Option = None; + for step in 0..30 { + pol.rate_ewma = 0.10 + 0.002 * step as f64; + pol.survive_ewma = 0.5; + let p = pol.draft_plan().min_p; + if let Some(l) = last { + assert!((p - l).abs() < 0.08, "floor jumped from {l} to {p} at step {step}"); + assert!(p >= l - 1e-6, "floor fell while the bar rose"); + } + last = Some(p); + } +} + +#[test] +fn a_trace_is_reproducible() { + let run = || { + let mut pol = AdaptivePolicy::new(cfg()); + let mut rng = Rng(1); + (0..300).map(|_| play(&PROSE_CHEAP, &mut rng, Some(&mut pol), None).2).collect::>() + }; + assert_eq!(run(), run()); +} + +#[test] +fn stats_line_reports_the_histograms() { + let mut s = SpecStats::default(); + s.record(4, 3, false, false, 50.0); + s.record(6, 0, true, true, 60.0); + let l = s.line(); + assert!(l.contains("rounds=2 tokens=5 tok_per_round=2.500") && l.contains("lookup_rounds=1 explored=1"), "{l}"); + assert!(l.contains("accepted=3/8"), "{l}"); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs b/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs index 1202607e..e1ef53ee 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs @@ -479,816 +479,4 @@ impl OriginalSpecController { } #[cfg(test)] -mod tests { - use super::*; - use super::super::original_spec_draft::{DraftPick,OriginalFirstDraftEngine}; - - const VOCAB:u32=1000; - /// The fake target model: greedy continuation depends only on the last token. - fn next(x:i32)->i32 {(x*5+1)%997} - #[derive(Debug)] - struct Verif {inputs:Vec,outputs:Vec,position:i64} - #[derive(Default)] - struct Fake { - log:Vec,committed:Vec,fail:Option<(&'static str,Error)>, - bad_draft:Option,probs:Vec,drafted:usize, - bad_output:Option<(usize,i32)>,cancel_after_verify:bool, - /// the highest cell a window row or a draft touched (+1), and the chain lengths the controller asked for - max_end:i64,plans:Vec<(usize,f32)>, - /// how many times the named failure repeats (0 = once) - fail_n:u32, - /// every restore of the target fails (the checkpoint cannot be reached) - fail_restore_target:bool, - /// a window completed and nothing was committed for it yet: like the driver's `window_ready`, it refuses the next window until - /// the commit or `discard_window` takes it back (the live stack answered `InvalidDimension`) - open:bool, - } - impl Fake { - fn new(prompt_prefix:&[i32])->Self {Self{committed:prompt_prefix.to_vec(),probs:vec![0.9;8],..Default::default()}} - fn trip(&mut self,op:&'static str)->Result<()> { - self.log.push(op.to_string()); - if let Some((name,e))=self.fail {if name==op {if self.fail_n>1 {self.fail_n-=1;} else {self.fail=None;}return Err(e);}} - Ok(()) - } - fn count(&self,op:&str)->usize {self.log.iter().filter(|l|l.as_str()==op).count()} - fn pick(&mut self,j:usize,token:i32)->DraftPick { - self.drafted+=1; - let t=if self.bad_draft==Some(j) {token+1} else {token}; - DraftPick{token:t,probability:self.probs[j]} - } - } - impl OriginalDraftEngine for Fake { - fn replay_target_kv(&mut self,v:&Verif,p:i64,outputs:&[i32])->Result<()> { - self.trip("replay")?;assert_eq!(v.position,p);assert_eq!(v.outputs,outputs);Ok(()) - } - fn set_draft_plan(&mut self,max_drafts:usize,min_p:f32)->Result<()> {self.plans.push((max_drafts,min_p));Ok(())} - fn full_target_seed(&mut self,v:&Verif,row:usize,cell:i64,token:i32,_coupled:bool)->Result { - self.trip("seed")?;assert_eq!(cell,v.position+row as i64);assert_eq!(token,v.outputs[row]); - self.max_end=self.max_end.max(cell+1); - Ok(self.pick(0,next(token))) - } - fn full_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,_coupled:bool)->Result { - self.trip("chain")?;assert!(cell>0);self.max_end=self.max_end.max(cell+1);Ok(self.pick(j,next(previous_token))) - } - fn stage_coupled_history(&mut self,_:&[i32],_:i32)->Result<()> {self.trip("stage_history")} - fn drain_draft(&mut self)->Result<()> {self.trip("drain_draft")} - } - impl OriginalSpecEngine for Fake { - type Verified=Verif;type TargetCheckpoint=usize;type DraftCheckpoint=u8;type AdaptiveWork=u64; - fn validate_current(&self,consumed:&[i32],_input:i32,position:i64)->Result<()> { - if consumed!=self.committed.as_slice()||position!=self.committed.len() as i64 {return Err(Error::IdentityMismatch);}Ok(()) - } - fn checkpoint_target(&self)->Result {Ok(self.committed.len())} - fn checkpoint_draft(&self)->Result {Ok(7)} - fn restore_target(&mut self,c:&usize)->Result<()> {self.trip("restore_target")?;if self.fail_restore_target {return Err(Error::CudaExecution);}self.committed.truncate(*c);Ok(())} - fn restore_draft(&mut self,c:&u8)->Result<()> {assert_eq!(*c,7);self.trip("restore_draft")} - fn apply_pending(&mut self)->Result<()> {self.trip("apply_pending")} - fn verify(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { - self.trip("verify")?;assert_eq!(consumed,self.committed.as_slice()); - if self.open {return Err(Error::InvalidDimension);}self.open=true; - self.max_end=self.max_end.max(position+inputs.len() as i64); - let mut outputs:Vec=inputs.iter().map(|&x|next(x)).collect(); - if let Some((i,v))=self.bad_output {if iResult<()> { - self.log_len();if v.position!=position||v.inputs!=inputs {return Err(Error::IdentityMismatch);}Ok(()) - } - fn outputs<'a>(&self,v:&'a Verif)->&'a[i32] {&v.outputs} - fn commit_verified(&mut self,v:&mut Verif,rows:usize)->Result<()> { - self.trip("commit")?;self.committed.extend_from_slice(&v.inputs[..rows]);self.open=false;Ok(()) - } - fn drain_verified(&mut self,_v:Verif)->Result<()> {self.trip("drain_verified")} - fn discard_window(&mut self)->Result<()> {self.trip("discard_window")?;self.open=false;Ok(())} - fn begin_adaptation(&mut self,round:u64)->Result {self.trip("begin_adaptation")?;Ok(round)} - fn join_adaptation(&mut self,work:u64)->Result<()> {self.trip("join_adaptation")?;assert!(work>0);Ok(())} - fn wait_commit(&mut self)->Result<()> {self.trip("wait_commit")} - } - impl Fake {fn log_len(&self){}} - - fn config(max_t:usize,mtp:usize,suffix:usize)->SpecConfig {SpecConfig::new(max_t,mtp,4096,VOCAB,suffix,false).unwrap()} - fn prompt(n:usize)->Vec {let mut v=vec![11];for i in 1..n {v.push(next(v[i-1]));}v} - /// Whole request: verify+commit, emit, finish_round until the controller stops. - fn drive(c:&mut OriginalSpecController,e:&mut Fake,cancel:&mut dyn FnMut()->bool)->std::result::Result,SpecError> { - let mut out=Vec::new(); - while let Some(round)=c.verify_commit(e,&mut *cancel)? { - out.extend_from_slice(round.tokens()); - c.finish_round(e,round,||1.0,&mut *cancel)?; - } - Ok(out) - } - fn expected(prompt:&[i32],n:usize)->Vec { - let mut x=*prompt.last().unwrap();let mut v=Vec::new();for _ in 0..n {x=next(x);v.push(x);}v - } - fn begin(c:&mut OriginalSpecController,p:&[i32],max_new:usize,eos:&[i32]) {c.begin_request(p,max_new,0.0,eos).unwrap();} - - #[test] - fn config_rejects_out_of_range_and_mtp_zero_means_max_t() { - assert!(SpecConfig::new(0,0,4096,VOCAB,0,false).is_err()); - assert!(SpecConfig::new(9,0,4096,VOCAB,0,false).is_err()); - assert!(SpecConfig::new(4,0,0,VOCAB,0,false).is_err()); - assert!(SpecConfig::new(4,0,262145,VOCAB,0,false).is_err()); - assert!(SpecConfig::new(4,0,4096,0,0,false).is_err()); - assert_eq!(SpecConfig::new(4,0,4096,VOCAB,0,false).unwrap().mtp_t,4); - assert_eq!(SpecConfig::new(4,9,4096,VOCAB,0,false).unwrap().mtp_t,4); - assert_eq!(SpecConfig::new(4,2,4096,VOCAB,0,false).unwrap().mtp_t,2); - } - - #[test] - fn host_budget_is_checked_and_grows_with_the_request() { - let c=config(4,4,0); - let a=OriginalSpecController::planned_host_bytes(&c,10,10,1).unwrap(); - let b=OriginalSpecController::planned_host_bytes(&c,100,10,1).unwrap(); - assert!(b>a); - assert!(OriginalSpecController::planned_host_bytes(&c,0,10,1).is_err()); - assert!(OriginalSpecController::planned_host_bytes(&c,5000,10,1).is_err()); - assert!(OriginalSpecController::planned_host_bytes(&c,10,usize::MAX,1).is_err()); - } - - #[test] - fn begin_request_validates_tokens_and_rejects_a_live_request() { - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - assert_eq!(c.begin_request(&[],4,0.0,&[]),Err(Error::InvalidDimension)); - assert_eq!(c.begin_request(&[1,2000],4,0.0,&[]),Err(Error::InvalidToken)); - assert_eq!(c.begin_request(&[1,2],4,f32::NAN,&[]),Err(Error::InvalidDimension)); - assert_eq!(c.begin_request(&[1,2],4,0.0,&[VOCAB as i32]),Err(Error::InvalidToken)); - begin(&mut c,&[1,2,3],4,&[]); - // the final prompt token is the first verify input, not yet consumed - assert_eq!(c.consumed().unwrap(),&[1,2]); - assert_eq!(c.begin_request(&[1],4,0.0,&[]),Err(Error::IdentityMismatch)); - } - - #[test] - fn the_adaptive_window_emits_the_same_text_as_a_fixed_one_under_any_drafter() { - use super::super::original_spec_adaptive::AdaptiveConfig; - for bad in [None,Some(0),Some(1),Some(3)] { - for probs in [vec![0.95;8],vec![0.3;8],vec![0.9,0.8,0.6,0.5,0.4,0.9,0.9,0.9]] { - for suffix in [0usize,3] { - let p=prompt(6);let mut e=Fake::new(&p[..5]); - e.bad_draft=bad;e.probs=probs.clone(); - let mut c=OriginalSpecController::new(config(6,6,suffix).with_adaptive(Some(AdaptiveConfig::new(6,5)))).unwrap(); - begin(&mut c,&p,70,&[]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - c.finish_request(&mut e).unwrap(); - assert_eq!(out,expected(&p,70),"bad {bad:?} probs {probs:?} suffix {suffix}"); - let stats=c.take_stats(); - assert!(stats.rounds>=2&&stats.tokens as usize>=stats.rounds as usize,"{}",stats.line()); - assert!(c.adaptive().is_some_and(|a|a.rounds()>=stats.rounds-1)); - } - } - } - } - - #[test] - fn the_adaptive_window_learns_to_verify_wide_when_the_drafter_is_perfect() { - use super::super::original_spec_adaptive::AdaptiveConfig; - let p=prompt(6);let mut e=Fake::new(&p[..5]); - let mut c=OriginalSpecController::new(config(6,6,0).with_adaptive(Some(AdaptiveConfig::new(6,5)))).unwrap(); - begin(&mut c,&p,200,&[]); - let mut widths=Vec::new(); - while let Some(round)=c.verify_commit(&mut e,&mut||false).unwrap() { - widths.push(round.offered()+1); - // a wider window costs a little more in this fake clock - let ms=30.0+1.0*(round.offered() as f64); - c.finish_round(&mut e,round,move||ms,&mut||false).unwrap(); - } - c.finish_request(&mut e).unwrap(); - let tail=&widths[widths.len()-8..]; - assert!(tail.iter().all(|&t|t>=5),"{widths:?}"); - } - - #[test] - fn perfect_drafter_accepts_whole_windows_and_emits_greedy_text() { - let p=prompt(6);let mut e=Fake::new(&p[..5]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,12,&[]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - c.finish_request(&mut e).unwrap(); - assert_eq!(out,expected(&p,12)); - assert!(c.finished()); - // first window is T=1 (nothing drafted yet); later windows verify 3 drafts + the input - assert_eq!(e.committed.len(),5+1+4+4+4,"windows commit input rows: 1 then 4 each"); - assert_eq!(e.count("verify"),1+(12-1+3)/4); - assert_eq!(e.count("wait_commit"),1); - // each committed round took a target AND a draft checkpoint restore-free path - assert_eq!(e.count("restore_target")+e.count("restore_draft"),0); - assert_eq!(e.count("begin_adaptation"),e.count("join_adaptation")); - assert_eq!(e.count("drain_verified"),e.count("verify")); - assert_eq!(e.count("drain_draft"),e.count("seed")); - } - - #[test] - fn rejected_draft_commits_only_the_accepted_prefix() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - e.bad_draft=Some(1); // the second draft token is wrong - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,9,&[]); - let r1=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - assert_eq!((r1.offered(),r1.accepted(),r1.committed_input_rows()),(0,0,1)); - c.finish_round(&mut e,r1,||1.0,&mut||false).unwrap(); - let r2=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - // inputs: x, d0 (right), d1 (wrong), d2 -> one draft accepted - assert_eq!((r2.offered(),r2.accepted(),r2.committed_input_rows()),(3,1,2)); - assert_eq!(r2.tokens().len(),2); - assert!(!r2.used_lookup()); - c.finish_round(&mut e,r2,||1.0,&mut||false).unwrap(); - // after any prefix the session holds exactly the consumed tokens - assert_eq!(c.consumed().unwrap(),e.committed.as_slice()); - } - - #[test] - fn min_p_shrinks_the_window_and_the_draft_chain() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - e.probs=vec![0.9,0.1,0.9,0.9,0.9,0.9,0.9,0.9]; - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - c.begin_request(&p,20,0.5,&[]).unwrap(); - let r1=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - c.finish_round(&mut e,r1,||1.0,&mut||false).unwrap(); - // the chain stopped after draft 1 (0.1 < min_p): seed + one chain step only - assert_eq!(e.drafted,2); - let r2=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - // draft 0 passes min_p, draft 1 does not: T = 2 - assert_eq!(r2.offered(),1); - c.finish_round(&mut e,r2,||1.0,&mut||false).unwrap(); - } - - #[test] - fn eos_stops_emission_skips_drafting_and_keeps_the_commit() { - let p=prompt(5);let want=expected(&p,12); - let eos=want[5]; - let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,30,&[eos]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - assert_eq!(out,want[..6].to_vec()); - assert!(c.finished()); - let before=e.count("seed"); - // last round hit EOS: no draft was prepared for it - assert!(e.count("verify")>=2&&before(Fake,Vec,OriginalSpecController) { - use super::super::original_spec_adaptive::AdaptiveConfig; - let p=prompt(prompt_len);let mut e=Fake::new(&p[..prompt_len-1]); - let mut cfg=SpecConfig::new(max_t,mtp,64,VOCAB,suffix,false).unwrap();cfg.max_context=max_context; - if adaptive {cfg=cfg.with_adaptive(Some(AdaptiveConfig::new(max_t,max_t-1)));} - let mut c=OriginalSpecController::new(cfg).unwrap(); - c.begin_request(&p,max_new,min_p,&[]).unwrap(); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - c.finish_request(&mut e).unwrap(); - (e,out,c) - } - - #[test] - fn a_window_near_the_context_end_takes_only_the_rows_that_fit() { - let p=prompt(4);let mut e=Fake::new(&p[..3]); - let mut cfg=SpecConfig::new(4,4,6,VOCAB,0,false).unwrap();cfg.max_context=6; - let mut c=OriginalSpecController::new(cfg).unwrap(); - begin(&mut c,&p,100,&[]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - // position 3: T=1; position 4: T=4 does not fit (4 + 4 > 6), so the window shrinks to the 2 rows left, not to "length" - assert!(c.finished()); - assert_eq!(e.committed.len(),6,"every cell of the context is used"); - assert_eq!(out,expected(&p,3),"the tokens of rows 3, 4 and 5 are all emitted"); - assert!(e.max_end<=6,"no row or draft past the context: {}",e.max_end); - } - - #[test] - fn spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end() { - // every distance k of the first window from the end, every window shape: fixed, min_p, suffix lookup, adaptive - for max_t in [2usize,4,6,8] { - for k in 1..=(max_t as i64+3) { - for (suffix,min_p,adaptive) in [(0usize,0.0f32,false),(3,0.0,false),(0,0.5,false),(3,0.5,true),(0,0.0,true)] { - let prompt_len=10usize; - let max_context=prompt_len as i64-1+k; - let (e,out,c)=run_to_the_end(max_context,prompt_len,1000,max_t,max_t,suffix,min_p,adaptive); - let tag=format!("max_t {max_t} k {k} suffix {suffix} min_p {min_p} adaptive {adaptive}"); - assert!(e.max_end<=max_context,"{tag}: touched cell {} of {max_context}",e.max_end); - // the request ended because the context is full, with the greedy text of every row that fits - assert_eq!(e.committed.len() as i64,max_context,"{tag}"); - assert_eq!(out,expected(&prompt(prompt_len),k as usize),"{tag}"); - assert!(c.finished()&&!c.is_failed(),"{tag}"); - assert_eq!(e.count("begin_adaptation"),e.count("join_adaptation"),"{tag}"); - assert_eq!(e.count("drain_verified"),e.count("verify"),"{tag}"); - } - } - } - } - - #[test] - fn the_chain_is_shortened_near_the_end_and_restored_after_it() { - // fixed window, perfect drafter: 4-wide windows, 3 drafts. The last round before the end drafts only the cells left. - let (e,_,_)=run_to_the_end(30,10,1000,4,4,0,0.0,false); - assert!(e.max_end<=30); - // plans: a clamped chain is asked for explicitly, never longer than the cells left - assert!(e.plans.iter().all(|&(n,_)|(1..=3).contains(&n)),"{:?}",e.plans); - assert!(e.plans.iter().any(|&(n,_)|n<3),"the last rounds draft fewer than the full chain: {:?}",e.plans); - // a request that never gets near the end never sets a plan (the fixed chain needs none) - let (e,_,_)=run_to_the_end(4096,10,40,4,4,0,0.0,false); - assert!(e.plans.is_empty(),"{:?}",e.plans); - } - - #[test] - fn a_chain_clamped_by_one_request_is_restored_for_the_next() { - let p=prompt(10); - let mut e=Fake::new(&p[..9]); - let mut cfg=SpecConfig::new(4,4,64,VOCAB,0,false).unwrap();cfg.max_context=20; - let mut c=OriginalSpecController::new(cfg).unwrap(); - c.begin_request(&p,1000,0.0,&[]).unwrap(); - drive(&mut c,&mut e,&mut||false).unwrap();c.finish_request(&mut e).unwrap(); - assert!(e.plans.last().is_some_and(|&(n,_)|n<3),"the request ended on a clamped chain: {:?}",e.plans); - // a short request on the same controller: its first drafting round puts the full chain back - let mut e2=Fake::new(&p[..9]); - c.begin_request(&p,3,0.0,&[]).unwrap(); - drive(&mut c,&mut e2,&mut||false).unwrap(); - assert_eq!(e2.plans.first().map(|x|x.0),Some(3),"{:?}",e2.plans); - } - - /// Upstream 41cf05a0 `aece46db`: position 0 was the CLI's "speculation not started" value, so a 1-token prompt on a native pack - /// (its only token is the first verify input, at position 0) never speculated. Here position 0 is a real start. - #[test] - fn a_one_token_prompt_speculates_from_position_zero() { - for (suffix,adaptive) in [(0usize,false),(3,false),(0,true)] { - use super::super::original_spec_adaptive::AdaptiveConfig; - let p=prompt(1); - let mut e=Fake::new(&[]); - let mut cfg=config(4,4,suffix); - if adaptive {cfg=cfg.with_adaptive(Some(AdaptiveConfig::new(4,3)));} - let mut c=OriginalSpecController::new(cfg).unwrap(); - begin(&mut c,&p,40,&[]); - assert_eq!(c.consumed().unwrap().len(),0); - let mut widths=Vec::new(); - while let Some(round)=c.verify_commit(&mut e,&mut||false).unwrap() { - widths.push(round.offered()+1); - c.finish_round(&mut e,round,||1.0,&mut||false).unwrap(); - } - c.finish_request(&mut e).unwrap(); - assert_eq!(widths[0],1,"the first window has nothing drafted yet"); - assert!(widths[1..].iter().any(|&t|t>1),"suffix {suffix} adaptive {adaptive}: no window ever speculated: {widths:?}"); - assert!(e.count("verify")<40,"suffix {suffix} adaptive {adaptive}: one window per token: {widths:?}"); - assert_eq!(e.committed.len(),widths.iter().sum::(),"every round committed its accepted rows only: windows {widths:?}"); - } - let p=prompt(1);let mut e=Fake::new(&[]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,40,&[]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - assert_eq!(out,expected(&p,40)); - } - - /// Upstream 41cf05a0 `f332a855` / `894f133b` (STRATA_NAN_GUARD, #879): a window whose output is not finite is not emitted; upstream ends the - /// request and its gateway repeats it. Here the window itself is run again from its round's checkpoint. - fn guarded(guard:NanGuard,max_new:usize)->(Fake,OriginalSpecController,Vec) { - let p=prompt(6);let e=Fake::new(&p[..5]); - let c=OriginalSpecController::new(config(4,4,0).with_nan_guard(guard)).unwrap(); - let _=max_new; - (e,c,p) - } - - #[test] - fn the_guard_reads_its_three_switches_and_refuses_a_malformed_one() { - assert_eq!(NanGuard::parse(None,None,None),Ok(if NanGuard::DEFAULT_ON {NanGuard::with_retries(NanGuard::DEFAULT_RETRIES)} else {NanGuard::off()})); - assert_eq!(NanGuard::parse(Some("on"),None,None),Ok(NanGuard::with_retries(2))); - assert_eq!(NanGuard::parse(Some(" ON "),Some("5"),None),Ok(NanGuard::with_retries(5))); - assert_eq!(NanGuard::parse(Some("off"),Some("5"),None),Ok(NanGuard::off())); - assert_eq!(NanGuard::parse(Some("1"),Some("0"),None),Ok(NanGuard::with_retries(0))); - assert_eq!(NanGuard::parse(Some("on"),None,Some("3")),Ok(NanGuard::with_retries(2).with_injection(3,1))); - assert_eq!(NanGuard::parse(Some("on"),None,Some("4x2")),Ok(NanGuard::with_retries(2).with_injection(4,2))); - for bad in [(Some("maybe"),None,None),(Some("on"),Some("9"),None),(Some("on"),Some("x"),None),(Some("on"),None,Some("0")),(Some("on"),None,Some("2x0")),(Some("on"),None,Some("a"))] { - assert!(NanGuard::parse(bad.0,bad.1,bad.2).is_err(),"{bad:?}"); - } - // an injection under a guard that is off does nothing: the guard has to be on to heal what it injects - let off=NanGuard::parse(Some("off"),None,Some("2")).unwrap(); - assert!(!off.injects(2,0)); - assert!(NanGuard::with_retries(2).with_injection(2,1).injects(2,0)); - assert!(!NanGuard::with_retries(2).with_injection(2,1).injects(2,1),"only the first attempt"); - assert!(!NanGuard::with_retries(2).with_injection(2,1).injects(3,0)); - } - - #[test] - fn a_non_finite_window_is_run_again_from_its_checkpoint_and_the_request_completes() { - let want=expected(&prompt(6),20); - for retries in [1u32,2,5] { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(retries),20); - e.fail=Some(("verify",Error::NonFinite)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - c.finish_request(&mut e).unwrap(); - assert_eq!(out,want,"retries {retries}: the text is the greedy one, nothing lost or repeated"); - assert!(!c.is_failed()&&c.finished()); - // one restore of each checkpoint, and the window was run twice: one more verify than a clean run - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - let (mut clean,mut cc,p2)=guarded(NanGuard::with_retries(retries),20); - cc.begin_request(&p2,20,0.0,&[]).unwrap(); - drive(&mut cc,&mut clean,&mut||false).unwrap(); - assert_eq!(e.count("verify"),clean.count("verify")+1); - assert_eq!(c.take_stats().healed,1); - // what the session committed is exactly what the clean run committed - assert_eq!(e.committed,clean.committed); - } - } - - #[test] - fn the_guard_costs_nothing_when_nothing_is_wrong() { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2),30); - c.begin_request(&p,30,0.0,&[]).unwrap(); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - assert_eq!(out,expected(&prompt(6),30)); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(0,0)); - assert_eq!(c.take_stats().healed,0); - // and the same request with the guard off runs the identical sequence of engine calls - let mut off=Fake::new(&prompt(6)[..5]); - let mut co=OriginalSpecController::new(config(4,4,0)).unwrap(); - co.begin_request(&prompt(6),30,0.0,&[]).unwrap(); - drive(&mut co,&mut off,&mut||false).unwrap(); - assert_eq!(e.log,off.log); - } - - #[test] - fn a_window_that_stays_non_finite_fails_the_request_after_the_retries() { - for retries in [1u32,2] { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(retries),20); - e.fail=Some(("verify",Error::NonFinite));e.fail_n=retries+1; - c.begin_request(&p,20,0.0,&[]).unwrap(); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::NonFinite)); - assert!(c.finished()&&!c.is_failed(),"the request ends, the controller stays usable (the checkpoints were restored)"); - // retries restores for the retries, one more for the abort that gives up - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(retries as usize+1,retries as usize+1)); - assert_eq!(e.count("verify"),retries as usize+1); - } - } - - #[test] - fn only_a_non_finite_failure_is_retried_and_a_guard_that_is_off_retries_nothing() { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(3),20); - e.fail=Some(("verify",Error::CudaExecution)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::CudaExecution))); - assert_eq!((e.count("verify"),e.count("restore_target")),(1,1),"not retried"); - let (mut e,mut c,p)=guarded(NanGuard::off(),20); - e.fail=Some(("verify",Error::NonFinite)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::NonFinite))); - assert_eq!((e.count("verify"),e.count("restore_target")),(1,1),"guard off: the first failure aborts as before"); - // a failed apply_pending of the adaptive tier is not a window either - let (mut e,mut c,p)=guarded(NanGuard::with_retries(3),20); - e.fail=Some(("apply_pending",Error::CudaExecution)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert!(c.verify_commit(&mut e,&mut||false).is_err()); - assert_eq!(e.count("verify"),0); - } - - #[test] - fn a_checkpoint_that_cannot_be_restored_ends_the_healing_with_the_original_error() { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(3),20); - e.fail=Some(("verify",Error::NonFinite)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - // the restore the guard asks for fails: the state is unknown - e.fail_restore_target=true; - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::NonFinite),"the primary error is kept"); - assert!(c.is_failed()&&c.finished(),"the controller is unusable: its state is unknown"); - assert_eq!(e.count("verify"),1); - } - - #[test] - fn the_injection_exercises_the_same_path_on_a_good_window_and_counts_windows_across_requests() { - // the 3rd checked window fails once: healed, text unchanged - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(3,1),20); - c.begin_request(&p,20,0.0,&[]).unwrap(); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - assert_eq!(out,expected(&prompt(6),20)); - assert_eq!(c.take_stats().healed,1); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - assert_eq!(e.count("discard_window"),1,"the injected window was taken back once"); - // the window that was injected was a real, good one: it was drained before the retry - assert_eq!(e.count("drain_verified"),e.count("verify")); - // two failures in a row on one window, two retries: healed after two restarts - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(2,2),20); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert_eq!(drive(&mut c,&mut e,&mut||false).unwrap(),expected(&prompt(6),20)); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(2,2)); - // three failures, two retries: the request fails and says why - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(2,3),20); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert_eq!(drive(&mut c,&mut e,&mut||false).err(),Some(SpecError::Forward(Error::NonFinite))); - // windows are counted across the requests of one controller - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(4,1),6); - c.begin_request(&p,6,0.0,&[]).unwrap(); - drive(&mut c,&mut e,&mut||false).unwrap(); - c.finish_request(&mut e).unwrap(); - let first_request_windows=e.count("verify"); - assert!(first_request_windows<4,"{first_request_windows}"); - let mut e2=Fake::new(&p[..5]); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert_eq!(drive(&mut c,&mut e2,&mut||false).unwrap(),expected(&p,20)); - assert_eq!(e2.count("restore_target"),1,"the injected window was one of the second request's"); - } - - #[test] - fn the_retry_takes_the_refused_window_back_before_it_stages_the_rows_again() { - // the live stack's first failure: a completed window that nothing was committed for refuses the next one (InvalidDimension) - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(1,1),20); - c.begin_request(&p,20,0.0,&[]).unwrap(); - let _first=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - assert!(!e.open,"the retried window was committed"); - assert_eq!(c.take_stats().healed,1); - // drain, restore both checkpoints, take the window back, then the same rows again - let at=e.log.iter().position(|l|l=="drain_verified").unwrap(); - let order:Vec<&str>=e.log[at..at+6].iter().map(String::as_str).collect(); - assert_eq!(order,["drain_verified","restore_target","restore_draft","discard_window","apply_pending","verify"]); - assert_eq!(e.count("discard_window"),1); - // a clean request never takes anything back - let (mut clean,mut cc,p2)=guarded(NanGuard::with_retries(2),20); - cc.begin_request(&p2,20,0.0,&[]).unwrap(); - drive(&mut cc,&mut clean,&mut||false).unwrap(); - assert_eq!(clean.count("discard_window"),0); - } - - #[test] - fn a_window_that_cannot_be_taken_back_ends_the_healing_with_the_original_error() { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(3).with_injection(1,1),20); - e.fail=Some(("discard_window",Error::CudaExecution)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::NonFinite),"the primary error is kept"); - assert!(c.is_failed()&&c.finished(),"the controller is unusable: the verifier still holds the window"); - assert_eq!((e.count("verify"),e.count("discard_window")),(1,1),"no second attempt on a verifier that still holds the window"); - } - - #[test] - fn verify_failure_restores_both_checkpoints_and_poisons_nothing_else() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - e.fail=Some(("verify",Error::CudaExecution)); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - assert!(c.finished()&&!c.is_failed()); - assert_eq!(e.committed.len(),4); - } - - #[test] - fn a_failed_window_preparation_also_restores_both_checkpoints() { - let p=prompt(5); - let mut e=Fake::new(&p[..4]); - e.fail=Some(("apply_pending",Error::CudaExecution)); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); - assert_eq!(e.count("verify"),0); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - assert!(!c.is_failed()); - } - - #[test] - fn restore_failure_makes_the_controller_unusable_but_keeps_the_primary_error() { - let p=prompt(5); - let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let target=e.checkpoint_target().unwrap();let draft=e.checkpoint_draft().unwrap(); - // the target restore fails: the draft restore must still be attempted - e.fail=Some(("restore_target",Error::CudaExecution)); - let primary=c.abort(&mut e,&target,&draft,SpecError::Forward(Error::InputRead)); - assert_eq!(primary,SpecError::Forward(Error::InputRead)); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - assert!(c.is_failed()); - assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::IdentityMismatch))); - // and a failing draft restore is equally fatal - let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - e.fail=Some(("restore_draft",Error::CudaExecution)); - let _=c.abort(&mut e,&target,&draft,SpecError::Cancelled); - assert!(c.is_failed()); - } - - #[test] - fn commit_failure_joins_adaptation_drains_and_restores() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - e.fail=Some(("commit",Error::CudaExecution)); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); - assert_eq!((e.count("begin_adaptation"),e.count("join_adaptation")),(1,1)); - assert_eq!(e.count("drain_verified"),1); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - assert_eq!(e.committed.len(),4); - } - - #[test] - fn begin_adaptation_failure_drains_and_restores_without_committing() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - e.fail=Some(("begin_adaptation",Error::CudaExecution)); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - assert!(c.verify_commit(&mut e,&mut||false).is_err()); - assert_eq!(e.count("commit"),0); - assert_eq!(e.count("join_adaptation"),0); - assert_eq!(e.count("drain_verified"),1); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - } - - #[test] - fn invalid_verified_output_is_refused_before_anything_commits() { - let p=prompt(5); - let mut e=Fake::new(&p[..4]);e.bad_output=Some((0,VOCAB as i32+5)); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::InvalidToken)); - assert_eq!((e.count("commit"),e.count("drain_verified"),e.count("restore_target")),(0,1,1)); - } - - #[test] - fn cancellation_before_verify_touches_nothing_and_after_verify_rolls_back() { - let p=prompt(5); - let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - assert_eq!(c.verify_commit(&mut e,&mut||true).err(),Some(SpecError::Cancelled)); - assert_eq!(e.count("verify"),0); - assert_eq!(e.count("restore_target"),0); - // cancelled after the window ran: drained, both restored, no commit - let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let mut calls=0; - let r=c.verify_commit(&mut e,&mut||{calls+=1;calls==2}); - assert_eq!(r.err(),Some(SpecError::Cancelled)); - assert_eq!((e.count("verify"),e.count("commit"),e.count("drain_verified")),(1,0,1)); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - assert_eq!(e.committed.len(),4); - } - - #[test] - fn draft_failure_after_commit_keeps_the_commit_joins_and_fails_the_request() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let round=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - let tokens=round.tokens().to_vec(); - e.fail=Some(("seed",Error::CudaExecution)); - let err=c.finish_round(&mut e,round,||1.0,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); - // the emitted prefix is real; pending adaptation was joined and the receipt drained - assert_eq!(tokens.len(),1); - assert_eq!(e.committed.len(),5); - assert_eq!((e.count("join_adaptation"),e.count("drain_verified"),e.count("drain_draft")),(1,1,1)); - assert!(c.is_failed()&&c.finished()); - } - - #[test] - fn adaptation_join_failure_is_reported_even_after_a_good_draft() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let round=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - e.fail=Some(("join_adaptation",Error::CudaExecution)); - assert_eq!(c.finish_round(&mut e,round,||1.0,&mut||false).err(),Some(SpecError::Forward(Error::CudaExecution))); - assert_eq!(e.count("drain_verified"),1); - assert!(c.is_failed()); - } - - #[test] - fn finish_round_refuses_a_receipt_from_another_controller() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - let mut a=OriginalSpecController::new(config(4,4,0)).unwrap(); - let mut b=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut a,&p,8,&[]);begin(&mut b,&p,8,&[]); - let round=a.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - assert_eq!(b.finish_round(&mut e,round,||1.0,&mut||false).err(),Some(SpecError::Forward(Error::IdentityMismatch))); - // the receipt was still drained and joined - assert_eq!((e.count("join_adaptation"),e.count("drain_verified")),(1,1)); - } - - #[test] - fn a_request_cannot_restart_while_a_draft_is_pending() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let round=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::IdentityMismatch))); - assert_eq!(c.finish_request(&mut e),Err(Error::IdentityMismatch)); - c.finish_round(&mut e,round,||1.0,&mut||false).unwrap(); - c.finish_request(&mut e).unwrap(); - } - - #[test] - fn policy_and_adaptive_cadence_survive_across_requests() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,6,&[]); - drive(&mut c,&mut e,&mut||false).unwrap(); - c.finish_request(&mut e).unwrap(); - let rounds_first=e.count("begin_adaptation"); - let mut e2=Fake::new(&p[..4]); - begin(&mut c,&p,6,&[]); - drive(&mut c,&mut e2,&mut||false).unwrap(); - // the adaptive round numbers keep counting (Original `rounds`), the engine sees them - assert!(rounds_first>0&&e2.count("begin_adaptation")>0); - // the first window of a new request is again T=1: one input row committed - assert_eq!(e2.committed.len(),4+1+4+4,"windows of 1, 4, 4 input rows for max_new=6"); - } - - #[test] - fn suffix_lookup_takes_a_longer_window_when_it_agrees_with_the_first_draft() { - // the fake model's orbit is a cycle: the suffix index proposes the continuation the MTP also drafts - let mut x=11;let mut seq=vec![x]; - let mut seen=std::collections::HashMap::new(); - let cycle=loop {if let Some(&at)=seen.get(&x) {break seq[at..seq.len()-1].to_vec();}seen.insert(x,seq.len()-1);x=next(x);seq.push(x);}; - assert!(cycle.len()>=3); - let mut seq=Vec::new();while seq.len()<1200 {seq.extend_from_slice(&cycle);} - let prompt=seq; - let mut e=Fake::new(&prompt[..prompt.len()-1]); - let mut c=OriginalSpecController::new(config(8,2,3)).unwrap(); - begin(&mut c,&prompt,40,&[]); - let mut windows=Vec::new(); - while let Some(round)=c.verify_commit(&mut e,&mut||false).unwrap() { - windows.push((round.offered()+1,round.used_lookup())); - c.finish_round(&mut e,round,||1.0,&mut||false).unwrap(); - } - // first window T=1; a lookup then widens the window beyond the MTP's T=2 - assert_eq!(windows[0],(1,false)); - assert!(windows.iter().skip(1).any(|&(t,lookup)|lookup&&t>2),"{windows:?}"); - } - - #[test] - fn output_is_the_greedy_text_for_every_window_shape_noise_and_stop_rule() { - // Output invariance: whatever the window sizes, the draft noise, the confidence floor, the suffix - // lookup, EOS and max_new do, the emitted tokens are the greedy continuation (cut at the first EOS or - // max_new) and the session ends up holding exactly the consumed tokens. - let p=prompt(40); - let full=expected(&p,64); - let noisy=[None,Some(0),Some(1),Some(2),Some(5)]; - let probs:[[f32;8];3]=[[0.9;8],[0.9,0.1,0.9,0.9,0.9,0.9,0.9,0.9],[0.02;8]]; - for max_t in 1..=8usize { for mtp in [0usize,1,2,max_t,9] { for suffix in [0usize,3] { - for bad in noisy { for pr in probs { for min_p in [0.0f32,0.5] { for max_new in [0usize,1,3,17] { - for eos_at in [None,Some(2usize),Some(9)] { - let eos:Vec=eos_at.map(|i|full[i]).into_iter().collect(); - let mut e=Fake::new(&p[..p.len()-1]);e.bad_draft=bad;e.probs=pr.to_vec(); - let mut c=OriginalSpecController::new(SpecConfig::new(max_t,mtp,4096,VOCAB,suffix,false).unwrap()).unwrap(); - c.begin_request(&p,max_new,min_p,&eos).unwrap(); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - c.finish_request(&mut e).unwrap(); - let mut want=full[..max_new].to_vec(); - if let Some(i)=eos_at {if i,fail:bool} - impl OriginalFirstDraftEngine for First { - fn replay_first_seed_kv(&mut self,_:&u8,t:usize,cell:i64,token:i32)->Result<()> { - self.log.push("replay");assert_eq!((t,cell,token),(4,9,5));Ok(()) - } - fn full_first_seed(&mut self,_:&u8,_cell:i64,token:i32,_c:bool)->Result { - self.log.push("seed");if self.fail {return Err(Error::CudaExecution);}Ok(DraftPick{token:next(token),probability:0.9}) - } - fn first_chain_step(&mut self,_cell:i64,_j:usize,prev:i32,_c:bool)->Result { - self.log.push("chain");Ok(DraftPick{token:next(prev),probability:0.9}) - } - fn drain_first_seed(&mut self)->Result<()> {self.log.push("drain");Ok(())} - } - let prep=DraftPreparation::new(4,3,VOCAB).unwrap(); - let mut f=First{log:Vec::new(),fail:false}; - let b=prep.from_committed_seed(&mut f,&0u8,9,5,0.0,false).unwrap(); - assert_eq!(b.produced(),3); - assert_eq!(f.log,["replay","seed","chain","chain","drain"]); - let mut f=First{log:Vec::new(),fail:true}; - assert_eq!(prep.from_committed_seed(&mut f,&0u8,9,5,0.0,false).err(),Some(Error::CudaExecution)); - assert_eq!(f.log.last(),Some(&"drain")); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/original_spec_controller/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_spec_controller/tests.rs new file mode 100644 index 00000000..fc377f6c --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_spec_controller/tests.rs @@ -0,0 +1,813 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use super::super::original_spec_draft::{DraftPick,OriginalFirstDraftEngine}; + +const VOCAB:u32=1000; +/// The fake target model: greedy continuation depends only on the last token. +fn next(x:i32)->i32 {(x*5+1)%997} +#[derive(Debug)] +struct Verif {inputs:Vec,outputs:Vec,position:i64} +#[derive(Default)] +struct Fake { + log:Vec,committed:Vec,fail:Option<(&'static str,Error)>, + bad_draft:Option,probs:Vec,drafted:usize, + bad_output:Option<(usize,i32)>,cancel_after_verify:bool, + /// the highest cell a window row or a draft touched (+1), and the chain lengths the controller asked for + max_end:i64,plans:Vec<(usize,f32)>, + /// how many times the named failure repeats (0 = once) + fail_n:u32, + /// every restore of the target fails (the checkpoint cannot be reached) + fail_restore_target:bool, + /// a window completed and nothing was committed for it yet: like the driver's `window_ready`, it refuses the next window until + /// the commit or `discard_window` takes it back (the live stack answered `InvalidDimension`) + open:bool, +} +impl Fake { + fn new(prompt_prefix:&[i32])->Self {Self{committed:prompt_prefix.to_vec(),probs:vec![0.9;8],..Default::default()}} + fn trip(&mut self,op:&'static str)->Result<()> { + self.log.push(op.to_string()); + if let Some((name,e))=self.fail {if name==op {if self.fail_n>1 {self.fail_n-=1;} else {self.fail=None;}return Err(e);}} + Ok(()) + } + fn count(&self,op:&str)->usize {self.log.iter().filter(|l|l.as_str()==op).count()} + fn pick(&mut self,j:usize,token:i32)->DraftPick { + self.drafted+=1; + let t=if self.bad_draft==Some(j) {token+1} else {token}; + DraftPick{token:t,probability:self.probs[j]} + } +} +impl OriginalDraftEngine for Fake { + fn replay_target_kv(&mut self,v:&Verif,p:i64,outputs:&[i32])->Result<()> { + self.trip("replay")?;assert_eq!(v.position,p);assert_eq!(v.outputs,outputs);Ok(()) + } + fn set_draft_plan(&mut self,max_drafts:usize,min_p:f32)->Result<()> {self.plans.push((max_drafts,min_p));Ok(())} + fn full_target_seed(&mut self,v:&Verif,row:usize,cell:i64,token:i32,_coupled:bool)->Result { + self.trip("seed")?;assert_eq!(cell,v.position+row as i64);assert_eq!(token,v.outputs[row]); + self.max_end=self.max_end.max(cell+1); + Ok(self.pick(0,next(token))) + } + fn full_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,_coupled:bool)->Result { + self.trip("chain")?;assert!(cell>0);self.max_end=self.max_end.max(cell+1);Ok(self.pick(j,next(previous_token))) + } + fn stage_coupled_history(&mut self,_:&[i32],_:i32)->Result<()> {self.trip("stage_history")} + fn drain_draft(&mut self)->Result<()> {self.trip("drain_draft")} +} +impl OriginalSpecEngine for Fake { + type Verified=Verif;type TargetCheckpoint=usize;type DraftCheckpoint=u8;type AdaptiveWork=u64; + fn validate_current(&self,consumed:&[i32],_input:i32,position:i64)->Result<()> { + if consumed!=self.committed.as_slice()||position!=self.committed.len() as i64 {return Err(Error::IdentityMismatch);}Ok(()) + } + fn checkpoint_target(&self)->Result {Ok(self.committed.len())} + fn checkpoint_draft(&self)->Result {Ok(7)} + fn restore_target(&mut self,c:&usize)->Result<()> {self.trip("restore_target")?;if self.fail_restore_target {return Err(Error::CudaExecution);}self.committed.truncate(*c);Ok(())} + fn restore_draft(&mut self,c:&u8)->Result<()> {assert_eq!(*c,7);self.trip("restore_draft")} + fn apply_pending(&mut self)->Result<()> {self.trip("apply_pending")} + fn verify(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { + self.trip("verify")?;assert_eq!(consumed,self.committed.as_slice()); + if self.open {return Err(Error::InvalidDimension);}self.open=true; + self.max_end=self.max_end.max(position+inputs.len() as i64); + let mut outputs:Vec=inputs.iter().map(|&x|next(x)).collect(); + if let Some((i,v))=self.bad_output {if iResult<()> { + self.log_len();if v.position!=position||v.inputs!=inputs {return Err(Error::IdentityMismatch);}Ok(()) + } + fn outputs<'a>(&self,v:&'a Verif)->&'a[i32] {&v.outputs} + fn commit_verified(&mut self,v:&mut Verif,rows:usize)->Result<()> { + self.trip("commit")?;self.committed.extend_from_slice(&v.inputs[..rows]);self.open=false;Ok(()) + } + fn drain_verified(&mut self,_v:Verif)->Result<()> {self.trip("drain_verified")} + fn discard_window(&mut self)->Result<()> {self.trip("discard_window")?;self.open=false;Ok(())} + fn begin_adaptation(&mut self,round:u64)->Result {self.trip("begin_adaptation")?;Ok(round)} + fn join_adaptation(&mut self,work:u64)->Result<()> {self.trip("join_adaptation")?;assert!(work>0);Ok(())} + fn wait_commit(&mut self)->Result<()> {self.trip("wait_commit")} +} +impl Fake {fn log_len(&self){}} + +fn config(max_t:usize,mtp:usize,suffix:usize)->SpecConfig {SpecConfig::new(max_t,mtp,4096,VOCAB,suffix,false).unwrap()} +fn prompt(n:usize)->Vec {let mut v=vec![11];for i in 1..n {v.push(next(v[i-1]));}v} +/// Whole request: verify+commit, emit, finish_round until the controller stops. +fn drive(c:&mut OriginalSpecController,e:&mut Fake,cancel:&mut dyn FnMut()->bool)->std::result::Result,SpecError> { + let mut out=Vec::new(); + while let Some(round)=c.verify_commit(e,&mut *cancel)? { + out.extend_from_slice(round.tokens()); + c.finish_round(e,round,||1.0,&mut *cancel)?; + } + Ok(out) +} +fn expected(prompt:&[i32],n:usize)->Vec { + let mut x=*prompt.last().unwrap();let mut v=Vec::new();for _ in 0..n {x=next(x);v.push(x);}v +} +fn begin(c:&mut OriginalSpecController,p:&[i32],max_new:usize,eos:&[i32]) {c.begin_request(p,max_new,0.0,eos).unwrap();} + +#[test] +fn config_rejects_out_of_range_and_mtp_zero_means_max_t() { + assert!(SpecConfig::new(0,0,4096,VOCAB,0,false).is_err()); + assert!(SpecConfig::new(9,0,4096,VOCAB,0,false).is_err()); + assert!(SpecConfig::new(4,0,0,VOCAB,0,false).is_err()); + assert!(SpecConfig::new(4,0,262145,VOCAB,0,false).is_err()); + assert!(SpecConfig::new(4,0,4096,0,0,false).is_err()); + assert_eq!(SpecConfig::new(4,0,4096,VOCAB,0,false).unwrap().mtp_t,4); + assert_eq!(SpecConfig::new(4,9,4096,VOCAB,0,false).unwrap().mtp_t,4); + assert_eq!(SpecConfig::new(4,2,4096,VOCAB,0,false).unwrap().mtp_t,2); +} + +#[test] +fn host_budget_is_checked_and_grows_with_the_request() { + let c=config(4,4,0); + let a=OriginalSpecController::planned_host_bytes(&c,10,10,1).unwrap(); + let b=OriginalSpecController::planned_host_bytes(&c,100,10,1).unwrap(); + assert!(b>a); + assert!(OriginalSpecController::planned_host_bytes(&c,0,10,1).is_err()); + assert!(OriginalSpecController::planned_host_bytes(&c,5000,10,1).is_err()); + assert!(OriginalSpecController::planned_host_bytes(&c,10,usize::MAX,1).is_err()); +} + +#[test] +fn begin_request_validates_tokens_and_rejects_a_live_request() { + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + assert_eq!(c.begin_request(&[],4,0.0,&[]),Err(Error::InvalidDimension)); + assert_eq!(c.begin_request(&[1,2000],4,0.0,&[]),Err(Error::InvalidToken)); + assert_eq!(c.begin_request(&[1,2],4,f32::NAN,&[]),Err(Error::InvalidDimension)); + assert_eq!(c.begin_request(&[1,2],4,0.0,&[VOCAB as i32]),Err(Error::InvalidToken)); + begin(&mut c,&[1,2,3],4,&[]); + // the final prompt token is the first verify input, not yet consumed + assert_eq!(c.consumed().unwrap(),&[1,2]); + assert_eq!(c.begin_request(&[1],4,0.0,&[]),Err(Error::IdentityMismatch)); +} + +#[test] +fn the_adaptive_window_emits_the_same_text_as_a_fixed_one_under_any_drafter() { + use super::super::original_spec_adaptive::AdaptiveConfig; + for bad in [None,Some(0),Some(1),Some(3)] { + for probs in [vec![0.95;8],vec![0.3;8],vec![0.9,0.8,0.6,0.5,0.4,0.9,0.9,0.9]] { + for suffix in [0usize,3] { + let p=prompt(6);let mut e=Fake::new(&p[..5]); + e.bad_draft=bad;e.probs=probs.clone(); + let mut c=OriginalSpecController::new(config(6,6,suffix).with_adaptive(Some(AdaptiveConfig::new(6,5)))).unwrap(); + begin(&mut c,&p,70,&[]); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + c.finish_request(&mut e).unwrap(); + assert_eq!(out,expected(&p,70),"bad {bad:?} probs {probs:?} suffix {suffix}"); + let stats=c.take_stats(); + assert!(stats.rounds>=2&&stats.tokens as usize>=stats.rounds as usize,"{}",stats.line()); + assert!(c.adaptive().is_some_and(|a|a.rounds()>=stats.rounds-1)); + } + } + } +} + +#[test] +fn the_adaptive_window_learns_to_verify_wide_when_the_drafter_is_perfect() { + use super::super::original_spec_adaptive::AdaptiveConfig; + let p=prompt(6);let mut e=Fake::new(&p[..5]); + let mut c=OriginalSpecController::new(config(6,6,0).with_adaptive(Some(AdaptiveConfig::new(6,5)))).unwrap(); + begin(&mut c,&p,200,&[]); + let mut widths=Vec::new(); + while let Some(round)=c.verify_commit(&mut e,&mut||false).unwrap() { + widths.push(round.offered()+1); + // a wider window costs a little more in this fake clock + let ms=30.0+1.0*(round.offered() as f64); + c.finish_round(&mut e,round,move||ms,&mut||false).unwrap(); + } + c.finish_request(&mut e).unwrap(); + let tail=&widths[widths.len()-8..]; + assert!(tail.iter().all(|&t|t>=5),"{widths:?}"); +} + +#[test] +fn perfect_drafter_accepts_whole_windows_and_emits_greedy_text() { + let p=prompt(6);let mut e=Fake::new(&p[..5]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,12,&[]); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + c.finish_request(&mut e).unwrap(); + assert_eq!(out,expected(&p,12)); + assert!(c.finished()); + // first window is T=1 (nothing drafted yet); later windows verify 3 drafts + the input + assert_eq!(e.committed.len(),5+1+4+4+4,"windows commit input rows: 1 then 4 each"); + assert_eq!(e.count("verify"),1+(12-1+3)/4); + assert_eq!(e.count("wait_commit"),1); + // each committed round took a target AND a draft checkpoint restore-free path + assert_eq!(e.count("restore_target")+e.count("restore_draft"),0); + assert_eq!(e.count("begin_adaptation"),e.count("join_adaptation")); + assert_eq!(e.count("drain_verified"),e.count("verify")); + assert_eq!(e.count("drain_draft"),e.count("seed")); +} + +#[test] +fn rejected_draft_commits_only_the_accepted_prefix() { + let p=prompt(5);let mut e=Fake::new(&p[..4]); + e.bad_draft=Some(1); // the second draft token is wrong + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,9,&[]); + let r1=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + assert_eq!((r1.offered(),r1.accepted(),r1.committed_input_rows()),(0,0,1)); + c.finish_round(&mut e,r1,||1.0,&mut||false).unwrap(); + let r2=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + // inputs: x, d0 (right), d1 (wrong), d2 -> one draft accepted + assert_eq!((r2.offered(),r2.accepted(),r2.committed_input_rows()),(3,1,2)); + assert_eq!(r2.tokens().len(),2); + assert!(!r2.used_lookup()); + c.finish_round(&mut e,r2,||1.0,&mut||false).unwrap(); + // after any prefix the session holds exactly the consumed tokens + assert_eq!(c.consumed().unwrap(),e.committed.as_slice()); +} + +#[test] +fn min_p_shrinks_the_window_and_the_draft_chain() { + let p=prompt(5);let mut e=Fake::new(&p[..4]); + e.probs=vec![0.9,0.1,0.9,0.9,0.9,0.9,0.9,0.9]; + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + c.begin_request(&p,20,0.5,&[]).unwrap(); + let r1=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + c.finish_round(&mut e,r1,||1.0,&mut||false).unwrap(); + // the chain stopped after draft 1 (0.1 < min_p): seed + one chain step only + assert_eq!(e.drafted,2); + let r2=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + // draft 0 passes min_p, draft 1 does not: T = 2 + assert_eq!(r2.offered(),1); + c.finish_round(&mut e,r2,||1.0,&mut||false).unwrap(); +} + +#[test] +fn eos_stops_emission_skips_drafting_and_keeps_the_commit() { + let p=prompt(5);let want=expected(&p,12); + let eos=want[5]; + let mut e=Fake::new(&p[..4]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,30,&[eos]); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + assert_eq!(out,want[..6].to_vec()); + assert!(c.finished()); + let before=e.count("seed"); + // last round hit EOS: no draft was prepared for it + assert!(e.count("verify")>=2&&before(Fake,Vec,OriginalSpecController) { + use super::super::original_spec_adaptive::AdaptiveConfig; + let p=prompt(prompt_len);let mut e=Fake::new(&p[..prompt_len-1]); + let mut cfg=SpecConfig::new(max_t,mtp,64,VOCAB,suffix,false).unwrap();cfg.max_context=max_context; + if adaptive {cfg=cfg.with_adaptive(Some(AdaptiveConfig::new(max_t,max_t-1)));} + let mut c=OriginalSpecController::new(cfg).unwrap(); + c.begin_request(&p,max_new,min_p,&[]).unwrap(); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + c.finish_request(&mut e).unwrap(); + (e,out,c) +} + +#[test] +fn a_window_near_the_context_end_takes_only_the_rows_that_fit() { + let p=prompt(4);let mut e=Fake::new(&p[..3]); + let mut cfg=SpecConfig::new(4,4,6,VOCAB,0,false).unwrap();cfg.max_context=6; + let mut c=OriginalSpecController::new(cfg).unwrap(); + begin(&mut c,&p,100,&[]); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + // position 3: T=1; position 4: T=4 does not fit (4 + 4 > 6), so the window shrinks to the 2 rows left, not to "length" + assert!(c.finished()); + assert_eq!(e.committed.len(),6,"every cell of the context is used"); + assert_eq!(out,expected(&p,3),"the tokens of rows 3, 4 and 5 are all emitted"); + assert!(e.max_end<=6,"no row or draft past the context: {}",e.max_end); +} + +#[test] +fn spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end() { + // every distance k of the first window from the end, every window shape: fixed, min_p, suffix lookup, adaptive + for max_t in [2usize,4,6,8] { + for k in 1..=(max_t as i64+3) { + for (suffix,min_p,adaptive) in [(0usize,0.0f32,false),(3,0.0,false),(0,0.5,false),(3,0.5,true),(0,0.0,true)] { + let prompt_len=10usize; + let max_context=prompt_len as i64-1+k; + let (e,out,c)=run_to_the_end(max_context,prompt_len,1000,max_t,max_t,suffix,min_p,adaptive); + let tag=format!("max_t {max_t} k {k} suffix {suffix} min_p {min_p} adaptive {adaptive}"); + assert!(e.max_end<=max_context,"{tag}: touched cell {} of {max_context}",e.max_end); + // the request ended because the context is full, with the greedy text of every row that fits + assert_eq!(e.committed.len() as i64,max_context,"{tag}"); + assert_eq!(out,expected(&prompt(prompt_len),k as usize),"{tag}"); + assert!(c.finished()&&!c.is_failed(),"{tag}"); + assert_eq!(e.count("begin_adaptation"),e.count("join_adaptation"),"{tag}"); + assert_eq!(e.count("drain_verified"),e.count("verify"),"{tag}"); + } + } + } +} + +#[test] +fn the_chain_is_shortened_near_the_end_and_restored_after_it() { + // fixed window, perfect drafter: 4-wide windows, 3 drafts. The last round before the end drafts only the cells left. + let (e,_,_)=run_to_the_end(30,10,1000,4,4,0,0.0,false); + assert!(e.max_end<=30); + // plans: a clamped chain is asked for explicitly, never longer than the cells left + assert!(e.plans.iter().all(|&(n,_)|(1..=3).contains(&n)),"{:?}",e.plans); + assert!(e.plans.iter().any(|&(n,_)|n<3),"the last rounds draft fewer than the full chain: {:?}",e.plans); + // a request that never gets near the end never sets a plan (the fixed chain needs none) + let (e,_,_)=run_to_the_end(4096,10,40,4,4,0,0.0,false); + assert!(e.plans.is_empty(),"{:?}",e.plans); +} + +#[test] +fn a_chain_clamped_by_one_request_is_restored_for_the_next() { + let p=prompt(10); + let mut e=Fake::new(&p[..9]); + let mut cfg=SpecConfig::new(4,4,64,VOCAB,0,false).unwrap();cfg.max_context=20; + let mut c=OriginalSpecController::new(cfg).unwrap(); + c.begin_request(&p,1000,0.0,&[]).unwrap(); + drive(&mut c,&mut e,&mut||false).unwrap();c.finish_request(&mut e).unwrap(); + assert!(e.plans.last().is_some_and(|&(n,_)|n<3),"the request ended on a clamped chain: {:?}",e.plans); + // a short request on the same controller: its first drafting round puts the full chain back + let mut e2=Fake::new(&p[..9]); + c.begin_request(&p,3,0.0,&[]).unwrap(); + drive(&mut c,&mut e2,&mut||false).unwrap(); + assert_eq!(e2.plans.first().map(|x|x.0),Some(3),"{:?}",e2.plans); +} + +/// Upstream 41cf05a0 `aece46db`: position 0 was the CLI's "speculation not started" value, so a 1-token prompt on a native pack +/// (its only token is the first verify input, at position 0) never speculated. Here position 0 is a real start. +#[test] +fn a_one_token_prompt_speculates_from_position_zero() { + for (suffix,adaptive) in [(0usize,false),(3,false),(0,true)] { + use super::super::original_spec_adaptive::AdaptiveConfig; + let p=prompt(1); + let mut e=Fake::new(&[]); + let mut cfg=config(4,4,suffix); + if adaptive {cfg=cfg.with_adaptive(Some(AdaptiveConfig::new(4,3)));} + let mut c=OriginalSpecController::new(cfg).unwrap(); + begin(&mut c,&p,40,&[]); + assert_eq!(c.consumed().unwrap().len(),0); + let mut widths=Vec::new(); + while let Some(round)=c.verify_commit(&mut e,&mut||false).unwrap() { + widths.push(round.offered()+1); + c.finish_round(&mut e,round,||1.0,&mut||false).unwrap(); + } + c.finish_request(&mut e).unwrap(); + assert_eq!(widths[0],1,"the first window has nothing drafted yet"); + assert!(widths[1..].iter().any(|&t|t>1),"suffix {suffix} adaptive {adaptive}: no window ever speculated: {widths:?}"); + assert!(e.count("verify")<40,"suffix {suffix} adaptive {adaptive}: one window per token: {widths:?}"); + assert_eq!(e.committed.len(),widths.iter().sum::(),"every round committed its accepted rows only: windows {widths:?}"); + } + let p=prompt(1);let mut e=Fake::new(&[]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,40,&[]); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + assert_eq!(out,expected(&p,40)); +} + +/// Upstream 41cf05a0 `f332a855` / `894f133b` (STRATA_NAN_GUARD, #879): a window whose output is not finite is not emitted; upstream ends the +/// request and its gateway repeats it. Here the window itself is run again from its round's checkpoint. +fn guarded(guard:NanGuard,max_new:usize)->(Fake,OriginalSpecController,Vec) { + let p=prompt(6);let e=Fake::new(&p[..5]); + let c=OriginalSpecController::new(config(4,4,0).with_nan_guard(guard)).unwrap(); + let _=max_new; + (e,c,p) +} + +#[test] +fn the_guard_reads_its_three_switches_and_refuses_a_malformed_one() { + assert_eq!(NanGuard::parse(None,None,None),Ok(if NanGuard::DEFAULT_ON {NanGuard::with_retries(NanGuard::DEFAULT_RETRIES)} else {NanGuard::off()})); + assert_eq!(NanGuard::parse(Some("on"),None,None),Ok(NanGuard::with_retries(2))); + assert_eq!(NanGuard::parse(Some(" ON "),Some("5"),None),Ok(NanGuard::with_retries(5))); + assert_eq!(NanGuard::parse(Some("off"),Some("5"),None),Ok(NanGuard::off())); + assert_eq!(NanGuard::parse(Some("1"),Some("0"),None),Ok(NanGuard::with_retries(0))); + assert_eq!(NanGuard::parse(Some("on"),None,Some("3")),Ok(NanGuard::with_retries(2).with_injection(3,1))); + assert_eq!(NanGuard::parse(Some("on"),None,Some("4x2")),Ok(NanGuard::with_retries(2).with_injection(4,2))); + for bad in [(Some("maybe"),None,None),(Some("on"),Some("9"),None),(Some("on"),Some("x"),None),(Some("on"),None,Some("0")),(Some("on"),None,Some("2x0")),(Some("on"),None,Some("a"))] { + assert!(NanGuard::parse(bad.0,bad.1,bad.2).is_err(),"{bad:?}"); + } + // an injection under a guard that is off does nothing: the guard has to be on to heal what it injects + let off=NanGuard::parse(Some("off"),None,Some("2")).unwrap(); + assert!(!off.injects(2,0)); + assert!(NanGuard::with_retries(2).with_injection(2,1).injects(2,0)); + assert!(!NanGuard::with_retries(2).with_injection(2,1).injects(2,1),"only the first attempt"); + assert!(!NanGuard::with_retries(2).with_injection(2,1).injects(3,0)); +} + +#[test] +fn a_non_finite_window_is_run_again_from_its_checkpoint_and_the_request_completes() { + let want=expected(&prompt(6),20); + for retries in [1u32,2,5] { + let (mut e,mut c,p)=guarded(NanGuard::with_retries(retries),20); + e.fail=Some(("verify",Error::NonFinite)); + c.begin_request(&p,20,0.0,&[]).unwrap(); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + c.finish_request(&mut e).unwrap(); + assert_eq!(out,want,"retries {retries}: the text is the greedy one, nothing lost or repeated"); + assert!(!c.is_failed()&&c.finished()); + // one restore of each checkpoint, and the window was run twice: one more verify than a clean run + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); + let (mut clean,mut cc,p2)=guarded(NanGuard::with_retries(retries),20); + cc.begin_request(&p2,20,0.0,&[]).unwrap(); + drive(&mut cc,&mut clean,&mut||false).unwrap(); + assert_eq!(e.count("verify"),clean.count("verify")+1); + assert_eq!(c.take_stats().healed,1); + // what the session committed is exactly what the clean run committed + assert_eq!(e.committed,clean.committed); + } +} + +#[test] +fn the_guard_costs_nothing_when_nothing_is_wrong() { + let (mut e,mut c,p)=guarded(NanGuard::with_retries(2),30); + c.begin_request(&p,30,0.0,&[]).unwrap(); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + assert_eq!(out,expected(&prompt(6),30)); + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(0,0)); + assert_eq!(c.take_stats().healed,0); + // and the same request with the guard off runs the identical sequence of engine calls + let mut off=Fake::new(&prompt(6)[..5]); + let mut co=OriginalSpecController::new(config(4,4,0)).unwrap(); + co.begin_request(&prompt(6),30,0.0,&[]).unwrap(); + drive(&mut co,&mut off,&mut||false).unwrap(); + assert_eq!(e.log,off.log); +} + +#[test] +fn a_window_that_stays_non_finite_fails_the_request_after_the_retries() { + for retries in [1u32,2] { + let (mut e,mut c,p)=guarded(NanGuard::with_retries(retries),20); + e.fail=Some(("verify",Error::NonFinite));e.fail_n=retries+1; + c.begin_request(&p,20,0.0,&[]).unwrap(); + let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); + assert_eq!(err,SpecError::Forward(Error::NonFinite)); + assert!(c.finished()&&!c.is_failed(),"the request ends, the controller stays usable (the checkpoints were restored)"); + // retries restores for the retries, one more for the abort that gives up + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(retries as usize+1,retries as usize+1)); + assert_eq!(e.count("verify"),retries as usize+1); + } +} + +#[test] +fn only_a_non_finite_failure_is_retried_and_a_guard_that_is_off_retries_nothing() { + let (mut e,mut c,p)=guarded(NanGuard::with_retries(3),20); + e.fail=Some(("verify",Error::CudaExecution)); + c.begin_request(&p,20,0.0,&[]).unwrap(); + assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::CudaExecution))); + assert_eq!((e.count("verify"),e.count("restore_target")),(1,1),"not retried"); + let (mut e,mut c,p)=guarded(NanGuard::off(),20); + e.fail=Some(("verify",Error::NonFinite)); + c.begin_request(&p,20,0.0,&[]).unwrap(); + assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::NonFinite))); + assert_eq!((e.count("verify"),e.count("restore_target")),(1,1),"guard off: the first failure aborts as before"); + // a failed apply_pending of the adaptive tier is not a window either + let (mut e,mut c,p)=guarded(NanGuard::with_retries(3),20); + e.fail=Some(("apply_pending",Error::CudaExecution)); + c.begin_request(&p,20,0.0,&[]).unwrap(); + assert!(c.verify_commit(&mut e,&mut||false).is_err()); + assert_eq!(e.count("verify"),0); +} + +#[test] +fn a_checkpoint_that_cannot_be_restored_ends_the_healing_with_the_original_error() { + let (mut e,mut c,p)=guarded(NanGuard::with_retries(3),20); + e.fail=Some(("verify",Error::NonFinite)); + c.begin_request(&p,20,0.0,&[]).unwrap(); + // the restore the guard asks for fails: the state is unknown + e.fail_restore_target=true; + let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); + assert_eq!(err,SpecError::Forward(Error::NonFinite),"the primary error is kept"); + assert!(c.is_failed()&&c.finished(),"the controller is unusable: its state is unknown"); + assert_eq!(e.count("verify"),1); +} + +#[test] +fn the_injection_exercises_the_same_path_on_a_good_window_and_counts_windows_across_requests() { + // the 3rd checked window fails once: healed, text unchanged + let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(3,1),20); + c.begin_request(&p,20,0.0,&[]).unwrap(); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + assert_eq!(out,expected(&prompt(6),20)); + assert_eq!(c.take_stats().healed,1); + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); + assert_eq!(e.count("discard_window"),1,"the injected window was taken back once"); + // the window that was injected was a real, good one: it was drained before the retry + assert_eq!(e.count("drain_verified"),e.count("verify")); + // two failures in a row on one window, two retries: healed after two restarts + let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(2,2),20); + c.begin_request(&p,20,0.0,&[]).unwrap(); + assert_eq!(drive(&mut c,&mut e,&mut||false).unwrap(),expected(&prompt(6),20)); + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(2,2)); + // three failures, two retries: the request fails and says why + let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(2,3),20); + c.begin_request(&p,20,0.0,&[]).unwrap(); + assert_eq!(drive(&mut c,&mut e,&mut||false).err(),Some(SpecError::Forward(Error::NonFinite))); + // windows are counted across the requests of one controller + let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(4,1),6); + c.begin_request(&p,6,0.0,&[]).unwrap(); + drive(&mut c,&mut e,&mut||false).unwrap(); + c.finish_request(&mut e).unwrap(); + let first_request_windows=e.count("verify"); + assert!(first_request_windows<4,"{first_request_windows}"); + let mut e2=Fake::new(&p[..5]); + c.begin_request(&p,20,0.0,&[]).unwrap(); + assert_eq!(drive(&mut c,&mut e2,&mut||false).unwrap(),expected(&p,20)); + assert_eq!(e2.count("restore_target"),1,"the injected window was one of the second request's"); +} + +#[test] +fn the_retry_takes_the_refused_window_back_before_it_stages_the_rows_again() { + // the live stack's first failure: a completed window that nothing was committed for refuses the next one (InvalidDimension) + let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(1,1),20); + c.begin_request(&p,20,0.0,&[]).unwrap(); + let _first=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + assert!(!e.open,"the retried window was committed"); + assert_eq!(c.take_stats().healed,1); + // drain, restore both checkpoints, take the window back, then the same rows again + let at=e.log.iter().position(|l|l=="drain_verified").unwrap(); + let order:Vec<&str>=e.log[at..at+6].iter().map(String::as_str).collect(); + assert_eq!(order,["drain_verified","restore_target","restore_draft","discard_window","apply_pending","verify"]); + assert_eq!(e.count("discard_window"),1); + // a clean request never takes anything back + let (mut clean,mut cc,p2)=guarded(NanGuard::with_retries(2),20); + cc.begin_request(&p2,20,0.0,&[]).unwrap(); + drive(&mut cc,&mut clean,&mut||false).unwrap(); + assert_eq!(clean.count("discard_window"),0); +} + +#[test] +fn a_window_that_cannot_be_taken_back_ends_the_healing_with_the_original_error() { + let (mut e,mut c,p)=guarded(NanGuard::with_retries(3).with_injection(1,1),20); + e.fail=Some(("discard_window",Error::CudaExecution)); + c.begin_request(&p,20,0.0,&[]).unwrap(); + let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); + assert_eq!(err,SpecError::Forward(Error::NonFinite),"the primary error is kept"); + assert!(c.is_failed()&&c.finished(),"the controller is unusable: the verifier still holds the window"); + assert_eq!((e.count("verify"),e.count("discard_window")),(1,1),"no second attempt on a verifier that still holds the window"); +} + +#[test] +fn verify_failure_restores_both_checkpoints_and_poisons_nothing_else() { + let p=prompt(5);let mut e=Fake::new(&p[..4]); + e.fail=Some(("verify",Error::CudaExecution)); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); + assert_eq!(err,SpecError::Forward(Error::CudaExecution)); + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); + assert!(c.finished()&&!c.is_failed()); + assert_eq!(e.committed.len(),4); +} + +#[test] +fn a_failed_window_preparation_also_restores_both_checkpoints() { + let p=prompt(5); + let mut e=Fake::new(&p[..4]); + e.fail=Some(("apply_pending",Error::CudaExecution)); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); + assert_eq!(err,SpecError::Forward(Error::CudaExecution)); + assert_eq!(e.count("verify"),0); + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); + assert!(!c.is_failed()); +} + +#[test] +fn restore_failure_makes_the_controller_unusable_but_keeps_the_primary_error() { + let p=prompt(5); + let mut e=Fake::new(&p[..4]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + let target=e.checkpoint_target().unwrap();let draft=e.checkpoint_draft().unwrap(); + // the target restore fails: the draft restore must still be attempted + e.fail=Some(("restore_target",Error::CudaExecution)); + let primary=c.abort(&mut e,&target,&draft,SpecError::Forward(Error::InputRead)); + assert_eq!(primary,SpecError::Forward(Error::InputRead)); + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); + assert!(c.is_failed()); + assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::IdentityMismatch))); + // and a failing draft restore is equally fatal + let mut e=Fake::new(&p[..4]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + e.fail=Some(("restore_draft",Error::CudaExecution)); + let _=c.abort(&mut e,&target,&draft,SpecError::Cancelled); + assert!(c.is_failed()); +} + +#[test] +fn commit_failure_joins_adaptation_drains_and_restores() { + let p=prompt(5);let mut e=Fake::new(&p[..4]); + e.fail=Some(("commit",Error::CudaExecution)); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); + assert_eq!(err,SpecError::Forward(Error::CudaExecution)); + assert_eq!((e.count("begin_adaptation"),e.count("join_adaptation")),(1,1)); + assert_eq!(e.count("drain_verified"),1); + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); + assert_eq!(e.committed.len(),4); +} + +#[test] +fn begin_adaptation_failure_drains_and_restores_without_committing() { + let p=prompt(5);let mut e=Fake::new(&p[..4]); + e.fail=Some(("begin_adaptation",Error::CudaExecution)); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + assert!(c.verify_commit(&mut e,&mut||false).is_err()); + assert_eq!(e.count("commit"),0); + assert_eq!(e.count("join_adaptation"),0); + assert_eq!(e.count("drain_verified"),1); + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); +} + +#[test] +fn invalid_verified_output_is_refused_before_anything_commits() { + let p=prompt(5); + let mut e=Fake::new(&p[..4]);e.bad_output=Some((0,VOCAB as i32+5)); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); + assert_eq!(err,SpecError::Forward(Error::InvalidToken)); + assert_eq!((e.count("commit"),e.count("drain_verified"),e.count("restore_target")),(0,1,1)); +} + +#[test] +fn cancellation_before_verify_touches_nothing_and_after_verify_rolls_back() { + let p=prompt(5); + let mut e=Fake::new(&p[..4]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + assert_eq!(c.verify_commit(&mut e,&mut||true).err(),Some(SpecError::Cancelled)); + assert_eq!(e.count("verify"),0); + assert_eq!(e.count("restore_target"),0); + // cancelled after the window ran: drained, both restored, no commit + let mut e=Fake::new(&p[..4]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + let mut calls=0; + let r=c.verify_commit(&mut e,&mut||{calls+=1;calls==2}); + assert_eq!(r.err(),Some(SpecError::Cancelled)); + assert_eq!((e.count("verify"),e.count("commit"),e.count("drain_verified")),(1,0,1)); + assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); + assert_eq!(e.committed.len(),4); +} + +#[test] +fn draft_failure_after_commit_keeps_the_commit_joins_and_fails_the_request() { + let p=prompt(5);let mut e=Fake::new(&p[..4]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + let round=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + let tokens=round.tokens().to_vec(); + e.fail=Some(("seed",Error::CudaExecution)); + let err=c.finish_round(&mut e,round,||1.0,&mut||false).err().unwrap(); + assert_eq!(err,SpecError::Forward(Error::CudaExecution)); + // the emitted prefix is real; pending adaptation was joined and the receipt drained + assert_eq!(tokens.len(),1); + assert_eq!(e.committed.len(),5); + assert_eq!((e.count("join_adaptation"),e.count("drain_verified"),e.count("drain_draft")),(1,1,1)); + assert!(c.is_failed()&&c.finished()); +} + +#[test] +fn adaptation_join_failure_is_reported_even_after_a_good_draft() { + let p=prompt(5);let mut e=Fake::new(&p[..4]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + let round=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + e.fail=Some(("join_adaptation",Error::CudaExecution)); + assert_eq!(c.finish_round(&mut e,round,||1.0,&mut||false).err(),Some(SpecError::Forward(Error::CudaExecution))); + assert_eq!(e.count("drain_verified"),1); + assert!(c.is_failed()); +} + +#[test] +fn finish_round_refuses_a_receipt_from_another_controller() { + let p=prompt(5);let mut e=Fake::new(&p[..4]); + let mut a=OriginalSpecController::new(config(4,4,0)).unwrap(); + let mut b=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut a,&p,8,&[]);begin(&mut b,&p,8,&[]); + let round=a.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + assert_eq!(b.finish_round(&mut e,round,||1.0,&mut||false).err(),Some(SpecError::Forward(Error::IdentityMismatch))); + // the receipt was still drained and joined + assert_eq!((e.count("join_adaptation"),e.count("drain_verified")),(1,1)); +} + +#[test] +fn a_request_cannot_restart_while_a_draft_is_pending() { + let p=prompt(5);let mut e=Fake::new(&p[..4]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,8,&[]); + let round=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::IdentityMismatch))); + assert_eq!(c.finish_request(&mut e),Err(Error::IdentityMismatch)); + c.finish_round(&mut e,round,||1.0,&mut||false).unwrap(); + c.finish_request(&mut e).unwrap(); +} + +#[test] +fn policy_and_adaptive_cadence_survive_across_requests() { + let p=prompt(5);let mut e=Fake::new(&p[..4]); + let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); + begin(&mut c,&p,6,&[]); + drive(&mut c,&mut e,&mut||false).unwrap(); + c.finish_request(&mut e).unwrap(); + let rounds_first=e.count("begin_adaptation"); + let mut e2=Fake::new(&p[..4]); + begin(&mut c,&p,6,&[]); + drive(&mut c,&mut e2,&mut||false).unwrap(); + // the adaptive round numbers keep counting (Original `rounds`), the engine sees them + assert!(rounds_first>0&&e2.count("begin_adaptation")>0); + // the first window of a new request is again T=1: one input row committed + assert_eq!(e2.committed.len(),4+1+4+4,"windows of 1, 4, 4 input rows for max_new=6"); +} + +#[test] +fn suffix_lookup_takes_a_longer_window_when_it_agrees_with_the_first_draft() { + // the fake model's orbit is a cycle: the suffix index proposes the continuation the MTP also drafts + let mut x=11;let mut seq=vec![x]; + let mut seen=std::collections::HashMap::new(); + let cycle=loop {if let Some(&at)=seen.get(&x) {break seq[at..seq.len()-1].to_vec();}seen.insert(x,seq.len()-1);x=next(x);seq.push(x);}; + assert!(cycle.len()>=3); + let mut seq=Vec::new();while seq.len()<1200 {seq.extend_from_slice(&cycle);} + let prompt=seq; + let mut e=Fake::new(&prompt[..prompt.len()-1]); + let mut c=OriginalSpecController::new(config(8,2,3)).unwrap(); + begin(&mut c,&prompt,40,&[]); + let mut windows=Vec::new(); + while let Some(round)=c.verify_commit(&mut e,&mut||false).unwrap() { + windows.push((round.offered()+1,round.used_lookup())); + c.finish_round(&mut e,round,||1.0,&mut||false).unwrap(); + } + // first window T=1; a lookup then widens the window beyond the MTP's T=2 + assert_eq!(windows[0],(1,false)); + assert!(windows.iter().skip(1).any(|&(t,lookup)|lookup&&t>2),"{windows:?}"); +} + +#[test] +fn output_is_the_greedy_text_for_every_window_shape_noise_and_stop_rule() { + // Output invariance: whatever the window sizes, the draft noise, the confidence floor, the suffix + // lookup, EOS and max_new do, the emitted tokens are the greedy continuation (cut at the first EOS or + // max_new) and the session ends up holding exactly the consumed tokens. + let p=prompt(40); + let full=expected(&p,64); + let noisy=[None,Some(0),Some(1),Some(2),Some(5)]; + let probs:[[f32;8];3]=[[0.9;8],[0.9,0.1,0.9,0.9,0.9,0.9,0.9,0.9],[0.02;8]]; + for max_t in 1..=8usize { for mtp in [0usize,1,2,max_t,9] { for suffix in [0usize,3] { + for bad in noisy { for pr in probs { for min_p in [0.0f32,0.5] { for max_new in [0usize,1,3,17] { + for eos_at in [None,Some(2usize),Some(9)] { + let eos:Vec=eos_at.map(|i|full[i]).into_iter().collect(); + let mut e=Fake::new(&p[..p.len()-1]);e.bad_draft=bad;e.probs=pr.to_vec(); + let mut c=OriginalSpecController::new(SpecConfig::new(max_t,mtp,4096,VOCAB,suffix,false).unwrap()).unwrap(); + c.begin_request(&p,max_new,min_p,&eos).unwrap(); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + c.finish_request(&mut e).unwrap(); + let mut want=full[..max_new].to_vec(); + if let Some(i)=eos_at {if i,fail:bool} + impl OriginalFirstDraftEngine for First { + fn replay_first_seed_kv(&mut self,_:&u8,t:usize,cell:i64,token:i32)->Result<()> { + self.log.push("replay");assert_eq!((t,cell,token),(4,9,5));Ok(()) + } + fn full_first_seed(&mut self,_:&u8,_cell:i64,token:i32,_c:bool)->Result { + self.log.push("seed");if self.fail {return Err(Error::CudaExecution);}Ok(DraftPick{token:next(token),probability:0.9}) + } + fn first_chain_step(&mut self,_cell:i64,_j:usize,prev:i32,_c:bool)->Result { + self.log.push("chain");Ok(DraftPick{token:next(prev),probability:0.9}) + } + fn drain_first_seed(&mut self)->Result<()> {self.log.push("drain");Ok(())} + } + let prep=DraftPreparation::new(4,3,VOCAB).unwrap(); + let mut f=First{log:Vec::new(),fail:false}; + let b=prep.from_committed_seed(&mut f,&0u8,9,5,0.0,false).unwrap(); + assert_eq!(b.produced(),3); + assert_eq!(f.log,["replay","seed","chain","chain","drain"]); + let mut f=First{log:Vec::new(),fail:true}; + assert_eq!(prep.from_committed_seed(&mut f,&0u8,9,5,0.0,false).err(),Some(Error::CudaExecution)); + assert_eq!(f.log.last(),Some(&"drain")); +} diff --git a/crates/leleka-runtime/src/qwen_forward/output.rs b/crates/leleka-runtime/src/qwen_forward/output.rs index 53284141..3efe5269 100644 --- a/crates/leleka-runtime/src/qwen_forward/output.rs +++ b/crates/leleka-runtime/src/qwen_forward/output.rs @@ -833,93 +833,4 @@ fn combine(primary: Result, cleanup: Result<()>) -> Result { } #[cfg(test)] -mod tests { - use super::*; - - fn finite_values(fill: f32) -> Vec { - vec![FiniteF32::new(fill).expect("finite fixture"); VOCABULARY] - } - - fn logits(values: Vec) -> FiniteLogits { - let vocabulary = Dimension::new(VOCABULARY as u64).expect("fixed vocabulary"); - FiniteLogits { - binding: BindingIdentity::test_identity(), - token: TokenId::new(7, vocabulary).expect("bounded token"), - position: Position::new(0, vocabulary).expect("bounded position"), - values: LogitValues::Full(values.into_boxed_slice()), - } - } - - #[test] - fn output_weights_refuse_cross_binding_before_invalid_extent() { - let owner = BindingIdentity::test_identity(); - let weights = OutputWeights::test_empty(owner.clone()); - assert_eq!( - validate_weight_owner(&weights, &owner), - Err(Error::InvalidDimension) - ); - assert_eq!( - validate_weight_owner(&weights, &BindingIdentity::test_identity()), - Err(Error::IdentityMismatch) - ); - assert!(weights.bytes().is_empty()); - assert!(weights.matches(&owner)); - } - - #[test] - fn greedy_ties_choose_the_lowest_vocabulary_id() { - let mut values = finite_values(0.0); - values[3] = FiniteF32::new(9.0).expect("finite max"); - values[VOCABULARY - 1] = FiniteF32::new(9.0).expect("finite tie"); - assert_eq!(greedy(logits(values)).map(TokenId::get), Ok(3)); - } - - #[test] - fn greedy_selects_a_strictly_greater_late_logit() { - let mut values = finite_values(0.0); - values[VOCABULARY - 1] = FiniteF32::new(1.0).expect("finite max"); - assert_eq!( - greedy(logits(values)).map(TokenId::get), - Ok((VOCABULARY - 1) as u32) - ); - } - - #[test] - fn greedy_refuses_an_incomplete_vector() { - let values = finite_values(0.0); - let mut incomplete = logits(values); - if let LogitValues::Full(values) = &mut incomplete.values { - *values = values[..VOCABULARY - 1].into(); - } - assert_eq!(greedy(incomplete), Err(Error::InvalidDimension)); - } - - #[test] - fn decoding_requires_the_full_finite_vocabulary_before_publication() { - let mut bytes = vec![0; LOGIT_BYTES]; - assert_eq!( - decode_logits(&bytes).map(|values| values.len()), - Ok(VOCABULARY) - ); - - bytes.truncate(LOGIT_BYTES - 1); - assert_eq!(decode_logits(&bytes), Err(Error::InvalidDimension)); - - bytes.resize(LOGIT_BYTES, 0); - bytes[(VOCABULARY - 1) * 4..VOCABULARY * 4] - .copy_from_slice(&f32::INFINITY.to_bits().to_le_bytes()); - assert_eq!(decode_logits(&bytes), Err(Error::NonFinite)); - } - - #[test] - fn cleanup_failure_takes_precedence_over_a_host_validation_error() { - assert_eq!( - combine::<()>(Err(Error::NonFinite), Err(Error::CudaExecution)), - Err(Error::CudaExecution) - ); - assert_eq!( - combine::<()>(Err(Error::NonFinite), Ok(())), - Err(Error::NonFinite) - ); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/output/tests.rs b/crates/leleka-runtime/src/qwen_forward/output/tests.rs new file mode 100644 index 00000000..61d82188 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/output/tests.rs @@ -0,0 +1,90 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn finite_values(fill: f32) -> Vec { + vec![FiniteF32::new(fill).expect("finite fixture"); VOCABULARY] +} + +fn logits(values: Vec) -> FiniteLogits { + let vocabulary = Dimension::new(VOCABULARY as u64).expect("fixed vocabulary"); + FiniteLogits { + binding: BindingIdentity::test_identity(), + token: TokenId::new(7, vocabulary).expect("bounded token"), + position: Position::new(0, vocabulary).expect("bounded position"), + values: LogitValues::Full(values.into_boxed_slice()), + } +} + +#[test] +fn output_weights_refuse_cross_binding_before_invalid_extent() { + let owner = BindingIdentity::test_identity(); + let weights = OutputWeights::test_empty(owner.clone()); + assert_eq!( + validate_weight_owner(&weights, &owner), + Err(Error::InvalidDimension) + ); + assert_eq!( + validate_weight_owner(&weights, &BindingIdentity::test_identity()), + Err(Error::IdentityMismatch) + ); + assert!(weights.bytes().is_empty()); + assert!(weights.matches(&owner)); +} + +#[test] +fn greedy_ties_choose_the_lowest_vocabulary_id() { + let mut values = finite_values(0.0); + values[3] = FiniteF32::new(9.0).expect("finite max"); + values[VOCABULARY - 1] = FiniteF32::new(9.0).expect("finite tie"); + assert_eq!(greedy(logits(values)).map(TokenId::get), Ok(3)); +} + +#[test] +fn greedy_selects_a_strictly_greater_late_logit() { + let mut values = finite_values(0.0); + values[VOCABULARY - 1] = FiniteF32::new(1.0).expect("finite max"); + assert_eq!( + greedy(logits(values)).map(TokenId::get), + Ok((VOCABULARY - 1) as u32) + ); +} + +#[test] +fn greedy_refuses_an_incomplete_vector() { + let values = finite_values(0.0); + let mut incomplete = logits(values); + if let LogitValues::Full(values) = &mut incomplete.values { + *values = values[..VOCABULARY - 1].into(); + } + assert_eq!(greedy(incomplete), Err(Error::InvalidDimension)); +} + +#[test] +fn decoding_requires_the_full_finite_vocabulary_before_publication() { + let mut bytes = vec![0; LOGIT_BYTES]; + assert_eq!( + decode_logits(&bytes).map(|values| values.len()), + Ok(VOCABULARY) + ); + + bytes.truncate(LOGIT_BYTES - 1); + assert_eq!(decode_logits(&bytes), Err(Error::InvalidDimension)); + + bytes.resize(LOGIT_BYTES, 0); + bytes[(VOCABULARY - 1) * 4..VOCABULARY * 4] + .copy_from_slice(&f32::INFINITY.to_bits().to_le_bytes()); + assert_eq!(decode_logits(&bytes), Err(Error::NonFinite)); +} + +#[test] +fn cleanup_failure_takes_precedence_over_a_host_validation_error() { + assert_eq!( + combine::<()>(Err(Error::NonFinite), Err(Error::CudaExecution)), + Err(Error::CudaExecution) + ); + assert_eq!( + combine::<()>(Err(Error::NonFinite), Ok(())), + Err(Error::NonFinite) + ); +} diff --git a/crates/leleka-runtime/src/qwen_forward/session.rs b/crates/leleka-runtime/src/qwen_forward/session.rs index f303ebcd..20db8f49 100644 --- a/crates/leleka-runtime/src/qwen_forward/session.rs +++ b/crates/leleka-runtime/src/qwen_forward/session.rs @@ -970,541 +970,4 @@ impl QwenSession<'_> { } #[cfg(test)] -mod tests { - use super::*; - use crate::model_binding::qwen4exp_input::BindingIdentity; - use crate::qwen_forward::contract::Dimension; - - #[test] - fn retained_gr_handoff_identity_is_lazy_and_refuses_same_position_rebegin() { - // Actual contextless begin/abort state; no fabricated device producer. - let mut session = QwenSession::test_session(BindingIdentity::test_identity()); - let session_owner = Rc::clone(&session.owner); - let first_owner = { - let first = session.begin(token(1), position(0)).unwrap(); - assert!(first.residual_handoff.get().is_none()); - let owner = first.residual_handoff_owner().unwrap(); - assert!(Rc::ptr_eq(&owner, &first.residual_handoff_owner().unwrap())); - owner - }; - assert!(Rc::ptr_eq(&session_owner, &session.owner)); - let second = session.begin(token(1), position(0)).unwrap(); - assert!(second.residual_handoff.get().is_none()); - assert!(!Rc::ptr_eq( - &first_owner, - &second.residual_handoff_owner().unwrap() - )); - } - - fn token(value: u64) -> TokenId { - TokenId::new(value, Dimension::new(248_320).unwrap()).unwrap() - } - - fn position(value: u64) -> Position { - Position::new(value, crate::qwen_forward::contract::position_dimension()).unwrap() - } - - #[test] - fn headfree_prefill_refuses_metadata_completion_without_actual_final_producer() { - let binding = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(binding.clone()); - session.layer_count = 48; - let result = session.transact_completion(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; - // Synthetic count is only a refusal fixture; it cannot certify prefill. - txn.completed_layers = 48; - Ok(None) - }); - assert_eq!(result, Err(Error::Unsupported(Stage::Executor))); - assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - } - - #[test] - fn headfree_prefill_refuses_zero_layer_fixture_and_preserves_history() { - let binding = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(binding.clone()); - let result = session.transact_completion(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; - Ok(None) - }); - assert_eq!(result, Err(Error::Unsupported(Stage::Executor))); - assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - } - - #[test] - fn qsa_session_prior_is_private_and_required_state_cannot_be_skipped() { - let binding = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(binding.clone()); - session.layer_count = 4; - session.qsa_layers[3] = true; - let layer = LayerId::new(3, Dimension::new(4).unwrap()).unwrap(); - { - let mut txn = session.begin(token(3), position(0)).unwrap(); - let prior = txn.qsa_prior(layer).unwrap(); - assert!(txn.qsa_prior(layer).unwrap().same_state(&prior)); - let foreign = QsaIndexPrior::empty(binding.clone(), &QsaOwner::new(), layer).unwrap(); - assert_eq!( - txn.validate_qsa_prior(&foreign, layer), - Err(Error::IdentityMismatch) - ); - assert_eq!(txn.validate_qsa_prior(&prior, layer), Ok(())); - let gdn_layer = LayerId::new(0, Dimension::new(4).unwrap()).unwrap(); - assert!(matches!(txn.qsa_prior(gdn_layer), Err(Error::InvalidLayer))); - } - assert!(session.qsa_states[3].is_none()); - assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - assert_eq!( - session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; - // Completion markers isolate the state gate, not model math. - txn.completed_layers = 4; - txn.forward_output = Some(token(4)); - Ok(token(4)) - }), - Err(Error::Unsupported(Stage::QsaIndex)) - ); - assert!(session.qsa_states[3].is_none()); - assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - } - - #[test] - fn qsa_session_reset_invalidates_old_generation_even_at_position_zero() { - let binding = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(binding.clone()); - session.layer_count = 4; - session.qsa_layers[3] = true; - let layer = LayerId::new(3, Dimension::new(4).unwrap()).unwrap(); - let prior = session - .begin(token(3), position(0)) - .unwrap() - .qsa_prior(layer) - .unwrap(); - session.reset().unwrap(); - let mut txn = session.begin(token(3), position(0)).unwrap(); - let fresh = txn.qsa_prior(layer).unwrap(); - assert!(!fresh.same_state(&prior)); - assert_eq!( - txn.validate_qsa_prior(&prior, layer), - Err(Error::IdentityMismatch) - ); - assert_eq!(txn.validate_qsa_prior(&fresh, layer), Ok(())); - } - - #[test] - fn ple_session_candidate_is_not_published_on_late_failure_or_missing_history() { - let binding = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(binding.clone()); - session.layer_count = 2; - session.ple_required = true; - let layer = LayerId::new(1, Dimension::new(2).unwrap()).unwrap(); - let identity = TokenLayer::new(token(3), position(0), layer); - let result = session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; - let prior = txn.ple_prior()?; - let foreign = PlePrior::zero(binding.clone(), &PleOwner::new())?; - assert_eq!( - txn.validate_ple_prior(&foreign), - Err(Error::IdentityMismatch) - ); - let pending = PlePending::test_next(&prior, &identity)?; - txn.stage_ple(&prior, pending)?; - assert_eq!( - txn.stage_ple(&prior, PlePending::test_next(&prior, &identity)?), - Err(Error::IdentityMismatch) - ); - Err(Error::NonFinite) - }); - assert_eq!(result, Err(Error::NonFinite)); - assert!(session.ple_state.is_none()); - assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - assert_eq!( - session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; - // Isolate the required PLE publication gate from full-model math. - txn.completed_layers = 2; - txn.forward_output = Some(token(4)); - Ok(token(4)) - }), - Err(Error::Unsupported(Stage::Input)) - ); - assert!(session.ple_state.is_none()); - assert_eq!(session.next_position, 0); - } - - #[test] - fn ple_session_commit_and_reset_preserve_exact_owner_and_prior_identity() { - let binding = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(binding.clone()); - session.layer_count = 2; - session.ple_required = true; - let layer = LayerId::new(1, Dimension::new(2).unwrap()).unwrap(); - session - .transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; - let prior = txn.ple_prior()?; - txn.stage_ple( - &prior, - PlePending::test_next(&prior, &TokenLayer::new(token(3), position(0), layer))?, - )?; - // Synthetic markers test state publication, not actual model logits. - txn.completed_layers = 2; - txn.forward_output = Some(token(4)); - Ok(token(4)) - }) - .unwrap(); - let committed = session.ple_state.as_ref().unwrap().clone(); - assert_eq!((session.next_position, committed.next_position()), (1, 1)); - { - let mut txn = session.begin(token(4), position(1)).unwrap(); - assert!(txn.ple_prior().unwrap().same_state(&committed)); - } - assert_eq!( - session.reset_after_completion(Err(Error::CudaExecution)), - Err(Error::CudaExecution) - ); - assert!(session.ple_state.as_ref().unwrap().same_state(&committed)); - assert_eq!( - committed.validate(&binding, &session.ple_owner, position(1)), - Ok(()) - ); - session.reset().unwrap(); - assert!(session.ple_state.is_none()); - assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - assert_eq!( - committed.validate(&binding, &session.ple_owner, position(1)), - Err(Error::IdentityMismatch) - ); - } - - #[test] - fn gdn_session_late_failure_discards_candidates_and_required_state_cannot_be_skipped() { - let binding = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(binding.clone()); - session.layer_count = 48; - session.gdn_layers[0] = true; - let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap(); - let identity = TokenLayer::new(token(3), position(0), layer); - let result = session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; - let prior = txn.gdn_prior(layer)?; - let foreign = GdnPrior::zero(binding.clone(), &GdnOwner::new(), layer)?; - assert_eq!( - txn.validate_gdn_prior(&foreign, layer), - Err(Error::IdentityMismatch) - ); - let pending = GdnPending::test_next(&prior, &identity)?; - txn.stage_gdn(&prior, pending)?; - let duplicate = GdnPending::test_next(&prior, &identity)?; - assert_eq!( - txn.stage_gdn(&prior, duplicate), - Err(Error::IdentityMismatch) - ); - Err(Error::NonFinite) - }); - assert_eq!(result, Err(Error::NonFinite)); - assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - assert!(session.gdn_states[0].is_none()); - assert_eq!( - session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; - Ok(token(4)) - }), - Err(Error::Unsupported(Stage::Gdn)) - ); - assert_eq!(session.next_position, 0); - assert!(session.gdn_states[0].is_none()); - } - - #[test] - fn gdn_session_commit_advances_all_state_once_and_failed_reset_preserves_owner() { - let binding = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(binding.clone()); - session.layer_count = 48; - session.gdn_layers[0] = true; - let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap(); - session - .transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; - let prior = txn.gdn_prior(layer)?; - let pending = - GdnPending::test_next(&prior, &TokenLayer::new(token(3), position(0), layer))?; - txn.stage_gdn(&prior, pending)?; - // Synthetic completion markers isolate recurrent publication; - // this test does not execute layers or produce model logits. - txn.completed_layers = 48; - txn.forward_output = Some(token(4)); - Ok(token(4)) - }) - .unwrap(); - let committed = session.gdn_states[0].as_ref().unwrap().clone(); - assert_eq!((session.next_position, committed.next_position()), (1, 1)); - assert_eq!( - session.reset_after_completion(Err(Error::CudaExecution)), - Err(Error::CudaExecution) - ); - assert!( - session.gdn_states[0] - .as_ref() - .unwrap() - .same_state(&committed) - ); - assert_eq!( - committed.validate(&binding, &session.gdn_owner, layer, position(1)), - Ok(()) - ); - session.reset().unwrap(); - assert!(session.gdn_states[0].is_none()); - assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - assert_eq!( - committed.validate(&binding, &session.gdn_owner, layer, position(1)), - Err(Error::IdentityMismatch) - ); - } - - #[test] - fn full_forward_guard_refuses_skipped_layers_missing_logits_and_wrong_callback_token() { - let binding = BindingIdentity::test_identity(); - for (completed, proved_output, expected) in [ - (0, Some(token(4)), Error::Unsupported(Stage::Executor)), - (1, None, Error::Unsupported(Stage::Executor)), - (1, Some(token(5)), Error::IdentityMismatch), - ] { - let mut session = QwenSession::test_session(binding.clone()); - session.layer_count = 1; - assert_eq!( - session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; - txn.completed_layers = completed; - txn.forward_output = proved_output; - Ok(token(4)) - }), - Err(expected) - ); - assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - } - let mut session = QwenSession::test_session(binding); - session.layer_count = 2; - let mut txn = session.begin(token(3), position(0)).unwrap(); - let bound = Dimension::new(2).unwrap(); - let identity = - |layer| TokenLayer::new(token(3), position(0), LayerId::new(layer, bound).unwrap()); - assert_eq!( - txn.validate_layer_completion(identity(1)), - Err(Error::IdentityMismatch) - ); - assert_eq!(txn.validate_layer_completion(identity(0)), Ok(())); - txn.completed_layers = 1; - assert_eq!( - txn.validate_layer_completion(identity(0)), - Err(Error::IdentityMismatch) - ); - txn.forward_output = Some(token(4)); - assert_eq!( - txn.validate_layer_completion(identity(1)), - Err(Error::IdentityMismatch) - ); - } - - #[test] - fn context_seam_missing_owner_refuses_after_identity_checks() { - let mut session = QwenSession::test_session(BindingIdentity::test_identity()); - let mut txn = session.begin(token(1), position(0)).unwrap(); - assert_eq!( - txn.cuda_context().err(), - Some(Error::Unsupported(Stage::Session)) - ); - txn.binding = BindingIdentity::test_identity(); - assert_eq!(txn.cuda_context().err(), Some(Error::IdentityMismatch)); - } - - #[test] - fn context_seam_wrong_thread_refuses_before_backend_access() { - let mut session = QwenSession::test_session(BindingIdentity::test_identity()); - let mut txn = session.begin(token(1), position(0)).unwrap(); - txn.owner_thread = std::thread::spawn(|| std::thread::current().id()) - .join() - .unwrap(); - assert_eq!(txn.cuda_context().err(), Some(Error::IdentityMismatch)); - } - - #[test] - fn context_seam_failed_reset_keeps_committed_snapshot() { - let mut session = QwenSession::test_session(BindingIdentity::test_identity()); - session.predecessors = [17, 21]; - session.next_position = 2; - session.cuda_failed = true; - let owner = Rc::clone(&session.owner); - assert_eq!( - session.reset_after_completion(Err(Error::CudaExecution)), - Err(Error::CudaExecution) - ); - assert_eq!(session.predecessors, [17, 21]); - assert_eq!(session.next_position, 2); - assert!(Rc::ptr_eq(&owner, &session.owner)); - assert!(session.cuda_failed); - session.reset_after_completion(Ok(())).unwrap(); - assert_eq!(session.predecessors, [-1, -1]); - assert_eq!(session.next_position, 0); - assert!(!Rc::ptr_eq(&owner, &session.owner)); - assert!(!session.cuda_failed); - } - - #[test] - fn context_seam_cuda_failure_blocks_new_steps_without_committing() { - let identity = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(identity.clone()); - assert_eq!( - session.transact(token(1), position(0), &identity, |_| Err( - Error::CudaExecution - )), - Err(Error::CudaExecution) - ); - assert_eq!(session.predecessors, [-1, -1]); - assert_eq!(session.next_position, 0); - assert_eq!( - session.begin(token(1), position(0)).err(), - Some(Error::CudaExecution) - ); - // Contextless fixtures exercise only the local state guard. A real - // device-backed reset additionally requires Context::synchronize. - session.reset().unwrap(); - assert!(session.begin(token(1), position(0)).is_ok()); - } - - #[test] - fn committed_predecessors_advance_oldest_first_and_reset() { - let identity = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(identity.clone()); - - let output = session - .transact(token(17), position(0), &identity, |txn| { - assert_eq!(txn.input_predecessors()?, [-1, -1]); - txn.stage_input(InputReady::test_fixture( - token(17), - position(0), - identity.clone(), - ))?; - Ok(token(18)) - }) - .unwrap(); - assert_eq!(output, token(18)); - - session - .transact(token(21), position(1), &identity, |txn| { - assert_eq!(txn.input_predecessors()?, [-1, 17]); - txn.stage_input(InputReady::test_fixture( - token(21), - position(1), - identity.clone(), - ))?; - Ok(token(22)) - }) - .unwrap(); - - let third = session.begin(token(22), position(2)).unwrap(); - assert_eq!(third.input_predecessors().unwrap(), [17, 21]); - drop(third); - - session.reset().unwrap(); - let fresh = session.begin(token(9), position(0)).unwrap(); - assert_eq!(fresh.input_predecessors().unwrap(), [-1, -1]); - } - - #[test] - fn failed_or_dropped_transaction_does_not_advance_committed_state() { - let identity = BindingIdentity::test_identity(); - let other = BindingIdentity::test_identity(); - let mut session = QwenSession::test_session(identity.clone()); - - assert_eq!( - session.transact(token(3), position(0), &other, |_| Ok(token(8))), - Err(Error::IdentityMismatch) - ); - assert_eq!( - session.transact(token(3), position(0), &identity, |txn| { - assert_eq!(txn.input_predecessors()?, [-1, -1]); - txn.stage_input(InputReady::test_fixture(token(3), position(0), other))?; - Ok(token(4)) - }), - Err(Error::IdentityMismatch) - ); - assert_eq!( - session.transact(token(3), position(0), &identity, |_txn| { - Err(Error::Unsupported(Stage::Input)) - }), - Err(Error::Unsupported(Stage::Input)) - ); - - let current = session.begin(token(4), position(0)).unwrap(); - assert_eq!(current.token(), token(4)); - assert_eq!(current.input_predecessors().unwrap(), [-1, -1]); - } - - #[test] - fn begin_rejects_skips_and_repeats_before_mutation() { - let mut session = QwenSession::test_session(BindingIdentity::test_identity()); - assert_eq!( - session.begin(token(1), position(1)).err(), - Some(Error::InvalidPosition) - ); - let binding = session.binding.clone(); - session - .transact(token(1), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(1), - position(0), - binding.clone(), - ))?; - Ok(token(2)) - }) - .unwrap(); - assert_eq!( - session.begin(token(1), position(0)).err(), - Some(Error::InvalidPosition) - ); - assert_eq!( - session.begin(token(2), position(1)).unwrap().token(), - token(2) - ); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/session/tests.rs b/crates/leleka-runtime/src/qwen_forward/session/tests.rs new file mode 100644 index 00000000..0ca87eaa --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session/tests.rs @@ -0,0 +1,538 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::model_binding::qwen4exp_input::BindingIdentity; +use crate::qwen_forward::contract::Dimension; + +#[test] +fn retained_gr_handoff_identity_is_lazy_and_refuses_same_position_rebegin() { + // Actual contextless begin/abort state; no fabricated device producer. + let mut session = QwenSession::test_session(BindingIdentity::test_identity()); + let session_owner = Rc::clone(&session.owner); + let first_owner = { + let first = session.begin(token(1), position(0)).unwrap(); + assert!(first.residual_handoff.get().is_none()); + let owner = first.residual_handoff_owner().unwrap(); + assert!(Rc::ptr_eq(&owner, &first.residual_handoff_owner().unwrap())); + owner + }; + assert!(Rc::ptr_eq(&session_owner, &session.owner)); + let second = session.begin(token(1), position(0)).unwrap(); + assert!(second.residual_handoff.get().is_none()); + assert!(!Rc::ptr_eq( + &first_owner, + &second.residual_handoff_owner().unwrap() + )); +} + +fn token(value: u64) -> TokenId { + TokenId::new(value, Dimension::new(248_320).unwrap()).unwrap() +} + +fn position(value: u64) -> Position { + Position::new(value, crate::qwen_forward::contract::position_dimension()).unwrap() +} + +#[test] +fn headfree_prefill_refuses_metadata_completion_without_actual_final_producer() { + let binding = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(binding.clone()); + session.layer_count = 48; + let result = session.transact_completion(token(3), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(3), + position(0), + binding.clone(), + ))?; + // Synthetic count is only a refusal fixture; it cannot certify prefill. + txn.completed_layers = 48; + Ok(None) + }); + assert_eq!(result, Err(Error::Unsupported(Stage::Executor))); + assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); +} + +#[test] +fn headfree_prefill_refuses_zero_layer_fixture_and_preserves_history() { + let binding = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(binding.clone()); + let result = session.transact_completion(token(3), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(3), + position(0), + binding.clone(), + ))?; + Ok(None) + }); + assert_eq!(result, Err(Error::Unsupported(Stage::Executor))); + assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); +} + +#[test] +fn qsa_session_prior_is_private_and_required_state_cannot_be_skipped() { + let binding = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(binding.clone()); + session.layer_count = 4; + session.qsa_layers[3] = true; + let layer = LayerId::new(3, Dimension::new(4).unwrap()).unwrap(); + { + let mut txn = session.begin(token(3), position(0)).unwrap(); + let prior = txn.qsa_prior(layer).unwrap(); + assert!(txn.qsa_prior(layer).unwrap().same_state(&prior)); + let foreign = QsaIndexPrior::empty(binding.clone(), &QsaOwner::new(), layer).unwrap(); + assert_eq!( + txn.validate_qsa_prior(&foreign, layer), + Err(Error::IdentityMismatch) + ); + assert_eq!(txn.validate_qsa_prior(&prior, layer), Ok(())); + let gdn_layer = LayerId::new(0, Dimension::new(4).unwrap()).unwrap(); + assert!(matches!(txn.qsa_prior(gdn_layer), Err(Error::InvalidLayer))); + } + assert!(session.qsa_states[3].is_none()); + assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); + assert_eq!( + session.transact(token(3), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(3), + position(0), + binding.clone(), + ))?; + // Completion markers isolate the state gate, not model math. + txn.completed_layers = 4; + txn.forward_output = Some(token(4)); + Ok(token(4)) + }), + Err(Error::Unsupported(Stage::QsaIndex)) + ); + assert!(session.qsa_states[3].is_none()); + assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); +} + +#[test] +fn qsa_session_reset_invalidates_old_generation_even_at_position_zero() { + let binding = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(binding.clone()); + session.layer_count = 4; + session.qsa_layers[3] = true; + let layer = LayerId::new(3, Dimension::new(4).unwrap()).unwrap(); + let prior = session + .begin(token(3), position(0)) + .unwrap() + .qsa_prior(layer) + .unwrap(); + session.reset().unwrap(); + let mut txn = session.begin(token(3), position(0)).unwrap(); + let fresh = txn.qsa_prior(layer).unwrap(); + assert!(!fresh.same_state(&prior)); + assert_eq!( + txn.validate_qsa_prior(&prior, layer), + Err(Error::IdentityMismatch) + ); + assert_eq!(txn.validate_qsa_prior(&fresh, layer), Ok(())); +} + +#[test] +fn ple_session_candidate_is_not_published_on_late_failure_or_missing_history() { + let binding = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(binding.clone()); + session.layer_count = 2; + session.ple_required = true; + let layer = LayerId::new(1, Dimension::new(2).unwrap()).unwrap(); + let identity = TokenLayer::new(token(3), position(0), layer); + let result = session.transact(token(3), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(3), + position(0), + binding.clone(), + ))?; + let prior = txn.ple_prior()?; + let foreign = PlePrior::zero(binding.clone(), &PleOwner::new())?; + assert_eq!( + txn.validate_ple_prior(&foreign), + Err(Error::IdentityMismatch) + ); + let pending = PlePending::test_next(&prior, &identity)?; + txn.stage_ple(&prior, pending)?; + assert_eq!( + txn.stage_ple(&prior, PlePending::test_next(&prior, &identity)?), + Err(Error::IdentityMismatch) + ); + Err(Error::NonFinite) + }); + assert_eq!(result, Err(Error::NonFinite)); + assert!(session.ple_state.is_none()); + assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); + assert_eq!( + session.transact(token(3), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(3), + position(0), + binding.clone(), + ))?; + // Isolate the required PLE publication gate from full-model math. + txn.completed_layers = 2; + txn.forward_output = Some(token(4)); + Ok(token(4)) + }), + Err(Error::Unsupported(Stage::Input)) + ); + assert!(session.ple_state.is_none()); + assert_eq!(session.next_position, 0); +} + +#[test] +fn ple_session_commit_and_reset_preserve_exact_owner_and_prior_identity() { + let binding = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(binding.clone()); + session.layer_count = 2; + session.ple_required = true; + let layer = LayerId::new(1, Dimension::new(2).unwrap()).unwrap(); + session + .transact(token(3), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(3), + position(0), + binding.clone(), + ))?; + let prior = txn.ple_prior()?; + txn.stage_ple( + &prior, + PlePending::test_next(&prior, &TokenLayer::new(token(3), position(0), layer))?, + )?; + // Synthetic markers test state publication, not actual model logits. + txn.completed_layers = 2; + txn.forward_output = Some(token(4)); + Ok(token(4)) + }) + .unwrap(); + let committed = session.ple_state.as_ref().unwrap().clone(); + assert_eq!((session.next_position, committed.next_position()), (1, 1)); + { + let mut txn = session.begin(token(4), position(1)).unwrap(); + assert!(txn.ple_prior().unwrap().same_state(&committed)); + } + assert_eq!( + session.reset_after_completion(Err(Error::CudaExecution)), + Err(Error::CudaExecution) + ); + assert!(session.ple_state.as_ref().unwrap().same_state(&committed)); + assert_eq!( + committed.validate(&binding, &session.ple_owner, position(1)), + Ok(()) + ); + session.reset().unwrap(); + assert!(session.ple_state.is_none()); + assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); + assert_eq!( + committed.validate(&binding, &session.ple_owner, position(1)), + Err(Error::IdentityMismatch) + ); +} + +#[test] +fn gdn_session_late_failure_discards_candidates_and_required_state_cannot_be_skipped() { + let binding = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(binding.clone()); + session.layer_count = 48; + session.gdn_layers[0] = true; + let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap(); + let identity = TokenLayer::new(token(3), position(0), layer); + let result = session.transact(token(3), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(3), + position(0), + binding.clone(), + ))?; + let prior = txn.gdn_prior(layer)?; + let foreign = GdnPrior::zero(binding.clone(), &GdnOwner::new(), layer)?; + assert_eq!( + txn.validate_gdn_prior(&foreign, layer), + Err(Error::IdentityMismatch) + ); + let pending = GdnPending::test_next(&prior, &identity)?; + txn.stage_gdn(&prior, pending)?; + let duplicate = GdnPending::test_next(&prior, &identity)?; + assert_eq!( + txn.stage_gdn(&prior, duplicate), + Err(Error::IdentityMismatch) + ); + Err(Error::NonFinite) + }); + assert_eq!(result, Err(Error::NonFinite)); + assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); + assert!(session.gdn_states[0].is_none()); + assert_eq!( + session.transact(token(3), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(3), + position(0), + binding.clone(), + ))?; + Ok(token(4)) + }), + Err(Error::Unsupported(Stage::Gdn)) + ); + assert_eq!(session.next_position, 0); + assert!(session.gdn_states[0].is_none()); +} + +#[test] +fn gdn_session_commit_advances_all_state_once_and_failed_reset_preserves_owner() { + let binding = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(binding.clone()); + session.layer_count = 48; + session.gdn_layers[0] = true; + let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap(); + session + .transact(token(3), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(3), + position(0), + binding.clone(), + ))?; + let prior = txn.gdn_prior(layer)?; + let pending = + GdnPending::test_next(&prior, &TokenLayer::new(token(3), position(0), layer))?; + txn.stage_gdn(&prior, pending)?; + // Synthetic completion markers isolate recurrent publication; + // this test does not execute layers or produce model logits. + txn.completed_layers = 48; + txn.forward_output = Some(token(4)); + Ok(token(4)) + }) + .unwrap(); + let committed = session.gdn_states[0].as_ref().unwrap().clone(); + assert_eq!((session.next_position, committed.next_position()), (1, 1)); + assert_eq!( + session.reset_after_completion(Err(Error::CudaExecution)), + Err(Error::CudaExecution) + ); + assert!( + session.gdn_states[0] + .as_ref() + .unwrap() + .same_state(&committed) + ); + assert_eq!( + committed.validate(&binding, &session.gdn_owner, layer, position(1)), + Ok(()) + ); + session.reset().unwrap(); + assert!(session.gdn_states[0].is_none()); + assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); + assert_eq!( + committed.validate(&binding, &session.gdn_owner, layer, position(1)), + Err(Error::IdentityMismatch) + ); +} + +#[test] +fn full_forward_guard_refuses_skipped_layers_missing_logits_and_wrong_callback_token() { + let binding = BindingIdentity::test_identity(); + for (completed, proved_output, expected) in [ + (0, Some(token(4)), Error::Unsupported(Stage::Executor)), + (1, None, Error::Unsupported(Stage::Executor)), + (1, Some(token(5)), Error::IdentityMismatch), + ] { + let mut session = QwenSession::test_session(binding.clone()); + session.layer_count = 1; + assert_eq!( + session.transact(token(3), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(3), + position(0), + binding.clone(), + ))?; + txn.completed_layers = completed; + txn.forward_output = proved_output; + Ok(token(4)) + }), + Err(expected) + ); + assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); + } + let mut session = QwenSession::test_session(binding); + session.layer_count = 2; + let mut txn = session.begin(token(3), position(0)).unwrap(); + let bound = Dimension::new(2).unwrap(); + let identity = + |layer| TokenLayer::new(token(3), position(0), LayerId::new(layer, bound).unwrap()); + assert_eq!( + txn.validate_layer_completion(identity(1)), + Err(Error::IdentityMismatch) + ); + assert_eq!(txn.validate_layer_completion(identity(0)), Ok(())); + txn.completed_layers = 1; + assert_eq!( + txn.validate_layer_completion(identity(0)), + Err(Error::IdentityMismatch) + ); + txn.forward_output = Some(token(4)); + assert_eq!( + txn.validate_layer_completion(identity(1)), + Err(Error::IdentityMismatch) + ); +} + +#[test] +fn context_seam_missing_owner_refuses_after_identity_checks() { + let mut session = QwenSession::test_session(BindingIdentity::test_identity()); + let mut txn = session.begin(token(1), position(0)).unwrap(); + assert_eq!( + txn.cuda_context().err(), + Some(Error::Unsupported(Stage::Session)) + ); + txn.binding = BindingIdentity::test_identity(); + assert_eq!(txn.cuda_context().err(), Some(Error::IdentityMismatch)); +} + +#[test] +fn context_seam_wrong_thread_refuses_before_backend_access() { + let mut session = QwenSession::test_session(BindingIdentity::test_identity()); + let mut txn = session.begin(token(1), position(0)).unwrap(); + txn.owner_thread = std::thread::spawn(|| std::thread::current().id()) + .join() + .unwrap(); + assert_eq!(txn.cuda_context().err(), Some(Error::IdentityMismatch)); +} + +#[test] +fn context_seam_failed_reset_keeps_committed_snapshot() { + let mut session = QwenSession::test_session(BindingIdentity::test_identity()); + session.predecessors = [17, 21]; + session.next_position = 2; + session.cuda_failed = true; + let owner = Rc::clone(&session.owner); + assert_eq!( + session.reset_after_completion(Err(Error::CudaExecution)), + Err(Error::CudaExecution) + ); + assert_eq!(session.predecessors, [17, 21]); + assert_eq!(session.next_position, 2); + assert!(Rc::ptr_eq(&owner, &session.owner)); + assert!(session.cuda_failed); + session.reset_after_completion(Ok(())).unwrap(); + assert_eq!(session.predecessors, [-1, -1]); + assert_eq!(session.next_position, 0); + assert!(!Rc::ptr_eq(&owner, &session.owner)); + assert!(!session.cuda_failed); +} + +#[test] +fn context_seam_cuda_failure_blocks_new_steps_without_committing() { + let identity = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(identity.clone()); + assert_eq!( + session.transact(token(1), position(0), &identity, |_| Err( + Error::CudaExecution + )), + Err(Error::CudaExecution) + ); + assert_eq!(session.predecessors, [-1, -1]); + assert_eq!(session.next_position, 0); + assert_eq!( + session.begin(token(1), position(0)).err(), + Some(Error::CudaExecution) + ); + // Contextless fixtures exercise only the local state guard. A real + // device-backed reset additionally requires Context::synchronize. + session.reset().unwrap(); + assert!(session.begin(token(1), position(0)).is_ok()); +} + +#[test] +fn committed_predecessors_advance_oldest_first_and_reset() { + let identity = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(identity.clone()); + + let output = session + .transact(token(17), position(0), &identity, |txn| { + assert_eq!(txn.input_predecessors()?, [-1, -1]); + txn.stage_input(InputReady::test_fixture( + token(17), + position(0), + identity.clone(), + ))?; + Ok(token(18)) + }) + .unwrap(); + assert_eq!(output, token(18)); + + session + .transact(token(21), position(1), &identity, |txn| { + assert_eq!(txn.input_predecessors()?, [-1, 17]); + txn.stage_input(InputReady::test_fixture( + token(21), + position(1), + identity.clone(), + ))?; + Ok(token(22)) + }) + .unwrap(); + + let third = session.begin(token(22), position(2)).unwrap(); + assert_eq!(third.input_predecessors().unwrap(), [17, 21]); + drop(third); + + session.reset().unwrap(); + let fresh = session.begin(token(9), position(0)).unwrap(); + assert_eq!(fresh.input_predecessors().unwrap(), [-1, -1]); +} + +#[test] +fn failed_or_dropped_transaction_does_not_advance_committed_state() { + let identity = BindingIdentity::test_identity(); + let other = BindingIdentity::test_identity(); + let mut session = QwenSession::test_session(identity.clone()); + + assert_eq!( + session.transact(token(3), position(0), &other, |_| Ok(token(8))), + Err(Error::IdentityMismatch) + ); + assert_eq!( + session.transact(token(3), position(0), &identity, |txn| { + assert_eq!(txn.input_predecessors()?, [-1, -1]); + txn.stage_input(InputReady::test_fixture(token(3), position(0), other))?; + Ok(token(4)) + }), + Err(Error::IdentityMismatch) + ); + assert_eq!( + session.transact(token(3), position(0), &identity, |_txn| { + Err(Error::Unsupported(Stage::Input)) + }), + Err(Error::Unsupported(Stage::Input)) + ); + + let current = session.begin(token(4), position(0)).unwrap(); + assert_eq!(current.token(), token(4)); + assert_eq!(current.input_predecessors().unwrap(), [-1, -1]); +} + +#[test] +fn begin_rejects_skips_and_repeats_before_mutation() { + let mut session = QwenSession::test_session(BindingIdentity::test_identity()); + assert_eq!( + session.begin(token(1), position(1)).err(), + Some(Error::InvalidPosition) + ); + let binding = session.binding.clone(); + session + .transact(token(1), position(0), &binding, |txn| { + txn.stage_input(InputReady::test_fixture( + token(1), + position(0), + binding.clone(), + ))?; + Ok(token(2)) + }) + .unwrap(); + assert_eq!( + session.begin(token(1), position(0)).err(), + Some(Error::InvalidPosition) + ); + assert_eq!( + session.begin(token(2), position(1)).unwrap().token(), + token(2) + ); +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk_verify.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify.rs index 3a643a0e..0c3da526 100644 --- a/crates/leleka-runtime/src/qwen_forward/session_chunk_verify.rs +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify.rs @@ -661,187 +661,5 @@ pub(in crate::qwen_forward) trait VerifiedDraftPublication { } #[cfg(test)] -mod tests { - use super::*; - fn token(value: u64) -> TokenId { - TokenId::new(value, Dimension::new(248320).unwrap()).unwrap() - } - #[test] - fn real_head_decision_stops_at_first_rejection_or_eos() { - let ids = [token(10), token(11), token(12)]; - let heads = [token(11), token(12), token(13)]; - let eos_token = token(2); - let eos = Some(eos_token); - assert_eq!( - greedy_prefix(ids[0], None, &ids, &heads), - Ok((3, token(13))) - ); - assert_eq!( - greedy_prefix( - ids[0], - None, - &[ids[0], ids[1], eos_token], - &[ids[1], eos_token, token(13)] - ), - Ok((3, token(13))) - ); - assert_eq!(greedy_prefix(ids[0], eos, &ids, &heads), Ok((3, token(13)))); - assert_eq!( - greedy_prefix(ids[0], eos, &[ids[0], token(99), ids[2]], &heads), - Ok((1, token(11))) - ); - assert_eq!( - greedy_prefix(ids[0], eos, &[ids[0], ids[1], token(99)], &heads), - Ok((2, token(12))) - ); - assert_eq!( - greedy_prefix(ids[0], eos, &ids, &[eos_token, ids[2], token(13)]), - Ok((1, eos_token)) - ); - assert_eq!( - greedy_prefix(ids[0], eos, &[token(99)], &heads[..1]), - Err(Error::IdentityMismatch) - ); - assert_eq!( - greedy_prefix(eos_token, eos, &ids, &heads), - Err(Error::IdentityMismatch) - ); - assert_eq!( - greedy_prefix(ids[0], eos, &ids, &heads[..2]), - Err(Error::IdentityMismatch) - ); - } - #[test] - fn complete_journal_charge_preserves_512_mib_refusal() { - assert_eq!( - verification_extra_charge(0, 1), - Err(Error::InvalidDimension) - ); - assert_eq!( - verification_extra_charge(5, 5), - Err(Error::InvalidDimension) - ); - assert_eq!( - verification_extra_charge(2, 262145), - Err(Error::InvalidDimension) - ); - for rows in [2, 3] { - let charge = host_charge_bounded(rows, rows as u64, 256).unwrap() - + verification_extra_charge(rows, rows as u64).unwrap(); - assert!(charge < HOST_LIMIT); - } - let four = - host_charge_bounded(4, 4, 256).unwrap() + verification_extra_charge(4, 4).unwrap(); - assert!(four > HOST_LIMIT); - assert!( - verification_extra_charge(3, 190000).unwrap() - > verification_extra_charge(3, 3).unwrap() - ); - } - - // This tests private session/phase admission, NOT a ModelBinding, CUDA - // numerical producer, completed model row, or a joint-commit certificate. - fn ple_gdn_fixture<'a>(session: &'a mut QwenSession<'static>) -> QwenChunkTxn<'a, 'static> { - session.layer_count = 48; - session.ple_required = true; - session.gdn_layers[1] = true; - let binding = session.binding.clone(); - let origin = session.target_origin().unwrap(); - let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(); - let input = crate::qwen_forward::input::InputReady::test_fixture(token(3), position, binding); - QwenChunkTxn { - verification: Some(VerificationJournal { - states: vec![PrefixState { ple: None, gdn: std::array::from_fn(|_| None), - device_gdn: std::array::from_fn(|_| None), - qsa: std::array::from_fn(|_| None), head: None }], device_lease: None, - }), - next_ple: None, next_gdn: std::array::from_fn(|_| None), gdn_chunk: None, - next_qsa: std::array::from_fn(|_| None), session, origin, chunk: Rc::new(()), - rows: vec![Row { token: token(3), position, predecessors: [-1, -1], - input: Some(Rc::new(input)), completed: 1 }], - witnesses: Vec::new(), next_layer: 1, next_row: 0, batch_layer: None, - batch_rows: Vec::new(), batch_completed: 0, attention_layer: None, - attention_next: 0, attention_sources: Vec::new(), attention_authorized: None, - known_next: None, output: None, finished: false, aborted: false, end: 1, - windowed: true, micro_cursor: 0, active_micro: None, - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - test_micro_width: 64, - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - test_window_journal: Vec::new(), - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - test_partial_words: 0, - } - } - #[test] - fn ple_journal_admits_only_current_layer_one_gdn_attention_phase() { - use crate::model_binding::qwen4exp_input::BindingIdentity; - use crate::qwen_forward::input::{PleOwner, PlePending}; - let layer = LayerId::new(1, Dimension::new(48).unwrap()).unwrap(); - let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(); - for refusal in 0..16 { - let mut session = QwenSession::test_session(BindingIdentity::test_identity()); - let mut txn = ple_gdn_fixture(&mut session); - // Production constructors mint this actual session's anchor/window. - let start = txn.begin_gdn_chunk(layer).unwrap(); - let window = txn.open_micro_window(layer).unwrap(); - txn.attention_layer = Some(layer); - let prior = PlePrior::zero(txn.session.binding.clone(), &txn.session.ple_owner).unwrap(); - let pending = PlePending::test_next(&prior, - &TokenLayer::new(token(3), position, layer)).unwrap(); - pending.validate(&prior, TokenLayer::new(token(3), position, layer)).unwrap(); - let next = pending.into_prior(); - txn.next_ple = Some(next.clone()); - // Original blanket guard still refuses host GDN prior publication. - assert_eq!(txn.verification_row_position(0, position), Err(Error::IdentityMismatch)); - assert_eq!(txn.record_verification_prior(0, layer, position), Err(Error::IdentityMismatch)); - assert_eq!(txn.record_verification_ple(0, position), Ok(())); - assert!(txn.verification.as_ref().unwrap().states[0].ple.as_ref().unwrap().same_state(&next)); - assert!(txn.verification.as_ref().unwrap().states[0].gdn[1].is_none()); - assert_eq!(txn.gdn_chunk.as_ref().unwrap().accepted, 0); - // Restore the empty private PLE journal slot before each refusal. - txn.verification.as_mut().unwrap().states[0].ple = None; - match refusal { - 0 => txn.chunk = Rc::new(()), - 1 | 2 | 3 => { - let anchor = &start.0; - txn.gdn_chunk.as_mut().unwrap().start = GdnChunkStart(Rc::new(GdnChunkAnchor { - binding: anchor.binding.clone(), chunk: anchor.chunk.clone(), prior: anchor.prior.clone(), - layer: if refusal == 1 { LayerId::new(0, Dimension::new(48).unwrap()).unwrap() } else { anchor.layer }, - first: anchor.first, end: if refusal == 2 { 2 } else { anchor.end }, - count: if refusal == 3 { 2 } else { anchor.count }, - })); - } - 4 => txn.attention_layer = None, - 5 => txn.attention_next = 1, - 6 => txn.rows[0].completed = 0, - 7 => txn.next_row = 1, - 8 => txn.gdn_chunk.as_mut().unwrap().accepted = 1, - 9 => txn.rows[0].position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(), - 10 => { - let foreign = PlePrior::zero(txn.session.binding.clone(), &PleOwner::new()).unwrap(); - txn.next_ple = Some(PlePending::test_next(&foreign, - &TokenLayer::new(token(3), position, layer)).unwrap().into_prior()); - } - 11 => txn.aborted = true, - 12 => txn.session.reset().unwrap(), - 13 => txn.active_micro = None, - 14 => txn.batch_layer = Some(layer), - 15 => txn.attention_authorized = Some(0), - _ => unreachable!(), - } - let error = txn.record_verification_ple(0, position).unwrap_err(); - assert!(matches!(error, Error::IdentityMismatch | Error::Unsupported(Stage::Session))); - assert!(txn.verification.as_ref().unwrap().states[0].ple.is_none()); - assert!(txn.verification.as_ref().unwrap().states[0].gdn[1].is_none()); - drop(window); - } - // The absent-GDN path preserves its existing position/owner/slot rules. - let mut session = QwenSession::test_session(BindingIdentity::test_identity()); - let mut txn = ple_gdn_fixture(&mut session); - let prior = PlePrior::zero(txn.session.binding.clone(), &txn.session.ple_owner).unwrap(); - txn.next_ple = Some(PlePending::test_next(&prior, - &TokenLayer::new(token(3), position, layer)).unwrap().into_prior()); - assert_eq!(txn.record_verification_ple(0, position), Ok(())); - assert_eq!(txn.record_verification_ple(0, position), Err(Error::IdentityMismatch)); - } -} +#[path = "session_chunk_verify/tests.rs"] +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/tests.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/tests.rs new file mode 100644 index 00000000..309ed105 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/tests.rs @@ -0,0 +1,184 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +fn token(value: u64) -> TokenId { + TokenId::new(value, Dimension::new(248320).unwrap()).unwrap() +} +#[test] +fn real_head_decision_stops_at_first_rejection_or_eos() { + let ids = [token(10), token(11), token(12)]; + let heads = [token(11), token(12), token(13)]; + let eos_token = token(2); + let eos = Some(eos_token); + assert_eq!( + greedy_prefix(ids[0], None, &ids, &heads), + Ok((3, token(13))) + ); + assert_eq!( + greedy_prefix( + ids[0], + None, + &[ids[0], ids[1], eos_token], + &[ids[1], eos_token, token(13)] + ), + Ok((3, token(13))) + ); + assert_eq!(greedy_prefix(ids[0], eos, &ids, &heads), Ok((3, token(13)))); + assert_eq!( + greedy_prefix(ids[0], eos, &[ids[0], token(99), ids[2]], &heads), + Ok((1, token(11))) + ); + assert_eq!( + greedy_prefix(ids[0], eos, &[ids[0], ids[1], token(99)], &heads), + Ok((2, token(12))) + ); + assert_eq!( + greedy_prefix(ids[0], eos, &ids, &[eos_token, ids[2], token(13)]), + Ok((1, eos_token)) + ); + assert_eq!( + greedy_prefix(ids[0], eos, &[token(99)], &heads[..1]), + Err(Error::IdentityMismatch) + ); + assert_eq!( + greedy_prefix(eos_token, eos, &ids, &heads), + Err(Error::IdentityMismatch) + ); + assert_eq!( + greedy_prefix(ids[0], eos, &ids, &heads[..2]), + Err(Error::IdentityMismatch) + ); +} +#[test] +fn complete_journal_charge_preserves_512_mib_refusal() { + assert_eq!( + verification_extra_charge(0, 1), + Err(Error::InvalidDimension) + ); + assert_eq!( + verification_extra_charge(5, 5), + Err(Error::InvalidDimension) + ); + assert_eq!( + verification_extra_charge(2, 262145), + Err(Error::InvalidDimension) + ); + for rows in [2, 3] { + let charge = host_charge_bounded(rows, rows as u64, 256).unwrap() + + verification_extra_charge(rows, rows as u64).unwrap(); + assert!(charge < HOST_LIMIT); + } + let four = + host_charge_bounded(4, 4, 256).unwrap() + verification_extra_charge(4, 4).unwrap(); + assert!(four > HOST_LIMIT); + assert!( + verification_extra_charge(3, 190000).unwrap() + > verification_extra_charge(3, 3).unwrap() + ); +} + +// This tests private session/phase admission, NOT a ModelBinding, CUDA +// numerical producer, completed model row, or a joint-commit certificate. +fn ple_gdn_fixture<'a>(session: &'a mut QwenSession<'static>) -> QwenChunkTxn<'a, 'static> { + session.layer_count = 48; + session.ple_required = true; + session.gdn_layers[1] = true; + let binding = session.binding.clone(); + let origin = session.target_origin().unwrap(); + let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(); + let input = crate::qwen_forward::input::InputReady::test_fixture(token(3), position, binding); + QwenChunkTxn { + verification: Some(VerificationJournal { + states: vec![PrefixState { ple: None, gdn: std::array::from_fn(|_| None), + device_gdn: std::array::from_fn(|_| None), + qsa: std::array::from_fn(|_| None), head: None }], device_lease: None, + }), + next_ple: None, next_gdn: std::array::from_fn(|_| None), gdn_chunk: None, + next_qsa: std::array::from_fn(|_| None), session, origin, chunk: Rc::new(()), + rows: vec![Row { token: token(3), position, predecessors: [-1, -1], + input: Some(Rc::new(input)), completed: 1 }], + witnesses: Vec::new(), next_layer: 1, next_row: 0, batch_layer: None, + batch_rows: Vec::new(), batch_completed: 0, attention_layer: None, + attention_next: 0, attention_sources: Vec::new(), attention_authorized: None, + known_next: None, output: None, finished: false, aborted: false, end: 1, + windowed: true, micro_cursor: 0, active_micro: None, + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + test_micro_width: 64, + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + test_window_journal: Vec::new(), + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + test_partial_words: 0, + } +} +#[test] +fn ple_journal_admits_only_current_layer_one_gdn_attention_phase() { + use crate::model_binding::qwen4exp_input::BindingIdentity; + use crate::qwen_forward::input::{PleOwner, PlePending}; + let layer = LayerId::new(1, Dimension::new(48).unwrap()).unwrap(); + let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(); + for refusal in 0..16 { + let mut session = QwenSession::test_session(BindingIdentity::test_identity()); + let mut txn = ple_gdn_fixture(&mut session); + // Production constructors mint this actual session's anchor/window. + let start = txn.begin_gdn_chunk(layer).unwrap(); + let window = txn.open_micro_window(layer).unwrap(); + txn.attention_layer = Some(layer); + let prior = PlePrior::zero(txn.session.binding.clone(), &txn.session.ple_owner).unwrap(); + let pending = PlePending::test_next(&prior, + &TokenLayer::new(token(3), position, layer)).unwrap(); + pending.validate(&prior, TokenLayer::new(token(3), position, layer)).unwrap(); + let next = pending.into_prior(); + txn.next_ple = Some(next.clone()); + // Original blanket guard still refuses host GDN prior publication. + assert_eq!(txn.verification_row_position(0, position), Err(Error::IdentityMismatch)); + assert_eq!(txn.record_verification_prior(0, layer, position), Err(Error::IdentityMismatch)); + assert_eq!(txn.record_verification_ple(0, position), Ok(())); + assert!(txn.verification.as_ref().unwrap().states[0].ple.as_ref().unwrap().same_state(&next)); + assert!(txn.verification.as_ref().unwrap().states[0].gdn[1].is_none()); + assert_eq!(txn.gdn_chunk.as_ref().unwrap().accepted, 0); + // Restore the empty private PLE journal slot before each refusal. + txn.verification.as_mut().unwrap().states[0].ple = None; + match refusal { + 0 => txn.chunk = Rc::new(()), + 1 | 2 | 3 => { + let anchor = &start.0; + txn.gdn_chunk.as_mut().unwrap().start = GdnChunkStart(Rc::new(GdnChunkAnchor { + binding: anchor.binding.clone(), chunk: anchor.chunk.clone(), prior: anchor.prior.clone(), + layer: if refusal == 1 { LayerId::new(0, Dimension::new(48).unwrap()).unwrap() } else { anchor.layer }, + first: anchor.first, end: if refusal == 2 { 2 } else { anchor.end }, + count: if refusal == 3 { 2 } else { anchor.count }, + })); + } + 4 => txn.attention_layer = None, + 5 => txn.attention_next = 1, + 6 => txn.rows[0].completed = 0, + 7 => txn.next_row = 1, + 8 => txn.gdn_chunk.as_mut().unwrap().accepted = 1, + 9 => txn.rows[0].position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(), + 10 => { + let foreign = PlePrior::zero(txn.session.binding.clone(), &PleOwner::new()).unwrap(); + txn.next_ple = Some(PlePending::test_next(&foreign, + &TokenLayer::new(token(3), position, layer)).unwrap().into_prior()); + } + 11 => txn.aborted = true, + 12 => txn.session.reset().unwrap(), + 13 => txn.active_micro = None, + 14 => txn.batch_layer = Some(layer), + 15 => txn.attention_authorized = Some(0), + _ => unreachable!(), + } + let error = txn.record_verification_ple(0, position).unwrap_err(); + assert!(matches!(error, Error::IdentityMismatch | Error::Unsupported(Stage::Session))); + assert!(txn.verification.as_ref().unwrap().states[0].ple.is_none()); + assert!(txn.verification.as_ref().unwrap().states[0].gdn[1].is_none()); + drop(window); + } + // The absent-GDN path preserves its existing position/owner/slot rules. + let mut session = QwenSession::test_session(BindingIdentity::test_identity()); + let mut txn = ple_gdn_fixture(&mut session); + let prior = PlePrior::zero(txn.session.binding.clone(), &txn.session.ple_owner).unwrap(); + txn.next_ple = Some(PlePending::test_next(&prior, + &TokenLayer::new(token(3), position, layer)).unwrap().into_prior()); + assert_eq!(txn.record_verification_ple(0, position), Ok(())); + assert_eq!(txn.record_verification_ple(0, position), Err(Error::IdentityMismatch)); +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_original_verified.rs b/crates/leleka-runtime/src/qwen_forward/session_original_verified.rs index 220319db..464a27bd 100644 --- a/crates/leleka-runtime/src/qwen_forward/session_original_verified.rs +++ b/crates/leleka-runtime/src/qwen_forward/session_original_verified.rs @@ -286,188 +286,5 @@ impl<'driver> QwenSession<'driver> { } #[cfg(test)] -mod tests { - use super::*; - use crate::model_binding::qwen4exp_input::BindingIdentity; - - fn session(gdn: &[usize], ple: bool) -> QwenSession<'static> { - let mut session = QwenSession::test_session(BindingIdentity::test_identity()); - session.layer_count = 48; - session.ple_required = ple; - for &slot in gdn { - session.gdn_layers[slot] = true; - } - session - } - fn gdn_after(prior: &GdnPrior, rows: usize) -> GdnPrior { - GdnPrior::from_original_verified( - prior, - rows, - vec![0.5; 128 * 48 * 128].into_boxed_slice(), - vec![0.25; 10240 * 3].into_boxed_slice(), - ) - .unwrap() - } - /// The priors the verifier would yield after `rows` more committed rows from the base's state position. - fn state_after(session: &QwenSession<'static>, rows: usize) -> OriginalVerifiedLineage<'static> { - let base = session.original_verified_base().unwrap(); - let mut lineage = OriginalVerifiedLineage::empty(); - for slot in 0..STATE_CAPACITY { - lineage.gdn[slot] = base.gdn[slot].as_ref().map(|prior| gdn_after(prior, rows)); - } - lineage.ple = base.ple.as_ref().map(|prior| { - PlePrior::from_original_verified(prior, rows, vec![0.125; 9 * 10240].into_boxed_slice()).unwrap() - }); - lineage - } - - #[test] - fn predecessors_follow_the_last_two_committed_tokens() { - assert_eq!(predecessors_after([-1, -1], &[7]), [-1, 7]); - assert_eq!(predecessors_after([3, 4], &[7]), [4, 7]); - assert_eq!(predecessors_after([3, 4], &[7, 8]), [7, 8]); - assert_eq!(predecessors_after([3, 4], &[7, 8, 9, 10]), [9, 10]); - assert_eq!(predecessors_after([3, 4], &[]), [3, 4]); - } - - #[test] - fn base_at_position_zero_is_the_zero_priors_and_publication_advances_exactly_the_accepted_rows() { - let mut session = session(&[0, 1, 2], true); - let base = session.original_verified_base().unwrap(); - assert_eq!((base.position, base.state_position), (0, 0)); - assert!(base.ple.is_some() && base.qsa.iter().all(Option::is_none)); - assert_eq!(base.gdn.iter().filter(|p| p.is_some()).count(), 3); - let lineage = state_after(&session, 3); - let origin = session.publish_original_verified(&[11, 12, 13], 1000, lineage).unwrap(); - assert_eq!(origin.next_position(), 3); - assert_eq!(session.next_position, 3); - assert_eq!(session.predecessors, [12, 13]); - origin.validate(&session).unwrap(); - // the next round starts from the published priors, not from zero - let base = session.original_verified_base().unwrap(); - assert_eq!((base.position, base.state_position), (3, 3)); - assert_eq!(base.gdn[1].as_ref().unwrap().next_position(), 3); - let lineage = state_after(&session, 1); - let origin = session.publish_original_verified(&[14], 1000, lineage).unwrap(); - assert_eq!((origin.next_position(), session.predecessors), (4, [13, 14])); - } - - #[test] - fn a_refused_publication_leaves_the_session_untouched() { - let mut session = session(&[0, 1], true); - // wrong row count for the priors: the priors end at 2, the accepted prefix at 3 - let lineage = state_after(&session, 2); - assert_eq!(session.publish_original_verified(&[1, 2, 3], 1000, lineage).err(), Some(Error::IdentityMismatch)); - // beyond the context bound - let lineage = state_after(&session, 2); - assert_eq!(session.publish_original_verified(&[1, 2], 1, lineage).err(), Some(Error::InvalidPosition)); - // a missing GDN prior - let mut lineage = state_after(&session, 1); - lineage.gdn[1] = None; - assert_eq!(session.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch)); - // a missing PLE prior while PLE is required, and a spurious one while it is not - let mut lineage = state_after(&session, 1); - lineage.ple = None; - assert_eq!(session.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch)); - let mut plain = self::session(&[0], false); - let mut lineage = state_after(&plain, 1); - lineage.ple = Some(PlePrior::zero(plain.binding.clone(), &plain.ple_owner).unwrap()); - assert_eq!(plain.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch)); - // out-of-range token / window shape - let lineage = state_after(&session, 1); - assert_eq!(session.publish_original_verified(&[248_320], 1000, lineage).err(), Some(Error::InvalidToken)); - assert_eq!( - session.publish_original_verified(&[], 1000, OriginalVerifiedLineage::empty()).err(), - Some(Error::IdentityMismatch) - ); - assert_eq!( - session.publish_original_verified(&[1; 9], 1000, OriginalVerifiedLineage::empty()).err(), - Some(Error::IdentityMismatch) - ); - assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - assert!(session.ple_state.is_none() && session.gdn_states.iter().all(Option::is_none)); - } - - #[test] - fn priors_of_another_owner_or_layer_are_refused() { - let mut session = session(&[0, 1], false); - let mut other = self::session(&[0, 1], false); - // a prior derived from another session's owner - let foreign = state_after(&other, 1); - assert_eq!(session.publish_original_verified(&[1], 1000, foreign).err(), Some(Error::IdentityMismatch)); - // a prior for the wrong layer in a slot - let mut lineage = state_after(&session, 1); - let swapped = lineage.gdn[0].take(); - lineage.gdn[1] = swapped; - assert_eq!(session.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch)); - assert_eq!(session.next_position, 0); - // the other session is unaffected and still publishes - let ok = state_after(&other, 1); - other.publish_original_verified(&[5], 1000, ok).unwrap(); - assert_eq!(other.next_position, 1); - } - - #[test] - fn rounds_advance_the_lineage_while_the_recurrent_state_lags_and_the_end_of_phase_publication_closes_it() { - let mut session = session(&[0, 1], true); - assert_eq!(session.original_state_lag(), None); - // three committed rounds (no QSA layers in this fixture), 2 + 1 + 3 rows - session.publish_original_verified_rows(&[10, 11], 1000, std::array::from_fn(|_| None)).unwrap(); - assert_eq!((session.next_position, session.original_state_lag()), (2, Some(0))); - session.publish_original_verified_rows(&[12], 1000, std::array::from_fn(|_| None)).unwrap(); - let origin = session.publish_original_verified_rows(&[13, 14, 15], 1000, std::array::from_fn(|_| None)).unwrap(); - assert_eq!((origin.next_position(), session.predecessors), (6, [14, 15])); - assert_eq!(session.original_state_lag(), Some(0), "the lag anchor is where the priors stand, not the last round"); - // the host priors still stand at 0 and the base says so - let base = session.original_verified_base().unwrap(); - assert_eq!((base.position, base.state_position), (6, 0)); - // priors at the wrong position are refused; the exact position closes the lag - let wrong = state_after(&session, 5); - assert_eq!(session.publish_original_resident_state(wrong.gdn, wrong.ple).err(), Some(Error::IdentityMismatch)); - assert_eq!(session.original_state_lag(), Some(0)); - let right = state_after(&session, 6); - session.publish_original_resident_state(right.gdn, right.ple).unwrap(); - assert_eq!(session.original_state_lag(), None); - let base = session.original_verified_base().unwrap(); - assert_eq!((base.position, base.state_position), (6, 6)); - assert_eq!(base.gdn[0].as_ref().unwrap().next_position(), 6); - // nothing to close any more - let again = state_after(&session, 1); - assert_eq!(session.publish_original_resident_state(again.gdn, again.ple).err(), Some(Error::IdentityMismatch)); - // the all-at-once path continues from the closed state - let next = state_after(&session, 1); - session.publish_original_verified(&[20], 1000, next).unwrap(); - assert_eq!(session.next_position, 7); - } - - #[test] - fn the_all_at_once_publication_refuses_an_open_lag_and_round_publication_enforces_the_same_bounds() { - let mut session = session(&[0], false); - session.publish_original_verified_rows(&[1], 100, std::array::from_fn(|_| None)).unwrap(); - let lineage = state_after(&session, 2); - assert_eq!(session.publish_original_verified(&[2], 100, lineage).err(), Some(Error::IdentityMismatch)); - assert_eq!( - session.publish_original_verified_rows(&[2; 9], 100, std::array::from_fn(|_| None)).err(), - Some(Error::IdentityMismatch) - ); - assert_eq!( - session.publish_original_verified_rows(&[2, 3], 2, std::array::from_fn(|_| None)).err(), - Some(Error::InvalidPosition) - ); - assert_eq!( - session.publish_original_verified_rows(&[-1], 100, std::array::from_fn(|_| None)).err(), - Some(Error::InvalidToken) - ); - assert_eq!((session.next_position, session.predecessors), (1, [-1, 1])); - } - - #[test] - fn origin_after_names_the_future_position_without_advancing() { - let session = session(&[0], false); - let after = session.original_origin_after(4).unwrap(); - assert_eq!(after.next_position(), 4); - assert!(after.validate(&session).is_err(), "a future origin is not valid until the session advanced"); - assert!(after.validate_projection_branch(&session).is_ok()); - assert_eq!(session.next_position, 0); - } -} +#[path = "session_original_verified/tests.rs"] +mod tests; diff --git a/crates/leleka-runtime/src/qwen_forward/session_original_verified/tests.rs b/crates/leleka-runtime/src/qwen_forward/session_original_verified/tests.rs new file mode 100644 index 00000000..63901d01 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_original_verified/tests.rs @@ -0,0 +1,185 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::model_binding::qwen4exp_input::BindingIdentity; + +fn session(gdn: &[usize], ple: bool) -> QwenSession<'static> { + let mut session = QwenSession::test_session(BindingIdentity::test_identity()); + session.layer_count = 48; + session.ple_required = ple; + for &slot in gdn { + session.gdn_layers[slot] = true; + } + session +} +fn gdn_after(prior: &GdnPrior, rows: usize) -> GdnPrior { + GdnPrior::from_original_verified( + prior, + rows, + vec![0.5; 128 * 48 * 128].into_boxed_slice(), + vec![0.25; 10240 * 3].into_boxed_slice(), + ) + .unwrap() +} +/// The priors the verifier would yield after `rows` more committed rows from the base's state position. +fn state_after(session: &QwenSession<'static>, rows: usize) -> OriginalVerifiedLineage<'static> { + let base = session.original_verified_base().unwrap(); + let mut lineage = OriginalVerifiedLineage::empty(); + for slot in 0..STATE_CAPACITY { + lineage.gdn[slot] = base.gdn[slot].as_ref().map(|prior| gdn_after(prior, rows)); + } + lineage.ple = base.ple.as_ref().map(|prior| { + PlePrior::from_original_verified(prior, rows, vec![0.125; 9 * 10240].into_boxed_slice()).unwrap() + }); + lineage +} + +#[test] +fn predecessors_follow_the_last_two_committed_tokens() { + assert_eq!(predecessors_after([-1, -1], &[7]), [-1, 7]); + assert_eq!(predecessors_after([3, 4], &[7]), [4, 7]); + assert_eq!(predecessors_after([3, 4], &[7, 8]), [7, 8]); + assert_eq!(predecessors_after([3, 4], &[7, 8, 9, 10]), [9, 10]); + assert_eq!(predecessors_after([3, 4], &[]), [3, 4]); +} + +#[test] +fn base_at_position_zero_is_the_zero_priors_and_publication_advances_exactly_the_accepted_rows() { + let mut session = session(&[0, 1, 2], true); + let base = session.original_verified_base().unwrap(); + assert_eq!((base.position, base.state_position), (0, 0)); + assert!(base.ple.is_some() && base.qsa.iter().all(Option::is_none)); + assert_eq!(base.gdn.iter().filter(|p| p.is_some()).count(), 3); + let lineage = state_after(&session, 3); + let origin = session.publish_original_verified(&[11, 12, 13], 1000, lineage).unwrap(); + assert_eq!(origin.next_position(), 3); + assert_eq!(session.next_position, 3); + assert_eq!(session.predecessors, [12, 13]); + origin.validate(&session).unwrap(); + // the next round starts from the published priors, not from zero + let base = session.original_verified_base().unwrap(); + assert_eq!((base.position, base.state_position), (3, 3)); + assert_eq!(base.gdn[1].as_ref().unwrap().next_position(), 3); + let lineage = state_after(&session, 1); + let origin = session.publish_original_verified(&[14], 1000, lineage).unwrap(); + assert_eq!((origin.next_position(), session.predecessors), (4, [13, 14])); +} + +#[test] +fn a_refused_publication_leaves_the_session_untouched() { + let mut session = session(&[0, 1], true); + // wrong row count for the priors: the priors end at 2, the accepted prefix at 3 + let lineage = state_after(&session, 2); + assert_eq!(session.publish_original_verified(&[1, 2, 3], 1000, lineage).err(), Some(Error::IdentityMismatch)); + // beyond the context bound + let lineage = state_after(&session, 2); + assert_eq!(session.publish_original_verified(&[1, 2], 1, lineage).err(), Some(Error::InvalidPosition)); + // a missing GDN prior + let mut lineage = state_after(&session, 1); + lineage.gdn[1] = None; + assert_eq!(session.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch)); + // a missing PLE prior while PLE is required, and a spurious one while it is not + let mut lineage = state_after(&session, 1); + lineage.ple = None; + assert_eq!(session.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch)); + let mut plain = self::session(&[0], false); + let mut lineage = state_after(&plain, 1); + lineage.ple = Some(PlePrior::zero(plain.binding.clone(), &plain.ple_owner).unwrap()); + assert_eq!(plain.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch)); + // out-of-range token / window shape + let lineage = state_after(&session, 1); + assert_eq!(session.publish_original_verified(&[248_320], 1000, lineage).err(), Some(Error::InvalidToken)); + assert_eq!( + session.publish_original_verified(&[], 1000, OriginalVerifiedLineage::empty()).err(), + Some(Error::IdentityMismatch) + ); + assert_eq!( + session.publish_original_verified(&[1; 9], 1000, OriginalVerifiedLineage::empty()).err(), + Some(Error::IdentityMismatch) + ); + assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); + assert!(session.ple_state.is_none() && session.gdn_states.iter().all(Option::is_none)); +} + +#[test] +fn priors_of_another_owner_or_layer_are_refused() { + let mut session = session(&[0, 1], false); + let mut other = self::session(&[0, 1], false); + // a prior derived from another session's owner + let foreign = state_after(&other, 1); + assert_eq!(session.publish_original_verified(&[1], 1000, foreign).err(), Some(Error::IdentityMismatch)); + // a prior for the wrong layer in a slot + let mut lineage = state_after(&session, 1); + let swapped = lineage.gdn[0].take(); + lineage.gdn[1] = swapped; + assert_eq!(session.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch)); + assert_eq!(session.next_position, 0); + // the other session is unaffected and still publishes + let ok = state_after(&other, 1); + other.publish_original_verified(&[5], 1000, ok).unwrap(); + assert_eq!(other.next_position, 1); +} + +#[test] +fn rounds_advance_the_lineage_while_the_recurrent_state_lags_and_the_end_of_phase_publication_closes_it() { + let mut session = session(&[0, 1], true); + assert_eq!(session.original_state_lag(), None); + // three committed rounds (no QSA layers in this fixture), 2 + 1 + 3 rows + session.publish_original_verified_rows(&[10, 11], 1000, std::array::from_fn(|_| None)).unwrap(); + assert_eq!((session.next_position, session.original_state_lag()), (2, Some(0))); + session.publish_original_verified_rows(&[12], 1000, std::array::from_fn(|_| None)).unwrap(); + let origin = session.publish_original_verified_rows(&[13, 14, 15], 1000, std::array::from_fn(|_| None)).unwrap(); + assert_eq!((origin.next_position(), session.predecessors), (6, [14, 15])); + assert_eq!(session.original_state_lag(), Some(0), "the lag anchor is where the priors stand, not the last round"); + // the host priors still stand at 0 and the base says so + let base = session.original_verified_base().unwrap(); + assert_eq!((base.position, base.state_position), (6, 0)); + // priors at the wrong position are refused; the exact position closes the lag + let wrong = state_after(&session, 5); + assert_eq!(session.publish_original_resident_state(wrong.gdn, wrong.ple).err(), Some(Error::IdentityMismatch)); + assert_eq!(session.original_state_lag(), Some(0)); + let right = state_after(&session, 6); + session.publish_original_resident_state(right.gdn, right.ple).unwrap(); + assert_eq!(session.original_state_lag(), None); + let base = session.original_verified_base().unwrap(); + assert_eq!((base.position, base.state_position), (6, 6)); + assert_eq!(base.gdn[0].as_ref().unwrap().next_position(), 6); + // nothing to close any more + let again = state_after(&session, 1); + assert_eq!(session.publish_original_resident_state(again.gdn, again.ple).err(), Some(Error::IdentityMismatch)); + // the all-at-once path continues from the closed state + let next = state_after(&session, 1); + session.publish_original_verified(&[20], 1000, next).unwrap(); + assert_eq!(session.next_position, 7); +} + +#[test] +fn the_all_at_once_publication_refuses_an_open_lag_and_round_publication_enforces_the_same_bounds() { + let mut session = session(&[0], false); + session.publish_original_verified_rows(&[1], 100, std::array::from_fn(|_| None)).unwrap(); + let lineage = state_after(&session, 2); + assert_eq!(session.publish_original_verified(&[2], 100, lineage).err(), Some(Error::IdentityMismatch)); + assert_eq!( + session.publish_original_verified_rows(&[2; 9], 100, std::array::from_fn(|_| None)).err(), + Some(Error::IdentityMismatch) + ); + assert_eq!( + session.publish_original_verified_rows(&[2, 3], 2, std::array::from_fn(|_| None)).err(), + Some(Error::InvalidPosition) + ); + assert_eq!( + session.publish_original_verified_rows(&[-1], 100, std::array::from_fn(|_| None)).err(), + Some(Error::InvalidToken) + ); + assert_eq!((session.next_position, session.predecessors), (1, [-1, 1])); +} + +#[test] +fn origin_after_names_the_future_position_without_advancing() { + let session = session(&[0], false); + let after = session.original_origin_after(4).unwrap(); + assert_eq!(after.next_position(), 4); + assert!(after.validate(&session).is_err(), "a future origin is not valid until the session advanced"); + assert!(after.validate_projection_branch(&session).is_ok()); + assert_eq!(session.next_position, 0); +} diff --git a/crates/leleka-runtime/src/serve_meta.rs b/crates/leleka-runtime/src/serve_meta.rs index c1438323..d7ff3d14 100644 --- a/crates/leleka-runtime/src/serve_meta.rs +++ b/crates/leleka-runtime/src/serve_meta.rs @@ -244,175 +244,4 @@ pub(crate) fn emit(lines: &[String]) { } #[cfg(test)] -mod tests { - use super::*; - - const DIGEST: &str = "sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"; - const PROFILE_SHA: &str = "b5ebb652ad9b091e0e045e44d8adeb49fa7319c2f365c2ad150a3d567221e0cb"; - const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567"; - - pub(super) fn build() -> BuildInfo { - BuildInfo { - commit: COMMIT.to_owned(), - dirty: "0".to_owned(), - target: "x86_64-unknown-linux-gnu".to_owned(), - features: "sm86".to_owned(), - cargo_profile: "release".to_owned(), - } - } - pub(super) fn config() -> ConfigFacts { - ConfigFacts { - context_tokens: 262_144, - chunk: 8192, - prefix_block: Some(8192), - prefix_tail: "reply", - cpu_workers: 15, - kv: "int8".to_owned(), - kv_resident_cells: 32_768, - expert_tier: "auto".to_owned(), - expert_per_layer: true, - expert_profile: true, - pcie_frac: 0.45, - spec_min_p: 0.0, - } - } - pub(super) fn model() -> ModelInfo { - ModelInfo { - digest: DIGEST.to_owned(), - files: vec![ - ModelFile { name: "model-00001-of-00002.gguf".to_owned(), bytes: Some(54_817_524_224), mtime_unix_s: Some(1_790_000_000) }, - ModelFile { name: "model-00002-of-00002.gguf".to_owned(), bytes: Some(28_800_138_432), mtime_unix_s: Some(1_790_000_001) }, - ], - } - } - pub(super) fn profile() -> ProfileInfo { - ProfileInfo::from_values(Some("rtx5090-32g"), Some(PROFILE_SHA)) - } - pub(super) fn cache() -> CacheFacts { - CacheFacts { prefix_on: true, prefix_entries: 0, prefix_blocks: 0, prefix_used_bytes: 0, prefix_budget_bytes: 5_713_000_000 } - } - - /// The golden sample is shared with `scripts/e2e/evidence` (capture.py parses the same file): this pins the format of every line. - #[test] - fn the_meta_lines_match_the_golden_sample_byte_for_byte() { - let mut lines = startup_lines(&build(), &profile(), &model(), &config()); - lines.push(cache_line(&cache())); - let produced: String = lines.iter().map(|l| format!("leleka-serve {l}\n")).collect(); - let golden = include_str!("../../../scripts/e2e/evidence/golden/engine_meta_sample.txt").replace("\r\n", "\n"); - let golden_meta: String = golden.lines().filter(|l| l.starts_with("leleka-serve meta: ")).map(|l| format!("{l}\n")).collect(); - assert_eq!(produced, golden_meta); - } - - #[test] - fn the_lines_are_exact() { - let lines = startup_lines(&build(), &profile(), &model(), &config()); - assert_eq!(lines.len(), 3); - assert_eq!( - lines[0], - format!( - "meta: build v=1 commit={COMMIT} dirty=0 target=x86_64-unknown-linux-gnu features=sm86 cargo_profile=release profile=rtx5090-32g profile_sha256={PROFILE_SHA} values_sha256={}", - config().values_sha256() - ) - ); - assert_eq!( - lines[1], - format!( - "meta: model v=1 digest={DIGEST} mapping={MODEL_DIGEST_MAPPING} verify=recorded-no-rehash files=2 file0=model-00001-of-00002.gguf:54817524224:1790000000 file1=model-00002-of-00002.gguf:28800138432:1790000001" - ) - ); - assert_eq!( - lines[2], - "meta: config v=1 context_tokens=262144 kv=int8 slots=1 batch=8192 speculation=mtp spec_min_p=0 chunk=8192 prefix_cache=on prefix_block=8192 prefix_tail=reply cpu_workers=15 kv_resident=32768 expert_tier=auto expert_per_layer=1 expert_profile=1 pcie_frac=0.45" - ); - assert_eq!( - cache_line(&cache()), - "meta: cache v=1 engine_state=EMPTY prefix_cache=on prefix_entries=0 prefix_blocks=0 prefix_used_bytes=0 prefix_budget_bytes=5713000000 os_page_cache=not-probed" - ); - } - - #[test] - fn every_line_is_one_section_of_single_blank_separated_key_value_tokens() { - let mut lines = startup_lines(&build(), &ProfileInfo::from_values(None, None), &model(), &config()); - lines.push(cache_line(&cache())); - for l in &lines { - let mut tokens = l.split(' '); - assert_eq!(tokens.next(), Some("meta:")); - let section = tokens.next().unwrap(); - assert!(["build", "model", "config", "cache"].contains(§ion), "{l}"); - assert_eq!(tokens.next(), Some("v=1"), "{l}"); - for t in tokens { - let (key, value) = t.split_once('=').unwrap_or_else(|| panic!("token without = in {l}")); - assert!(!key.is_empty() && !value.is_empty() && !value.contains('='), "{t} in {l}"); - } - assert!(!l.contains(" ") && !l.contains('\n') && !l.contains('\r')); - } - } - - #[test] - fn an_unset_profile_is_printed_as_none_and_unset_and_a_bad_hash_is_refused() { - let lines = startup_lines(&build(), &ProfileInfo::from_values(None, None), &model(), &config()); - assert!(lines[0].contains(" profile=none profile_sha256=unset values_sha256=")); - assert_eq!(ProfileInfo::from_values(Some(" "), Some("not-a-hash")), ProfileInfo { name: None, sha256: None }); - assert_eq!(ProfileInfo::from_values(Some("x"), Some(&PROFILE_SHA.to_ascii_uppercase())).sha256.as_deref(), Some(PROFILE_SHA)); - } - - #[test] - fn values_sha256_follows_the_values_and_nothing_else() { - let base = config(); - assert_eq!(base.values_sha256(), config().values_sha256()); - assert_eq!(base.values_sha256().len(), 64); - for changed in [ - ConfigFacts { chunk: 2048, ..config() }, - ConfigFacts { cpu_workers: 14, ..config() }, - ConfigFacts { prefix_block: None, prefix_tail: "none", ..config() }, - ConfigFacts { expert_tier: "off".to_owned(), ..config() }, - ConfigFacts { kv_resident_cells: 0, ..config() }, - ] { - assert_ne!(base.values_sha256(), changed.values_sha256()); - } - } - - #[test] - fn values_with_blanks_or_equals_cannot_split_a_token() { - let odd = ModelInfo { digest: "sha256:a b=c".to_owned(), files: vec![ModelFile { name: "my model=1.gguf".to_owned(), bytes: None, mtime_unix_s: None }] }; - let lines = startup_lines(&build(), &profile(), &odd, &config()); - assert!(lines[1].contains(" digest=sha256:a_b_c "), "{}", lines[1]); - assert!(lines[1].ends_with(" file0=my_model_1.gguf:-:-"), "{}", lines[1]); - assert_eq!(token(""), "-"); - } - - #[test] - fn a_cache_with_entries_is_warm() { - let warm = CacheFacts { prefix_entries: 3, prefix_blocks: 12, prefix_used_bytes: 7, ..cache() }; - assert!(cache_line(&warm).contains(" engine_state=WARM ")); - let off = CacheFacts { prefix_on: false, prefix_budget_bytes: 0, ..cache() }; - assert!(cache_line(&off).contains(" engine_state=EMPTY prefix_cache=off ")); - } - - /// Start-up reads file metadata only: a missing file is `-`, an existing one is its length and mtime, and nothing reads its content. - #[test] - fn model_files_are_statted_never_read() { - let missing = ModelFile::stat(Path::new("/definitely/not/here/model.gguf")); - assert_eq!((missing.name.as_str(), missing.bytes, missing.mtime_unix_s), ("model.gguf", None, None)); - let here = ModelFile::stat(Path::new(file!())); - assert!(here.bytes.is_none() || here.bytes.unwrap() > 0); - } - - /// The formatting is a pure function of its inputs (no clock, no environment, no file): the same inputs give the same lines, so enabling the - /// report cannot change a result that does not read stderr. - #[test] - fn formatting_is_deterministic() { - let a = startup_lines(&build(), &profile(), &model(), &config()); - let b = startup_lines(&build(), &profile(), &model(), &config()); - assert_eq!(a, b); - } - - #[test] - fn this_build_reports_its_own_identity() { - let current = BuildInfo::current(); - assert!(!current.commit.is_empty() && !current.target.is_empty() && !current.features.is_empty()); - assert!(["0", "1", "unknown"].contains(¤t.dirty.as_str())); - assert!(current.commit == "unknown" || current.commit.len() >= 7, "{}", current.commit); - assert!(!current.commit.contains(char::is_whitespace) && !current.features.contains(char::is_whitespace)); - } -} +mod tests; diff --git a/crates/leleka-runtime/src/serve_meta/tests.rs b/crates/leleka-runtime/src/serve_meta/tests.rs new file mode 100644 index 00000000..cfa374b9 --- /dev/null +++ b/crates/leleka-runtime/src/serve_meta/tests.rs @@ -0,0 +1,172 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +const DIGEST: &str = "sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"; +const PROFILE_SHA: &str = "b5ebb652ad9b091e0e045e44d8adeb49fa7319c2f365c2ad150a3d567221e0cb"; +const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567"; + +pub(super) fn build() -> BuildInfo { + BuildInfo { + commit: COMMIT.to_owned(), + dirty: "0".to_owned(), + target: "x86_64-unknown-linux-gnu".to_owned(), + features: "sm86".to_owned(), + cargo_profile: "release".to_owned(), + } +} +pub(super) fn config() -> ConfigFacts { + ConfigFacts { + context_tokens: 262_144, + chunk: 8192, + prefix_block: Some(8192), + prefix_tail: "reply", + cpu_workers: 15, + kv: "int8".to_owned(), + kv_resident_cells: 32_768, + expert_tier: "auto".to_owned(), + expert_per_layer: true, + expert_profile: true, + pcie_frac: 0.45, + spec_min_p: 0.0, + } +} +pub(super) fn model() -> ModelInfo { + ModelInfo { + digest: DIGEST.to_owned(), + files: vec![ + ModelFile { name: "model-00001-of-00002.gguf".to_owned(), bytes: Some(54_817_524_224), mtime_unix_s: Some(1_790_000_000) }, + ModelFile { name: "model-00002-of-00002.gguf".to_owned(), bytes: Some(28_800_138_432), mtime_unix_s: Some(1_790_000_001) }, + ], + } +} +pub(super) fn profile() -> ProfileInfo { + ProfileInfo::from_values(Some("rtx5090-32g"), Some(PROFILE_SHA)) +} +pub(super) fn cache() -> CacheFacts { + CacheFacts { prefix_on: true, prefix_entries: 0, prefix_blocks: 0, prefix_used_bytes: 0, prefix_budget_bytes: 5_713_000_000 } +} + +/// The golden sample is shared with `scripts/e2e/evidence` (capture.py parses the same file): this pins the format of every line. +#[test] +fn the_meta_lines_match_the_golden_sample_byte_for_byte() { + let mut lines = startup_lines(&build(), &profile(), &model(), &config()); + lines.push(cache_line(&cache())); + let produced: String = lines.iter().map(|l| format!("leleka-serve {l}\n")).collect(); + let golden = include_str!("../../../../scripts/e2e/evidence/golden/engine_meta_sample.txt").replace("\r\n", "\n"); + let golden_meta: String = golden.lines().filter(|l| l.starts_with("leleka-serve meta: ")).map(|l| format!("{l}\n")).collect(); + assert_eq!(produced, golden_meta); +} + +#[test] +fn the_lines_are_exact() { + let lines = startup_lines(&build(), &profile(), &model(), &config()); + assert_eq!(lines.len(), 3); + assert_eq!( + lines[0], + format!( + "meta: build v=1 commit={COMMIT} dirty=0 target=x86_64-unknown-linux-gnu features=sm86 cargo_profile=release profile=rtx5090-32g profile_sha256={PROFILE_SHA} values_sha256={}", + config().values_sha256() + ) + ); + assert_eq!( + lines[1], + format!( + "meta: model v=1 digest={DIGEST} mapping={MODEL_DIGEST_MAPPING} verify=recorded-no-rehash files=2 file0=model-00001-of-00002.gguf:54817524224:1790000000 file1=model-00002-of-00002.gguf:28800138432:1790000001" + ) + ); + assert_eq!( + lines[2], + "meta: config v=1 context_tokens=262144 kv=int8 slots=1 batch=8192 speculation=mtp spec_min_p=0 chunk=8192 prefix_cache=on prefix_block=8192 prefix_tail=reply cpu_workers=15 kv_resident=32768 expert_tier=auto expert_per_layer=1 expert_profile=1 pcie_frac=0.45" + ); + assert_eq!( + cache_line(&cache()), + "meta: cache v=1 engine_state=EMPTY prefix_cache=on prefix_entries=0 prefix_blocks=0 prefix_used_bytes=0 prefix_budget_bytes=5713000000 os_page_cache=not-probed" + ); +} + +#[test] +fn every_line_is_one_section_of_single_blank_separated_key_value_tokens() { + let mut lines = startup_lines(&build(), &ProfileInfo::from_values(None, None), &model(), &config()); + lines.push(cache_line(&cache())); + for l in &lines { + let mut tokens = l.split(' '); + assert_eq!(tokens.next(), Some("meta:")); + let section = tokens.next().unwrap(); + assert!(["build", "model", "config", "cache"].contains(§ion), "{l}"); + assert_eq!(tokens.next(), Some("v=1"), "{l}"); + for t in tokens { + let (key, value) = t.split_once('=').unwrap_or_else(|| panic!("token without = in {l}")); + assert!(!key.is_empty() && !value.is_empty() && !value.contains('='), "{t} in {l}"); + } + assert!(!l.contains(" ") && !l.contains('\n') && !l.contains('\r')); + } +} + +#[test] +fn an_unset_profile_is_printed_as_none_and_unset_and_a_bad_hash_is_refused() { + let lines = startup_lines(&build(), &ProfileInfo::from_values(None, None), &model(), &config()); + assert!(lines[0].contains(" profile=none profile_sha256=unset values_sha256=")); + assert_eq!(ProfileInfo::from_values(Some(" "), Some("not-a-hash")), ProfileInfo { name: None, sha256: None }); + assert_eq!(ProfileInfo::from_values(Some("x"), Some(&PROFILE_SHA.to_ascii_uppercase())).sha256.as_deref(), Some(PROFILE_SHA)); +} + +#[test] +fn values_sha256_follows_the_values_and_nothing_else() { + let base = config(); + assert_eq!(base.values_sha256(), config().values_sha256()); + assert_eq!(base.values_sha256().len(), 64); + for changed in [ + ConfigFacts { chunk: 2048, ..config() }, + ConfigFacts { cpu_workers: 14, ..config() }, + ConfigFacts { prefix_block: None, prefix_tail: "none", ..config() }, + ConfigFacts { expert_tier: "off".to_owned(), ..config() }, + ConfigFacts { kv_resident_cells: 0, ..config() }, + ] { + assert_ne!(base.values_sha256(), changed.values_sha256()); + } +} + +#[test] +fn values_with_blanks_or_equals_cannot_split_a_token() { + let odd = ModelInfo { digest: "sha256:a b=c".to_owned(), files: vec![ModelFile { name: "my model=1.gguf".to_owned(), bytes: None, mtime_unix_s: None }] }; + let lines = startup_lines(&build(), &profile(), &odd, &config()); + assert!(lines[1].contains(" digest=sha256:a_b_c "), "{}", lines[1]); + assert!(lines[1].ends_with(" file0=my_model_1.gguf:-:-"), "{}", lines[1]); + assert_eq!(token(""), "-"); +} + +#[test] +fn a_cache_with_entries_is_warm() { + let warm = CacheFacts { prefix_entries: 3, prefix_blocks: 12, prefix_used_bytes: 7, ..cache() }; + assert!(cache_line(&warm).contains(" engine_state=WARM ")); + let off = CacheFacts { prefix_on: false, prefix_budget_bytes: 0, ..cache() }; + assert!(cache_line(&off).contains(" engine_state=EMPTY prefix_cache=off ")); +} + +/// Start-up reads file metadata only: a missing file is `-`, an existing one is its length and mtime, and nothing reads its content. +#[test] +fn model_files_are_statted_never_read() { + let missing = ModelFile::stat(Path::new("/definitely/not/here/model.gguf")); + assert_eq!((missing.name.as_str(), missing.bytes, missing.mtime_unix_s), ("model.gguf", None, None)); + let here = ModelFile::stat(Path::new(file!())); + assert!(here.bytes.is_none() || here.bytes.unwrap() > 0); +} + +/// The formatting is a pure function of its inputs (no clock, no environment, no file): the same inputs give the same lines, so enabling the +/// report cannot change a result that does not read stderr. +#[test] +fn formatting_is_deterministic() { + let a = startup_lines(&build(), &profile(), &model(), &config()); + let b = startup_lines(&build(), &profile(), &model(), &config()); + assert_eq!(a, b); +} + +#[test] +fn this_build_reports_its_own_identity() { + let current = BuildInfo::current(); + assert!(!current.commit.is_empty() && !current.target.is_empty() && !current.features.is_empty()); + assert!(["0", "1", "unknown"].contains(¤t.dirty.as_str())); + assert!(current.commit == "unknown" || current.commit.len() >= 7, "{}", current.commit); + assert!(!current.commit.contains(char::is_whitespace) && !current.features.contains(char::is_whitespace)); +} diff --git a/crates/libc-shim/src/cuda_trace.rs b/crates/libc-shim/src/cuda_trace.rs index 10319058..82a568d7 100644 --- a/crates/libc-shim/src/cuda_trace.rs +++ b/crates/libc-shim/src/cuda_trace.rs @@ -446,29 +446,4 @@ pub(crate) fn interpose(handle: *mut c_void, symbol: &CStr, real: *mut c_void) - } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn untouched_symbols_and_foreign_handles_pass_through() { - let marker = 0x1234usize as *mut c_void; - assert_eq!(interpose(std::ptr::null_mut(), c"cuLaunchKernel", marker), marker); - assert_eq!(interpose(marker, c"cuLaunchKernel", marker), marker); - assert_eq!(interpose(nvcuda(), c"cuInit", marker), marker); - } - - #[test] - fn a_batched_copy_is_described_by_its_count_and_stream() { - let s = State { ring: vec![None; 4], next: 1, names: HashMap::new(), stream_ok: HashMap::new(), ctx_ok: 0, capturing: HashMap::new(), failures: 0, streams: Vec::new() }; - let e = Entry { seq: 9, a: 0x1000, b: 0x2000, n: 21, stream: 0x30, ..blank("batch-async") }; - assert_eq!(describe(&s, &e), "#9 batch-async copies 21 dsts 0x1000 srcs 0x2000 stream 0x30"); - } - - #[test] - fn the_ring_describes_a_kernel_by_name() { - let mut s = State { ring: vec![None; 4], next: 1, names: HashMap::new(), stream_ok: HashMap::new(), ctx_ok: 0, capturing: HashMap::new(), failures: 0, streams: Vec::new() }; - s.names.insert(7, "k_moe".into()); - let e = Entry { seq: 3, a: 7, grid: [2, 1, 1], block: [128, 1, 1], smem: 4096, stream: 0x10, ..blank("kernel") }; - assert_eq!(describe(&s, &e), "#3 kernel k_moe grid 2x1x1 block 128x1x1 smem 4096 stream 0x10"); - } -} +mod tests; diff --git a/crates/libc-shim/src/cuda_trace/tests.rs b/crates/libc-shim/src/cuda_trace/tests.rs new file mode 100644 index 00000000..a8761867 --- /dev/null +++ b/crates/libc-shim/src/cuda_trace/tests.rs @@ -0,0 +1,26 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn untouched_symbols_and_foreign_handles_pass_through() { + let marker = 0x1234usize as *mut c_void; + assert_eq!(interpose(std::ptr::null_mut(), c"cuLaunchKernel", marker), marker); + assert_eq!(interpose(marker, c"cuLaunchKernel", marker), marker); + assert_eq!(interpose(nvcuda(), c"cuInit", marker), marker); +} + +#[test] +fn a_batched_copy_is_described_by_its_count_and_stream() { + let s = State { ring: vec![None; 4], next: 1, names: HashMap::new(), stream_ok: HashMap::new(), ctx_ok: 0, capturing: HashMap::new(), failures: 0, streams: Vec::new() }; + let e = Entry { seq: 9, a: 0x1000, b: 0x2000, n: 21, stream: 0x30, ..blank("batch-async") }; + assert_eq!(describe(&s, &e), "#9 batch-async copies 21 dsts 0x1000 srcs 0x2000 stream 0x30"); +} + +#[test] +fn the_ring_describes_a_kernel_by_name() { + let mut s = State { ring: vec![None; 4], next: 1, names: HashMap::new(), stream_ok: HashMap::new(), ctx_ok: 0, capturing: HashMap::new(), failures: 0, streams: Vec::new() }; + s.names.insert(7, "k_moe".into()); + let e = Entry { seq: 3, a: 7, grid: [2, 1, 1], block: [128, 1, 1], smem: 4096, stream: 0x10, ..blank("kernel") }; + assert_eq!(describe(&s, &e), "#3 kernel k_moe grid 2x1x1 block 128x1x1 smem 4096 stream 0x10"); +} diff --git a/crates/model-format/src/bulk_read.rs b/crates/model-format/src/bulk_read.rs index ade86d4c..2874c966 100644 --- a/crates/model-format/src/bulk_read.rs +++ b/crates/model-format/src/bulk_read.rs @@ -414,157 +414,4 @@ pub fn read_into(file: &File, start: u64, dest: &mut [u8], plan: Plan) -> io::Re } #[cfg(test)] -mod tests { - use super::*; - use std::io::Write; - - fn pattern(size: usize) -> Vec { - (0..size) - .map(|n| ((n / 4096) as u8).wrapping_mul(31) ^ (n as u8) ^ ((n >> 17) as u8)) - .collect() - } - - fn temp(name: &str, bytes: &[u8]) -> (std::path::PathBuf, File) { - let path = std::env::temp_dir().join(format!("leleka-bulk-{name}-{}", std::process::id())); - let mut file = File::create(&path).unwrap(); - file.write_all(bytes).unwrap(); - file.sync_all().unwrap(); - drop(file); - let file = File::open(&path).unwrap(); - (path, file) - } - - fn plans() -> Vec { - let mut all = Vec::new(); - for strategy in [Strategy::Direct, Strategy::Advise, Strategy::Plain] { - for (threads, chunk) in [(1, 4096), (3, 8192), (8, 64 << 10), (4, 1 << 20)] { - all.push(Plan { - strategy, - threads, - chunk, - ahead: 256 << 10, - }); - } - } - all - } - - #[test] - fn every_strategy_returns_the_same_bytes_for_aligned_and_ragged_spans() { - let payload = pattern((3 << 20) + 5000); - let (path, file) = temp("same", &payload); - for plan in plans() { - for (start, len) in [ - (0usize, payload.len()), - (1, 100_000), - (4095, 4097), - (4096, 8192), - (12_345, (2 << 20) + 17), - (payload.len() - 1, 1), - (payload.len() - 10_001, 10_001), - ] { - let mut dest = vec![0u8; len]; - let report = read_into(&file, start as u64, &mut dest, plan).unwrap(); - assert_eq!(report.bytes, len as u64); - assert!( - dest == payload[start..start + len], - "{plan:?} start {start} len {len}" - ); - } - } - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn for_each_chunk_covers_the_span_exactly_once() { - let payload = pattern((1 << 20) + 777); - let (path, file) = temp("cover", &payload); - for plan in plans() { - let seen = Mutex::new(vec![0u8; payload.len()]); - let count = AtomicU64::new(0); - for_each_chunk( - &file, - 100, - payload.len() as u64 - 100, - plan, - |offset, bytes| { - count.fetch_add(bytes.len() as u64, Ordering::Relaxed); - let mut seen = seen.lock().unwrap(); - for (i, b) in bytes.iter().enumerate() { - assert_eq!(seen[offset as usize + i], 0, "byte visited twice"); - assert_eq!(*b, payload[offset as usize + i]); - seen[offset as usize + i] = 1; - } - Ok(()) - }, - ) - .unwrap(); - assert_eq!(count.load(Ordering::Relaxed), payload.len() as u64 - 100); - assert!(seen.lock().unwrap()[100..].iter().all(|&v| v == 1)); - } - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn a_span_past_the_end_and_a_sink_error_are_errors() { - let payload = pattern(100_000); - let (path, file) = temp("err", &payload); - let mut dest = vec![0u8; 10]; - assert_eq!( - read_into(&file, 99_995, &mut dest, Plan::default()) - .unwrap_err() - .kind(), - io::ErrorKind::UnexpectedEof - ); - for plan in plans() { - let error = for_each_chunk(&file, 0, 100_000, plan, |_, _| { - Err(io::Error::other("sink refused")) - }) - .unwrap_err(); - assert_eq!(error.to_string(), "sink refused"); - } - let empty = for_each_chunk(&file, 5, 0, Plan::default(), |_, _| Ok(())).unwrap(); - assert_eq!(empty.bytes, 0); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn a_file_shorter_than_it_was_measured_is_unexpected_eof() { - let payload = pattern(50_000); - let (path, file) = temp("short", &payload); - // Grow the claimed length by truncating after the metadata read: emulate with a span the file cannot serve. - std::fs::OpenOptions::new() - .write(true) - .open(&path) - .unwrap() - .set_len(20_000) - .unwrap(); - let mut dest = vec![0u8; 50_000]; - for plan in plans() { - assert!(read_into(&file, 0, &mut dest, plan).is_err()); - } - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn the_environment_overrides_the_defaults() { - let plan = Plan::with_overrides(Plan::default(), |name| match name { - "LELEKA_LOAD_READ" => Some("advise".into()), - "LELEKA_LOAD_THREADS" => Some("7".into()), - "LELEKA_LOAD_CHUNK_MIB" => Some("16".into()), - "LELEKA_LOAD_AHEAD_MIB" => Some("64".into()), - _ => None, - }); - assert_eq!( - plan, - Plan { - strategy: Strategy::Advise, - threads: 7, - chunk: 16 << 20, - ahead: 64 << 20 - } - ); - let kept = Plan::with_overrides(Plan::default(), |_| Some("nonsense".into())); - assert_eq!(kept, Plan::default()); - } -} +mod tests; diff --git a/crates/model-format/src/bulk_read/tests.rs b/crates/model-format/src/bulk_read/tests.rs new file mode 100644 index 00000000..8f5481c3 --- /dev/null +++ b/crates/model-format/src/bulk_read/tests.rs @@ -0,0 +1,154 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use std::io::Write; + +fn pattern(size: usize) -> Vec { + (0..size) + .map(|n| ((n / 4096) as u8).wrapping_mul(31) ^ (n as u8) ^ ((n >> 17) as u8)) + .collect() +} + +fn temp(name: &str, bytes: &[u8]) -> (std::path::PathBuf, File) { + let path = std::env::temp_dir().join(format!("leleka-bulk-{name}-{}", std::process::id())); + let mut file = File::create(&path).unwrap(); + file.write_all(bytes).unwrap(); + file.sync_all().unwrap(); + drop(file); + let file = File::open(&path).unwrap(); + (path, file) +} + +fn plans() -> Vec { + let mut all = Vec::new(); + for strategy in [Strategy::Direct, Strategy::Advise, Strategy::Plain] { + for (threads, chunk) in [(1, 4096), (3, 8192), (8, 64 << 10), (4, 1 << 20)] { + all.push(Plan { + strategy, + threads, + chunk, + ahead: 256 << 10, + }); + } + } + all +} + +#[test] +fn every_strategy_returns_the_same_bytes_for_aligned_and_ragged_spans() { + let payload = pattern((3 << 20) + 5000); + let (path, file) = temp("same", &payload); + for plan in plans() { + for (start, len) in [ + (0usize, payload.len()), + (1, 100_000), + (4095, 4097), + (4096, 8192), + (12_345, (2 << 20) + 17), + (payload.len() - 1, 1), + (payload.len() - 10_001, 10_001), + ] { + let mut dest = vec![0u8; len]; + let report = read_into(&file, start as u64, &mut dest, plan).unwrap(); + assert_eq!(report.bytes, len as u64); + assert!( + dest == payload[start..start + len], + "{plan:?} start {start} len {len}" + ); + } + } + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn for_each_chunk_covers_the_span_exactly_once() { + let payload = pattern((1 << 20) + 777); + let (path, file) = temp("cover", &payload); + for plan in plans() { + let seen = Mutex::new(vec![0u8; payload.len()]); + let count = AtomicU64::new(0); + for_each_chunk( + &file, + 100, + payload.len() as u64 - 100, + plan, + |offset, bytes| { + count.fetch_add(bytes.len() as u64, Ordering::Relaxed); + let mut seen = seen.lock().unwrap(); + for (i, b) in bytes.iter().enumerate() { + assert_eq!(seen[offset as usize + i], 0, "byte visited twice"); + assert_eq!(*b, payload[offset as usize + i]); + seen[offset as usize + i] = 1; + } + Ok(()) + }, + ) + .unwrap(); + assert_eq!(count.load(Ordering::Relaxed), payload.len() as u64 - 100); + assert!(seen.lock().unwrap()[100..].iter().all(|&v| v == 1)); + } + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn a_span_past_the_end_and_a_sink_error_are_errors() { + let payload = pattern(100_000); + let (path, file) = temp("err", &payload); + let mut dest = vec![0u8; 10]; + assert_eq!( + read_into(&file, 99_995, &mut dest, Plan::default()) + .unwrap_err() + .kind(), + io::ErrorKind::UnexpectedEof + ); + for plan in plans() { + let error = for_each_chunk(&file, 0, 100_000, plan, |_, _| { + Err(io::Error::other("sink refused")) + }) + .unwrap_err(); + assert_eq!(error.to_string(), "sink refused"); + } + let empty = for_each_chunk(&file, 5, 0, Plan::default(), |_, _| Ok(())).unwrap(); + assert_eq!(empty.bytes, 0); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn a_file_shorter_than_it_was_measured_is_unexpected_eof() { + let payload = pattern(50_000); + let (path, file) = temp("short", &payload); + // Grow the claimed length by truncating after the metadata read: emulate with a span the file cannot serve. + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(20_000) + .unwrap(); + let mut dest = vec![0u8; 50_000]; + for plan in plans() { + assert!(read_into(&file, 0, &mut dest, plan).is_err()); + } + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn the_environment_overrides_the_defaults() { + let plan = Plan::with_overrides(Plan::default(), |name| match name { + "LELEKA_LOAD_READ" => Some("advise".into()), + "LELEKA_LOAD_THREADS" => Some("7".into()), + "LELEKA_LOAD_CHUNK_MIB" => Some("16".into()), + "LELEKA_LOAD_AHEAD_MIB" => Some("64".into()), + _ => None, + }); + assert_eq!( + plan, + Plan { + strategy: Strategy::Advise, + threads: 7, + chunk: 16 << 20, + ahead: 64 << 20 + } + ); + let kept = Plan::with_overrides(Plan::default(), |_| Some("nonsense".into())); + assert_eq!(kept, Plan::default()); +} diff --git a/crates/model-format/src/native_dense_plan.rs b/crates/model-format/src/native_dense_plan.rs index 5d370aad..06f585bc 100644 --- a/crates/model-format/src/native_dense_plan.rs +++ b/crates/model-format/src/native_dense_plan.rs @@ -300,141 +300,4 @@ pub fn attached_types(plan: &DensePlan) -> BTreeMap<&str, u32> { } #[cfg(test)] -mod tests { - use super::*; - - fn row(name: &str, kind: u32, shape: &[u64], offset: u64) -> TensorRow { - TensorRow { name: name.into(), shape: shape.to_vec(), kind, offset } - } - fn shard(rows: Vec) -> ShardInfo { - ShardInfo { has_architecture: true, data_start: 1000, file_size: 1_000_000, tensors: rows, ..Default::default() } - } - fn canon(ne0: i64, ne1: i64) -> Canonical { - Canonical { quantized: true, ne0, ne1, native_attached: false } - } - fn all(c: Canonical) -> impl Fn(&str) -> Option { - move |_| Some(c) - } - - #[test] - fn weight_bytes_follow_the_original_tables() { - assert_eq!(native_mmvq_weight_bytes(12, 2560, 10240), Ok(2560 / 256 * 144 * 10240)); - assert_eq!(native_mmvq_weight_bytes(42, 2560, 2), Ok(2560 / 64 * 18 * 2)); - assert_eq!(native_mmvq_weight_bytes(8, 640, 2560), Ok(640 / 32 * 34 * 2560)); - assert_eq!(native_mmvq_weight_bytes(18, 256, 1), Ok(98)); - assert!(native_mmvq_weight_bytes(12, 2561, 1).is_err()); - assert!(native_mmvq_weight_bytes(12, 256, 0).is_err()); - assert!(native_mmvq_weight_bytes(0, 256, 1).is_err()); - assert!(native_mmvq_weight_bytes(14, 256, i64::MAX).is_err() || native_mmvq_weight_bytes(14, 256, i64::MAX).is_ok()); - assert_eq!(native_q8_1_bytes(2560), Ok(2560 / 32 * 36)); - assert!(native_q8_1_bytes(33).is_err()); - for t in 0..64 { - assert_eq!(native_mmvq_supported(t), weight_block(t).is_some(), "type {t}"); - } - } - - #[test] - fn eligibility_matches_the_name_and_type_rules() { - let yes = ["blk.0.attn_qkv.weight", "blk.3.ssm_out.weight", "blk.47.ffn_down_shexp.weight", "blk.9.attn_output.weight"]; - for n in yes { - assert!(eligible(&row(n, 12, &[256, 2], 0), false), "{n}"); - } - for n in ["token_embd.weight", "blk.0.ffn_gate_inp.weight", "blk.0.attn_norm.weight", "output.weight"] { - assert!(!eligible(&row(n, 12, &[256, 2], 0), false), "{n}"); - } - assert!(!eligible(&row("blk.1.ple_key.weight", 42, &[256, 2], 0), false)); - for kind in [42, 18, 23, 8] { - assert!(eligible(&row("blk.1.ple_key.weight", kind, &[256, 2], 0), true), "{kind}"); - } - assert!(!eligible(&row("blk.1.ple_key.weight", 12, &[256, 2], 0), true)); - // names only - let s = shard(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_q.weight", 12, &[256], 8000), row("blk.1.ple_key.weight", 23, &[256, 2], 16000), row("blk.2.attn_k.weight", 1, &[4, 2], 20000)]); - assert_eq!(served_names(&[s.clone()], false).into_iter().collect::>(), vec!["blk.0.attn_qkv.weight"]); - assert_eq!(served_names(&[s], true).len(), 2); - let mut skip = BTreeSet::from(["blk.1.ple_key.weight".to_string(), "x".to_string()]); - keep_unquantized_ple_key(&mut skip, Some(4)); - assert!(skip.contains("blk.1.ple_key.weight")); - keep_unquantized_ple_key(&mut skip, Some(0)); - assert!(!skip.contains("blk.1.ple_key.weight") && skip.contains("x")); - } - - #[test] - fn a_valid_two_shard_model_produces_the_upload_plan() { - let mut first = shard(vec![row("blk.0.attn_qkv.weight", 12, &[2560, 1024], 0), row("blk.0.attn_norm.weight", 0, &[2560], 2_000_000)]); - first.split_count = Some(2); - first.split_no = Some(0); - first.split_tensors = Some(4); - let mut second = ShardInfo { has_architecture: false, data_start: 500, file_size: 900_000, split_count: Some(2), split_no: Some(1), split_tensors: Some(4), ..Default::default() }; - second.tensors = vec![row("blk.3.ssm_out.weight", 8, &[640, 512], 0)]; - first.file_size = 5_000_000; - let plan = plan_load(&[first, second], &|name| match name { - "blk.0.attn_qkv.weight" => Some(canon(2560, 1024)), - "blk.3.ssm_out.weight" => Some(canon(640, 512)), - _ => None, - }, false).unwrap(); - assert_eq!(plan.items.len(), 2); - assert_eq!(plan.items[0].bytes, 2560 / 256 * 144 * 1024); - assert_eq!(plan.items[0].file_offset, 1000); - assert_eq!(plan.items[1].shard, 1); - assert_eq!(plan.items[1].file_offset, 500); - assert_eq!(plan.max_in, 2560); - assert_eq!(plan.total_bytes, plan.items.iter().map(|i| i.bytes).sum::()); - assert_eq!(plan.scratch_bytes, 2560 / 32 * 36); - assert_eq!(attached_types(&plan)["blk.3.ssm_out.weight"], 8); - } - - #[test] - fn refusals_carry_the_original_messages() { - let ok = |t: Vec| shard(t); - let good = canon(256, 4); - let c = all(good); - let one = || vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0)]; - assert_eq!(plan_load(&[], &c, false).unwrap_err(), "native dense: at least one GGUF shard is required"); - // architecture error is returned verbatim - let mut s = ok(one()); - s.architecture_error = "architecture is 'llama', this engine requires 'qwen4exp'".into(); - assert_eq!(plan_load(&[s], &c, false).unwrap_err(), "architecture is 'llama', this engine requires 'qwen4exp'"); - // a second shard without the first's split metadata - let mut first = ok(one()); - first.split_count = Some(2); - first.split_no = Some(0); - first.split_tensors = Some(2); - let extra = ShardInfo { has_architecture: false, data_start: 0, file_size: 100_000, ..Default::default() }; - assert_eq!(plan_load(&[first.clone(), extra], &c, false).unwrap_err(), "native dense: additional shard must match the architecture-validated first shard's split metadata"); - let dup = ShardInfo { split_count: Some(2), split_no: Some(0), split_tensors: Some(2), ..Default::default() }; - assert!(plan_load(&[first.clone(), dup], &c, false).unwrap_err().contains("additional shard must match")); - let mut again = first.clone(); - again.tensors = vec![row("blk.9.attn_qkv.weight", 12, &[256, 4], 0)]; - assert_eq!(plan_load(&[first.clone(), again], &c, false).unwrap_err(), "native dense: duplicate split shard number"); - // payload offsets / geometry / truncation / overlap - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_q.weight", 12, &[256, 4], 0)])], &c, false).unwrap_err(), "native dense: tensor payload offsets overlap"); - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[250, 4], 0)])], &c, false).unwrap_err(), "native dense: invalid block geometry blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[], 0)])], &c, false).unwrap_err(), "native dense: invalid block geometry blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 0], 0)])], &c, false).unwrap_err(), "native dense: invalid tensor extent blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 999_900)])], &c, false).unwrap_err(), "native dense: truncated payload blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_norm.weight", 0, &[8], 100)])], &c, false).unwrap_err(), "native dense: overlapping payload blk.0.attn_qkv.weight"); - // the unsupported/overlapping non-eligible tensor still blocks the model (checked before upload) - // canonical-table problems - assert_eq!(plan_load(&[ok(one())], &|_| None, false).unwrap_err(), "native dense: tensor absent from canonical table: blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(one())], &all(Canonical { native_attached: true, ..good }), false).unwrap_err(), "native dense: override already attached"); - assert_eq!(plan_load(&[ok(one())], &all(Canonical { quantized: false, ..good }), false).unwrap_err(), "native dense: incompatible matrix blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(one())], &all(canon(256, 5)), false).unwrap_err(), "native dense: incompatible matrix blk.0.attn_qkv.weight"); - // unsupported type keeps the canonical path and nothing is left to upload - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 1, &[8, 4], 0)])], &c, false).unwrap_err(), "native dense: no supported GDN/QSA matrices in supplied shards"); - // a duplicate eligible name across shards (the second declared as shard 1 of 2) - let mut a = ok(one()); - a.split_count = Some(2); a.split_no = Some(0); a.split_tensors = Some(2); - let b = ShardInfo { data_start: 0, file_size: 100_000, split_count: Some(2), split_no: Some(1), split_tensors: Some(2), tensors: one(), ..Default::default() }; - assert_eq!(plan_load(&[a, b], &c, false).unwrap_err(), "native dense: duplicate tensor blk.0.attn_qkv.weight"); - } - - #[test] - fn an_unquantized_ple_key_is_skipped_not_refused() { - let ple = row("blk.1.ple_key.weight", 23, &[256, 4], 0); - let q = row("blk.0.attn_q.weight", 12, &[256, 4], 50_000); - let canonical = |name: &str| Some(Canonical { quantized: name != "blk.1.ple_key.weight", ne0: 256, ne1: 4, native_attached: false }); - let plan = plan_load(&[shard(vec![ple, q])], &canonical, true).unwrap(); - assert_eq!(plan.items.len(), 1); - assert_eq!(plan.items[0].name, "blk.0.attn_q.weight"); - } -} +mod tests; diff --git a/crates/model-format/src/native_dense_plan/tests.rs b/crates/model-format/src/native_dense_plan/tests.rs new file mode 100644 index 00000000..1469daa5 --- /dev/null +++ b/crates/model-format/src/native_dense_plan/tests.rs @@ -0,0 +1,138 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn row(name: &str, kind: u32, shape: &[u64], offset: u64) -> TensorRow { + TensorRow { name: name.into(), shape: shape.to_vec(), kind, offset } +} +fn shard(rows: Vec) -> ShardInfo { + ShardInfo { has_architecture: true, data_start: 1000, file_size: 1_000_000, tensors: rows, ..Default::default() } +} +fn canon(ne0: i64, ne1: i64) -> Canonical { + Canonical { quantized: true, ne0, ne1, native_attached: false } +} +fn all(c: Canonical) -> impl Fn(&str) -> Option { + move |_| Some(c) +} + +#[test] +fn weight_bytes_follow_the_original_tables() { + assert_eq!(native_mmvq_weight_bytes(12, 2560, 10240), Ok(2560 / 256 * 144 * 10240)); + assert_eq!(native_mmvq_weight_bytes(42, 2560, 2), Ok(2560 / 64 * 18 * 2)); + assert_eq!(native_mmvq_weight_bytes(8, 640, 2560), Ok(640 / 32 * 34 * 2560)); + assert_eq!(native_mmvq_weight_bytes(18, 256, 1), Ok(98)); + assert!(native_mmvq_weight_bytes(12, 2561, 1).is_err()); + assert!(native_mmvq_weight_bytes(12, 256, 0).is_err()); + assert!(native_mmvq_weight_bytes(0, 256, 1).is_err()); + assert!(native_mmvq_weight_bytes(14, 256, i64::MAX).is_err() || native_mmvq_weight_bytes(14, 256, i64::MAX).is_ok()); + assert_eq!(native_q8_1_bytes(2560), Ok(2560 / 32 * 36)); + assert!(native_q8_1_bytes(33).is_err()); + for t in 0..64 { + assert_eq!(native_mmvq_supported(t), weight_block(t).is_some(), "type {t}"); + } +} + +#[test] +fn eligibility_matches_the_name_and_type_rules() { + let yes = ["blk.0.attn_qkv.weight", "blk.3.ssm_out.weight", "blk.47.ffn_down_shexp.weight", "blk.9.attn_output.weight"]; + for n in yes { + assert!(eligible(&row(n, 12, &[256, 2], 0), false), "{n}"); + } + for n in ["token_embd.weight", "blk.0.ffn_gate_inp.weight", "blk.0.attn_norm.weight", "output.weight"] { + assert!(!eligible(&row(n, 12, &[256, 2], 0), false), "{n}"); + } + assert!(!eligible(&row("blk.1.ple_key.weight", 42, &[256, 2], 0), false)); + for kind in [42, 18, 23, 8] { + assert!(eligible(&row("blk.1.ple_key.weight", kind, &[256, 2], 0), true), "{kind}"); + } + assert!(!eligible(&row("blk.1.ple_key.weight", 12, &[256, 2], 0), true)); + // names only + let s = shard(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_q.weight", 12, &[256], 8000), row("blk.1.ple_key.weight", 23, &[256, 2], 16000), row("blk.2.attn_k.weight", 1, &[4, 2], 20000)]); + assert_eq!(served_names(&[s.clone()], false).into_iter().collect::>(), vec!["blk.0.attn_qkv.weight"]); + assert_eq!(served_names(&[s], true).len(), 2); + let mut skip = BTreeSet::from(["blk.1.ple_key.weight".to_string(), "x".to_string()]); + keep_unquantized_ple_key(&mut skip, Some(4)); + assert!(skip.contains("blk.1.ple_key.weight")); + keep_unquantized_ple_key(&mut skip, Some(0)); + assert!(!skip.contains("blk.1.ple_key.weight") && skip.contains("x")); +} + +#[test] +fn a_valid_two_shard_model_produces_the_upload_plan() { + let mut first = shard(vec![row("blk.0.attn_qkv.weight", 12, &[2560, 1024], 0), row("blk.0.attn_norm.weight", 0, &[2560], 2_000_000)]); + first.split_count = Some(2); + first.split_no = Some(0); + first.split_tensors = Some(4); + let mut second = ShardInfo { has_architecture: false, data_start: 500, file_size: 900_000, split_count: Some(2), split_no: Some(1), split_tensors: Some(4), ..Default::default() }; + second.tensors = vec![row("blk.3.ssm_out.weight", 8, &[640, 512], 0)]; + first.file_size = 5_000_000; + let plan = plan_load(&[first, second], &|name| match name { + "blk.0.attn_qkv.weight" => Some(canon(2560, 1024)), + "blk.3.ssm_out.weight" => Some(canon(640, 512)), + _ => None, + }, false).unwrap(); + assert_eq!(plan.items.len(), 2); + assert_eq!(plan.items[0].bytes, 2560 / 256 * 144 * 1024); + assert_eq!(plan.items[0].file_offset, 1000); + assert_eq!(plan.items[1].shard, 1); + assert_eq!(plan.items[1].file_offset, 500); + assert_eq!(plan.max_in, 2560); + assert_eq!(plan.total_bytes, plan.items.iter().map(|i| i.bytes).sum::()); + assert_eq!(plan.scratch_bytes, 2560 / 32 * 36); + assert_eq!(attached_types(&plan)["blk.3.ssm_out.weight"], 8); +} + +#[test] +fn refusals_carry_the_original_messages() { + let ok = |t: Vec| shard(t); + let good = canon(256, 4); + let c = all(good); + let one = || vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0)]; + assert_eq!(plan_load(&[], &c, false).unwrap_err(), "native dense: at least one GGUF shard is required"); + // architecture error is returned verbatim + let mut s = ok(one()); + s.architecture_error = "architecture is 'llama', this engine requires 'qwen4exp'".into(); + assert_eq!(plan_load(&[s], &c, false).unwrap_err(), "architecture is 'llama', this engine requires 'qwen4exp'"); + // a second shard without the first's split metadata + let mut first = ok(one()); + first.split_count = Some(2); + first.split_no = Some(0); + first.split_tensors = Some(2); + let extra = ShardInfo { has_architecture: false, data_start: 0, file_size: 100_000, ..Default::default() }; + assert_eq!(plan_load(&[first.clone(), extra], &c, false).unwrap_err(), "native dense: additional shard must match the architecture-validated first shard's split metadata"); + let dup = ShardInfo { split_count: Some(2), split_no: Some(0), split_tensors: Some(2), ..Default::default() }; + assert!(plan_load(&[first.clone(), dup], &c, false).unwrap_err().contains("additional shard must match")); + let mut again = first.clone(); + again.tensors = vec![row("blk.9.attn_qkv.weight", 12, &[256, 4], 0)]; + assert_eq!(plan_load(&[first.clone(), again], &c, false).unwrap_err(), "native dense: duplicate split shard number"); + // payload offsets / geometry / truncation / overlap + assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_q.weight", 12, &[256, 4], 0)])], &c, false).unwrap_err(), "native dense: tensor payload offsets overlap"); + assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[250, 4], 0)])], &c, false).unwrap_err(), "native dense: invalid block geometry blk.0.attn_qkv.weight"); + assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[], 0)])], &c, false).unwrap_err(), "native dense: invalid block geometry blk.0.attn_qkv.weight"); + assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 0], 0)])], &c, false).unwrap_err(), "native dense: invalid tensor extent blk.0.attn_qkv.weight"); + assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 999_900)])], &c, false).unwrap_err(), "native dense: truncated payload blk.0.attn_qkv.weight"); + assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_norm.weight", 0, &[8], 100)])], &c, false).unwrap_err(), "native dense: overlapping payload blk.0.attn_qkv.weight"); + // the unsupported/overlapping non-eligible tensor still blocks the model (checked before upload) + // canonical-table problems + assert_eq!(plan_load(&[ok(one())], &|_| None, false).unwrap_err(), "native dense: tensor absent from canonical table: blk.0.attn_qkv.weight"); + assert_eq!(plan_load(&[ok(one())], &all(Canonical { native_attached: true, ..good }), false).unwrap_err(), "native dense: override already attached"); + assert_eq!(plan_load(&[ok(one())], &all(Canonical { quantized: false, ..good }), false).unwrap_err(), "native dense: incompatible matrix blk.0.attn_qkv.weight"); + assert_eq!(plan_load(&[ok(one())], &all(canon(256, 5)), false).unwrap_err(), "native dense: incompatible matrix blk.0.attn_qkv.weight"); + // unsupported type keeps the canonical path and nothing is left to upload + assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 1, &[8, 4], 0)])], &c, false).unwrap_err(), "native dense: no supported GDN/QSA matrices in supplied shards"); + // a duplicate eligible name across shards (the second declared as shard 1 of 2) + let mut a = ok(one()); + a.split_count = Some(2); a.split_no = Some(0); a.split_tensors = Some(2); + let b = ShardInfo { data_start: 0, file_size: 100_000, split_count: Some(2), split_no: Some(1), split_tensors: Some(2), tensors: one(), ..Default::default() }; + assert_eq!(plan_load(&[a, b], &c, false).unwrap_err(), "native dense: duplicate tensor blk.0.attn_qkv.weight"); +} + +#[test] +fn an_unquantized_ple_key_is_skipped_not_refused() { + let ple = row("blk.1.ple_key.weight", 23, &[256, 4], 0); + let q = row("blk.0.attn_q.weight", 12, &[256, 4], 50_000); + let canonical = |name: &str| Some(Canonical { quantized: name != "blk.1.ple_key.weight", ne0: 256, ne1: 4, native_attached: false }); + let plan = plan_load(&[shard(vec![ple, q])], &canonical, true).unwrap(); + assert_eq!(plan.items.len(), 1); + assert_eq!(plan.items[0].name, "blk.0.attn_q.weight"); +} diff --git a/crates/model-format/src/pinned_arena_plan.rs b/crates/model-format/src/pinned_arena_plan.rs index 1d880868..9cb2b146 100644 --- a/crates/model-format/src/pinned_arena_plan.rs +++ b/crates/model-format/src/pinned_arena_plan.rs @@ -395,157 +395,4 @@ fn read_up_to(file: &std::fs::File, buf: &mut [u8], offset: u64) -> usize { } #[cfg(test)] -mod tests { - use super::*; - - fn temp(name: &str) -> std::path::PathBuf { - let mut p = std::env::temp_dir(); - p.push(format!("leleka_pinned_{}_{name}", std::process::id())); - p - } - - #[test] - fn fnv_matches_the_textbook_recurrence_with_the_originals_seed() { - assert_eq!(fnv1a64(b"", FNV_SEED), FNV_SEED); - // FNV-1a over "a" with the standard offset is 0xaf63dc4c8601ec8c; the Original's seed differs by one digit - assert_eq!(fnv1a64(b"a", 14_695_981_039_346_656_037), 0xaf63_dc4c_8601_ec8c); - assert_ne!(fnv1a64(b"a", FNV_SEED), 0xaf63_dc4c_8601_ec8c); - assert_eq!(fnv1a64(b"ab", FNV_SEED), fnv1a64(b"b", fnv1a64(b"a", FNV_SEED)), "chaining through the seed"); - } - - #[test] - fn header_layout_and_admission() { - let h = SharedArenaHeader::new(1 << 20, 0xfeed); - let e = h.encode(); - assert_eq!(&e[..15], b"STRATA-ARENA-V1"); - assert_eq!(SharedArenaHeader::decode(&e), Some(h)); - assert_eq!(SharedArenaHeader::decode(&e[..71]), None); - let size = SHARED_ARENA_HEADER_BYTES + (1 << 20); - let p = "/dev/shm/x"; - assert_eq!(plan_shared_file(p, 1 << 20, 0, None).unwrap_err(), "shared arena requires a nonzero pack hash"); - assert_eq!(plan_shared_file(p, u64::MAX, 1, None).unwrap_err(), "shared arena size overflows its header"); - assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, None), Ok(SharedFileAction::Create { file_bytes: size, header: h })); - assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((0, &[]))), Ok(SharedFileAction::Create { file_bytes: size, header: h })); - assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &e))), Ok(SharedFileAction::Reuse { file_bytes: size })); - assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size + 1, &e))).unwrap_err(), format!("shared arena {p} is {} B, expected {size} B including its header", size + 1)); - assert_eq!(plan_shared_file(p, 1 << 20, 0xbeef, Some((size, &e))).unwrap_err(), format!("shared arena {p} was written for pack hash 000000000000feed, expected 000000000000beef")); - let mut bad = e; - bad[3] ^= 1; - assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &bad))).unwrap_err(), format!("shared arena {p} has an incompatible or missing header")); - assert!(plan_shared_file(p, 1 << 21, 0xfeed, Some((SHARED_ARENA_HEADER_BYTES + (1 << 21), &e))).unwrap_err().contains("incompatible"), "arena_bytes mismatch"); - assert!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &e[..10]))).unwrap_err().contains("incompatible")); - assert_eq!(shared_mapping_note("/dev/shm/a"), "MAP_SHARED file /dev/shm/a (pack hash checked)"); - } - - #[cfg(unix)] - #[test] - fn the_shared_file_is_created_once_then_checked() { - let path = temp("shared"); - let _ = std::fs::remove_file(&path); - let (_f, action) = open_shared_arena_file(&path, 8192, 0xabc).unwrap(); - assert!(matches!(action, SharedFileAction::Create { file_bytes, .. } if file_bytes == 4096 + 8192)); - assert_eq!(std::fs::metadata(&path).unwrap().len(), 4096 + 8192); - use std::os::unix::fs::PermissionsExt; - assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); - let (_f, again) = open_shared_arena_file(&path, 8192, 0xabc).unwrap(); - assert_eq!(again, SharedFileAction::Reuse { file_bytes: 4096 + 8192 }); - assert!(open_shared_arena_file(&path, 8192, 0xabd).unwrap_err().contains("was written for pack hash")); - assert!(open_shared_arena_file(&path, 4096, 0xabc).unwrap_err().contains("expected")); - assert_eq!(open_shared_arena_file(&path, 8192, 0).unwrap_err(), "shared arena requires a nonzero pack hash"); - std::fs::remove_file(&path).unwrap(); - } - - #[test] - fn pin_cap_environment_and_bounds() { - assert_eq!(arena_pin_cap_gib(None), -1); - assert_eq!(arena_pin_cap_gib(Some("")), -1); - assert_eq!(arena_pin_cap_gib(Some("auto")), -2); - assert_eq!(arena_pin_cap_gib(Some("0")), 0); - assert_eq!(arena_pin_cap_gib(Some("24")), 24); - assert_eq!(arena_pin_cap_gib(Some("-3")), -1); - assert_eq!(arena_pin_cap_gib(Some("12abc")), 12); - assert_eq!(arena_pin_cap_gib(Some("abc")), 0); - assert_eq!(uniform_bounds(10, 4), vec![0, 4, 8]); - assert_eq!(uniform_bounds(12, 4), vec![0, 4, 8, 12]); - assert!(uniform_bounds(3, 4).is_empty()); - assert!(uniform_bounds(10, 0).is_empty()); - assert!(arena_lock_enabled(None) && arena_lock_enabled(Some("1")) && !arena_lock_enabled(Some("0"))); - } - - #[test] - fn pin_decision_and_sliced_registration() { - let gib = 1u64 << 30; - let d = decide_pin(64 * gib, 10, 0, -1); - assert_eq!((d.cap, d.capped), (0, false)); - let d = decide_pin(64 * gib, 10, 0, 24); - assert_eq!((d.cap, d.cap_why, d.capped), (24 * gib, "by STRATA_ARENA_PIN_GIB", true)); - // the engine's cap wins over the environment; a cap above the arena is not a cap; one slice cannot be sliced - assert_eq!(decide_pin(64 * gib, 10, 8 * gib, 24).cap, 8 * gib); - assert!(!decide_pin(16 * gib, 10, 24 * gib, -1).capped); - assert!(!decide_pin(64 * gib, 1, 8 * gib, -1).capped); - // slices stop at the driver's refusal and at the limit - let bounds = uniform_bounds(100, 10); - let refuse_at = 40; - let r = pin_sliced(&bounds, None, |off, _| off < refuse_at); - assert_eq!(r, SlicedPin { slice_starts: vec![0, 10, 20, 30], registered_bytes: 40, registered_slices: 4 }); - let r = pin_sliced(&bounds, Some(55), |_, _| true); - assert_eq!((r.registered_slices, r.registered_bytes), (5, 50)); - let r = pin_sliced(&bounds, Some(55), |_, _| true); - assert_eq!(r.slice_starts.last(), Some(&40), "slice 50..60 would pass the limit"); - // the constructor's note - let capped = decide_pin(64 * gib, 10, 0, 24); - let pinned = SlicedPin { slice_starts: vec![0], registered_bytes: 24 * gib, registered_slices: 24 }; - assert_eq!( - sliced_note(&capped, "", false, 0, "", &pinned, "MAP_PRIVATE"), - "cudaHostRegister limited to 24 GiB by STRATA_ARENA_PIN_GIB; 24 slices pinned (24 GiB); MAP_PRIVATE" - ); - let refused = decide_pin(64 * gib, 10, 0, -1); - assert_eq!( - sliced_note(&refused, "out of memory", true, 26 * gib, "the GPU's shared-memory budget", &pinned, "n"), - "cudaHostRegister of the whole arena FAILED (out of memory); slices capped at 26.0 GiB (the GPU's shared-memory budget; STRATA_ARENA_PIN_GIB=auto; N sets a cap; #243); 24 slices pinned (24 GiB); n" - ); - } - - #[cfg(unix)] - #[test] - fn parallel_load_matches_a_serial_read_and_reports_the_layer_checksums() { - let path = temp("experts"); - // 5 layers of different sizes at uneven offsets, a gap between layers, random-ish bytes - let mut x = 0x1234_5678_9abc_def0u64; - let file: Vec = (0..100_000).map(|_| { x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (x >> 56) as u8 }).collect(); - std::fs::write(&path, &file).unwrap(); - let off = [0u64, 7_001, 30_000, 31_000, 90_000]; - let len = [7_000u64, 22_999, 1_000, 40_000, 9_999]; - for threads in [1usize, 3, 8] { - for chunk in [1u64, 97, 4096, 1 << 20] { - let mut dst = vec![0xeeu8; 100_000]; - let stats = load_experts_ranges(&path, &mut dst, &off, &len, threads, chunk); - assert!(stats.ok, "{}", stats.error); - assert_eq!(stats.layers, 5); - assert_eq!(stats.bytes, len.iter().sum::()); - for l in 0..5 { - let r = off[l] as usize..(off[l] + len[l]) as usize; - assert_eq!(&dst[r.clone()], &file[r.clone()], "layer {l}"); - assert_eq!(stats.layer_checksums[l], fnv1a64(&file[r], FNV_SEED), "layer {l} checksum (chunking must not change it)"); - } - assert!(dst[7_000..7_001].iter().all(|b| *b == 0xee), "bytes between layers stay untouched"); - } - } - // uniform wrapper - let mut dst = vec![0u8; 50_000]; - let stats = load_experts(&path, &mut dst, 1000, 10, 5, 4, 3000); - assert!(stats.ok); - assert_eq!(&dst[..], &file[..50_000]); - // a short read names the layer and the offset; nothing is silently zero filled - let mut dst = vec![0u8; 200_000]; - let stats = load_experts_ranges(&path, &mut dst, &[0, 150_000], &[1000, 1000], 2, 512); - assert!(!stats.ok && stats.seconds < 0.0); - assert_eq!(stats.error, "short read in layer 1: got 0 of 512 B at offset 150000"); - // hardening: overlapping or out-of-range windows are refused before any read - let mut dst = vec![0u8; 1000]; - assert!(!load_experts_ranges(&path, &mut dst, &[0, 500], &[600, 100], 1, 64).ok); - assert!(!load_experts_ranges(&path, &mut dst, &[900], &[200], 1, 64).ok); - assert!(!load_experts_ranges(&temp("missing"), &mut dst, &[0], &[10], 1, 64).ok); - std::fs::remove_file(&path).unwrap(); - } -} +mod tests; diff --git a/crates/model-format/src/pinned_arena_plan/tests.rs b/crates/model-format/src/pinned_arena_plan/tests.rs new file mode 100644 index 00000000..f98f4696 --- /dev/null +++ b/crates/model-format/src/pinned_arena_plan/tests.rs @@ -0,0 +1,154 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn temp(name: &str) -> std::path::PathBuf { + let mut p = std::env::temp_dir(); + p.push(format!("leleka_pinned_{}_{name}", std::process::id())); + p +} + +#[test] +fn fnv_matches_the_textbook_recurrence_with_the_originals_seed() { + assert_eq!(fnv1a64(b"", FNV_SEED), FNV_SEED); + // FNV-1a over "a" with the standard offset is 0xaf63dc4c8601ec8c; the Original's seed differs by one digit + assert_eq!(fnv1a64(b"a", 14_695_981_039_346_656_037), 0xaf63_dc4c_8601_ec8c); + assert_ne!(fnv1a64(b"a", FNV_SEED), 0xaf63_dc4c_8601_ec8c); + assert_eq!(fnv1a64(b"ab", FNV_SEED), fnv1a64(b"b", fnv1a64(b"a", FNV_SEED)), "chaining through the seed"); +} + +#[test] +fn header_layout_and_admission() { + let h = SharedArenaHeader::new(1 << 20, 0xfeed); + let e = h.encode(); + assert_eq!(&e[..15], b"STRATA-ARENA-V1"); + assert_eq!(SharedArenaHeader::decode(&e), Some(h)); + assert_eq!(SharedArenaHeader::decode(&e[..71]), None); + let size = SHARED_ARENA_HEADER_BYTES + (1 << 20); + let p = "/dev/shm/x"; + assert_eq!(plan_shared_file(p, 1 << 20, 0, None).unwrap_err(), "shared arena requires a nonzero pack hash"); + assert_eq!(plan_shared_file(p, u64::MAX, 1, None).unwrap_err(), "shared arena size overflows its header"); + assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, None), Ok(SharedFileAction::Create { file_bytes: size, header: h })); + assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((0, &[]))), Ok(SharedFileAction::Create { file_bytes: size, header: h })); + assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &e))), Ok(SharedFileAction::Reuse { file_bytes: size })); + assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size + 1, &e))).unwrap_err(), format!("shared arena {p} is {} B, expected {size} B including its header", size + 1)); + assert_eq!(plan_shared_file(p, 1 << 20, 0xbeef, Some((size, &e))).unwrap_err(), format!("shared arena {p} was written for pack hash 000000000000feed, expected 000000000000beef")); + let mut bad = e; + bad[3] ^= 1; + assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &bad))).unwrap_err(), format!("shared arena {p} has an incompatible or missing header")); + assert!(plan_shared_file(p, 1 << 21, 0xfeed, Some((SHARED_ARENA_HEADER_BYTES + (1 << 21), &e))).unwrap_err().contains("incompatible"), "arena_bytes mismatch"); + assert!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &e[..10]))).unwrap_err().contains("incompatible")); + assert_eq!(shared_mapping_note("/dev/shm/a"), "MAP_SHARED file /dev/shm/a (pack hash checked)"); +} + +#[cfg(unix)] +#[test] +fn the_shared_file_is_created_once_then_checked() { + let path = temp("shared"); + let _ = std::fs::remove_file(&path); + let (_f, action) = open_shared_arena_file(&path, 8192, 0xabc).unwrap(); + assert!(matches!(action, SharedFileAction::Create { file_bytes, .. } if file_bytes == 4096 + 8192)); + assert_eq!(std::fs::metadata(&path).unwrap().len(), 4096 + 8192); + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let (_f, again) = open_shared_arena_file(&path, 8192, 0xabc).unwrap(); + assert_eq!(again, SharedFileAction::Reuse { file_bytes: 4096 + 8192 }); + assert!(open_shared_arena_file(&path, 8192, 0xabd).unwrap_err().contains("was written for pack hash")); + assert!(open_shared_arena_file(&path, 4096, 0xabc).unwrap_err().contains("expected")); + assert_eq!(open_shared_arena_file(&path, 8192, 0).unwrap_err(), "shared arena requires a nonzero pack hash"); + std::fs::remove_file(&path).unwrap(); +} + +#[test] +fn pin_cap_environment_and_bounds() { + assert_eq!(arena_pin_cap_gib(None), -1); + assert_eq!(arena_pin_cap_gib(Some("")), -1); + assert_eq!(arena_pin_cap_gib(Some("auto")), -2); + assert_eq!(arena_pin_cap_gib(Some("0")), 0); + assert_eq!(arena_pin_cap_gib(Some("24")), 24); + assert_eq!(arena_pin_cap_gib(Some("-3")), -1); + assert_eq!(arena_pin_cap_gib(Some("12abc")), 12); + assert_eq!(arena_pin_cap_gib(Some("abc")), 0); + assert_eq!(uniform_bounds(10, 4), vec![0, 4, 8]); + assert_eq!(uniform_bounds(12, 4), vec![0, 4, 8, 12]); + assert!(uniform_bounds(3, 4).is_empty()); + assert!(uniform_bounds(10, 0).is_empty()); + assert!(arena_lock_enabled(None) && arena_lock_enabled(Some("1")) && !arena_lock_enabled(Some("0"))); +} + +#[test] +fn pin_decision_and_sliced_registration() { + let gib = 1u64 << 30; + let d = decide_pin(64 * gib, 10, 0, -1); + assert_eq!((d.cap, d.capped), (0, false)); + let d = decide_pin(64 * gib, 10, 0, 24); + assert_eq!((d.cap, d.cap_why, d.capped), (24 * gib, "by STRATA_ARENA_PIN_GIB", true)); + // the engine's cap wins over the environment; a cap above the arena is not a cap; one slice cannot be sliced + assert_eq!(decide_pin(64 * gib, 10, 8 * gib, 24).cap, 8 * gib); + assert!(!decide_pin(16 * gib, 10, 24 * gib, -1).capped); + assert!(!decide_pin(64 * gib, 1, 8 * gib, -1).capped); + // slices stop at the driver's refusal and at the limit + let bounds = uniform_bounds(100, 10); + let refuse_at = 40; + let r = pin_sliced(&bounds, None, |off, _| off < refuse_at); + assert_eq!(r, SlicedPin { slice_starts: vec![0, 10, 20, 30], registered_bytes: 40, registered_slices: 4 }); + let r = pin_sliced(&bounds, Some(55), |_, _| true); + assert_eq!((r.registered_slices, r.registered_bytes), (5, 50)); + let r = pin_sliced(&bounds, Some(55), |_, _| true); + assert_eq!(r.slice_starts.last(), Some(&40), "slice 50..60 would pass the limit"); + // the constructor's note + let capped = decide_pin(64 * gib, 10, 0, 24); + let pinned = SlicedPin { slice_starts: vec![0], registered_bytes: 24 * gib, registered_slices: 24 }; + assert_eq!( + sliced_note(&capped, "", false, 0, "", &pinned, "MAP_PRIVATE"), + "cudaHostRegister limited to 24 GiB by STRATA_ARENA_PIN_GIB; 24 slices pinned (24 GiB); MAP_PRIVATE" + ); + let refused = decide_pin(64 * gib, 10, 0, -1); + assert_eq!( + sliced_note(&refused, "out of memory", true, 26 * gib, "the GPU's shared-memory budget", &pinned, "n"), + "cudaHostRegister of the whole arena FAILED (out of memory); slices capped at 26.0 GiB (the GPU's shared-memory budget; STRATA_ARENA_PIN_GIB=auto; N sets a cap; #243); 24 slices pinned (24 GiB); n" + ); +} + +#[cfg(unix)] +#[test] +fn parallel_load_matches_a_serial_read_and_reports_the_layer_checksums() { + let path = temp("experts"); + // 5 layers of different sizes at uneven offsets, a gap between layers, random-ish bytes + let mut x = 0x1234_5678_9abc_def0u64; + let file: Vec = (0..100_000).map(|_| { x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (x >> 56) as u8 }).collect(); + std::fs::write(&path, &file).unwrap(); + let off = [0u64, 7_001, 30_000, 31_000, 90_000]; + let len = [7_000u64, 22_999, 1_000, 40_000, 9_999]; + for threads in [1usize, 3, 8] { + for chunk in [1u64, 97, 4096, 1 << 20] { + let mut dst = vec![0xeeu8; 100_000]; + let stats = load_experts_ranges(&path, &mut dst, &off, &len, threads, chunk); + assert!(stats.ok, "{}", stats.error); + assert_eq!(stats.layers, 5); + assert_eq!(stats.bytes, len.iter().sum::()); + for l in 0..5 { + let r = off[l] as usize..(off[l] + len[l]) as usize; + assert_eq!(&dst[r.clone()], &file[r.clone()], "layer {l}"); + assert_eq!(stats.layer_checksums[l], fnv1a64(&file[r], FNV_SEED), "layer {l} checksum (chunking must not change it)"); + } + assert!(dst[7_000..7_001].iter().all(|b| *b == 0xee), "bytes between layers stay untouched"); + } + } + // uniform wrapper + let mut dst = vec![0u8; 50_000]; + let stats = load_experts(&path, &mut dst, 1000, 10, 5, 4, 3000); + assert!(stats.ok); + assert_eq!(&dst[..], &file[..50_000]); + // a short read names the layer and the offset; nothing is silently zero filled + let mut dst = vec![0u8; 200_000]; + let stats = load_experts_ranges(&path, &mut dst, &[0, 150_000], &[1000, 1000], 2, 512); + assert!(!stats.ok && stats.seconds < 0.0); + assert_eq!(stats.error, "short read in layer 1: got 0 of 512 B at offset 150000"); + // hardening: overlapping or out-of-range windows are refused before any read + let mut dst = vec![0u8; 1000]; + assert!(!load_experts_ranges(&path, &mut dst, &[0, 500], &[600, 100], 1, 64).ok); + assert!(!load_experts_ranges(&path, &mut dst, &[900], &[200], 1, 64).ok); + assert!(!load_experts_ranges(&temp("missing"), &mut dst, &[0], &[10], 1, 64).ok); + std::fs::remove_file(&path).unwrap(); +} diff --git a/crates/runtime-client/src/client.rs b/crates/runtime-client/src/client.rs index 6504cb04..80f8d2ab 100644 --- a/crates/runtime-client/src/client.rs +++ b/crates/runtime-client/src/client.rs @@ -323,261 +323,4 @@ impl Drop for RuntimeGeneration { } #[cfg(test)] -mod tests { - use super::*; - use futures_util::Stream; - use std::{ - pin::Pin, - sync::{ - Arc, - atomic::{AtomicUsize, Ordering}, - }, - }; - use tonic::Response; - #[test] - fn runtime_client_retained_handle_is_not_ready() { - let model = leleka_backend_api::ModelDescriptor { - family: "fixture".into(), - architecture: "fixture".into(), - weight_format: "fixture".into(), - artifact_digest: format!("sha256:{}", "a".repeat(64)), - }; - let loaded = leleka_backend_api::LoadedModel { - handle: "retained-fixture".into(), - descriptor: model, - load_config_version: 1, - effective_mode: leleka_backend_api::InferenceMode::Native, - mode_identity_digest: format!("sha256:{}", "b".repeat(64)), - }; - let mut snapshot = proto::Snapshot { - protocol_version: 1, - backend_api_version: 2, - epoch: uuid::Uuid::new_v4().to_string(), - sequence: 1, - full_snapshot: true, - transport_ready: true, - model_ready: false, - loaded: Some(convert::loaded_to_proto(&loaded)), - capabilities: Some(proto::Capabilities::default()), - active_request_id: String::new(), - prefix_cache_json: String::new(), - memory_json: String::new(), - telemetry_json: String::new(), - }; - assert!(validate_snapshot(&snapshot).is_ok()); - snapshot - .capabilities - .as_mut() - .unwrap() - .models - .push(proto::SupportedModelTuple { - family: "fixture".into(), - architecture: "fixture".into(), - weight_format: "fixture".into(), - }); - assert!(validate_snapshot(&snapshot).is_err()); - snapshot.capabilities = Some(proto::Capabilities::default()); - snapshot.loaded = None; - snapshot.model_ready = true; - assert!(validate_snapshot(&snapshot).is_err()); - } - #[derive(Clone)] - struct FaultServer { - epoch: String, - fault: u8, - cancels: Arc, - } - impl FaultServer { - fn snapshot(&self) -> proto::Snapshot { - proto::Snapshot { - protocol_version: 1, - backend_api_version: 2, - epoch: self.epoch.clone(), - sequence: 1, - full_snapshot: true, - transport_ready: true, - model_ready: false, - loaded: None, - capabilities: Some(proto::Capabilities::default()), - active_request_id: String::new(), - prefix_cache_json: String::new(), - memory_json: String::new(), - telemetry_json: String::new(), - } - } - } - #[tonic::async_trait] - impl proto::runtime_server::Runtime for FaultServer { - async fn handshake( - &self, - _: Request, - ) -> Result, Status> { - Ok(Response::new(self.snapshot())) - } - async fn snapshot( - &self, - _: Request, - ) -> Result, Status> { - Ok(Response::new(self.snapshot())) - } - type WatchStream = Pin> + Send>>; - async fn watch( - &self, - _: Request, - ) -> Result, Status> { - Err(Status::unimplemented("fixture")) - } - async fn load( - &self, - _: Request, - ) -> Result, Status> { - Err(Status::unimplemented("fixture")) - } - async fn unload( - &self, - _: Request, - ) -> Result, Status> { - Err(Status::unimplemented("fixture")) - } - async fn operation( - &self, - _: Request, - ) -> Result, Status> { - Err(Status::unimplemented("fixture")) - } - async fn reconfigure( - &self, - _: Request, - ) -> Result, Status> { - Err(Status::unimplemented("fixture")) - } - async fn cancel( - &self, - request: Request, - ) -> Result, Status> { - self.cancels.fetch_add(1, Ordering::SeqCst); - Ok(Response::new(proto::CancelAck { - request_id: request.get_ref().request_id.clone(), - epoch: self.epoch.clone(), - acknowledged: true, - })) - } - type GenerateStream = - Pin> + Send>>; - async fn generate( - &self, - request: Request, - ) -> Result, Status> { - let id = request.into_inner().request_id; - let frame = |sequence, payload| proto::GenerationFrame { - request_id: id.clone(), - epoch: self.epoch.clone(), - sequence, - payload: Some(payload), - }; - let mut frames = vec![Ok(frame( - 1, - proto::generation_frame::Payload::Accepted(proto::Accepted { accepted: true }), - ))]; - let terminal = frame( - if self.fault == 4 { 5 } else { 2 }, - proto::generation_frame::Payload::Terminal(proto::Terminal { - state: 1, - reason: "stop".into(), - usage: Some(proto::Usage::default()), - error_code: String::new(), - retryable: false, - }), - ); - if self.fault != 1 { - frames.push(Ok(terminal)); - } - if self.fault == 2 { - frames.push(Ok(frame( - 3, - proto::generation_frame::Payload::Text(proto::TextDelta { - text: "must-not-publish".into(), - }), - ))); - } - if self.fault == 3 { - frames.push(Err(Status::internal("fixture_trailer_error"))); - } - let stream = Box::pin(tokio_stream::iter(frames)) as Self::GenerateStream; - let mut response = Response::new(stream); - response - .metadata_mut() - .insert("x-leleka-accepted", "true".parse().unwrap()); - Ok(response) - } - } - #[tokio::test(flavor = "current_thread")] - async fn runtime_client_requires_terminal_eof_and_rejects_trailing_data_or_status() { - for fault in 0..=4 { - let epoch = uuid::Uuid::new_v4().to_string(); - let cancels = Arc::new(AtomicUsize::new(0)); - let service = FaultServer { - epoch: epoch.clone(), - fault, - cancels: cancels.clone(), - }; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let (stop, stopped) = tokio::sync::oneshot::channel(); - let task = tokio::spawn(async move { - tonic::transport::Server::builder() - .add_service(proto::runtime_server::RuntimeServer::new(service)) - .serve_with_incoming_shutdown( - tokio_stream::wrappers::TcpListenerStream::new(listener), - async { - let _ = stopped.await; - }, - ) - .await - .unwrap(); - }); - let mut client = - RuntimeClient::connect(address, "synthetic-runtime-test-token-00000000".into()) - .await - .unwrap(); - let mut stream = client - .generate(proto::GenerateRequest { - request_id: uuid::Uuid::new_v4().to_string(), - expected_epoch: epoch, - handle: "fixture".into(), - prompt: String::new(), - max_output_tokens: 1, - temperature_milli: 0, - ..Default::default() - }) - .await - .unwrap(); - assert!(matches!( - stream.message().await.unwrap().unwrap().payload, - Some(proto::generation_frame::Payload::Accepted(_)) - )); - if fault == 0 { - assert!(matches!( - stream.message().await.unwrap().unwrap().payload, - Some(proto::generation_frame::Payload::Terminal(_)) - )); - assert!(stream.message().await.unwrap().is_none()); - } else { - assert!(stream.message().await.is_err()); - } - drop(stream); - if fault != 0 { - for _ in 0..50 { - if cancels.load(Ordering::SeqCst) > 0 { - break; - } - tokio::time::sleep(Duration::from_millis(2)).await; - } - assert_eq!(cancels.load(Ordering::SeqCst), 1); - } - drop(client); - stop.send(()).unwrap(); - task.await.unwrap(); - } - } -} +mod tests; diff --git a/crates/runtime-client/src/client/tests.rs b/crates/runtime-client/src/client/tests.rs new file mode 100644 index 00000000..1a7340de --- /dev/null +++ b/crates/runtime-client/src/client/tests.rs @@ -0,0 +1,258 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use futures_util::Stream; +use std::{ + pin::Pin, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; +use tonic::Response; +#[test] +fn runtime_client_retained_handle_is_not_ready() { + let model = leleka_backend_api::ModelDescriptor { + family: "fixture".into(), + architecture: "fixture".into(), + weight_format: "fixture".into(), + artifact_digest: format!("sha256:{}", "a".repeat(64)), + }; + let loaded = leleka_backend_api::LoadedModel { + handle: "retained-fixture".into(), + descriptor: model, + load_config_version: 1, + effective_mode: leleka_backend_api::InferenceMode::Native, + mode_identity_digest: format!("sha256:{}", "b".repeat(64)), + }; + let mut snapshot = proto::Snapshot { + protocol_version: 1, + backend_api_version: 2, + epoch: uuid::Uuid::new_v4().to_string(), + sequence: 1, + full_snapshot: true, + transport_ready: true, + model_ready: false, + loaded: Some(convert::loaded_to_proto(&loaded)), + capabilities: Some(proto::Capabilities::default()), + active_request_id: String::new(), + prefix_cache_json: String::new(), + memory_json: String::new(), + telemetry_json: String::new(), + }; + assert!(validate_snapshot(&snapshot).is_ok()); + snapshot + .capabilities + .as_mut() + .unwrap() + .models + .push(proto::SupportedModelTuple { + family: "fixture".into(), + architecture: "fixture".into(), + weight_format: "fixture".into(), + }); + assert!(validate_snapshot(&snapshot).is_err()); + snapshot.capabilities = Some(proto::Capabilities::default()); + snapshot.loaded = None; + snapshot.model_ready = true; + assert!(validate_snapshot(&snapshot).is_err()); +} +#[derive(Clone)] +struct FaultServer { + epoch: String, + fault: u8, + cancels: Arc, +} +impl FaultServer { + fn snapshot(&self) -> proto::Snapshot { + proto::Snapshot { + protocol_version: 1, + backend_api_version: 2, + epoch: self.epoch.clone(), + sequence: 1, + full_snapshot: true, + transport_ready: true, + model_ready: false, + loaded: None, + capabilities: Some(proto::Capabilities::default()), + active_request_id: String::new(), + prefix_cache_json: String::new(), + memory_json: String::new(), + telemetry_json: String::new(), + } + } +} +#[tonic::async_trait] +impl proto::runtime_server::Runtime for FaultServer { + async fn handshake( + &self, + _: Request, + ) -> Result, Status> { + Ok(Response::new(self.snapshot())) + } + async fn snapshot( + &self, + _: Request, + ) -> Result, Status> { + Ok(Response::new(self.snapshot())) + } + type WatchStream = Pin> + Send>>; + async fn watch( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn load( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn unload( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn operation( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn reconfigure( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn cancel( + &self, + request: Request, + ) -> Result, Status> { + self.cancels.fetch_add(1, Ordering::SeqCst); + Ok(Response::new(proto::CancelAck { + request_id: request.get_ref().request_id.clone(), + epoch: self.epoch.clone(), + acknowledged: true, + })) + } + type GenerateStream = + Pin> + Send>>; + async fn generate( + &self, + request: Request, + ) -> Result, Status> { + let id = request.into_inner().request_id; + let frame = |sequence, payload| proto::GenerationFrame { + request_id: id.clone(), + epoch: self.epoch.clone(), + sequence, + payload: Some(payload), + }; + let mut frames = vec![Ok(frame( + 1, + proto::generation_frame::Payload::Accepted(proto::Accepted { accepted: true }), + ))]; + let terminal = frame( + if self.fault == 4 { 5 } else { 2 }, + proto::generation_frame::Payload::Terminal(proto::Terminal { + state: 1, + reason: "stop".into(), + usage: Some(proto::Usage::default()), + error_code: String::new(), + retryable: false, + }), + ); + if self.fault != 1 { + frames.push(Ok(terminal)); + } + if self.fault == 2 { + frames.push(Ok(frame( + 3, + proto::generation_frame::Payload::Text(proto::TextDelta { + text: "must-not-publish".into(), + }), + ))); + } + if self.fault == 3 { + frames.push(Err(Status::internal("fixture_trailer_error"))); + } + let stream = Box::pin(tokio_stream::iter(frames)) as Self::GenerateStream; + let mut response = Response::new(stream); + response + .metadata_mut() + .insert("x-leleka-accepted", "true".parse().unwrap()); + Ok(response) + } +} +#[tokio::test(flavor = "current_thread")] +async fn runtime_client_requires_terminal_eof_and_rejects_trailing_data_or_status() { + for fault in 0..=4 { + let epoch = uuid::Uuid::new_v4().to_string(); + let cancels = Arc::new(AtomicUsize::new(0)); + let service = FaultServer { + epoch: epoch.clone(), + fault, + cancels: cancels.clone(), + }; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (stop, stopped) = tokio::sync::oneshot::channel(); + let task = tokio::spawn(async move { + tonic::transport::Server::builder() + .add_service(proto::runtime_server::RuntimeServer::new(service)) + .serve_with_incoming_shutdown( + tokio_stream::wrappers::TcpListenerStream::new(listener), + async { + let _ = stopped.await; + }, + ) + .await + .unwrap(); + }); + let mut client = + RuntimeClient::connect(address, "synthetic-runtime-test-token-00000000".into()) + .await + .unwrap(); + let mut stream = client + .generate(proto::GenerateRequest { + request_id: uuid::Uuid::new_v4().to_string(), + expected_epoch: epoch, + handle: "fixture".into(), + prompt: String::new(), + max_output_tokens: 1, + temperature_milli: 0, + ..Default::default() + }) + .await + .unwrap(); + assert!(matches!( + stream.message().await.unwrap().unwrap().payload, + Some(proto::generation_frame::Payload::Accepted(_)) + )); + if fault == 0 { + assert!(matches!( + stream.message().await.unwrap().unwrap().payload, + Some(proto::generation_frame::Payload::Terminal(_)) + )); + assert!(stream.message().await.unwrap().is_none()); + } else { + assert!(stream.message().await.is_err()); + } + drop(stream); + if fault != 0 { + for _ in 0..50 { + if cancels.load(Ordering::SeqCst) > 0 { + break; + } + tokio::time::sleep(Duration::from_millis(2)).await; + } + assert_eq!(cancels.load(Ordering::SeqCst), 1); + } + drop(client); + stop.send(()).unwrap(); + task.await.unwrap(); + } +} diff --git a/crates/sampler-ref/src/chain.rs b/crates/sampler-ref/src/chain.rs index 685200e4..b5011664 100644 --- a/crates/sampler-ref/src/chain.rs +++ b/crates/sampler-ref/src/chain.rs @@ -384,172 +384,4 @@ pub fn sample_tokens( } #[cfg(test)] -mod tests { - use super::*; - - fn p() -> SamplerParams { - SamplerParams { - seed: 7, - ..SamplerParams::default() - } - } - - #[test] - fn sampled_k_rules() { - assert_eq!(sampled_k(20, 1000), 20); - assert_eq!(sampled_k(0, 1000), 64); - assert_eq!(sampled_k(-5, 1000), 64); - assert_eq!(sampled_k(63, 1000), 63); - assert_eq!(sampled_k(64, 1000), 64); - assert_eq!(sampled_k(65, 1000), 64); - assert_eq!(sampled_k(20, 8), 8); - } - - #[test] - fn repeat_penalty_multiplies_negative_and_divides_positive() { - let q = SamplerParams { - penalty_repeat: 2.0, - ..p() - }; - assert_eq!(apply_penalties(-3.0, 1, &q), -6.0); - assert_eq!(apply_penalties(4.0, 1, &q), 2.0); - assert_eq!(apply_penalties(4.0, 0, &q), 4.0); - let r = SamplerParams { - penalty_freq: 0.5, - penalty_present: 1.5, - ..p() - }; - // count 3: 3*0.5 + 1*1.5 = 3.0 off the (unchanged) logit - assert_eq!(apply_penalties(10.0, 3, &r), 7.0); - } - - #[test] - fn greedy_ties_go_to_lowest_index_and_empty_rows_answer_zero() { - assert_eq!(greedy_pick(&[1.0, 3.0, 3.0, 2.0]), 1); - assert_eq!(greedy_pick(&[f32::NEG_INFINITY, f32::NAN]), 0); - assert_eq!(greedy_pick(&[f32::NAN, -1.0]), 1); - } - - #[test] - fn selection_is_descending_with_lowest_id_ties() { - let s = select_topk(&[1.0, 5.0, 5.0, 2.0, 5.0], 4); - assert_eq!(s.ids, vec![1, 2, 4, 3]); - assert_eq!(s.logits, vec![5.0, 5.0, 5.0, 2.0]); - } - - #[test] - fn selection_sentinel_is_id_zero_neg_inf() { - let s = select_topk(&[f32::NEG_INFINITY, 1.0, f32::NAN], 3); - assert_eq!(s.ids, vec![1, 0, 0]); - assert_eq!(s.logits[0], 1.0); - assert!(s.logits[1] == f32::NEG_INFINITY && s.logits[2] == f32::NEG_INFINITY); - } - - #[test] - fn penalty_window_is_the_tail() { - let h = [-1, -1, 5, 6, 7]; - assert_eq!(penalty_window(&h, 2), &[6, 7]); - assert_eq!(penalty_window(&h, 99), &h); - assert_eq!(penalty_window(&h, 0), &[] as &[i32]); - assert_eq!(penalty_window(&h, -3), &[] as &[i32]); - } - - #[test] - fn history_is_required_when_penalising() { - let q = SamplerParams { - penalty_last_n: 4, - ..p() - }; - assert_eq!( - sample_row(&[0.0, 1.0], &[], &q, 0), - Err(SamplerError::HistoryRequired) - ); - assert_eq!( - sample_tokens(&[0.0, 1.0], 1, 2, None, &q), - Err(SamplerError::HistoryRequired) - ); - } - - #[test] - fn shapes_are_checked() { - assert_eq!( - sample_tokens(&[0.0; 5], 2, 3, None, &p()), - Err(SamplerError::LogitsLength { - expected: 6, - actual: 5 - }) - ); - assert_eq!( - sample_tokens(&[0.0; 6], 2, 3, Some((&[0; 5], 3)), &p()), - Err(SamplerError::HistoryShape { - expected: 6, - actual: 5 - }) - ); - assert_eq!(sample_tokens(&[], 0, 3, None, &p()), Ok(vec![])); - assert_eq!( - sample_tokens(&[], 1, 0, None, &p()), - Err(SamplerError::EmptyVocabulary) - ); - } - - #[test] - fn counter_advances_per_row_and_batch_equals_singles() { - let vocab = 16; - let count = 32; - let logits = vec![0.0f32; count * vocab]; - let q = SamplerParams { - top_k: 16, - top_p: 1.0, - seed: 123, - counter: (1 << 32) + 7, - ..p() - }; - let batch = sample_tokens(&logits, count, vocab, None, &q).unwrap(); - let singles: Vec = (0..count) - .map(|i| { - let one = SamplerParams { - counter: q.counter + i as u64, - ..q - }; - sample_tokens(&logits[..vocab], 1, vocab, None, &one).unwrap()[0] - }) - .collect(); - assert_eq!(batch, singles); - assert!( - batch.iter().any(|&t| t != batch[0]), - "uniform logits must vary across draws" - ); - } - - #[test] - fn temperature_zero_or_greedy_flag_is_argmax() { - let l = [0.0, 2.0, 1.0]; - let q = SamplerParams { - temperature: 0.0, - ..p() - }; - assert_eq!(sample_row(&l, &[], &q, 0), Ok(1)); - let g = SamplerParams { - greedy: true, - temperature: 1.0, - ..p() - }; - assert_eq!(sample_row(&l, &[], &g, 0), Ok(1)); - } - - #[test] - fn min_p_cuts_a_prefix_of_the_list() { - let sel = Selection { - ids: vec![3, 1, 2], - logits: vec![5.0, 4.9, 0.0], - }; - let q = SamplerParams { - top_p: 1.0, - min_p: 0.5, - ..p() - }; - let pick = pick_from_list(&sel, &q, 0); - assert_eq!(pick.n_keep, 2); - } -} +mod tests; diff --git a/crates/sampler-ref/src/chain/tests.rs b/crates/sampler-ref/src/chain/tests.rs new file mode 100644 index 00000000..976981d5 --- /dev/null +++ b/crates/sampler-ref/src/chain/tests.rs @@ -0,0 +1,169 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn p() -> SamplerParams { + SamplerParams { + seed: 7, + ..SamplerParams::default() + } +} + +#[test] +fn sampled_k_rules() { + assert_eq!(sampled_k(20, 1000), 20); + assert_eq!(sampled_k(0, 1000), 64); + assert_eq!(sampled_k(-5, 1000), 64); + assert_eq!(sampled_k(63, 1000), 63); + assert_eq!(sampled_k(64, 1000), 64); + assert_eq!(sampled_k(65, 1000), 64); + assert_eq!(sampled_k(20, 8), 8); +} + +#[test] +fn repeat_penalty_multiplies_negative_and_divides_positive() { + let q = SamplerParams { + penalty_repeat: 2.0, + ..p() + }; + assert_eq!(apply_penalties(-3.0, 1, &q), -6.0); + assert_eq!(apply_penalties(4.0, 1, &q), 2.0); + assert_eq!(apply_penalties(4.0, 0, &q), 4.0); + let r = SamplerParams { + penalty_freq: 0.5, + penalty_present: 1.5, + ..p() + }; + // count 3: 3*0.5 + 1*1.5 = 3.0 off the (unchanged) logit + assert_eq!(apply_penalties(10.0, 3, &r), 7.0); +} + +#[test] +fn greedy_ties_go_to_lowest_index_and_empty_rows_answer_zero() { + assert_eq!(greedy_pick(&[1.0, 3.0, 3.0, 2.0]), 1); + assert_eq!(greedy_pick(&[f32::NEG_INFINITY, f32::NAN]), 0); + assert_eq!(greedy_pick(&[f32::NAN, -1.0]), 1); +} + +#[test] +fn selection_is_descending_with_lowest_id_ties() { + let s = select_topk(&[1.0, 5.0, 5.0, 2.0, 5.0], 4); + assert_eq!(s.ids, vec![1, 2, 4, 3]); + assert_eq!(s.logits, vec![5.0, 5.0, 5.0, 2.0]); +} + +#[test] +fn selection_sentinel_is_id_zero_neg_inf() { + let s = select_topk(&[f32::NEG_INFINITY, 1.0, f32::NAN], 3); + assert_eq!(s.ids, vec![1, 0, 0]); + assert_eq!(s.logits[0], 1.0); + assert!(s.logits[1] == f32::NEG_INFINITY && s.logits[2] == f32::NEG_INFINITY); +} + +#[test] +fn penalty_window_is_the_tail() { + let h = [-1, -1, 5, 6, 7]; + assert_eq!(penalty_window(&h, 2), &[6, 7]); + assert_eq!(penalty_window(&h, 99), &h); + assert_eq!(penalty_window(&h, 0), &[] as &[i32]); + assert_eq!(penalty_window(&h, -3), &[] as &[i32]); +} + +#[test] +fn history_is_required_when_penalising() { + let q = SamplerParams { + penalty_last_n: 4, + ..p() + }; + assert_eq!( + sample_row(&[0.0, 1.0], &[], &q, 0), + Err(SamplerError::HistoryRequired) + ); + assert_eq!( + sample_tokens(&[0.0, 1.0], 1, 2, None, &q), + Err(SamplerError::HistoryRequired) + ); +} + +#[test] +fn shapes_are_checked() { + assert_eq!( + sample_tokens(&[0.0; 5], 2, 3, None, &p()), + Err(SamplerError::LogitsLength { + expected: 6, + actual: 5 + }) + ); + assert_eq!( + sample_tokens(&[0.0; 6], 2, 3, Some((&[0; 5], 3)), &p()), + Err(SamplerError::HistoryShape { + expected: 6, + actual: 5 + }) + ); + assert_eq!(sample_tokens(&[], 0, 3, None, &p()), Ok(vec![])); + assert_eq!( + sample_tokens(&[], 1, 0, None, &p()), + Err(SamplerError::EmptyVocabulary) + ); +} + +#[test] +fn counter_advances_per_row_and_batch_equals_singles() { + let vocab = 16; + let count = 32; + let logits = vec![0.0f32; count * vocab]; + let q = SamplerParams { + top_k: 16, + top_p: 1.0, + seed: 123, + counter: (1 << 32) + 7, + ..p() + }; + let batch = sample_tokens(&logits, count, vocab, None, &q).unwrap(); + let singles: Vec = (0..count) + .map(|i| { + let one = SamplerParams { + counter: q.counter + i as u64, + ..q + }; + sample_tokens(&logits[..vocab], 1, vocab, None, &one).unwrap()[0] + }) + .collect(); + assert_eq!(batch, singles); + assert!( + batch.iter().any(|&t| t != batch[0]), + "uniform logits must vary across draws" + ); +} + +#[test] +fn temperature_zero_or_greedy_flag_is_argmax() { + let l = [0.0, 2.0, 1.0]; + let q = SamplerParams { + temperature: 0.0, + ..p() + }; + assert_eq!(sample_row(&l, &[], &q, 0), Ok(1)); + let g = SamplerParams { + greedy: true, + temperature: 1.0, + ..p() + }; + assert_eq!(sample_row(&l, &[], &g, 0), Ok(1)); +} + +#[test] +fn min_p_cuts_a_prefix_of_the_list() { + let sel = Selection { + ids: vec![3, 1, 2], + logits: vec![5.0, 4.9, 0.0], + }; + let q = SamplerParams { + top_p: 1.0, + min_p: 0.5, + ..p() + }; + let pick = pick_from_list(&sel, &q, 0); + assert_eq!(pick.n_keep, 2); +} diff --git a/crates/sampler-ref/src/params.rs b/crates/sampler-ref/src/params.rs index 50536392..7ece7cd3 100644 --- a/crates/sampler-ref/src/params.rs +++ b/crates/sampler-ref/src/params.rs @@ -392,353 +392,4 @@ pub fn py_float_repr(x: f64) -> String { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn python_repr_matches_known_values() { - for (x, want) in [ - (0.0, "0.0"), - (1.0, "1.0"), - (0.7, "0.7"), - (0.95, "0.95"), - (100.0, "100.0"), - (1e15, "1000000000000000.0"), - (1e16, "1e+16"), - (1.5e16, "1.5e+16"), - (0.0001, "0.0001"), - (0.00001, "1e-05"), - (1.5e-7, "1.5e-07"), - (123.456, "123.456"), - (-2.5, "-2.5"), - (0.1 + 0.2, "0.30000000000000004"), - ] { - assert_eq!(py_float_repr(x), want, "{x:?}"); - } - } - - #[test] - fn absent_fields_are_the_originals_gen_defaults() { - let p = SamplingParams::resolve(&RequestSampling::default()).unwrap(); - assert!(p.is_greedy()); - assert_eq!((p.top_p, p.top_k, p.min_p), (1.0, 20, 0.0)); - assert_eq!( - (p.penalty_repeat, p.penalty_freq, p.penalty_present), - (1.0, 0.0, 0.0) - ); - assert_eq!(p.penalty_last_n, 0); - assert_eq!(p.seed, None); - assert_eq!(RequestSampling::default().gen_keys().unwrap(), ""); - } - - #[test] - fn top_k_normalises_to_the_engine_range() { - for (given, want) in [(0, 64), (1, 1), (20, 20), (64, 64), (65, 64), (100_000, 64)] { - let r = RequestSampling { - top_k: Some(given), - ..Default::default() - }; - assert_eq!(SamplingParams::resolve(&r).unwrap().top_k, want); - assert_eq!(r.gen_keys().unwrap(), format!(" top_k={want}")); - } - } - - #[test] - fn a_penalty_without_a_window_gets_64() { - let r = RequestSampling { - presence_penalty: Some(0.5), - ..Default::default() - }; - let p = SamplingParams::resolve(&r).unwrap(); - assert_eq!(p.penalty_last_n, 64); - assert_eq!( - r.gen_keys().unwrap(), - " penalty_present=0.5 penalty_last_n=64" - ); - // a window with no active penalty is not emitted and not applied - let r = RequestSampling { - penalty_last_n: Some(10), - ..Default::default() - }; - assert_eq!(SamplingParams::resolve(&r).unwrap().penalty_last_n, 0); - assert_eq!(r.gen_keys().unwrap(), ""); - // an explicit window wins; a zero window falls back to 64 like Python - let r = RequestSampling { - repetition_penalty: Some(1.1), - penalty_last_n: Some(0), - ..Default::default() - }; - assert_eq!(SamplingParams::resolve(&r).unwrap().penalty_last_n, 64); - let r = RequestSampling { - repetition_penalty: Some(1.1), - penalty_last_n: Some(4097), - ..Default::default() - }; - let p = SamplingParams::resolve(&r).unwrap(); - assert_eq!(p.penalty_last_n, 4097); - assert_eq!(p.history_slots(), 4096); - } - - #[test] - fn engine_params_follow_generate_cpp() { - let r = RequestSampling { - temperature: Some(0.7), - top_p: Some(0.9), - seed: Some(42), - ..Default::default() - }; - let sp = SamplingParams::resolve(&r).unwrap().to_sampler_params(999); - assert!(!sp.greedy); - assert_eq!(sp.seed, 42); - assert_eq!(sp.counter, 0); - assert_eq!(sp.min_keep, 1); - assert_eq!(sp.temperature, 0.7f32); - // no seed: the caller's entropy - let r = RequestSampling { - temperature: Some(1.0), - ..Default::default() - }; - assert_eq!( - SamplingParams::resolve(&r) - .unwrap() - .to_sampler_params(999) - .seed, - 999 - ); - // temperature 0 stays greedy whatever else is set - let r = RequestSampling { - temperature: Some(0.0), - top_p: Some(0.5), - ..Default::default() - }; - assert!( - SamplingParams::resolve(&r) - .unwrap() - .to_sampler_params(1) - .greedy - ); - } - - #[test] - fn invalid_fields_are_rejected() { - let bad = |r: RequestSampling| SamplingParams::resolve(&r).unwrap_err().field; - let d = RequestSampling::default; - assert_eq!( - bad(RequestSampling { - temperature: Some(-0.1), - ..d() - }), - "temperature" - ); - assert_eq!( - bad(RequestSampling { - temperature: Some(2.5), - ..d() - }), - "temperature" - ); - assert_eq!( - bad(RequestSampling { - temperature: Some(f64::NAN), - ..d() - }), - "temperature" - ); - assert_eq!( - bad(RequestSampling { - top_p: Some(1.5), - ..d() - }), - "top_p" - ); - assert_eq!( - bad(RequestSampling { - top_p: Some(f64::INFINITY), - ..d() - }), - "top_p" - ); - assert_eq!( - bad(RequestSampling { - top_k: Some(-1), - ..d() - }), - "top_k" - ); - assert_eq!( - bad(RequestSampling { - min_p: Some(1.01), - ..d() - }), - "min_p" - ); - assert_eq!( - bad(RequestSampling { - repetition_penalty: Some(0.0), - ..d() - }), - "repetition_penalty" - ); - assert_eq!( - bad(RequestSampling { - frequency_penalty: Some(3.0), - ..d() - }), - "frequency_penalty" - ); - assert_eq!( - bad(RequestSampling { - presence_penalty: Some(f64::NAN), - ..d() - }), - "presence_penalty" - ); - assert_eq!( - bad(RequestSampling { - penalty_last_n: Some(-1), - ..d() - }), - "penalty_last_n" - ); - // a bad request never reaches the wire either - assert!( - RequestSampling { - top_k: Some(-5), - ..d() - } - .gen_keys() - .is_err() - ); - } - - #[test] - fn config_defaults_use_the_servers_stricter_ranges() { - let d = RequestSampling::default; - assert!( - RequestSampling { - top_p: Some(0.0), - ..d() - } - .validate() - .is_ok() - ); - assert!( - RequestSampling { - top_p: Some(0.0), - ..d() - } - .validate_config_defaults() - .is_err() - ); - assert!( - RequestSampling { - top_k: Some(0), - ..d() - } - .validate_config_defaults() - .is_err() - ); - assert!( - RequestSampling { - top_k: Some(65), - ..d() - } - .validate_config_defaults() - .is_err() - ); - assert!( - RequestSampling { - presence_penalty: Some(-0.5), - ..d() - } - .validate_config_defaults() - .is_err() - ); - assert!( - RequestSampling { - seed: Some(0), - ..d() - } - .validate_config_defaults() - .is_err() - ); - assert!( - RequestSampling { - temperature: Some(0.6), - top_k: Some(20), - seed: Some(7), - ..d() - } - .validate_config_defaults() - .is_ok() - ); - } - - #[test] - fn overlay_lets_the_request_win_including_explicit_zero() { - let defaults = RequestSampling { - temperature: Some(0.6), - top_p: Some(0.95), - top_k: Some(20), - ..Default::default() - }; - let request = RequestSampling { - temperature: Some(0.0), - seed: Some(9), - ..Default::default() - }; - let merged = RequestSampling::overlay(&defaults, &request); - assert_eq!(merged.temperature, Some(0.0)); - assert_eq!(merged.top_p, Some(0.95)); - assert_eq!(merged.seed, Some(9)); - assert!(SamplingParams::resolve(&merged).unwrap().is_greedy()); - } - - #[test] - fn fixed_point_requests_match_the_decimal_the_client_wrote() { - let f = FixedPoint { - temperature_milli: 700, - top_p_micro: Some(950_000), - top_k: Some(40), - min_p_micro: Some(50_000), - repetition_penalty_micro: Some(1_100_000), - frequency_penalty_micro: Some(-250_000), - presence_penalty_micro: Some(500_000), - penalty_last_n: Some(128), - seed: Some(9), - }; - let r = RequestSampling::from_fixed_point(&f); - assert_eq!(r.temperature, Some(0.7)); - assert_eq!(r.top_p, Some(0.95)); - assert_eq!(r.min_p, Some(0.05)); - assert_eq!(r.repetition_penalty, Some(1.1)); - assert_eq!(r.frequency_penalty, Some(-0.25)); - let p = SamplingParams::resolve(&r).unwrap(); - assert!(p.needs_sampler() && !p.is_greedy()); - assert_eq!((p.top_k, p.penalty_last_n), (40, 128)); - // the all-default request stays on the plain greedy path - let d = SamplingParams::resolve(&RequestSampling::from_fixed_point(&FixedPoint::default())) - .unwrap(); - assert!(d.is_greedy() && !d.needs_sampler()); - // greedy with a penalty still needs the penalised argmax - let g = FixedPoint { - presence_penalty_micro: Some(500_000), - ..FixedPoint::default() - }; - let g = SamplingParams::resolve(&RequestSampling::from_fixed_point(&g)).unwrap(); - assert!(g.is_greedy() && g.needs_sampler()); - // out-of-range temperatures are refused - let hot = FixedPoint { - temperature_milli: 2001, - ..FixedPoint::default() - }; - assert!(SamplingParams::resolve(&RequestSampling::from_fixed_point(&hot)).is_err()); - } - - #[test] - fn wire_floats_go_through_the_decimal_text() { - assert_eq!(wire_f32(0.7), 0.7f32); - assert_eq!(wire_f32(1e-7), 1e-7f32); - assert_eq!(wire_f32(1.0), 1.0f32); - } -} +mod tests; diff --git a/crates/sampler-ref/src/params/tests.rs b/crates/sampler-ref/src/params/tests.rs new file mode 100644 index 00000000..a48d37a5 --- /dev/null +++ b/crates/sampler-ref/src/params/tests.rs @@ -0,0 +1,350 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +#[test] +fn python_repr_matches_known_values() { + for (x, want) in [ + (0.0, "0.0"), + (1.0, "1.0"), + (0.7, "0.7"), + (0.95, "0.95"), + (100.0, "100.0"), + (1e15, "1000000000000000.0"), + (1e16, "1e+16"), + (1.5e16, "1.5e+16"), + (0.0001, "0.0001"), + (0.00001, "1e-05"), + (1.5e-7, "1.5e-07"), + (123.456, "123.456"), + (-2.5, "-2.5"), + (0.1 + 0.2, "0.30000000000000004"), + ] { + assert_eq!(py_float_repr(x), want, "{x:?}"); + } +} + +#[test] +fn absent_fields_are_the_originals_gen_defaults() { + let p = SamplingParams::resolve(&RequestSampling::default()).unwrap(); + assert!(p.is_greedy()); + assert_eq!((p.top_p, p.top_k, p.min_p), (1.0, 20, 0.0)); + assert_eq!( + (p.penalty_repeat, p.penalty_freq, p.penalty_present), + (1.0, 0.0, 0.0) + ); + assert_eq!(p.penalty_last_n, 0); + assert_eq!(p.seed, None); + assert_eq!(RequestSampling::default().gen_keys().unwrap(), ""); +} + +#[test] +fn top_k_normalises_to_the_engine_range() { + for (given, want) in [(0, 64), (1, 1), (20, 20), (64, 64), (65, 64), (100_000, 64)] { + let r = RequestSampling { + top_k: Some(given), + ..Default::default() + }; + assert_eq!(SamplingParams::resolve(&r).unwrap().top_k, want); + assert_eq!(r.gen_keys().unwrap(), format!(" top_k={want}")); + } +} + +#[test] +fn a_penalty_without_a_window_gets_64() { + let r = RequestSampling { + presence_penalty: Some(0.5), + ..Default::default() + }; + let p = SamplingParams::resolve(&r).unwrap(); + assert_eq!(p.penalty_last_n, 64); + assert_eq!( + r.gen_keys().unwrap(), + " penalty_present=0.5 penalty_last_n=64" + ); + // a window with no active penalty is not emitted and not applied + let r = RequestSampling { + penalty_last_n: Some(10), + ..Default::default() + }; + assert_eq!(SamplingParams::resolve(&r).unwrap().penalty_last_n, 0); + assert_eq!(r.gen_keys().unwrap(), ""); + // an explicit window wins; a zero window falls back to 64 like Python + let r = RequestSampling { + repetition_penalty: Some(1.1), + penalty_last_n: Some(0), + ..Default::default() + }; + assert_eq!(SamplingParams::resolve(&r).unwrap().penalty_last_n, 64); + let r = RequestSampling { + repetition_penalty: Some(1.1), + penalty_last_n: Some(4097), + ..Default::default() + }; + let p = SamplingParams::resolve(&r).unwrap(); + assert_eq!(p.penalty_last_n, 4097); + assert_eq!(p.history_slots(), 4096); +} + +#[test] +fn engine_params_follow_generate_cpp() { + let r = RequestSampling { + temperature: Some(0.7), + top_p: Some(0.9), + seed: Some(42), + ..Default::default() + }; + let sp = SamplingParams::resolve(&r).unwrap().to_sampler_params(999); + assert!(!sp.greedy); + assert_eq!(sp.seed, 42); + assert_eq!(sp.counter, 0); + assert_eq!(sp.min_keep, 1); + assert_eq!(sp.temperature, 0.7f32); + // no seed: the caller's entropy + let r = RequestSampling { + temperature: Some(1.0), + ..Default::default() + }; + assert_eq!( + SamplingParams::resolve(&r) + .unwrap() + .to_sampler_params(999) + .seed, + 999 + ); + // temperature 0 stays greedy whatever else is set + let r = RequestSampling { + temperature: Some(0.0), + top_p: Some(0.5), + ..Default::default() + }; + assert!( + SamplingParams::resolve(&r) + .unwrap() + .to_sampler_params(1) + .greedy + ); +} + +#[test] +fn invalid_fields_are_rejected() { + let bad = |r: RequestSampling| SamplingParams::resolve(&r).unwrap_err().field; + let d = RequestSampling::default; + assert_eq!( + bad(RequestSampling { + temperature: Some(-0.1), + ..d() + }), + "temperature" + ); + assert_eq!( + bad(RequestSampling { + temperature: Some(2.5), + ..d() + }), + "temperature" + ); + assert_eq!( + bad(RequestSampling { + temperature: Some(f64::NAN), + ..d() + }), + "temperature" + ); + assert_eq!( + bad(RequestSampling { + top_p: Some(1.5), + ..d() + }), + "top_p" + ); + assert_eq!( + bad(RequestSampling { + top_p: Some(f64::INFINITY), + ..d() + }), + "top_p" + ); + assert_eq!( + bad(RequestSampling { + top_k: Some(-1), + ..d() + }), + "top_k" + ); + assert_eq!( + bad(RequestSampling { + min_p: Some(1.01), + ..d() + }), + "min_p" + ); + assert_eq!( + bad(RequestSampling { + repetition_penalty: Some(0.0), + ..d() + }), + "repetition_penalty" + ); + assert_eq!( + bad(RequestSampling { + frequency_penalty: Some(3.0), + ..d() + }), + "frequency_penalty" + ); + assert_eq!( + bad(RequestSampling { + presence_penalty: Some(f64::NAN), + ..d() + }), + "presence_penalty" + ); + assert_eq!( + bad(RequestSampling { + penalty_last_n: Some(-1), + ..d() + }), + "penalty_last_n" + ); + // a bad request never reaches the wire either + assert!( + RequestSampling { + top_k: Some(-5), + ..d() + } + .gen_keys() + .is_err() + ); +} + +#[test] +fn config_defaults_use_the_servers_stricter_ranges() { + let d = RequestSampling::default; + assert!( + RequestSampling { + top_p: Some(0.0), + ..d() + } + .validate() + .is_ok() + ); + assert!( + RequestSampling { + top_p: Some(0.0), + ..d() + } + .validate_config_defaults() + .is_err() + ); + assert!( + RequestSampling { + top_k: Some(0), + ..d() + } + .validate_config_defaults() + .is_err() + ); + assert!( + RequestSampling { + top_k: Some(65), + ..d() + } + .validate_config_defaults() + .is_err() + ); + assert!( + RequestSampling { + presence_penalty: Some(-0.5), + ..d() + } + .validate_config_defaults() + .is_err() + ); + assert!( + RequestSampling { + seed: Some(0), + ..d() + } + .validate_config_defaults() + .is_err() + ); + assert!( + RequestSampling { + temperature: Some(0.6), + top_k: Some(20), + seed: Some(7), + ..d() + } + .validate_config_defaults() + .is_ok() + ); +} + +#[test] +fn overlay_lets_the_request_win_including_explicit_zero() { + let defaults = RequestSampling { + temperature: Some(0.6), + top_p: Some(0.95), + top_k: Some(20), + ..Default::default() + }; + let request = RequestSampling { + temperature: Some(0.0), + seed: Some(9), + ..Default::default() + }; + let merged = RequestSampling::overlay(&defaults, &request); + assert_eq!(merged.temperature, Some(0.0)); + assert_eq!(merged.top_p, Some(0.95)); + assert_eq!(merged.seed, Some(9)); + assert!(SamplingParams::resolve(&merged).unwrap().is_greedy()); +} + +#[test] +fn fixed_point_requests_match_the_decimal_the_client_wrote() { + let f = FixedPoint { + temperature_milli: 700, + top_p_micro: Some(950_000), + top_k: Some(40), + min_p_micro: Some(50_000), + repetition_penalty_micro: Some(1_100_000), + frequency_penalty_micro: Some(-250_000), + presence_penalty_micro: Some(500_000), + penalty_last_n: Some(128), + seed: Some(9), + }; + let r = RequestSampling::from_fixed_point(&f); + assert_eq!(r.temperature, Some(0.7)); + assert_eq!(r.top_p, Some(0.95)); + assert_eq!(r.min_p, Some(0.05)); + assert_eq!(r.repetition_penalty, Some(1.1)); + assert_eq!(r.frequency_penalty, Some(-0.25)); + let p = SamplingParams::resolve(&r).unwrap(); + assert!(p.needs_sampler() && !p.is_greedy()); + assert_eq!((p.top_k, p.penalty_last_n), (40, 128)); + // the all-default request stays on the plain greedy path + let d = SamplingParams::resolve(&RequestSampling::from_fixed_point(&FixedPoint::default())) + .unwrap(); + assert!(d.is_greedy() && !d.needs_sampler()); + // greedy with a penalty still needs the penalised argmax + let g = FixedPoint { + presence_penalty_micro: Some(500_000), + ..FixedPoint::default() + }; + let g = SamplingParams::resolve(&RequestSampling::from_fixed_point(&g)).unwrap(); + assert!(g.is_greedy() && g.needs_sampler()); + // out-of-range temperatures are refused + let hot = FixedPoint { + temperature_milli: 2001, + ..FixedPoint::default() + }; + assert!(SamplingParams::resolve(&RequestSampling::from_fixed_point(&hot)).is_err()); +} + +#[test] +fn wire_floats_go_through_the_decimal_text() { + assert_eq!(wire_f32(0.7), 0.7f32); + assert_eq!(wire_f32(1e-7), 1e-7f32); + assert_eq!(wire_f32(1.0), 1.0f32); +} diff --git a/crates/sampler-ref/src/serve.rs b/crates/sampler-ref/src/serve.rs index 5ccbc713..afd5675b 100644 --- a/crates/sampler-ref/src/serve.rs +++ b/crates/sampler-ref/src/serve.rs @@ -231,178 +231,4 @@ pub fn settle_window( } #[cfg(test)] -mod tests { - use super::*; - - fn request(f: impl FnOnce(&mut SamplerParams)) -> SamplerParams { - let mut p = SamplerParams { - temperature: 0.8, - ..SamplerParams::default() - }; - f(&mut p); - p - } - - #[test] - fn request_parameters_follow_the_serve_loop() { - let s = ServeSampling::new(&request(|p| p.counter = 77), 555, true); - assert_eq!( - (s.params().seed, s.params().counter), - (555, 0), - "seed 0 takes the clock; counter restarts" - ); - let s = ServeSampling::new(&request(|p| p.seed = 9), 555, true); - assert_eq!(s.params().seed, 9); - let s = ServeSampling::new(&request(|p| p.min_p = 3.0), 1, true); - assert_eq!(s.params().min_p, 1.0); - let s = ServeSampling::new(&request(|p| p.min_p = -1.0), 1, true); - assert_eq!(s.params().min_p, 0.0); - let s = ServeSampling::new(&request(|p| p.penalty_last_n = -5), 1, true); - assert_eq!((s.params().penalty_last_n, s.hist_n()), (0, 0)); - let s = ServeSampling::new(&request(|p| p.penalty_last_n = 100_000), 1, true); - assert_eq!((s.params().penalty_last_n, s.hist_n()), (100_000, 4096)); - // greedy iff temperature <= 0, whatever else the request says - for (t, greedy) in [(0.0, true), (-1.0, true), (0.01, false)] { - let s = ServeSampling::new(&request(|p| p.temperature = t), 1, true); - assert_eq!((s.params().greedy, s.sampled()), (greedy, !greedy)); - } - } - - #[test] - fn coupled_drafting_needs_setup_and_a_sampled_request() { - for (ready, temperature, active) in [ - (true, 0.8, true), - (false, 0.8, false), - (true, 0.0, false), - (false, 0.0, false), - ] { - let s = ServeSampling::new(&request(|p| p.temperature = temperature), 1, ready); - assert_eq!(s.coupled_active(), active); - assert_eq!(s.draft_params().is_some(), active); - } - } - - #[test] - fn a_window_draws_counter_p_plus_row_over_the_literal_histories() { - let s = ServeSampling::new(&request(|p| p.penalty_last_n = 3), 1, true); - let stage = s.window(40, &[1, 2, 3, 4], &[9, 10, 11]).unwrap(); - assert_eq!(stage.params.counter, 40); - assert_eq!(stage.rows, 3); - // rows: last 3 of consumed ++ window[..=t] - assert_eq!(stage.history, vec![3, 4, 9, 4, 9, 10, 9, 10, 11]); - let off = ServeSampling::new(&request(|_| {}), 1, true); - assert!(off.window(0, &[], &[5]).unwrap().history.is_empty()); - assert_eq!(off.window(0, &[], &[]).unwrap_err(), ServeError::WindowRows); - assert_eq!( - off.window(0, &[], &[0; 9]).unwrap_err(), - ServeError::WindowRows - ); - assert_eq!(off.window(0, &[-1], &[5]).unwrap_err(), ServeError::Token); - assert_eq!( - off.window(u64::MAX, &[], &[5]).unwrap_err(), - ServeError::Position - ); - } - - #[test] - fn the_draft_history_is_staged_only_when_it_will_be_read() { - let s = ServeSampling::new(&request(|p| p.penalty_last_n = 4), 1, true); - assert!(s.draft_history_due(false, 3, 10)); - assert!( - !s.draft_history_due(true, 3, 10), - "the request ended on a stop token" - ); - assert!(!s.draft_history_due(false, 10, 10), "max_new reached"); - let off = ServeSampling::new(&request(|_| {}), 1, true); - assert!( - !off.draft_history_due(false, 0, 10), - "no penalties, no history" - ); - let no_setup = ServeSampling::new(&request(|p| p.penalty_last_n = 4), 1, false); - assert!(!no_setup.draft_history_due(false, 0, 10)); - assert_eq!(s.draft_history(&[1, 2, 3], 9).unwrap(), vec![1, 2, 3, 9]); - assert_eq!(s.draft_history(&[0, 1, 2, 3], 9).unwrap(), vec![1, 2, 3, 9]); - assert_eq!(s.draft_history(&[], 9).unwrap(), vec![-1, -1, -1, 9]); - assert_eq!(s.draft_history(&[], -1).unwrap_err(), ServeError::Token); - } - - #[test] - fn draft_counters_are_the_verifying_rows() { - // after a window at p with a accepted, draft j is verified by row j of the window at p + a + 1 - for p in [0i64, 1, 17, 1000] { - for a in 0..8usize { - for j in 0..7usize { - assert_eq!( - ServeSampling::draft_counter(p, a, j).unwrap(), - (p + a as i64 + 1) as u64 + j as u64 - ); - } - } - } - assert_eq!( - ServeSampling::draft_counter(-1, 0, 0).unwrap(), - 0, - "draft_first for a window at p = 0" - ); - assert_eq!( - ServeSampling::draft_counter(-2, 0, 0).unwrap_err(), - ServeError::Position - ); - } - - #[test] - fn window_rows_follow_the_confidence_floor() { - assert_eq!(window_rows(5, 0.3, &[0.9; 4], true), 1); - assert_eq!(window_rows(5, 0.0, &[], false), 5); - assert_eq!(window_rows(5, 0.3, &[0.9, 0.5, 0.2, 0.9], false), 3); - assert_eq!(window_rows(5, 0.3, &[0.1, 0.9, 0.9, 0.9], false), 1); - assert_eq!(window_rows(5, 0.3, &[0.9, 0.9, 0.9, 0.9], false), 5); - assert_eq!(window_rows(1, 0.3, &[0.9], false), 1); - } - - #[test] - fn settling_a_window_follows_the_emit_loop() { - // window [x, 7, 8, 9]; picks 7, 8, 5, 6: two drafts accepted, three picks emitted - let s = settle_window(&[1, 7, 8, 9], &[7, 8, 5, 6], &[], 0, 100); - assert_eq!( - s, - Settled { - accepted: 2, - emitted: 3, - eos: false - } - ); - // a stop token among the emitted picks ends the request after it - let s = settle_window(&[1, 7, 8, 9], &[7, 8, 5, 6], &[8], 0, 100); - assert_eq!( - s, - Settled { - accepted: 2, - emitted: 2, - eos: true - } - ); - // max_new cuts the emission - let s = settle_window(&[1, 7, 8, 9], &[7, 8, 5, 6], &[], 98, 100); - assert_eq!( - s, - Settled { - accepted: 2, - emitted: 2, - eos: false - } - ); - let s = settle_window(&[1, 7, 8, 9], &[7, 8, 5, 6], &[], 100, 100); - assert_eq!(s.emitted, 0); - // nothing accepted: one pick - assert_eq!(settle_window(&[1, 7], &[2, 3], &[], 0, 9).emitted, 1); - assert_eq!( - settle_window(&[1], &[2], &[], 0, 9), - Settled { - accepted: 0, - emitted: 1, - eos: false - } - ); - } -} +mod tests; diff --git a/crates/sampler-ref/src/serve/tests.rs b/crates/sampler-ref/src/serve/tests.rs new file mode 100644 index 00000000..c18b0164 --- /dev/null +++ b/crates/sampler-ref/src/serve/tests.rs @@ -0,0 +1,175 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn request(f: impl FnOnce(&mut SamplerParams)) -> SamplerParams { + let mut p = SamplerParams { + temperature: 0.8, + ..SamplerParams::default() + }; + f(&mut p); + p +} + +#[test] +fn request_parameters_follow_the_serve_loop() { + let s = ServeSampling::new(&request(|p| p.counter = 77), 555, true); + assert_eq!( + (s.params().seed, s.params().counter), + (555, 0), + "seed 0 takes the clock; counter restarts" + ); + let s = ServeSampling::new(&request(|p| p.seed = 9), 555, true); + assert_eq!(s.params().seed, 9); + let s = ServeSampling::new(&request(|p| p.min_p = 3.0), 1, true); + assert_eq!(s.params().min_p, 1.0); + let s = ServeSampling::new(&request(|p| p.min_p = -1.0), 1, true); + assert_eq!(s.params().min_p, 0.0); + let s = ServeSampling::new(&request(|p| p.penalty_last_n = -5), 1, true); + assert_eq!((s.params().penalty_last_n, s.hist_n()), (0, 0)); + let s = ServeSampling::new(&request(|p| p.penalty_last_n = 100_000), 1, true); + assert_eq!((s.params().penalty_last_n, s.hist_n()), (100_000, 4096)); + // greedy iff temperature <= 0, whatever else the request says + for (t, greedy) in [(0.0, true), (-1.0, true), (0.01, false)] { + let s = ServeSampling::new(&request(|p| p.temperature = t), 1, true); + assert_eq!((s.params().greedy, s.sampled()), (greedy, !greedy)); + } +} + +#[test] +fn coupled_drafting_needs_setup_and_a_sampled_request() { + for (ready, temperature, active) in [ + (true, 0.8, true), + (false, 0.8, false), + (true, 0.0, false), + (false, 0.0, false), + ] { + let s = ServeSampling::new(&request(|p| p.temperature = temperature), 1, ready); + assert_eq!(s.coupled_active(), active); + assert_eq!(s.draft_params().is_some(), active); + } +} + +#[test] +fn a_window_draws_counter_p_plus_row_over_the_literal_histories() { + let s = ServeSampling::new(&request(|p| p.penalty_last_n = 3), 1, true); + let stage = s.window(40, &[1, 2, 3, 4], &[9, 10, 11]).unwrap(); + assert_eq!(stage.params.counter, 40); + assert_eq!(stage.rows, 3); + // rows: last 3 of consumed ++ window[..=t] + assert_eq!(stage.history, vec![3, 4, 9, 4, 9, 10, 9, 10, 11]); + let off = ServeSampling::new(&request(|_| {}), 1, true); + assert!(off.window(0, &[], &[5]).unwrap().history.is_empty()); + assert_eq!(off.window(0, &[], &[]).unwrap_err(), ServeError::WindowRows); + assert_eq!( + off.window(0, &[], &[0; 9]).unwrap_err(), + ServeError::WindowRows + ); + assert_eq!(off.window(0, &[-1], &[5]).unwrap_err(), ServeError::Token); + assert_eq!( + off.window(u64::MAX, &[], &[5]).unwrap_err(), + ServeError::Position + ); +} + +#[test] +fn the_draft_history_is_staged_only_when_it_will_be_read() { + let s = ServeSampling::new(&request(|p| p.penalty_last_n = 4), 1, true); + assert!(s.draft_history_due(false, 3, 10)); + assert!( + !s.draft_history_due(true, 3, 10), + "the request ended on a stop token" + ); + assert!(!s.draft_history_due(false, 10, 10), "max_new reached"); + let off = ServeSampling::new(&request(|_| {}), 1, true); + assert!( + !off.draft_history_due(false, 0, 10), + "no penalties, no history" + ); + let no_setup = ServeSampling::new(&request(|p| p.penalty_last_n = 4), 1, false); + assert!(!no_setup.draft_history_due(false, 0, 10)); + assert_eq!(s.draft_history(&[1, 2, 3], 9).unwrap(), vec![1, 2, 3, 9]); + assert_eq!(s.draft_history(&[0, 1, 2, 3], 9).unwrap(), vec![1, 2, 3, 9]); + assert_eq!(s.draft_history(&[], 9).unwrap(), vec![-1, -1, -1, 9]); + assert_eq!(s.draft_history(&[], -1).unwrap_err(), ServeError::Token); +} + +#[test] +fn draft_counters_are_the_verifying_rows() { + // after a window at p with a accepted, draft j is verified by row j of the window at p + a + 1 + for p in [0i64, 1, 17, 1000] { + for a in 0..8usize { + for j in 0..7usize { + assert_eq!( + ServeSampling::draft_counter(p, a, j).unwrap(), + (p + a as i64 + 1) as u64 + j as u64 + ); + } + } + } + assert_eq!( + ServeSampling::draft_counter(-1, 0, 0).unwrap(), + 0, + "draft_first for a window at p = 0" + ); + assert_eq!( + ServeSampling::draft_counter(-2, 0, 0).unwrap_err(), + ServeError::Position + ); +} + +#[test] +fn window_rows_follow_the_confidence_floor() { + assert_eq!(window_rows(5, 0.3, &[0.9; 4], true), 1); + assert_eq!(window_rows(5, 0.0, &[], false), 5); + assert_eq!(window_rows(5, 0.3, &[0.9, 0.5, 0.2, 0.9], false), 3); + assert_eq!(window_rows(5, 0.3, &[0.1, 0.9, 0.9, 0.9], false), 1); + assert_eq!(window_rows(5, 0.3, &[0.9, 0.9, 0.9, 0.9], false), 5); + assert_eq!(window_rows(1, 0.3, &[0.9], false), 1); +} + +#[test] +fn settling_a_window_follows_the_emit_loop() { + // window [x, 7, 8, 9]; picks 7, 8, 5, 6: two drafts accepted, three picks emitted + let s = settle_window(&[1, 7, 8, 9], &[7, 8, 5, 6], &[], 0, 100); + assert_eq!( + s, + Settled { + accepted: 2, + emitted: 3, + eos: false + } + ); + // a stop token among the emitted picks ends the request after it + let s = settle_window(&[1, 7, 8, 9], &[7, 8, 5, 6], &[8], 0, 100); + assert_eq!( + s, + Settled { + accepted: 2, + emitted: 2, + eos: true + } + ); + // max_new cuts the emission + let s = settle_window(&[1, 7, 8, 9], &[7, 8, 5, 6], &[], 98, 100); + assert_eq!( + s, + Settled { + accepted: 2, + emitted: 2, + eos: false + } + ); + let s = settle_window(&[1, 7, 8, 9], &[7, 8, 5, 6], &[], 100, 100); + assert_eq!(s.emitted, 0); + // nothing accepted: one pick + assert_eq!(settle_window(&[1, 7], &[2, 3], &[], 0, 9).emitted, 1); + assert_eq!( + settle_window(&[1], &[2], &[], 0, 9), + Settled { + accepted: 0, + emitted: 1, + eos: false + } + ); +} diff --git a/crates/serving-policy/src/cvec.rs b/crates/serving-policy/src/cvec.rs index 187e836a..1c420638 100644 --- a/crates/serving-policy/src/cvec.rs +++ b/crates/serving-policy/src/cvec.rs @@ -418,154 +418,4 @@ pub fn parse_mode(text: &str) -> Result { } #[cfg(test)] -mod tests { - use super::*; - - fn vector(layers: &[(u32, [f32; 3])]) -> VectorFile { - VectorFile { - architecture: Some("controlvector".into()), - model_hint: Some("qwen4exp".into()), - tensors: layers - .iter() - .map(|(layer, values)| VectorTensor { - name: format!("direction.{layer}"), - kind: 0, - elements: 3, - values: values.to_vec(), - }) - .collect(), - } - } - - #[test] - fn add_mode_sums_scaled_files() { - let a = vector(&[(1, [1.0, 2.0, 3.0])]); - let b = vector(&[(1, [10.0, 10.0, 10.0]), (2, [1.0, 0.0, 0.0])]); - let tables = build_tables( - &[("a".into(), a, 1.0), ("b".into(), b, 0.5)], - 4, - 3, - Options::default(), - ) - .unwrap(); - assert_eq!(&tables.dir[3..6], &[6.0, 7.0, 8.0]); - assert_eq!(&tables.dir[6..9], &[0.5, 0.0, 0.0]); - assert_eq!(tables.s, vec![0.0, 1.0, 1.0, 0.0]); - assert_eq!(tables.summary, "add:1-3"); - assert_eq!(tables.steered, 2); - } - - #[test] - fn project_mode_stores_the_unit_vector_and_its_norm() { - let tables = build_tables( - &[("a".into(), vector(&[(1, [3.0, 4.0, 0.0])]), 1.0)], - 2, - 3, - Options { - mode: Mode::Project, - ..Default::default() - }, - ) - .unwrap(); - assert_eq!(tables.s[1], 5.0); - assert_eq!(&tables.dir[3..6], &[0.6f32, 0.8f32, 0.0]); - assert_eq!(tables.summary, "project:1-1"); - } - - #[test] - fn loader_errors_use_the_engines_words() { - let ok = vector(&[(1, [1.0, 1.0, 1.0])]); - let not_cvec = VectorFile { - architecture: Some("llama".into()), - ..ok.clone() - }; - assert_eq!( - build_tables(&[("f".into(), not_cvec, 1.0)], 4, 3, Options::default()).unwrap_err(), - "f: not a control vector GGUF (general.architecture is not 'controlvector')" - ); - let none = VectorFile { - tensors: vec![], - ..ok.clone() - }; - assert_eq!( - build_tables(&[("f".into(), none, 1.0)], 4, 3, Options::default()).unwrap_err(), - "f: no direction. tensors" - ); - assert_eq!( - build_tables( - &[("f".into(), ok.clone(), 1.0)], - 4, - 3, - Options { - first: 3, - last: 3, - ..Default::default() - } - ) - .unwrap_err(), - "the control vector has no direction in layers 3..3" - ); - assert_eq!( - build_tables( - &[("f".into(), ok, 1.0)], - 4, - 3, - Options { - mode: Mode::Project, - single: 2, - ..Default::default() - } - ) - .unwrap_err(), - "--cvec-dir single:2: the vector has no direction for that layer" - ); - } - - #[test] - fn cli_values_parse_like_the_engine() { - assert_eq!( - parse_scaled_list("a.gguf:0.5,C:\\v.gguf:-2").unwrap(), - vec![("a.gguf".to_owned(), 0.5), ("C:\\v.gguf".to_owned(), -2.0)] - ); - for bad in ["a.gguf", ":1", "a.gguf:", "a.gguf:x", "a.gguf:1x"] { - assert!(parse_scaled_list(bad).is_err(), "{bad}"); - } - assert_eq!(parse_dir("per-layer"), Ok(-1)); - assert_eq!(parse_dir("single:12"), Ok(12)); - assert!(parse_dir("every").is_err()); - assert_eq!(parse_mode("project"), Ok(Mode::Project)); - assert!(parse_mode("x").is_err()); - } - - #[test] - fn gguf_files_round_trip_through_the_parser() { - let mut file = b"GGUF".to_vec(); - file.extend_from_slice(&3u32.to_le_bytes()); - file.extend_from_slice(&1u64.to_le_bytes()); - file.extend_from_slice(&1u64.to_le_bytes()); - let key = b"general.architecture"; - file.extend_from_slice(&(key.len() as u64).to_le_bytes()); - file.extend_from_slice(key); - file.extend_from_slice(&8u32.to_le_bytes()); - file.extend_from_slice(&13u64.to_le_bytes()); - file.extend_from_slice(b"controlvector"); - let name = b"direction.1"; - file.extend_from_slice(&(name.len() as u64).to_le_bytes()); - file.extend_from_slice(name); - file.extend_from_slice(&1u32.to_le_bytes()); - file.extend_from_slice(&2u64.to_le_bytes()); - file.extend_from_slice(&0u32.to_le_bytes()); - file.extend_from_slice(&0u64.to_le_bytes()); - while !file.len().is_multiple_of(32) { - file.push(0); - } - file.extend_from_slice(&1.5f32.to_le_bytes()); - file.extend_from_slice(&(-2.0f32).to_le_bytes()); - let parsed = parse_gguf(&file).unwrap(); - assert_eq!(parsed.architecture.as_deref(), Some("controlvector")); - assert_eq!(parsed.tensors[0].values, vec![1.5, -2.0]); - assert!(parse_gguf(&file[..file.len() - 1]).is_err()); - assert!(parse_gguf(b"GGUX").is_err()); - assert!(parse_gguf(&[]).is_err()); - } -} +mod tests; diff --git a/crates/serving-policy/src/cvec/tests.rs b/crates/serving-policy/src/cvec/tests.rs new file mode 100644 index 00000000..edaa03ae --- /dev/null +++ b/crates/serving-policy/src/cvec/tests.rs @@ -0,0 +1,151 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +fn vector(layers: &[(u32, [f32; 3])]) -> VectorFile { + VectorFile { + architecture: Some("controlvector".into()), + model_hint: Some("qwen4exp".into()), + tensors: layers + .iter() + .map(|(layer, values)| VectorTensor { + name: format!("direction.{layer}"), + kind: 0, + elements: 3, + values: values.to_vec(), + }) + .collect(), + } +} + +#[test] +fn add_mode_sums_scaled_files() { + let a = vector(&[(1, [1.0, 2.0, 3.0])]); + let b = vector(&[(1, [10.0, 10.0, 10.0]), (2, [1.0, 0.0, 0.0])]); + let tables = build_tables( + &[("a".into(), a, 1.0), ("b".into(), b, 0.5)], + 4, + 3, + Options::default(), + ) + .unwrap(); + assert_eq!(&tables.dir[3..6], &[6.0, 7.0, 8.0]); + assert_eq!(&tables.dir[6..9], &[0.5, 0.0, 0.0]); + assert_eq!(tables.s, vec![0.0, 1.0, 1.0, 0.0]); + assert_eq!(tables.summary, "add:1-3"); + assert_eq!(tables.steered, 2); +} + +#[test] +fn project_mode_stores_the_unit_vector_and_its_norm() { + let tables = build_tables( + &[("a".into(), vector(&[(1, [3.0, 4.0, 0.0])]), 1.0)], + 2, + 3, + Options { + mode: Mode::Project, + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(tables.s[1], 5.0); + assert_eq!(&tables.dir[3..6], &[0.6f32, 0.8f32, 0.0]); + assert_eq!(tables.summary, "project:1-1"); +} + +#[test] +fn loader_errors_use_the_engines_words() { + let ok = vector(&[(1, [1.0, 1.0, 1.0])]); + let not_cvec = VectorFile { + architecture: Some("llama".into()), + ..ok.clone() + }; + assert_eq!( + build_tables(&[("f".into(), not_cvec, 1.0)], 4, 3, Options::default()).unwrap_err(), + "f: not a control vector GGUF (general.architecture is not 'controlvector')" + ); + let none = VectorFile { + tensors: vec![], + ..ok.clone() + }; + assert_eq!( + build_tables(&[("f".into(), none, 1.0)], 4, 3, Options::default()).unwrap_err(), + "f: no direction. tensors" + ); + assert_eq!( + build_tables( + &[("f".into(), ok.clone(), 1.0)], + 4, + 3, + Options { + first: 3, + last: 3, + ..Default::default() + } + ) + .unwrap_err(), + "the control vector has no direction in layers 3..3" + ); + assert_eq!( + build_tables( + &[("f".into(), ok, 1.0)], + 4, + 3, + Options { + mode: Mode::Project, + single: 2, + ..Default::default() + } + ) + .unwrap_err(), + "--cvec-dir single:2: the vector has no direction for that layer" + ); +} + +#[test] +fn cli_values_parse_like_the_engine() { + assert_eq!( + parse_scaled_list("a.gguf:0.5,C:\\v.gguf:-2").unwrap(), + vec![("a.gguf".to_owned(), 0.5), ("C:\\v.gguf".to_owned(), -2.0)] + ); + for bad in ["a.gguf", ":1", "a.gguf:", "a.gguf:x", "a.gguf:1x"] { + assert!(parse_scaled_list(bad).is_err(), "{bad}"); + } + assert_eq!(parse_dir("per-layer"), Ok(-1)); + assert_eq!(parse_dir("single:12"), Ok(12)); + assert!(parse_dir("every").is_err()); + assert_eq!(parse_mode("project"), Ok(Mode::Project)); + assert!(parse_mode("x").is_err()); +} + +#[test] +fn gguf_files_round_trip_through_the_parser() { + let mut file = b"GGUF".to_vec(); + file.extend_from_slice(&3u32.to_le_bytes()); + file.extend_from_slice(&1u64.to_le_bytes()); + file.extend_from_slice(&1u64.to_le_bytes()); + let key = b"general.architecture"; + file.extend_from_slice(&(key.len() as u64).to_le_bytes()); + file.extend_from_slice(key); + file.extend_from_slice(&8u32.to_le_bytes()); + file.extend_from_slice(&13u64.to_le_bytes()); + file.extend_from_slice(b"controlvector"); + let name = b"direction.1"; + file.extend_from_slice(&(name.len() as u64).to_le_bytes()); + file.extend_from_slice(name); + file.extend_from_slice(&1u32.to_le_bytes()); + file.extend_from_slice(&2u64.to_le_bytes()); + file.extend_from_slice(&0u32.to_le_bytes()); + file.extend_from_slice(&0u64.to_le_bytes()); + while !file.len().is_multiple_of(32) { + file.push(0); + } + file.extend_from_slice(&1.5f32.to_le_bytes()); + file.extend_from_slice(&(-2.0f32).to_le_bytes()); + let parsed = parse_gguf(&file).unwrap(); + assert_eq!(parsed.architecture.as_deref(), Some("controlvector")); + assert_eq!(parsed.tensors[0].values, vec![1.5, -2.0]); + assert!(parse_gguf(&file[..file.len() - 1]).is_err()); + assert!(parse_gguf(b"GGUX").is_err()); + assert!(parse_gguf(&[]).is_err()); +} diff --git a/crates/serving-policy/src/shared.rs b/crates/serving-policy/src/shared.rs index a131aed6..2fc13916 100644 --- a/crates/serving-policy/src/shared.rs +++ b/crates/serving-policy/src/shared.rs @@ -406,142 +406,4 @@ pub fn shared_max_tokens(request_max: Option, shared: &SharedDefaults) -> O } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn unknown_keys_are_refused_unless_their_value_is_empty() { - let d = clean_shared_defaults(&json!({"top_p": null, "x": null, "min_p": ""})).unwrap(); - assert!(d.is_empty()); - assert_eq!( - clean_shared_defaults(&json!({"min_p": 0.1})), - Err("unknown setting 'min_p'".to_owned()) - ); - } - - #[test] - fn empty_and_null_values_are_dropped() { - let d = clean_shared_defaults(&json!({"temperature": "", "top_p": null})).unwrap(); - assert!(d.is_empty()); - assert!(clean_shared_defaults(&Value::Null).unwrap().is_empty()); - assert!(clean_shared_defaults(&json!([1])).is_err()); - } - - #[test] - fn valid_values_are_normalised_like_the_original() { - let d = clean_shared_defaults(&json!({"temperature": 1, "top_k": 40.0, "seed": 7, - "reasoning_effort": "high", "max_tokens": 100, "top_p": 1})) - .unwrap(); - assert_eq!(d.temperature, Some(1.0)); - assert_eq!(d.top_k, Some(40)); - assert_eq!(d.seed, Some(7)); - assert_eq!(d.max_tokens, Some(100)); - assert_eq!(d.top_p, Some(1.0)); - assert_eq!( - d.to_json(), - json!({"reasoning_effort": "high", "temperature": 1.0, "top_p": 1.0, "top_k": 40, - "seed": 7, "max_tokens": 100}) - ); - } - - #[test] - fn config_block_checks_the_originals_ranges() { - let c = sampling_defaults_from_config(&json!({"temperature": 0.7, "top_p": 0.9, - "top_k": 40, "min_p": 0.05, "presence_penalty": 0.5, "repetition_penalty": 1.1, - "frequency_penalty": 0.0, "penalty_last_n": 128, "seed": 5, - "experimental_speed_projection": true, "nonsense": 1})) - .unwrap(); - assert_eq!(c.sampling.top_k, Some(40)); - assert_eq!(c.ignored, vec!["nonsense".to_owned()]); - assert_eq!(c.experimental_speed_projection, Some(true)); - for (key, bad) in [ - ("temperature", json!(-1)), - ("top_p", json!(0)), - ("min_p", json!(1.5)), - ("top_k", json!(0)), - ("top_k", json!(65)), - ("top_k", json!(1.5)), - ("presence_penalty", json!(-0.1)), - ("repetition_penalty", json!(0)), - ("penalty_last_n", json!(-1)), - ("seed", json!(0)), - ("seed", json!(true)), - ("experimental_speed_projection", json!(1)), - ] { - assert!( - sampling_defaults_from_config(&json!({ key: bad.clone() })).is_err(), - "{key}={bad}" - ); - } - } - - #[test] - fn shared_wins_over_config_and_the_request_wins_over_both() { - let config = - sampling_defaults_from_config(&json!({"temperature": 0.3, "min_p": 0.1})).unwrap(); - let shared = clean_shared_defaults(&json!({"temperature": 0.9, "seed": 4})).unwrap(); - let merged = merged_defaults(&config, &shared); - assert_eq!(merged.sampling.temperature, Some(0.9)); - assert_eq!(merged.sampling.min_p, Some(0.1)); - assert_eq!(merged.sampling.seed, Some(4)); - let request = RequestSampling { - temperature: Some(0.0), - ..Default::default() - }; - let effective = RequestSampling::overlay(&merged.sampling, &request); - assert_eq!(effective.temperature, Some(0.0), "explicit 0 stays greedy"); - assert_eq!(effective.min_p, Some(0.1)); - } - - #[test] - fn props_params_use_llama_server_names() { - let config = sampling_defaults_from_config( - &json!({"repetition_penalty": 1.1, "penalty_last_n": 64}), - ) - .unwrap(); - let shared = clean_shared_defaults(&json!({"max_tokens": 512})).unwrap(); - let params = merged_defaults(&config, &shared).props_params(&shared); - assert_eq!( - params, - json!({"repeat_penalty": 1.1, "repeat_last_n": 64, "n_predict": 512}) - ); - } - - #[test] - fn aliases_are_trimmed_deduplicated_and_never_the_model() { - assert_eq!( - normalize_aliases(&json!([" gpt ", "gpt", "", "m", "claude"]), "m"), - Ok(vec!["gpt".to_owned(), "claude".to_owned()]) - ); - assert_eq!( - normalize_aliases(&json!("a, b ,a,,m"), "m"), - Ok(vec!["a".to_owned(), "b".to_owned()]) - ); - assert_eq!(normalize_aliases(&Value::Null, "m"), Ok(vec![])); - assert_eq!( - normalize_aliases(&json!([1]), "m").unwrap_err(), - "aliases=[1]: expected a list of model names" - ); - assert!(normalize_aliases(&json!({"a": 1}), "m").is_err()); - } - - #[test] - fn python_repr_of_values() { - assert_eq!(py_repr(&json!(true)), "True"); - assert_eq!(py_repr(&json!(null)), "None"); - assert_eq!(py_repr(&json!("it's")), "\"it's\""); - assert_eq!(py_repr(&json!(1.5)), "1.5"); - assert_eq!(py_repr(&json!([1, "a"])), "[1, 'a']"); - assert_eq!(py_repr(&json!({"a": 1})), "{'a': 1}"); - } - - #[test] - fn shared_max_tokens_only_fills_a_missing_limit() { - let shared = clean_shared_defaults(&json!({"max_tokens": 77})).unwrap(); - assert_eq!(shared_max_tokens(None, &shared), Some(77)); - assert_eq!(shared_max_tokens(Some(0), &shared), Some(77)); - assert_eq!(shared_max_tokens(Some(5), &shared), Some(5)); - assert_eq!(shared_max_tokens(None, &SharedDefaults::default()), None); - } -} +mod tests; diff --git a/crates/serving-policy/src/shared/tests.rs b/crates/serving-policy/src/shared/tests.rs new file mode 100644 index 00000000..7b27858a --- /dev/null +++ b/crates/serving-policy/src/shared/tests.rs @@ -0,0 +1,139 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use serde_json::json; + +#[test] +fn unknown_keys_are_refused_unless_their_value_is_empty() { + let d = clean_shared_defaults(&json!({"top_p": null, "x": null, "min_p": ""})).unwrap(); + assert!(d.is_empty()); + assert_eq!( + clean_shared_defaults(&json!({"min_p": 0.1})), + Err("unknown setting 'min_p'".to_owned()) + ); +} + +#[test] +fn empty_and_null_values_are_dropped() { + let d = clean_shared_defaults(&json!({"temperature": "", "top_p": null})).unwrap(); + assert!(d.is_empty()); + assert!(clean_shared_defaults(&Value::Null).unwrap().is_empty()); + assert!(clean_shared_defaults(&json!([1])).is_err()); +} + +#[test] +fn valid_values_are_normalised_like_the_original() { + let d = clean_shared_defaults(&json!({"temperature": 1, "top_k": 40.0, "seed": 7, + "reasoning_effort": "high", "max_tokens": 100, "top_p": 1})) + .unwrap(); + assert_eq!(d.temperature, Some(1.0)); + assert_eq!(d.top_k, Some(40)); + assert_eq!(d.seed, Some(7)); + assert_eq!(d.max_tokens, Some(100)); + assert_eq!(d.top_p, Some(1.0)); + assert_eq!( + d.to_json(), + json!({"reasoning_effort": "high", "temperature": 1.0, "top_p": 1.0, "top_k": 40, + "seed": 7, "max_tokens": 100}) + ); +} + +#[test] +fn config_block_checks_the_originals_ranges() { + let c = sampling_defaults_from_config(&json!({"temperature": 0.7, "top_p": 0.9, + "top_k": 40, "min_p": 0.05, "presence_penalty": 0.5, "repetition_penalty": 1.1, + "frequency_penalty": 0.0, "penalty_last_n": 128, "seed": 5, + "experimental_speed_projection": true, "nonsense": 1})) + .unwrap(); + assert_eq!(c.sampling.top_k, Some(40)); + assert_eq!(c.ignored, vec!["nonsense".to_owned()]); + assert_eq!(c.experimental_speed_projection, Some(true)); + for (key, bad) in [ + ("temperature", json!(-1)), + ("top_p", json!(0)), + ("min_p", json!(1.5)), + ("top_k", json!(0)), + ("top_k", json!(65)), + ("top_k", json!(1.5)), + ("presence_penalty", json!(-0.1)), + ("repetition_penalty", json!(0)), + ("penalty_last_n", json!(-1)), + ("seed", json!(0)), + ("seed", json!(true)), + ("experimental_speed_projection", json!(1)), + ] { + assert!( + sampling_defaults_from_config(&json!({ key: bad.clone() })).is_err(), + "{key}={bad}" + ); + } +} + +#[test] +fn shared_wins_over_config_and_the_request_wins_over_both() { + let config = + sampling_defaults_from_config(&json!({"temperature": 0.3, "min_p": 0.1})).unwrap(); + let shared = clean_shared_defaults(&json!({"temperature": 0.9, "seed": 4})).unwrap(); + let merged = merged_defaults(&config, &shared); + assert_eq!(merged.sampling.temperature, Some(0.9)); + assert_eq!(merged.sampling.min_p, Some(0.1)); + assert_eq!(merged.sampling.seed, Some(4)); + let request = RequestSampling { + temperature: Some(0.0), + ..Default::default() + }; + let effective = RequestSampling::overlay(&merged.sampling, &request); + assert_eq!(effective.temperature, Some(0.0), "explicit 0 stays greedy"); + assert_eq!(effective.min_p, Some(0.1)); +} + +#[test] +fn props_params_use_llama_server_names() { + let config = sampling_defaults_from_config( + &json!({"repetition_penalty": 1.1, "penalty_last_n": 64}), + ) + .unwrap(); + let shared = clean_shared_defaults(&json!({"max_tokens": 512})).unwrap(); + let params = merged_defaults(&config, &shared).props_params(&shared); + assert_eq!( + params, + json!({"repeat_penalty": 1.1, "repeat_last_n": 64, "n_predict": 512}) + ); +} + +#[test] +fn aliases_are_trimmed_deduplicated_and_never_the_model() { + assert_eq!( + normalize_aliases(&json!([" gpt ", "gpt", "", "m", "claude"]), "m"), + Ok(vec!["gpt".to_owned(), "claude".to_owned()]) + ); + assert_eq!( + normalize_aliases(&json!("a, b ,a,,m"), "m"), + Ok(vec!["a".to_owned(), "b".to_owned()]) + ); + assert_eq!(normalize_aliases(&Value::Null, "m"), Ok(vec![])); + assert_eq!( + normalize_aliases(&json!([1]), "m").unwrap_err(), + "aliases=[1]: expected a list of model names" + ); + assert!(normalize_aliases(&json!({"a": 1}), "m").is_err()); +} + +#[test] +fn python_repr_of_values() { + assert_eq!(py_repr(&json!(true)), "True"); + assert_eq!(py_repr(&json!(null)), "None"); + assert_eq!(py_repr(&json!("it's")), "\"it's\""); + assert_eq!(py_repr(&json!(1.5)), "1.5"); + assert_eq!(py_repr(&json!([1, "a"])), "[1, 'a']"); + assert_eq!(py_repr(&json!({"a": 1})), "{'a': 1}"); +} + +#[test] +fn shared_max_tokens_only_fills_a_missing_limit() { + let shared = clean_shared_defaults(&json!({"max_tokens": 77})).unwrap(); + assert_eq!(shared_max_tokens(None, &shared), Some(77)); + assert_eq!(shared_max_tokens(Some(0), &shared), Some(77)); + assert_eq!(shared_max_tokens(Some(5), &shared), Some(5)); + assert_eq!(shared_max_tokens(None, &SharedDefaults::default()), None); +} diff --git a/crates/serving-policy/src/vision.rs b/crates/serving-policy/src/vision.rs index 8a69d22f..2ee130b6 100644 --- a/crates/serving-policy/src/vision.rs +++ b/crates/serving-policy/src/vision.rs @@ -336,165 +336,4 @@ pub fn expand_image_pads( } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn record(n: i32, nx: i32, ny: i32, width: i32, seed: f32) -> Vec { - let mut out = Vec::new(); - for v in [SVE1_MAGIC, n, nx, ny, width] { - out.extend_from_slice(&v.to_le_bytes()); - } - for i in 0..n * width { - out.extend_from_slice(&(seed + i as f32 * 0.5).to_le_bytes()); - } - out - } - - #[test] - fn identity_positions_for_text() { - let ids: Vec = vec![5, 6, 7]; - let positions = build_positions(&ids, 8, &Embeddings::default(), 4, IMAGE_PAD_ID).unwrap(); - assert_eq!(positions.table, identity_table(8)); - assert!(positions.images.is_empty()); - } - - #[test] - fn an_image_shares_t_and_text_continues_after_its_larger_side() { - let file = record(6, 3, 2, 4, 1.0); - let embeddings = parse_embeddings(&file, 4).unwrap(); - let p = IMAGE_PAD_ID; - let ids = vec![1, p, p, p, p, p, p, 9]; - let positions = build_positions(&ids, 12, &embeddings, 4, p).unwrap(); - assert_eq!(positions.table[0], [0, 0, 0]); - assert_eq!(positions.table[1], [1, 1, 1]); - assert_eq!(positions.table[3], [1, 1, 3]); - assert_eq!(positions.table[4], [1, 2, 1]); - assert_eq!(positions.table[6], [1, 2, 3]); - // the text after the image: p = 1 + max(3, 2) = 4 - assert_eq!(positions.table[7], [4, 4, 4]); - assert_eq!(positions.table[8], [5, 5, 5]); - assert_eq!(positions.row_offset[1], Some(0)); - assert_eq!(positions.row_offset[2], Some(4)); - assert_eq!(positions.row_offset[0], None); - } - - #[test] - fn every_failure_has_the_engines_words() { - let one = record(1, 1, 1, 4, 1.0); - let p = IMAGE_PAD_ID; - let embed = |bytes: &[u8]| parse_embeddings(bytes, 4); - assert_eq!( - embed(&one[..12]).unwrap_err(), - "bad embeddings file (expected strata-vision records of width 4)" - ); - assert_eq!( - embed(&one[..one.len() - 3]).unwrap_err(), - "short embeddings file" - ); - assert!(embed(&record(1, 1, 1, 8, 1.0)).is_err()); - assert!(embed(&record(6, 3, 3, 4, 1.0)).is_err()); - let embeddings = embed(&one).unwrap(); - assert_eq!( - build_positions(&[1, p, 2, p, 3], 16, &embeddings, 4, p).unwrap_err(), - "the prompt has more images than the embeddings file" - ); - assert_eq!( - build_positions(&[1, 2], 16, &embeddings, 4, p).unwrap_err(), - "the embeddings file has more images than the prompt" - ); - assert_eq!( - build_positions(&[1, p], 16, &embeddings, 4, p).unwrap_err(), - "the prompt cannot end in an image" - ); - let six = embed(&record(6, 3, 2, 4, 0.0)).unwrap(); - assert_eq!( - build_positions(&[1, p, p, 2, 3], 16, &six, 4, p).unwrap_err(), - "image 1 has 6 rows but fewer <|image_pad|> tokens" - ); - assert_eq!( - build_positions(&[1, 2, 3, 4, 5], 3, &Embeddings::default(), 4, p).unwrap_err(), - "the prompt is longer than the position table" - ); - } - - #[test] - fn sources_follow_the_frontends() { - assert_eq!( - image_source(&json!({"type": "image_url", "image_url": {"url": "https://x/y.png"}})), - "https://x/y.png" - ); - assert_eq!( - image_source(&json!({"type": "image_url", "image_url": "data:abc"})), - "data:abc" - ); - assert_eq!( - image_source(&json!({"type": "input_image", "image_url": "file:///a.png"})), - "file:///a.png" - ); - assert_eq!( - image_source( - &json!({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}}) - ), - "data:image/jpeg;base64,QQ==" - ); - assert_eq!( - image_source(&json!({"type": "image", "source": {"type": "base64", "data": "QQ=="}})), - "data:image/png;base64,QQ==" - ); - assert_eq!( - image_source(&json!({"type": "image", "source": {"type": "url", "url": "http://u"}})), - "http://u" - ); - assert_eq!( - image_source(&json!({"type": "image", "source": {"path": "/p.png"}})), - "/p.png" - ); - assert_eq!(image_source(&json!({"type": "image"})), ""); - assert!(is_image_part(&json!({"type": "input_image"}))); - assert!(!is_image_part(&json!({"type": "text"}))); - } - - #[test] - fn only_markers_after_vision_start_are_images() { - let (pad, start) = (9, 8); - let ids = [1, start, pad, 7, pad, 2, start, pad, 3]; - let out = expand_image_pads(&ids, pad, start, &[50, 51], &[3, 2]).unwrap(); - assert_eq!(out, vec![1, 8, 9, 9, 9, 7, 50, 51, 2, 8, 9, 9, 3]); - // More markers than images: the surplus marker stays plain text (as in the Original). - assert_eq!( - expand_image_pads(&ids, pad, start, &[50], &[3]).unwrap(), - vec![1, 8, 9, 9, 9, 7, 50, 2, 8, 50, 3] - ); - // More images than markers is the error. - assert_eq!( - expand_image_pads(&ids, pad, start, &[50], &[1, 1, 1]).unwrap_err(), - "the prompt and its images do not match" - ); - } - - #[test] - fn native_formats_pass_through() { - assert!(is_native_image_format(&[0xFF, 0xD8, 0xFF, 0xE0])); - assert!(is_native_image_format(b"\x89PNG\r\n\x1a\nrest")); - assert!(is_native_image_format(b"BM....")); - assert!(is_native_image_format(b"GIF89a..")); - assert!(!is_native_image_format(b"RIFF....WEBP")); - assert!(!is_native_image_format(b"")); - } - - #[test] - fn base64_matches_pythons_lenient_decoder() { - assert_eq!(b64decode("QQ==").unwrap(), b"A"); - assert_eq!(b64decode("QUI=").unwrap(), b"AB"); - assert_eq!(b64decode("QUJD").unwrap(), b"ABC"); - assert_eq!(b64decode("QU\nJD").unwrap(), b"ABC"); - assert_eq!(b64decode("").unwrap(), b""); - assert_eq!(b64decode("QQ").unwrap_err(), "Incorrect padding"); - assert!( - b64decode("Q") - .unwrap_err() - .contains("1 more than a multiple of 4") - ); - } -} +mod tests; diff --git a/crates/serving-policy/src/vision/tests.rs b/crates/serving-policy/src/vision/tests.rs new file mode 100644 index 00000000..2b4c2119 --- /dev/null +++ b/crates/serving-policy/src/vision/tests.rs @@ -0,0 +1,162 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use serde_json::json; + +fn record(n: i32, nx: i32, ny: i32, width: i32, seed: f32) -> Vec { + let mut out = Vec::new(); + for v in [SVE1_MAGIC, n, nx, ny, width] { + out.extend_from_slice(&v.to_le_bytes()); + } + for i in 0..n * width { + out.extend_from_slice(&(seed + i as f32 * 0.5).to_le_bytes()); + } + out +} + +#[test] +fn identity_positions_for_text() { + let ids: Vec = vec![5, 6, 7]; + let positions = build_positions(&ids, 8, &Embeddings::default(), 4, IMAGE_PAD_ID).unwrap(); + assert_eq!(positions.table, identity_table(8)); + assert!(positions.images.is_empty()); +} + +#[test] +fn an_image_shares_t_and_text_continues_after_its_larger_side() { + let file = record(6, 3, 2, 4, 1.0); + let embeddings = parse_embeddings(&file, 4).unwrap(); + let p = IMAGE_PAD_ID; + let ids = vec![1, p, p, p, p, p, p, 9]; + let positions = build_positions(&ids, 12, &embeddings, 4, p).unwrap(); + assert_eq!(positions.table[0], [0, 0, 0]); + assert_eq!(positions.table[1], [1, 1, 1]); + assert_eq!(positions.table[3], [1, 1, 3]); + assert_eq!(positions.table[4], [1, 2, 1]); + assert_eq!(positions.table[6], [1, 2, 3]); + // the text after the image: p = 1 + max(3, 2) = 4 + assert_eq!(positions.table[7], [4, 4, 4]); + assert_eq!(positions.table[8], [5, 5, 5]); + assert_eq!(positions.row_offset[1], Some(0)); + assert_eq!(positions.row_offset[2], Some(4)); + assert_eq!(positions.row_offset[0], None); +} + +#[test] +fn every_failure_has_the_engines_words() { + let one = record(1, 1, 1, 4, 1.0); + let p = IMAGE_PAD_ID; + let embed = |bytes: &[u8]| parse_embeddings(bytes, 4); + assert_eq!( + embed(&one[..12]).unwrap_err(), + "bad embeddings file (expected strata-vision records of width 4)" + ); + assert_eq!( + embed(&one[..one.len() - 3]).unwrap_err(), + "short embeddings file" + ); + assert!(embed(&record(1, 1, 1, 8, 1.0)).is_err()); + assert!(embed(&record(6, 3, 3, 4, 1.0)).is_err()); + let embeddings = embed(&one).unwrap(); + assert_eq!( + build_positions(&[1, p, 2, p, 3], 16, &embeddings, 4, p).unwrap_err(), + "the prompt has more images than the embeddings file" + ); + assert_eq!( + build_positions(&[1, 2], 16, &embeddings, 4, p).unwrap_err(), + "the embeddings file has more images than the prompt" + ); + assert_eq!( + build_positions(&[1, p], 16, &embeddings, 4, p).unwrap_err(), + "the prompt cannot end in an image" + ); + let six = embed(&record(6, 3, 2, 4, 0.0)).unwrap(); + assert_eq!( + build_positions(&[1, p, p, 2, 3], 16, &six, 4, p).unwrap_err(), + "image 1 has 6 rows but fewer <|image_pad|> tokens" + ); + assert_eq!( + build_positions(&[1, 2, 3, 4, 5], 3, &Embeddings::default(), 4, p).unwrap_err(), + "the prompt is longer than the position table" + ); +} + +#[test] +fn sources_follow_the_frontends() { + assert_eq!( + image_source(&json!({"type": "image_url", "image_url": {"url": "https://x/y.png"}})), + "https://x/y.png" + ); + assert_eq!( + image_source(&json!({"type": "image_url", "image_url": "data:abc"})), + "data:abc" + ); + assert_eq!( + image_source(&json!({"type": "input_image", "image_url": "file:///a.png"})), + "file:///a.png" + ); + assert_eq!( + image_source( + &json!({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}}) + ), + "data:image/jpeg;base64,QQ==" + ); + assert_eq!( + image_source(&json!({"type": "image", "source": {"type": "base64", "data": "QQ=="}})), + "data:image/png;base64,QQ==" + ); + assert_eq!( + image_source(&json!({"type": "image", "source": {"type": "url", "url": "http://u"}})), + "http://u" + ); + assert_eq!( + image_source(&json!({"type": "image", "source": {"path": "/p.png"}})), + "/p.png" + ); + assert_eq!(image_source(&json!({"type": "image"})), ""); + assert!(is_image_part(&json!({"type": "input_image"}))); + assert!(!is_image_part(&json!({"type": "text"}))); +} + +#[test] +fn only_markers_after_vision_start_are_images() { + let (pad, start) = (9, 8); + let ids = [1, start, pad, 7, pad, 2, start, pad, 3]; + let out = expand_image_pads(&ids, pad, start, &[50, 51], &[3, 2]).unwrap(); + assert_eq!(out, vec![1, 8, 9, 9, 9, 7, 50, 51, 2, 8, 9, 9, 3]); + // More markers than images: the surplus marker stays plain text (as in the Original). + assert_eq!( + expand_image_pads(&ids, pad, start, &[50], &[3]).unwrap(), + vec![1, 8, 9, 9, 9, 7, 50, 2, 8, 50, 3] + ); + // More images than markers is the error. + assert_eq!( + expand_image_pads(&ids, pad, start, &[50], &[1, 1, 1]).unwrap_err(), + "the prompt and its images do not match" + ); +} + +#[test] +fn native_formats_pass_through() { + assert!(is_native_image_format(&[0xFF, 0xD8, 0xFF, 0xE0])); + assert!(is_native_image_format(b"\x89PNG\r\n\x1a\nrest")); + assert!(is_native_image_format(b"BM....")); + assert!(is_native_image_format(b"GIF89a..")); + assert!(!is_native_image_format(b"RIFF....WEBP")); + assert!(!is_native_image_format(b"")); +} + +#[test] +fn base64_matches_pythons_lenient_decoder() { + assert_eq!(b64decode("QQ==").unwrap(), b"A"); + assert_eq!(b64decode("QUI=").unwrap(), b"AB"); + assert_eq!(b64decode("QUJD").unwrap(), b"ABC"); + assert_eq!(b64decode("QU\nJD").unwrap(), b"ABC"); + assert_eq!(b64decode("").unwrap(), b""); + assert_eq!(b64decode("QQ").unwrap_err(), "Incorrect padding"); + assert!( + b64decode("Q") + .unwrap_err() + .contains("1 more than a multiple of 4") + ); +} diff --git a/crates/tokenizer/src/gguf_bpe.rs b/crates/tokenizer/src/gguf_bpe.rs index 15e294f7..7fc82bed 100644 --- a/crates/tokenizer/src/gguf_bpe.rs +++ b/crates/tokenizer/src/gguf_bpe.rs @@ -435,152 +435,4 @@ impl Utf8Stream { } #[cfg(test)] -mod tests { - use super::*; - - /// A tiny vocabulary: all 256 byte tokens, a few merges, and two special tokens. - fn tiny() -> GgufBpe { - let chars = byte_chars(); - let mut tokens: Vec = chars.iter().map(|c| c.to_string()).collect(); - let sp = chars[usize::from(b' ')].to_string(); // 'Ġ' - let extra = [ - format!("{sp}t"), // 256 - "he".to_string(), // 257 - format!("{sp}th"), // 258 - "the".to_string(), // 259 - format!("{sp}the"), // 260 - "<|a|>".to_string(), - "<|b|>".to_string(), - ]; - tokens.extend(extra.iter().cloned()); - let mut types = vec![1i64; tokens.len()]; - types[261] = TYPE_CONTROL; - types[262] = TYPE_USER_DEFINED; - let merges = [ - format!("{sp} t"), - format!("{sp}t h"), - format!("{sp}th e"), - "h e".to_string(), - "t he".to_string(), - ]; - let t: Vec<&str> = tokens.iter().map(String::as_str).collect(); - let m: Vec<&str> = merges.iter().map(String::as_str).collect(); - GgufBpe::from_parts(&t, &types, &m, None, None, None).unwrap() - } - - #[test] - fn the_byte_map_matches_gpt2() { - let c = byte_chars(); - assert_eq!(c[usize::from(b'A')], 'A'); - assert_eq!(c[usize::from(b' ')], 'Ġ'); // U+0120 - assert_eq!(c[usize::from(b'\n')], 'Ċ'); // U+010A - assert_eq!(c[0], 'Ā'); // U+0100 - assert_eq!(c[0xAD], 'Ń'); // the soft hyphen is not printable, so it gets a code point above 255 - let mut seen: Vec = c.to_vec(); - seen.sort_unstable(); - seen.dedup(); - assert_eq!(seen.len(), 256); - } - - #[test] - fn merges_apply_in_rank_order() { - let t = tiny(); - // " the" -> " t" + "h" + "e" -> " th" "e" -> " the" - assert_eq!(t.encode(" the", false), vec![260]); - // "the" -> "t" + "he" (rank 3 needs "t he") -> "the" - assert_eq!(t.encode("the", false), vec![259]); - assert_eq!(t.encode("he", false), vec![257]); - // a lone merge that cannot continue - assert_eq!(t.encode(" th", false), vec![258]); - assert_eq!(t.decode(&t.encode("the cat the", false)), "the cat the"); - } - - #[test] - fn special_tokens_are_parsed_only_on_request() { - let t = tiny(); - assert_eq!(t.encode("<|a|>the<|b|>", true), vec![261, 259, 262]); - let plain = t.encode("<|a|>", false); - assert!(plain.len() > 1 && !plain.contains(&261)); - assert_eq!(t.decode(&[261, 259, 262]), "<|a|>the<|b|>"); - assert!(t.is_special(261) && !t.is_special(259)); - } - - #[test] - fn every_byte_sequence_round_trips() { - let t = tiny(); - let samples = [ - "", - "plain ascii, with punctuation!?", - "line1\nline2\r\n\r\n indented\ttab", - "héllo wörld — ünïcödé", - "日本語のテキスト", - "emoji 😀🎉 and 𝔘𝔫𝔦𝔠𝔬𝔡𝔢", - "1234567890 12 123 1234", - " ", - "a\u{0}b", - ]; - for s in samples { - assert_eq!(t.decode(&t.encode(s, false)), s, "round trip of {s:?}"); - } - // arbitrary bytes that are not UTF-8 survive at the byte level - let ids: Vec = (0..=255u8).map(|b| t.byte_id[usize::from(b)]).collect(); - assert_eq!(t.decode_bytes(&ids), (0..=255u8).collect::>()); - } - - #[test] - fn the_pre_tokenizer_splits_like_o200k() { - let re = Regex::new(GPT4O_PATTERN).unwrap(); - let pieces = |s: &str| -> Vec { - re.find_iter(s) - .map(|m| m.unwrap().as_str().to_owned()) - .collect() - }; - assert_eq!(pieces("Hello world"), ["Hello", " world"]); - assert_eq!(pieces("don't STOP"), ["don't", " STOP"]); - assert_eq!(pieces("x=12345"), ["x", "=", "123", "45"]); - assert_eq!(pieces("a b"), ["a", " ", " b"]); - assert_eq!(pieces("a\n\nb"), ["a", "\n\n", "b"]); - assert_eq!(pieces("CamelCaseWord"), ["Camel", "Case", "Word"]); - assert_eq!(pieces("end.\n"), ["end", ".\n"]); - } - - #[test] - fn long_pieces_do_not_blow_up() { - let t = tiny(); - let long = "the".repeat(20_000); - let ids = t.encode(&long, false); - assert_eq!(t.decode(&ids), long); - let spaces = " ".repeat(50_000); - assert_eq!(t.decode(&t.encode(&spaces, false)), spaces); - } - - #[test] - fn utf8_stream_never_splits_a_character() { - let bytes = "a😀é".as_bytes(); - for split in 0..=bytes.len() { - let mut s = Utf8Stream::default(); - let mut text = s.push(&bytes[..split]); - text.push_str(&s.push(&bytes[split..])); - text.push_str(&s.finish()); - assert_eq!(text, "a😀é", "split at {split}"); - } - let mut s = Utf8Stream::default(); - assert_eq!(s.push(&[0xF0, 0x9F]), ""); - assert_eq!(s.finish(), "\u{FFFD}"); - assert_eq!(s.push(&[0xFF, b'x']), "\u{FFFD}x"); - } - - #[test] - fn bad_vocabularies_are_refused() { - let chars = byte_chars(); - let all: Vec = chars.iter().map(|c| c.to_string()).collect(); - let t: Vec<&str> = all.iter().map(String::as_str).collect(); - let ok_types = vec![1i64; t.len()]; - assert!(GgufBpe::from_parts(&t, &ok_types, &[], None, None, None).is_ok()); - assert!(GgufBpe::from_parts(&t[1..], &ok_types[1..], &[], None, None, None).is_err()); - assert!(GgufBpe::from_parts(&t, &ok_types[1..], &[], None, None, None).is_err()); - assert!(GgufBpe::from_parts(&t, &ok_types, &["nospace"], None, None, None).is_err()); - assert!(GgufBpe::from_parts(&t, &ok_types, &["zz yy"], None, None, None).is_err()); - assert!(GgufBpe::from_parts(&t, &ok_types, &[], Some(9999), None, None).is_err()); - } -} +mod tests; diff --git a/crates/tokenizer/src/gguf_bpe/tests.rs b/crates/tokenizer/src/gguf_bpe/tests.rs new file mode 100644 index 00000000..d641e28a --- /dev/null +++ b/crates/tokenizer/src/gguf_bpe/tests.rs @@ -0,0 +1,149 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; + +/// A tiny vocabulary: all 256 byte tokens, a few merges, and two special tokens. +fn tiny() -> GgufBpe { + let chars = byte_chars(); + let mut tokens: Vec = chars.iter().map(|c| c.to_string()).collect(); + let sp = chars[usize::from(b' ')].to_string(); // 'Ġ' + let extra = [ + format!("{sp}t"), // 256 + "he".to_string(), // 257 + format!("{sp}th"), // 258 + "the".to_string(), // 259 + format!("{sp}the"), // 260 + "<|a|>".to_string(), + "<|b|>".to_string(), + ]; + tokens.extend(extra.iter().cloned()); + let mut types = vec![1i64; tokens.len()]; + types[261] = TYPE_CONTROL; + types[262] = TYPE_USER_DEFINED; + let merges = [ + format!("{sp} t"), + format!("{sp}t h"), + format!("{sp}th e"), + "h e".to_string(), + "t he".to_string(), + ]; + let t: Vec<&str> = tokens.iter().map(String::as_str).collect(); + let m: Vec<&str> = merges.iter().map(String::as_str).collect(); + GgufBpe::from_parts(&t, &types, &m, None, None, None).unwrap() +} + +#[test] +fn the_byte_map_matches_gpt2() { + let c = byte_chars(); + assert_eq!(c[usize::from(b'A')], 'A'); + assert_eq!(c[usize::from(b' ')], 'Ġ'); // U+0120 + assert_eq!(c[usize::from(b'\n')], 'Ċ'); // U+010A + assert_eq!(c[0], 'Ā'); // U+0100 + assert_eq!(c[0xAD], 'Ń'); // the soft hyphen is not printable, so it gets a code point above 255 + let mut seen: Vec = c.to_vec(); + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), 256); +} + +#[test] +fn merges_apply_in_rank_order() { + let t = tiny(); + // " the" -> " t" + "h" + "e" -> " th" "e" -> " the" + assert_eq!(t.encode(" the", false), vec![260]); + // "the" -> "t" + "he" (rank 3 needs "t he") -> "the" + assert_eq!(t.encode("the", false), vec![259]); + assert_eq!(t.encode("he", false), vec![257]); + // a lone merge that cannot continue + assert_eq!(t.encode(" th", false), vec![258]); + assert_eq!(t.decode(&t.encode("the cat the", false)), "the cat the"); +} + +#[test] +fn special_tokens_are_parsed_only_on_request() { + let t = tiny(); + assert_eq!(t.encode("<|a|>the<|b|>", true), vec![261, 259, 262]); + let plain = t.encode("<|a|>", false); + assert!(plain.len() > 1 && !plain.contains(&261)); + assert_eq!(t.decode(&[261, 259, 262]), "<|a|>the<|b|>"); + assert!(t.is_special(261) && !t.is_special(259)); +} + +#[test] +fn every_byte_sequence_round_trips() { + let t = tiny(); + let samples = [ + "", + "plain ascii, with punctuation!?", + "line1\nline2\r\n\r\n indented\ttab", + "héllo wörld — ünïcödé", + "日本語のテキスト", + "emoji 😀🎉 and 𝔘𝔫𝔦𝔠𝔬𝔡𝔢", + "1234567890 12 123 1234", + " ", + "a\u{0}b", + ]; + for s in samples { + assert_eq!(t.decode(&t.encode(s, false)), s, "round trip of {s:?}"); + } + // arbitrary bytes that are not UTF-8 survive at the byte level + let ids: Vec = (0..=255u8).map(|b| t.byte_id[usize::from(b)]).collect(); + assert_eq!(t.decode_bytes(&ids), (0..=255u8).collect::>()); +} + +#[test] +fn the_pre_tokenizer_splits_like_o200k() { + let re = Regex::new(GPT4O_PATTERN).unwrap(); + let pieces = |s: &str| -> Vec { + re.find_iter(s) + .map(|m| m.unwrap().as_str().to_owned()) + .collect() + }; + assert_eq!(pieces("Hello world"), ["Hello", " world"]); + assert_eq!(pieces("don't STOP"), ["don't", " STOP"]); + assert_eq!(pieces("x=12345"), ["x", "=", "123", "45"]); + assert_eq!(pieces("a b"), ["a", " ", " b"]); + assert_eq!(pieces("a\n\nb"), ["a", "\n\n", "b"]); + assert_eq!(pieces("CamelCaseWord"), ["Camel", "Case", "Word"]); + assert_eq!(pieces("end.\n"), ["end", ".\n"]); +} + +#[test] +fn long_pieces_do_not_blow_up() { + let t = tiny(); + let long = "the".repeat(20_000); + let ids = t.encode(&long, false); + assert_eq!(t.decode(&ids), long); + let spaces = " ".repeat(50_000); + assert_eq!(t.decode(&t.encode(&spaces, false)), spaces); +} + +#[test] +fn utf8_stream_never_splits_a_character() { + let bytes = "a😀é".as_bytes(); + for split in 0..=bytes.len() { + let mut s = Utf8Stream::default(); + let mut text = s.push(&bytes[..split]); + text.push_str(&s.push(&bytes[split..])); + text.push_str(&s.finish()); + assert_eq!(text, "a😀é", "split at {split}"); + } + let mut s = Utf8Stream::default(); + assert_eq!(s.push(&[0xF0, 0x9F]), ""); + assert_eq!(s.finish(), "\u{FFFD}"); + assert_eq!(s.push(&[0xFF, b'x']), "\u{FFFD}x"); +} + +#[test] +fn bad_vocabularies_are_refused() { + let chars = byte_chars(); + let all: Vec = chars.iter().map(|c| c.to_string()).collect(); + let t: Vec<&str> = all.iter().map(String::as_str).collect(); + let ok_types = vec![1i64; t.len()]; + assert!(GgufBpe::from_parts(&t, &ok_types, &[], None, None, None).is_ok()); + assert!(GgufBpe::from_parts(&t[1..], &ok_types[1..], &[], None, None, None).is_err()); + assert!(GgufBpe::from_parts(&t, &ok_types[1..], &[], None, None, None).is_err()); + assert!(GgufBpe::from_parts(&t, &ok_types, &["nospace"], None, None, None).is_err()); + assert!(GgufBpe::from_parts(&t, &ok_types, &["zz yy"], None, None, None).is_err()); + assert!(GgufBpe::from_parts(&t, &ok_types, &[], Some(9999), None, None).is_err()); +} diff --git a/desktop-core/src/runtime_gateway.rs b/desktop-core/src/runtime_gateway.rs index dfa0286e..eba5a05b 100644 --- a/desktop-core/src/runtime_gateway.rs +++ b/desktop-core/src/runtime_gateway.rs @@ -942,189 +942,4 @@ async fn tool_responses(registry: Registry, index: usize, value: Value) -> Respo } #[cfg(test)] -mod tests { - use super::*; - #[test] - fn runtime_gateway_refuses_tools_state_and_out_of_contract_sampling() { - for extra in [ - json!({"temperature":2.5}), - json!({"temperature":0.1234}), - json!({"top_p":1.5}), - json!({"top_k":1.5}), - json!({"seed":-1}), - json!({"repetition_penalty":0}), - json!({"stop":["x"]}), - json!({"tools":[{"type":"function","name":"run"}]}), - json!({"previous_response_id":"resp_x"}), - json!({"store":true}), - json!({"max_output_tokens":0}), - ] { - let mut value = json!({"model":"native","input":"hello"}); - value - .as_object_mut() - .unwrap() - .extend(extra.as_object().unwrap().clone()); - assert!(render(&value).is_err()); - } - let (prompt, limit, greedy) = - render(&json!({"model":"native","input":"hello","max_output_tokens":2,"store":false})) - .unwrap(); - assert_eq!(limit, 2); - assert_eq!(greedy, FixedPoint::default()); - assert!(prompt.ends_with("<|im_start|>assistant\n\n\n\n\n")); - } - #[test] - fn runtime_gateway_forwards_the_full_sampling_contract_to_the_runtime_request() { - let (_, _, fixed) = render(&json!({ - "model":"native","input":"hello","temperature":0.7,"top_p":0.9,"top_k":40,"min_p":0.05, - "repetition_penalty":1.1,"frequency_penalty":0.25,"presence_penalty":-0.5, - "penalty_last_n":128,"seed":42 - })) - .unwrap(); - let mut request = proto::GenerateRequest::default(); - crate::runtime_sampling::apply(&mut request, &fixed); - assert_eq!(request.temperature_milli, 700); - assert_eq!(request.top_p_micro, Some(900_000)); - assert_eq!(request.top_k, Some(40)); - assert_eq!(request.min_p_micro, Some(50_000)); - assert_eq!(request.repetition_penalty_micro, Some(1_100_000)); - assert_eq!(request.frequency_penalty_micro, Some(250_000)); - assert_eq!(request.presence_penalty_micro, Some(-500_000)); - assert_eq!(request.penalty_last_n, Some(128)); - assert_eq!(request.seed, Some(42)); - let backend = crate::runtime_sampling::to_backend(&request).unwrap(); - assert_eq!(backend.top_p_micro, Some(900_000)); - assert_eq!(backend.seed, Some(42)); - request.top_p_micro = Some(1_000_001); - assert!(crate::runtime_sampling::to_backend(&request).is_err()); - } - fn trace() -> Trace { - Trace { - id: "resp_test".into(), - model: "native".into(), - text: String::new(), - usage: proto::Usage::default(), - sequence: 0, - } - } - #[test] - fn runtime_gateway_sse_lifecycle_has_one_terminal_and_ordered_parts() { - let mut trace = trace(); - let mut events = trace.beginning(); - events.extend( - trace - .frame(proto::GenerationFrame { - payload: Some(proto::generation_frame::Payload::Text(proto::TextDelta { - text: "ok".into(), - })), - ..Default::default() - }) - .unwrap(), - ); - events.extend( - trace - .frame(proto::GenerationFrame { - payload: Some(proto::generation_frame::Payload::Terminal( - proto::Terminal { - state: 1, - reason: "length".into(), - usage: Some(proto::Usage { - input_tokens: 3, - output_tokens: 2, - reused_input_tokens: 0, - }), - ..Default::default() - }, - )), - ..Default::default() - }) - .unwrap(), - ); - let parsed = events - .iter() - .map(|b| { - serde_json::from_str::( - std::str::from_utf8(b) - .unwrap() - .lines() - .find_map(|l| l.strip_prefix("data: ")) - .unwrap(), - ) - .unwrap() - }) - .collect::>(); - let kinds = parsed - .iter() - .map(|v| v["type"].as_str().unwrap()) - .collect::>(); - assert_eq!( - kinds, - [ - "response.created", - "response.in_progress", - "response.output_item.added", - "response.content_part.added", - "response.output_text.delta", - "response.output_text.done", - "response.content_part.done", - "response.output_item.done", - "response.incomplete" - ] - ); - for (i, event) in parsed.iter().enumerate() { - assert_eq!(event["sequence_number"], i); - } - assert_eq!( - parsed.last().unwrap()["response"]["output"][0]["content"][0]["text"], - "ok" - ); - assert_eq!( - parsed.last().unwrap()["response"]["usage"]["total_tokens"], - 5 - ); - } - #[test] - fn runtime_gateway_unadvertised_tool_is_terminal_failure_not_success() { - let mut trace = trace(); - assert!( - trace - .frame(proto::GenerationFrame { - payload: Some(proto::generation_frame::Payload::Tool( - proto::ToolCallDelta::default() - )), - ..Default::default() - }) - .is_err() - ); - let failure = trace.interrupted(); - assert!( - std::str::from_utf8(&failure) - .unwrap() - .starts_with("event: response.failed\n") - ); - assert!( - !std::str::from_utf8(&failure) - .unwrap() - .contains("response.completed") - ); - } - #[test] - fn runtime_gateway_terminal_without_advertised_text_finish_is_refused() { - for reason in ["tool_calls", "unknown", ""] { - assert!( - trace() - .frame(proto::GenerationFrame { - payload: Some(proto::generation_frame::Payload::Terminal( - proto::Terminal { - state: 1, - reason: reason.into(), - ..Default::default() - } - )), - ..Default::default() - }) - .is_err() - ); - } - } -} +mod tests; diff --git a/desktop-core/src/runtime_gateway/tests.rs b/desktop-core/src/runtime_gateway/tests.rs new file mode 100644 index 00000000..b7ababaa --- /dev/null +++ b/desktop-core/src/runtime_gateway/tests.rs @@ -0,0 +1,186 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +#[test] +fn runtime_gateway_refuses_tools_state_and_out_of_contract_sampling() { + for extra in [ + json!({"temperature":2.5}), + json!({"temperature":0.1234}), + json!({"top_p":1.5}), + json!({"top_k":1.5}), + json!({"seed":-1}), + json!({"repetition_penalty":0}), + json!({"stop":["x"]}), + json!({"tools":[{"type":"function","name":"run"}]}), + json!({"previous_response_id":"resp_x"}), + json!({"store":true}), + json!({"max_output_tokens":0}), + ] { + let mut value = json!({"model":"native","input":"hello"}); + value + .as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + assert!(render(&value).is_err()); + } + let (prompt, limit, greedy) = + render(&json!({"model":"native","input":"hello","max_output_tokens":2,"store":false})) + .unwrap(); + assert_eq!(limit, 2); + assert_eq!(greedy, FixedPoint::default()); + assert!(prompt.ends_with("<|im_start|>assistant\n\n\n\n\n")); +} +#[test] +fn runtime_gateway_forwards_the_full_sampling_contract_to_the_runtime_request() { + let (_, _, fixed) = render(&json!({ + "model":"native","input":"hello","temperature":0.7,"top_p":0.9,"top_k":40,"min_p":0.05, + "repetition_penalty":1.1,"frequency_penalty":0.25,"presence_penalty":-0.5, + "penalty_last_n":128,"seed":42 + })) + .unwrap(); + let mut request = proto::GenerateRequest::default(); + crate::runtime_sampling::apply(&mut request, &fixed); + assert_eq!(request.temperature_milli, 700); + assert_eq!(request.top_p_micro, Some(900_000)); + assert_eq!(request.top_k, Some(40)); + assert_eq!(request.min_p_micro, Some(50_000)); + assert_eq!(request.repetition_penalty_micro, Some(1_100_000)); + assert_eq!(request.frequency_penalty_micro, Some(250_000)); + assert_eq!(request.presence_penalty_micro, Some(-500_000)); + assert_eq!(request.penalty_last_n, Some(128)); + assert_eq!(request.seed, Some(42)); + let backend = crate::runtime_sampling::to_backend(&request).unwrap(); + assert_eq!(backend.top_p_micro, Some(900_000)); + assert_eq!(backend.seed, Some(42)); + request.top_p_micro = Some(1_000_001); + assert!(crate::runtime_sampling::to_backend(&request).is_err()); +} +fn trace() -> Trace { + Trace { + id: "resp_test".into(), + model: "native".into(), + text: String::new(), + usage: proto::Usage::default(), + sequence: 0, + } +} +#[test] +fn runtime_gateway_sse_lifecycle_has_one_terminal_and_ordered_parts() { + let mut trace = trace(); + let mut events = trace.beginning(); + events.extend( + trace + .frame(proto::GenerationFrame { + payload: Some(proto::generation_frame::Payload::Text(proto::TextDelta { + text: "ok".into(), + })), + ..Default::default() + }) + .unwrap(), + ); + events.extend( + trace + .frame(proto::GenerationFrame { + payload: Some(proto::generation_frame::Payload::Terminal( + proto::Terminal { + state: 1, + reason: "length".into(), + usage: Some(proto::Usage { + input_tokens: 3, + output_tokens: 2, + reused_input_tokens: 0, + }), + ..Default::default() + }, + )), + ..Default::default() + }) + .unwrap(), + ); + let parsed = events + .iter() + .map(|b| { + serde_json::from_str::( + std::str::from_utf8(b) + .unwrap() + .lines() + .find_map(|l| l.strip_prefix("data: ")) + .unwrap(), + ) + .unwrap() + }) + .collect::>(); + let kinds = parsed + .iter() + .map(|v| v["type"].as_str().unwrap()) + .collect::>(); + assert_eq!( + kinds, + [ + "response.created", + "response.in_progress", + "response.output_item.added", + "response.content_part.added", + "response.output_text.delta", + "response.output_text.done", + "response.content_part.done", + "response.output_item.done", + "response.incomplete" + ] + ); + for (i, event) in parsed.iter().enumerate() { + assert_eq!(event["sequence_number"], i); + } + assert_eq!( + parsed.last().unwrap()["response"]["output"][0]["content"][0]["text"], + "ok" + ); + assert_eq!( + parsed.last().unwrap()["response"]["usage"]["total_tokens"], + 5 + ); +} +#[test] +fn runtime_gateway_unadvertised_tool_is_terminal_failure_not_success() { + let mut trace = trace(); + assert!( + trace + .frame(proto::GenerationFrame { + payload: Some(proto::generation_frame::Payload::Tool( + proto::ToolCallDelta::default() + )), + ..Default::default() + }) + .is_err() + ); + let failure = trace.interrupted(); + assert!( + std::str::from_utf8(&failure) + .unwrap() + .starts_with("event: response.failed\n") + ); + assert!( + !std::str::from_utf8(&failure) + .unwrap() + .contains("response.completed") + ); +} +#[test] +fn runtime_gateway_terminal_without_advertised_text_finish_is_refused() { + for reason in ["tool_calls", "unknown", ""] { + assert!( + trace() + .frame(proto::GenerationFrame { + payload: Some(proto::generation_frame::Payload::Terminal( + proto::Terminal { + state: 1, + reason: reason.into(), + ..Default::default() + } + )), + ..Default::default() + }) + .is_err() + ); + } +} diff --git a/desktop-core/src/runtime_rpc.rs b/desktop-core/src/runtime_rpc.rs index 6f5e05ae..c80735a0 100644 --- a/desktop-core/src/runtime_rpc.rs +++ b/desktop-core/src/runtime_rpc.rs @@ -1074,631 +1074,4 @@ fn event_to_proto(value: api::GenerationEvent) -> proto::generation_frame::Paylo } #[cfg(test)] -mod tests { - use super::*; - use crate::runtime_client::RuntimeClient; - use std::net::SocketAddr; - use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; - const TOKEN: &str = "synthetic-runtime-test-token-00000000"; - struct Mock { - loads: Arc, - cancel: Arc, - } - fn model() -> api::ModelDescriptor { - api::ModelDescriptor { - family: "fixture".into(), - architecture: "fixture".into(), - weight_format: "fixture".into(), - artifact_digest: format!("sha256:{}", "a".repeat(64)), - } - } - fn config() -> api::RuntimeConfig { - api::RuntimeConfig { - load_config_version: 1, - inference_mode: api::InferenceMode::Native, - gpu_memory_limit_bytes: Some(1024), - allow_experimental: false, - } - } - fn loaded() -> api::LoadedModel { - api::LoadedModel { - handle: "fixture-handle".into(), - descriptor: model(), - load_config_version: 1, - effective_mode: api::InferenceMode::Native, - mode_identity_digest: format!("sha256:{}", "b".repeat(64)), - } - } - impl api::Backend for Mock { - fn identity(&self) -> api::BackendIdentity { - api::BackendIdentity { - name: "fixture".into(), - implementation_version: "1".into(), - api_version: 2, - } - } - fn capabilities(&self) -> api::BackendCapabilities { - api::BackendCapabilities { - supported_models: vec![api::SupportedModelTuple { - family: "fixture".into(), - architecture: "fixture".into(), - weight_format: "fixture".into(), - }], - max_concurrent_generations: 1, - supports_cancellation: true, - supports_tool_call_streaming: false, - } - } - fn load( - &mut self, - _model: api::ModelDescriptor, - config: api::RuntimeConfig, - ) -> Result { - self.loads.fetch_add(1, Ordering::SeqCst); - if config.inference_mode != api::InferenceMode::Native { - return Err(api::BackendError { - code: api::ErrorCode::UnsupportedModel, - message: "private-path-must-not-leak".into(), - retryable: false, - }); - } - Ok(loaded()) - } - fn unload(&mut self, _: api::LoadedModel) -> Result<(), api::BackendError> { - Ok(()) - } - fn cancel(&mut self, _: &str) -> Result<(), api::BackendError> { - self.cancel.store(true, Ordering::SeqCst); - Ok(()) - } - fn start_generation( - &mut self, - _: &api::LoadedModel, - request: api::GenerationRequest, - ) -> Result { - let (sink, stream) = api::GenerationSink::channel(); - let cancelled = self.cancel.clone(); - cancelled.store(false, Ordering::SeqCst); - std::thread::spawn(move || { - if request.prompt == "missing" { - return; - } - if request.prompt == "slow-missing" { - // Ends without a terminal, but only after the client is gone. - std::thread::sleep(std::time::Duration::from_millis(150)); - return; - } - if request.prompt == "wait" { - while !cancelled.load(Ordering::SeqCst) { - std::thread::park_timeout(std::time::Duration::from_millis(2)); - } - let _ = sink.cancel(); - return; - } - let _ = sink.emit(api::GenerationEvent::TextDelta { text: "A".into() }); - let usage = api::Usage { - input_tokens: 1, - output_tokens: 1, - reused_input_tokens: 0, - }; - let _ = sink.emit(api::GenerationEvent::Usage(usage.clone())); - let _ = sink.complete(api::FinishReason::Stop, usage); - }); - Ok(stream) - } - } - async fn fixture() -> ( - RuntimeClient, - RuntimeServer, - tokio::sync::oneshot::Sender<()>, - tokio::task::JoinHandle<()>, - Arc, - Arc, - SocketAddr, - ) { - let loads = Arc::new(AtomicUsize::new(0)); - let cancel = Arc::new(AtomicBool::new(false)); - let server = RuntimeServer::new( - Box::new(Mock { - loads: loads.clone(), - cancel: cancel.clone(), - }), - TOKEN.into(), - ) - .unwrap(); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let (stop, stopped) = tokio::sync::oneshot::channel(); - let owned = server.clone(); - let task = tokio::spawn(async move { - owned - .serve(listener, async { - let _ = stopped.await; - }) - .await - .unwrap(); - }); - let client = RuntimeClient::connect(address, TOKEN.into()).await.unwrap(); - (client, server, stop, task, loads, cancel, address) - } - async fn load_fixture(client: &mut RuntimeClient) -> (String, String) { - let snapshot = client.snapshot().await.unwrap(); - assert!(snapshot.transport_ready && !snapshot.model_ready); - assert!(snapshot.capabilities.unwrap().models.is_empty()); - let id = Uuid::new_v4().to_string(); - client - .load(proto::LoadRequest { - operation_id: id.clone(), - expected_epoch: snapshot.epoch.clone(), - model: Some(descriptor_to_proto(&model())), - config: Some(config_to_proto(&config())), - }) - .await - .unwrap(); - for _ in 0..100 { - let operation = client - .operation(proto::OperationQuery { - operation_id: id.clone(), - expected_epoch: snapshot.epoch.clone(), - }) - .await - .unwrap(); - if operation.state == 2 { - return (snapshot.epoch, operation.loaded.unwrap().handle); - } - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - } - panic!("fixture_load_timeout") - } - fn request(epoch: &str, handle: &str, prompt: &str) -> proto::GenerateRequest { - proto::GenerateRequest { - request_id: Uuid::new_v4().to_string(), - expected_epoch: epoch.into(), - handle: handle.into(), - prompt: prompt.into(), - max_output_tokens: 2, - temperature_milli: 0, - ..Default::default() - } - } - #[tokio::test(flavor = "current_thread")] - async fn runtime_rpc_load_dedup_preserves_mode_and_generation_order() { - let (mut client, server, stop, task, loads, _, _) = fixture().await; - let (epoch, handle) = load_fixture(&mut client).await; - let command = { - let state = server.inner.state.lock().unwrap(); - state - .operations - .values() - .next() - .unwrap() - .result - .operation_id - .clone() - }; - let load = proto::LoadRequest { - operation_id: command.clone(), - expected_epoch: epoch.clone(), - model: Some(descriptor_to_proto(&model())), - config: Some(config_to_proto(&config())), - }; - assert_eq!(client.load(load.clone()).await.unwrap().state, 2); - assert_eq!(loads.load(Ordering::SeqCst), 1); - let mut conflict = load; - conflict.config.as_mut().unwrap().gpu_memory_limit_bytes = Some(2048); - assert_eq!( - client.load(conflict).await.unwrap_err().code(), - tonic::Code::AlreadyExists - ); - let mut stream = client - .generate(request(&epoch, &handle, "normal")) - .await - .unwrap(); - let mut frames = Vec::new(); - while let Some(frame) = stream.message().await.unwrap() { - frames.push(frame); - } - assert_eq!( - frames.iter().map(|f| f.sequence).collect::>(), - vec![1, 2, 3, 4] - ); - assert!(matches!( - frames[0].payload, - Some(proto::generation_frame::Payload::Accepted(_)) - )); - assert!(matches!( - frames[1].payload, - Some(proto::generation_frame::Payload::Text(_)) - )); - assert!(matches!( - frames[2].payload, - Some(proto::generation_frame::Payload::Usage(_)) - )); - assert!(matches!( - frames[3].payload, - Some(proto::generation_frame::Payload::Terminal( - proto::Terminal { state: 1, .. } - )) - )); - let mut ple = config(); - ple.allow_experimental = true; - ple.inference_mode = api::InferenceMode::ExperimentalKarPle { - profile_id: "unqualified".into(), - }; - let operation = Uuid::new_v4().to_string(); - client - .load(proto::LoadRequest { - operation_id: operation.clone(), - expected_epoch: epoch.clone(), - model: Some(descriptor_to_proto(&model())), - config: Some(config_to_proto(&ple)), - }) - .await - .unwrap(); - for _ in 0..100 { - if client - .operation(proto::OperationQuery { - operation_id: operation.clone(), - expected_epoch: epoch.clone(), - }) - .await - .unwrap() - .state - == 3 - { - break; - } - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - } - let current = client.snapshot().await.unwrap(); - assert!(current.model_ready); - assert_eq!(current.loaded.unwrap().handle, handle); - drop(stream); - drop(client); - drop(server); - stop.send(()).unwrap(); - task.await.unwrap(); - } - #[tokio::test(flavor = "current_thread")] - async fn runtime_rpc_unconfirmed_terminal_after_client_loss_keeps_slot_owned() { - let (mut client, server, stop, task, _, _, _) = fixture().await; - let (epoch, handle) = load_fixture(&mut client).await; - let mut stream = client - .generate(request(&epoch, &handle, "slow-missing")) - .await - .unwrap(); - assert!(stream.message().await.unwrap().is_some()); - drop(stream); - tokio::time::sleep(std::time::Duration::from_millis(400)).await; - let snapshot = client.snapshot().await.unwrap(); - // A synthesized terminal is no completion proof: the slot stays owned - // and model admission is closed rather than reopened. - assert!(!snapshot.active_request_id.is_empty()); - assert!(!snapshot.model_ready); - drop(client); - drop(server); - stop.send(()).unwrap(); - task.await.unwrap(); - } - fn operation_entry(id: &str, state: proto::operation_result::State) -> Operation { - Operation { - digest: [0; 32], - result: proto::OperationResult { - operation_id: id.into(), - epoch: String::new(), - state: state as i32, - reason: String::new(), - loaded: None, - }, - } - } - #[tokio::test(flavor = "current_thread")] - async fn lifecycle_guard_ends_only_its_own_unresolved_operation() { - let (client, server, stop, task, _, _, _) = fixture().await; - let (first, second) = (Uuid::new_v4().to_string(), Uuid::new_v4().to_string()); - { - // The first worker already published its completion and disarmed - // nothing yet; a second operation then took the lifecycle gate. - let mut state = server.inner.state.lock().unwrap(); - state.operations.insert( - first.clone(), - operation_entry(&first, proto::operation_result::State::Completed), - ); - state.operations.insert( - second.clone(), - operation_entry(&second, proto::operation_result::State::Accepted), - ); - state.lifecycle_busy = true; - state.loaded = Some(loaded()); - } - // A stale armed guard of the finished first operation must be inert. - drop(LifecycleGuard { - inner: server.inner.clone(), - operation_id: first.clone(), - armed: true, - }); - { - let state = server.inner.state.lock().unwrap(); - assert!(state.lifecycle_busy && state.loaded.is_some()); - assert_eq!( - state.operations[&second].result.state, - proto::operation_result::State::Accepted as i32 - ); - } - // A disarmed guard is inert even for its own unresolved operation. - drop(LifecycleGuard { - inner: server.inner.clone(), - operation_id: second.clone(), - armed: false, - }); - assert!(server.inner.state.lock().unwrap().lifecycle_busy); - // The failed worker's own unresolved operation ends as indeterminate. - drop(LifecycleGuard { - inner: server.inner.clone(), - operation_id: second.clone(), - armed: true, - }); - { - let state = server.inner.state.lock().unwrap(); - assert!(!state.lifecycle_busy && state.loaded.is_none()); - assert_eq!( - state.operations[&second].result.state, - proto::operation_result::State::Indeterminate as i32 - ); - assert_eq!( - state.operations[&second].result.reason, - "lifecycle_worker_failed" - ); - assert_eq!( - state.operations[&first].result.state, - proto::operation_result::State::Completed as i32 - ); - } - drop(client); - drop(server); - stop.send(()).unwrap(); - task.await.unwrap(); - } - #[tokio::test(flavor = "current_thread")] - async fn runtime_rpc_disconnect_cancels_and_missing_terminal_closes_admission() { - let (mut client, server, stop, task, _, cancelled, _) = fixture().await; - let (epoch, handle) = load_fixture(&mut client).await; - let command = request(&epoch, &handle, "wait"); - let mut stream = client.generate(command.clone()).await.unwrap(); - assert!(stream.message().await.unwrap().is_some()); - drop(stream); - for _ in 0..100 { - if client - .snapshot() - .await - .unwrap() - .active_request_id - .is_empty() - { - break; - } - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - } - assert!(cancelled.load(Ordering::SeqCst)); - assert!( - client - .snapshot() - .await - .unwrap() - .active_request_id - .is_empty() - ); - assert_eq!( - client.generate(command).await.err().unwrap().code(), - tonic::Code::AlreadyExists - ); - let mut missing = client - .generate(request(&epoch, &handle, "missing")) - .await - .unwrap(); - missing.message().await.unwrap(); - let terminal = missing.message().await.unwrap().unwrap(); - assert!(matches!( - terminal.payload, - Some(proto::generation_frame::Payload::Terminal( - proto::Terminal { - state: 2, - retryable: false, - .. - } - )) - )); - assert!(missing.message().await.unwrap().is_none()); - let closed = client.snapshot().await.unwrap(); - assert!(!closed.model_ready); - assert!(!closed.active_request_id.is_empty()); - drop(missing); - drop(client); - drop(server); - stop.send(()).unwrap(); - task.await.unwrap(); - } - #[tokio::test(flavor = "current_thread")] - async fn runtime_rpc_accepted_identity_stays_fenced_while_a_full_ledger_rolls_over() { - let (mut client, server, stop, task, _, _, _) = fixture().await; - let (epoch, handle) = load_fixture(&mut client).await; - let accepted = request(&epoch, &handle, "A"); - let other_active = Uuid::new_v4().to_string(); - { - let mut state = server.inner.state.lock().unwrap(); - let capacity = state.requests.capacity(); - // The accepted identity is the newest of a full ledger. - for _ in 1..capacity { - state.requests.insert(&Uuid::new_v4().to_string()); - } - state.requests.insert(&accepted.request_id); - assert_eq!(state.requests.len(), capacity); - } - // A busy slot or a repeated identity is refused, whatever the ledger holds. - for active in [None, Some(accepted.request_id.clone()), Some(other_active)] { - server.inner.state.lock().unwrap().active = active.clone(); - let duplicate = client.generate(accepted.clone()).await.err().unwrap(); - assert_eq!(duplicate.code(), tonic::Code::AlreadyExists); - assert_eq!(duplicate.message(), "generation_not_replayed"); - assert!(duplicate.metadata().get("x-leleka-accepted").is_none()); - if active.is_some() { - // A new identity meets the busy slot, not a full ledger, and is proven unaccepted. - let fresh = client - .generate(request(&epoch, &handle, "A")) - .await - .err() - .unwrap(); - assert_eq!(fresh.code(), tonic::Code::ResourceExhausted); - assert_eq!(fresh.metadata().get("x-leleka-accepted").unwrap(), "false"); - } - let state = server.inner.state.lock().unwrap(); - assert_eq!(state.active, active); - assert_eq!(state.requests.len(), state.requests.capacity()); - assert!(state.requests.contains(&accepted.request_id)); - } - drop(client); - drop(server); - stop.send(()).unwrap(); - task.await.unwrap(); - } - #[tokio::test(flavor = "current_thread")] - async fn runtime_rpc_auth_epoch_bounds_and_operation_capacity() { - for code in [api::ErrorCode::BackendUnavailable, api::ErrorCode::Internal] { - assert!( - backend_status(&api::BackendError { - code, - message: "private".into(), - retryable: true - }) - .metadata() - .get("x-leleka-accepted") - .is_none() - ); - } - for code in [ - api::ErrorCode::InvalidRequest, - api::ErrorCode::UnsupportedModel, - api::ErrorCode::ResourceExhausted, - ] { - assert_eq!( - backend_status(&api::BackendError { - code, - message: "private".into(), - retryable: true - }) - .metadata() - .get("x-leleka-accepted") - .unwrap(), - "false" - ); - } - let (mut client, server, stop, task, _, _, local_address) = fixture().await; - let (epoch, handle) = load_fixture(&mut client).await; - let mut wrong = client.clone(); - assert_eq!( - RuntimeClient::connect(local_address, "wrong-synthetic-runtime-token-000000".into()) - .await - .err() - .unwrap() - .code(), - tonic::Code::Unauthenticated - ); - let mut watches = Vec::new(); - for _ in 0..16 { - let mut watch = client - .watch(proto::Cursor { - epoch: epoch.clone(), - sequence: 0, - }) - .await - .unwrap(); - assert_eq!(watch.message().await.unwrap().unwrap().epoch, epoch); - watches.push(watch); - } - assert_eq!( - client - .watch(proto::Cursor { - epoch: epoch.clone(), - sequence: 0 - }) - .await - .err() - .unwrap() - .code(), - tonic::Code::ResourceExhausted - ); - drop(watches); - // The client rejects direct nonloopback endpoints before connecting. - let address = SocketAddr::from(([192, 0, 2, 1], 1)); - assert_eq!( - RuntimeClient::connect(address, TOKEN.into()) - .await - .err() - .unwrap() - .code(), - tonic::Code::PermissionDenied - ); - let old = Uuid::new_v4().to_string(); - assert_eq!( - wrong - .generate(request(&old, &handle, "normal")) - .await - .err() - .unwrap() - .message(), - "epoch_mismatch" - ); - let mut huge = request(&epoch, &handle, "normal"); - huge.max_output_tokens = api::MAX_OUTPUT_TOKENS + 1; - let rejected = client.generate(huge).await.err().unwrap(); - assert_eq!( - rejected.metadata().get("x-leleka-accepted").unwrap(), - "false" - ); - let unknown = client - .operation(proto::OperationQuery { - operation_id: Uuid::new_v4().to_string(), - expected_epoch: old, - }) - .await - .unwrap(); - assert_eq!(unknown.state, 4); - { - let mut state = server.inner.state.lock().unwrap(); - for _ in state.operations.len()..MAX_IDS { - let id = Uuid::new_v4().to_string(); - state.operations.insert( - id.clone(), - Operation { - digest: [0; 32], - result: proto::OperationResult { - operation_id: id, - epoch: epoch.clone(), - state: 2, - reason: "fixture".into(), - loaded: None, - }, - }, - ); - } - } - assert_eq!( - server - .reserve(&Uuid::new_v4().to_string(), &epoch, [1; 32]) - .unwrap_err() - .code(), - tonic::Code::ResourceExhausted - ); - let (id, digest) = { - let state = server.inner.state.lock().unwrap(); - let (id, op) = state.operations.iter().next().unwrap(); - (id.clone(), op.digest) - }; - assert!(!server.reserve(&id, &epoch, digest).unwrap().1); - drop(wrong); - drop(client); - drop(server); - stop.send(()).unwrap(); - task.await.unwrap(); - } -} +mod tests; diff --git a/desktop-core/src/runtime_rpc/tests.rs b/desktop-core/src/runtime_rpc/tests.rs new file mode 100644 index 00000000..b9a7a96a --- /dev/null +++ b/desktop-core/src/runtime_rpc/tests.rs @@ -0,0 +1,628 @@ +//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). + +use super::*; +use crate::runtime_client::RuntimeClient; +use std::net::SocketAddr; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +const TOKEN: &str = "synthetic-runtime-test-token-00000000"; +struct Mock { + loads: Arc, + cancel: Arc, +} +fn model() -> api::ModelDescriptor { + api::ModelDescriptor { + family: "fixture".into(), + architecture: "fixture".into(), + weight_format: "fixture".into(), + artifact_digest: format!("sha256:{}", "a".repeat(64)), + } +} +fn config() -> api::RuntimeConfig { + api::RuntimeConfig { + load_config_version: 1, + inference_mode: api::InferenceMode::Native, + gpu_memory_limit_bytes: Some(1024), + allow_experimental: false, + } +} +fn loaded() -> api::LoadedModel { + api::LoadedModel { + handle: "fixture-handle".into(), + descriptor: model(), + load_config_version: 1, + effective_mode: api::InferenceMode::Native, + mode_identity_digest: format!("sha256:{}", "b".repeat(64)), + } +} +impl api::Backend for Mock { + fn identity(&self) -> api::BackendIdentity { + api::BackendIdentity { + name: "fixture".into(), + implementation_version: "1".into(), + api_version: 2, + } + } + fn capabilities(&self) -> api::BackendCapabilities { + api::BackendCapabilities { + supported_models: vec![api::SupportedModelTuple { + family: "fixture".into(), + architecture: "fixture".into(), + weight_format: "fixture".into(), + }], + max_concurrent_generations: 1, + supports_cancellation: true, + supports_tool_call_streaming: false, + } + } + fn load( + &mut self, + _model: api::ModelDescriptor, + config: api::RuntimeConfig, + ) -> Result { + self.loads.fetch_add(1, Ordering::SeqCst); + if config.inference_mode != api::InferenceMode::Native { + return Err(api::BackendError { + code: api::ErrorCode::UnsupportedModel, + message: "private-path-must-not-leak".into(), + retryable: false, + }); + } + Ok(loaded()) + } + fn unload(&mut self, _: api::LoadedModel) -> Result<(), api::BackendError> { + Ok(()) + } + fn cancel(&mut self, _: &str) -> Result<(), api::BackendError> { + self.cancel.store(true, Ordering::SeqCst); + Ok(()) + } + fn start_generation( + &mut self, + _: &api::LoadedModel, + request: api::GenerationRequest, + ) -> Result { + let (sink, stream) = api::GenerationSink::channel(); + let cancelled = self.cancel.clone(); + cancelled.store(false, Ordering::SeqCst); + std::thread::spawn(move || { + if request.prompt == "missing" { + return; + } + if request.prompt == "slow-missing" { + // Ends without a terminal, but only after the client is gone. + std::thread::sleep(std::time::Duration::from_millis(150)); + return; + } + if request.prompt == "wait" { + while !cancelled.load(Ordering::SeqCst) { + std::thread::park_timeout(std::time::Duration::from_millis(2)); + } + let _ = sink.cancel(); + return; + } + let _ = sink.emit(api::GenerationEvent::TextDelta { text: "A".into() }); + let usage = api::Usage { + input_tokens: 1, + output_tokens: 1, + reused_input_tokens: 0, + }; + let _ = sink.emit(api::GenerationEvent::Usage(usage.clone())); + let _ = sink.complete(api::FinishReason::Stop, usage); + }); + Ok(stream) + } +} +async fn fixture() -> ( + RuntimeClient, + RuntimeServer, + tokio::sync::oneshot::Sender<()>, + tokio::task::JoinHandle<()>, + Arc, + Arc, + SocketAddr, +) { + let loads = Arc::new(AtomicUsize::new(0)); + let cancel = Arc::new(AtomicBool::new(false)); + let server = RuntimeServer::new( + Box::new(Mock { + loads: loads.clone(), + cancel: cancel.clone(), + }), + TOKEN.into(), + ) + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (stop, stopped) = tokio::sync::oneshot::channel(); + let owned = server.clone(); + let task = tokio::spawn(async move { + owned + .serve(listener, async { + let _ = stopped.await; + }) + .await + .unwrap(); + }); + let client = RuntimeClient::connect(address, TOKEN.into()).await.unwrap(); + (client, server, stop, task, loads, cancel, address) +} +async fn load_fixture(client: &mut RuntimeClient) -> (String, String) { + let snapshot = client.snapshot().await.unwrap(); + assert!(snapshot.transport_ready && !snapshot.model_ready); + assert!(snapshot.capabilities.unwrap().models.is_empty()); + let id = Uuid::new_v4().to_string(); + client + .load(proto::LoadRequest { + operation_id: id.clone(), + expected_epoch: snapshot.epoch.clone(), + model: Some(descriptor_to_proto(&model())), + config: Some(config_to_proto(&config())), + }) + .await + .unwrap(); + for _ in 0..100 { + let operation = client + .operation(proto::OperationQuery { + operation_id: id.clone(), + expected_epoch: snapshot.epoch.clone(), + }) + .await + .unwrap(); + if operation.state == 2 { + return (snapshot.epoch, operation.loaded.unwrap().handle); + } + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + } + panic!("fixture_load_timeout") +} +fn request(epoch: &str, handle: &str, prompt: &str) -> proto::GenerateRequest { + proto::GenerateRequest { + request_id: Uuid::new_v4().to_string(), + expected_epoch: epoch.into(), + handle: handle.into(), + prompt: prompt.into(), + max_output_tokens: 2, + temperature_milli: 0, + ..Default::default() + } +} +#[tokio::test(flavor = "current_thread")] +async fn runtime_rpc_load_dedup_preserves_mode_and_generation_order() { + let (mut client, server, stop, task, loads, _, _) = fixture().await; + let (epoch, handle) = load_fixture(&mut client).await; + let command = { + let state = server.inner.state.lock().unwrap(); + state + .operations + .values() + .next() + .unwrap() + .result + .operation_id + .clone() + }; + let load = proto::LoadRequest { + operation_id: command.clone(), + expected_epoch: epoch.clone(), + model: Some(descriptor_to_proto(&model())), + config: Some(config_to_proto(&config())), + }; + assert_eq!(client.load(load.clone()).await.unwrap().state, 2); + assert_eq!(loads.load(Ordering::SeqCst), 1); + let mut conflict = load; + conflict.config.as_mut().unwrap().gpu_memory_limit_bytes = Some(2048); + assert_eq!( + client.load(conflict).await.unwrap_err().code(), + tonic::Code::AlreadyExists + ); + let mut stream = client + .generate(request(&epoch, &handle, "normal")) + .await + .unwrap(); + let mut frames = Vec::new(); + while let Some(frame) = stream.message().await.unwrap() { + frames.push(frame); + } + assert_eq!( + frames.iter().map(|f| f.sequence).collect::>(), + vec![1, 2, 3, 4] + ); + assert!(matches!( + frames[0].payload, + Some(proto::generation_frame::Payload::Accepted(_)) + )); + assert!(matches!( + frames[1].payload, + Some(proto::generation_frame::Payload::Text(_)) + )); + assert!(matches!( + frames[2].payload, + Some(proto::generation_frame::Payload::Usage(_)) + )); + assert!(matches!( + frames[3].payload, + Some(proto::generation_frame::Payload::Terminal( + proto::Terminal { state: 1, .. } + )) + )); + let mut ple = config(); + ple.allow_experimental = true; + ple.inference_mode = api::InferenceMode::ExperimentalKarPle { + profile_id: "unqualified".into(), + }; + let operation = Uuid::new_v4().to_string(); + client + .load(proto::LoadRequest { + operation_id: operation.clone(), + expected_epoch: epoch.clone(), + model: Some(descriptor_to_proto(&model())), + config: Some(config_to_proto(&ple)), + }) + .await + .unwrap(); + for _ in 0..100 { + if client + .operation(proto::OperationQuery { + operation_id: operation.clone(), + expected_epoch: epoch.clone(), + }) + .await + .unwrap() + .state + == 3 + { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + } + let current = client.snapshot().await.unwrap(); + assert!(current.model_ready); + assert_eq!(current.loaded.unwrap().handle, handle); + drop(stream); + drop(client); + drop(server); + stop.send(()).unwrap(); + task.await.unwrap(); +} +#[tokio::test(flavor = "current_thread")] +async fn runtime_rpc_unconfirmed_terminal_after_client_loss_keeps_slot_owned() { + let (mut client, server, stop, task, _, _, _) = fixture().await; + let (epoch, handle) = load_fixture(&mut client).await; + let mut stream = client + .generate(request(&epoch, &handle, "slow-missing")) + .await + .unwrap(); + assert!(stream.message().await.unwrap().is_some()); + drop(stream); + tokio::time::sleep(std::time::Duration::from_millis(400)).await; + let snapshot = client.snapshot().await.unwrap(); + // A synthesized terminal is no completion proof: the slot stays owned + // and model admission is closed rather than reopened. + assert!(!snapshot.active_request_id.is_empty()); + assert!(!snapshot.model_ready); + drop(client); + drop(server); + stop.send(()).unwrap(); + task.await.unwrap(); +} +fn operation_entry(id: &str, state: proto::operation_result::State) -> Operation { + Operation { + digest: [0; 32], + result: proto::OperationResult { + operation_id: id.into(), + epoch: String::new(), + state: state as i32, + reason: String::new(), + loaded: None, + }, + } +} +#[tokio::test(flavor = "current_thread")] +async fn lifecycle_guard_ends_only_its_own_unresolved_operation() { + let (client, server, stop, task, _, _, _) = fixture().await; + let (first, second) = (Uuid::new_v4().to_string(), Uuid::new_v4().to_string()); + { + // The first worker already published its completion and disarmed + // nothing yet; a second operation then took the lifecycle gate. + let mut state = server.inner.state.lock().unwrap(); + state.operations.insert( + first.clone(), + operation_entry(&first, proto::operation_result::State::Completed), + ); + state.operations.insert( + second.clone(), + operation_entry(&second, proto::operation_result::State::Accepted), + ); + state.lifecycle_busy = true; + state.loaded = Some(loaded()); + } + // A stale armed guard of the finished first operation must be inert. + drop(LifecycleGuard { + inner: server.inner.clone(), + operation_id: first.clone(), + armed: true, + }); + { + let state = server.inner.state.lock().unwrap(); + assert!(state.lifecycle_busy && state.loaded.is_some()); + assert_eq!( + state.operations[&second].result.state, + proto::operation_result::State::Accepted as i32 + ); + } + // A disarmed guard is inert even for its own unresolved operation. + drop(LifecycleGuard { + inner: server.inner.clone(), + operation_id: second.clone(), + armed: false, + }); + assert!(server.inner.state.lock().unwrap().lifecycle_busy); + // The failed worker's own unresolved operation ends as indeterminate. + drop(LifecycleGuard { + inner: server.inner.clone(), + operation_id: second.clone(), + armed: true, + }); + { + let state = server.inner.state.lock().unwrap(); + assert!(!state.lifecycle_busy && state.loaded.is_none()); + assert_eq!( + state.operations[&second].result.state, + proto::operation_result::State::Indeterminate as i32 + ); + assert_eq!( + state.operations[&second].result.reason, + "lifecycle_worker_failed" + ); + assert_eq!( + state.operations[&first].result.state, + proto::operation_result::State::Completed as i32 + ); + } + drop(client); + drop(server); + stop.send(()).unwrap(); + task.await.unwrap(); +} +#[tokio::test(flavor = "current_thread")] +async fn runtime_rpc_disconnect_cancels_and_missing_terminal_closes_admission() { + let (mut client, server, stop, task, _, cancelled, _) = fixture().await; + let (epoch, handle) = load_fixture(&mut client).await; + let command = request(&epoch, &handle, "wait"); + let mut stream = client.generate(command.clone()).await.unwrap(); + assert!(stream.message().await.unwrap().is_some()); + drop(stream); + for _ in 0..100 { + if client + .snapshot() + .await + .unwrap() + .active_request_id + .is_empty() + { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + } + assert!(cancelled.load(Ordering::SeqCst)); + assert!( + client + .snapshot() + .await + .unwrap() + .active_request_id + .is_empty() + ); + assert_eq!( + client.generate(command).await.err().unwrap().code(), + tonic::Code::AlreadyExists + ); + let mut missing = client + .generate(request(&epoch, &handle, "missing")) + .await + .unwrap(); + missing.message().await.unwrap(); + let terminal = missing.message().await.unwrap().unwrap(); + assert!(matches!( + terminal.payload, + Some(proto::generation_frame::Payload::Terminal( + proto::Terminal { + state: 2, + retryable: false, + .. + } + )) + )); + assert!(missing.message().await.unwrap().is_none()); + let closed = client.snapshot().await.unwrap(); + assert!(!closed.model_ready); + assert!(!closed.active_request_id.is_empty()); + drop(missing); + drop(client); + drop(server); + stop.send(()).unwrap(); + task.await.unwrap(); +} +#[tokio::test(flavor = "current_thread")] +async fn runtime_rpc_accepted_identity_stays_fenced_while_a_full_ledger_rolls_over() { + let (mut client, server, stop, task, _, _, _) = fixture().await; + let (epoch, handle) = load_fixture(&mut client).await; + let accepted = request(&epoch, &handle, "A"); + let other_active = Uuid::new_v4().to_string(); + { + let mut state = server.inner.state.lock().unwrap(); + let capacity = state.requests.capacity(); + // The accepted identity is the newest of a full ledger. + for _ in 1..capacity { + state.requests.insert(&Uuid::new_v4().to_string()); + } + state.requests.insert(&accepted.request_id); + assert_eq!(state.requests.len(), capacity); + } + // A busy slot or a repeated identity is refused, whatever the ledger holds. + for active in [None, Some(accepted.request_id.clone()), Some(other_active)] { + server.inner.state.lock().unwrap().active = active.clone(); + let duplicate = client.generate(accepted.clone()).await.err().unwrap(); + assert_eq!(duplicate.code(), tonic::Code::AlreadyExists); + assert_eq!(duplicate.message(), "generation_not_replayed"); + assert!(duplicate.metadata().get("x-leleka-accepted").is_none()); + if active.is_some() { + // A new identity meets the busy slot, not a full ledger, and is proven unaccepted. + let fresh = client + .generate(request(&epoch, &handle, "A")) + .await + .err() + .unwrap(); + assert_eq!(fresh.code(), tonic::Code::ResourceExhausted); + assert_eq!(fresh.metadata().get("x-leleka-accepted").unwrap(), "false"); + } + let state = server.inner.state.lock().unwrap(); + assert_eq!(state.active, active); + assert_eq!(state.requests.len(), state.requests.capacity()); + assert!(state.requests.contains(&accepted.request_id)); + } + drop(client); + drop(server); + stop.send(()).unwrap(); + task.await.unwrap(); +} +#[tokio::test(flavor = "current_thread")] +async fn runtime_rpc_auth_epoch_bounds_and_operation_capacity() { + for code in [api::ErrorCode::BackendUnavailable, api::ErrorCode::Internal] { + assert!( + backend_status(&api::BackendError { + code, + message: "private".into(), + retryable: true + }) + .metadata() + .get("x-leleka-accepted") + .is_none() + ); + } + for code in [ + api::ErrorCode::InvalidRequest, + api::ErrorCode::UnsupportedModel, + api::ErrorCode::ResourceExhausted, + ] { + assert_eq!( + backend_status(&api::BackendError { + code, + message: "private".into(), + retryable: true + }) + .metadata() + .get("x-leleka-accepted") + .unwrap(), + "false" + ); + } + let (mut client, server, stop, task, _, _, local_address) = fixture().await; + let (epoch, handle) = load_fixture(&mut client).await; + let mut wrong = client.clone(); + assert_eq!( + RuntimeClient::connect(local_address, "wrong-synthetic-runtime-token-000000".into()) + .await + .err() + .unwrap() + .code(), + tonic::Code::Unauthenticated + ); + let mut watches = Vec::new(); + for _ in 0..16 { + let mut watch = client + .watch(proto::Cursor { + epoch: epoch.clone(), + sequence: 0, + }) + .await + .unwrap(); + assert_eq!(watch.message().await.unwrap().unwrap().epoch, epoch); + watches.push(watch); + } + assert_eq!( + client + .watch(proto::Cursor { + epoch: epoch.clone(), + sequence: 0 + }) + .await + .err() + .unwrap() + .code(), + tonic::Code::ResourceExhausted + ); + drop(watches); + // The client rejects direct nonloopback endpoints before connecting. + let address = SocketAddr::from(([192, 0, 2, 1], 1)); + assert_eq!( + RuntimeClient::connect(address, TOKEN.into()) + .await + .err() + .unwrap() + .code(), + tonic::Code::PermissionDenied + ); + let old = Uuid::new_v4().to_string(); + assert_eq!( + wrong + .generate(request(&old, &handle, "normal")) + .await + .err() + .unwrap() + .message(), + "epoch_mismatch" + ); + let mut huge = request(&epoch, &handle, "normal"); + huge.max_output_tokens = api::MAX_OUTPUT_TOKENS + 1; + let rejected = client.generate(huge).await.err().unwrap(); + assert_eq!( + rejected.metadata().get("x-leleka-accepted").unwrap(), + "false" + ); + let unknown = client + .operation(proto::OperationQuery { + operation_id: Uuid::new_v4().to_string(), + expected_epoch: old, + }) + .await + .unwrap(); + assert_eq!(unknown.state, 4); + { + let mut state = server.inner.state.lock().unwrap(); + for _ in state.operations.len()..MAX_IDS { + let id = Uuid::new_v4().to_string(); + state.operations.insert( + id.clone(), + Operation { + digest: [0; 32], + result: proto::OperationResult { + operation_id: id, + epoch: epoch.clone(), + state: 2, + reason: "fixture".into(), + loaded: None, + }, + }, + ); + } + } + assert_eq!( + server + .reserve(&Uuid::new_v4().to_string(), &epoch, [1; 32]) + .unwrap_err() + .code(), + tonic::Code::ResourceExhausted + ); + let (id, digest) = { + let state = server.inner.state.lock().unwrap(); + let (id, op) = state.operations.iter().next().unwrap(); + (id.clone(), op.digest) + }; + assert!(!server.reserve(&id, &epoch, digest).unwrap().1); + drop(wrong); + drop(client); + drop(server); + stop.send(()).unwrap(); + task.await.unwrap(); +} diff --git a/scripts/archcheck/baseline.py b/scripts/archcheck/baseline.py index cb41c8f5..78859461 100644 --- a/scripts/archcheck/baseline.py +++ b/scripts/archcheck/baseline.py @@ -36,12 +36,17 @@ def _stem_root(path, oversize): return None +SPLIT_OVERHEAD = 3 # lines a split adds per new file: the `mod` declaration and its attributes + + def _family_lines(old, new): + """Lines of each original oversize file plus its same-stem split files; every new file may add its declaration.""" totals = {} for path, n in new.items(): root = path if path in old else _stem_root(path, old) if root: - totals[root] = totals.get(root, 0) + n + overhead = 0 if path in old else SPLIT_OVERHEAD + totals[root] = totals.get(root, 0) + n - overhead return totals diff --git a/scripts/check_architecture_test.py b/scripts/check_architecture_test.py index ce9b8160..2634d802 100644 --- a/scripts/check_architecture_test.py +++ b/scripts/check_architecture_test.py @@ -119,6 +119,10 @@ class BaselineRewrite(unittest.TestCase): self.assertEqual(len(bl.raised(old, base(oversize={"src/sub/a.rs": 501}))), 1) self.assertEqual(len(bl.raised(old, base(oversize={"src/a.rs": 500, "src/b.rs": 450}))), 1) + def test_a_split_may_add_only_its_module_declaration(self): + old = base(oversize={"src/big.rs": 1000}) + self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 503, "src/big/tests.rs": 500})), []) + def test_a_split_into_a_same_stem_directory_may_not_gain_lines(self): old = base(oversize={"src/big.rs": 1000}) self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 500, "src/big/part.rs": 480})), []) diff --git a/scripts/dev/elf-sections-equal.sh b/scripts/dev/elf-sections-equal.sh new file mode 100644 index 00000000..fc3826d5 --- /dev/null +++ b/scripts/dev/elf-sections-equal.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Prove that two release binaries run the same code: compare every loadable section byte for byte (STRA-338). +# +# scripts/dev/elf-sections-equal.sh A B exit 0 when .text, .rodata, .data* , .eh_frame*, .gcc_except_table, .init/.fini*, +# .tdata, .got and .plt of A and B are identical; exit 1 and a diff otherwise +# +# Two builds of the same program can differ in the symbol table only: LLVM suffixes private symbols with `.llvm.` and +# the hash follows the module layout, so `cmp` and `sha256sum` of the whole file are the wrong test after a pure source move. +# Build both with the same RUSTFLAGS `--remap-path-prefix==/src` so that panic locations carry no machine path. +# Needs GNU objcopy (binutils); run it in Linux or WSL. +set -euo pipefail +SECTIONS=(.text .rodata .data .data.rel.ro .eh_frame .eh_frame_hdr .gcc_except_table .init_array .fini_array .tdata .got .plt .plt.got .init .fini) + +sums() { # $1 = ELF file: one "section sha256 size" line per non-empty section + local file=$1 dir section + dir=$(mktemp -d) + for section in "${SECTIONS[@]}"; do + if objcopy -O binary --only-section="$section" "$file" "$dir/s" 2>/dev/null && [[ -s "$dir/s" ]]; then + echo "$section $(sha256sum <"$dir/s" | cut -c1-64) $(stat -c %s "$dir/s")" + fi + done + rm -rf "$dir" +} + +main() { + [[ $# -eq 2 ]] || { sed -n '2,11p' "$0"; exit 2; } + if diff <(sums "$1") <(sums "$2"); then + echo "sections identical: $1 == $2" + else + echo "sections DIFFER" >&2 + exit 1 + fi +} + +main "$@" diff --git a/scripts/dev/extract_tests.py b/scripts/dev/extract_tests.py new file mode 100644 index 00000000..c220755f --- /dev/null +++ b/scripts/dev/extract_tests.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Move a trailing inline `#[cfg(test)] mod tests { ... }` of a Rust module file into its own file (STRA-338). + +`foo.rs` gets `#[cfg(test)]` and `mod tests;`; the body moves, dedented, to `foo/tests.rs`, so the test ids +(`foo::tests::name`) and the production code stay exactly as they were. A file that was itself loaded through +`#[path]` looks for `tests.rs` beside it instead: the compiler reports those, add `#[path = "foo/tests.rs"]` by hand. +Crate roots (lib.rs, main.rs, bin/*, examples/*) are skipped. Relative `include_str!` / `include_bytes!` paths inside +the moved body get one more `../` (the file sits one directory deeper). The compiler is the judge of the rest. + +Usage: scripts/dev/extract_tests.py [--dry-run] FILE.rs... prints "moved|skipped " per file +""" +import argparse +import pathlib +import re +import sys + +OPEN = re.compile(r"^(?:pub(?:\(crate\))? )?mod tests \{$") +INCLUDE = re.compile(r'(include_(?:str|bytes)!\(\s*")(?=[^/])') +HEADER = "//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).\n\n" + + +def read(path): + with open(path, encoding="utf-8", newline="") as handle: + return handle.read().replace("\r\n", "\n") + + +def write(path, text): + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text) + + +def find_block(lines): + """Index of the one `#[cfg(test)]` line that opens a `mod tests {` at column 0, or None.""" + hits = [i for i, row in enumerate(lines[:-1]) if row == "#[cfg(test)]" and OPEN.match(lines[i + 1])] + return hits[0] if len(hits) == 1 else None + + +def block_end(lines, start): + """Index of the column-0 `}` that closes the tests module, or None when code follows it.""" + end = next((i for i in range(start + 2, len(lines)) if lines[i] == "}"), None) + return end if end is not None and not any(row.strip() for row in lines[end + 1:]) else None + + +def is_plain_module(path): + """False for crate roots, bins, examples and benches.""" + parts = path.parts + if path.name in ("lib.rs", "main.rs") or any(d in parts for d in ("bin", "examples", "benches")): + return False + return "tests" not in parts[:-1] + + +def dedent(rows): + return [row[4:] if row.startswith(" ") else row for row in rows] + + +def deepen_includes(text): + """One more `../` before every relative include path; the macro and its string may sit on different lines.""" + return INCLUDE.sub(lambda m: m.group(1) + "../", text) + + +def target_path(path): + """`foo.rs` -> `foo/tests.rs`; `foo/mod.rs` -> `foo/tests.rs`.""" + return path.with_name("tests.rs") if path.name == "mod.rs" else path.with_suffix("") / "tests.rs" + + +def split_text(text): + """(new source, tests file text), or a reason string when the file has no single trailing tests module.""" + lines = text.split("\n") + start = find_block(lines) + end = block_end(lines, start) if start is not None else None + if end is None: + return "no single trailing mod tests block that ends the file" + body = deepen_includes("\n".join(dedent(lines[start + 2:end]))) + declaration = ["#[cfg(test)]", "mod tests;", ""] + return "\n".join(lines[:start] + declaration), HEADER + body.rstrip("\n") + "\n" + + +def process(path, dry_run): + if not is_plain_module(path): + return "skipped", "crate root, bin, example or bench" + result = split_text(read(path)) + if isinstance(result, str): + return "skipped", result + destination = target_path(path) + if destination.exists(): + return "skipped", f"{destination} already exists" + if not dry_run: + destination.parent.mkdir(parents=True, exist_ok=True) + write(destination, result[1]) + write(path, result[0]) + return "moved", str(destination) + + +def main(argv): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("files", nargs="+") + args = parser.parse_args(argv) + for name in args.files: + verdict, detail = process(pathlib.Path(name), args.dry_run) + print(f"{verdict} {name} {detail}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:]))