From 056ab3d689b9570f3432ee7b93c85c8a922e6696 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 23 Nov 2026 21:19:11 +0100 Subject: [PATCH] Retire the oracles, generators and scripts that only worked against the vendored Strata tree (STRA-406) The vendored Strata tree engine/strata is removed for good (owner decision 2026-11-23): Leleka never builds or runs it, the vanilla benchmark builds from its own checkout, the comparison measurements are finished and the CUDA ports are frozen. Everything below compiled or read that tree, so it cannot run without it and is retired (the tree stays in git history, see third_party/strata/UPSTREAM.md). Checked-in fixtures, golden JSON, sealed PTX, seal plans and MANIFEST hashes are untouched and keep being replayed by the cargo tests. Drift guard - crates/experimental-ref/tests/literal_port.rs: include_str! of the Original .cu files compared with the checked-in experimental ports. Oracle generators and builders (they compile or extract from the Strata C++/Python sources; their outputs are the checked-in goldens) - crates/experimental-ref/oracle/gen_{cvec,kv,remote,stream}_golden.{cpp,sh}, gen_seal_additions.py and the cuda_runtime stub they used - crates/sampler-ref/oracle/build_oracle.sh, gen_fixtures.cpp, gen_sampling_keys.py, stub/ (run_port_host_tests.sh and the fixtures stay) - crates/serving-policy/oracle/ (build_oracle.sh, gen_{host,cvec,vision}_fixtures.cpp) - crates/context/tests/rope_plan_golden/gen_* (plan, rope, kv pool) - crates/engine-core/src/conversation/golden/gen*.{sh,cpp} and stub/ - crates/cuda-driver/oracle/gen_prefill_ring_trace.py and drivers/prefill_ring_trace.cpp (extracted prefill.cpp), check_cu_syntax.sh - crates/engine-qwen35-cuda/tests/stra161_reference/reference.py (fixtures.json and the Rust constants stay) - control-plane/tests/golden/gen_goldens.py, scripts/offline/ (Python differentials and golden generators against the Strata Python tools) Source-compiling CUDA oracles and builders - scripts/build-cuda-{projection-family,q5,q6,qsa}-oracle.sh with scripts/cuda-{projection-family,q5,q6,qsa}-oracle/ (include the Original .cu; sha256 pins of them) - scripts/build-original-verify-ptx.sh, scripts/q8/rebuild_quantizer_ptx.sh, scripts/decode-sm120/make_iq_prefix.py (needs engine/strata/include) - scripts/cuda-stubs/ (check-cu.py and literal_diff.py need the strata headers and the Original sources; the stub headers served only them) - tools/chain-probe/build.sh, tools/kernel-ab/{cpp,aa.sh,smoke.sh,time_smoke.sh} (the C++ comparator is built from the Strata CPU kernels; verify_manifest.py stays) - scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/ (compiles the upstream kernel from the tree) Engine builds and Python smokes that need the tree - scripts/build-cpu.sh, scripts/build-static-cuda.sh, scripts/check-keyless-gpu.sh, scripts/test-static-cuda-profile.py (CMake of engine/strata) - scripts/compare-real-tokenizer.py, scripts/smoke-mtp-pack.py (reads src/core/mtp.cpp and a bench manifest), scripts/prepare-keyless-routing.py and its test - scripts/smoke-native-pack.py became scripts/native-pack-fixture.py: the synthetic GGUF fixtures the four other smokes import stay, the iq_pack.py oracle comparison goes Gates and CI - scripts/check-local.sh: no live Python oracle differentials, no literal_port note, no check-cu, no build-cpu, no retired test scripts - .github/workflows/linux.yml: the keyless-cuda, static-cuda-package and hosted-cuda-package jobs (they built the engine from the tree) and their dispatch inputs, and the two oracle smoke steps; .github/workflows/port.yml: the Python oracle environment and the llama.cpp fetch of port-oracles (the sampler host shim still runs) - limits.json and scripts/check_limits_test.py exclude third_party/strata/ instead of engine/strata/ Documentation and comments: README.md names third_party/strata and the pin; deploy/README.md marks the retired build and smoke commands; comments in Rust, Python and Markdown that named engine/strata/... now name "Strata 41cf05a0, ..."; the gpu-bringup scratch-copy test no longer copies the removed include directories. Stale engine/strata paths in sealed .cu, .ptx, seal-plan and MANIFEST files are left as they are (hashes may depend on the bytes). --- .github/workflows/linux.yml | 311 --------- .github/workflows/port.yml | 38 +- PORT-GAPS-MODE17.md | 2 +- README.md | 8 +- control-plane/src/hardware_view.rs | 2 +- control-plane/src/mcp.rs | 2 +- control-plane/src/mtp_pack.rs | 4 +- control-plane/src/request_monitor.rs | 2 +- control-plane/src/server_api.rs | 2 +- .../tests/gguf_header_differential.rs | 2 +- control-plane/tests/golden/gen_goldens.py | 617 ---------------- control-plane/tests/http_surface.rs | 2 +- control-plane/tests/mcp_hub/main.rs | 2 +- control-plane/tests/mtp_fetch.rs | 2 +- crates/context/src/rope_scaling.rs | 2 +- crates/context/src/setup_policy.rs | 2 +- .../rope_plan_golden/gen_kv_pool_golden.cpp | 49 -- .../tests/rope_plan_golden/gen_plan_golden.py | 62 -- .../tests/rope_plan_golden/gen_plan_golden.sh | 7 - .../rope_plan_golden/gen_rope_golden.cpp | 196 ------ .../tests/rope_plan_golden/gen_rope_golden.sh | 19 - crates/cuda-driver/oracle/check_cu_syntax.sh | 7 - .../oracle/drivers/prefill_ring_trace.cpp | 463 ------------ .../oracle/gen_prefill_ring_trace.py | 321 --------- .../prefill/scalar/physical_layout.rs | 2 +- .../src/original_mtp_draft_vocab.rs | 2 +- crates/cuda-driver/src/original_mtp_rt.rs | 2 +- .../cuda-driver/src/original_verify/down.rs | 2 +- crates/cuda-driver/src/original_verify/moe.rs | 2 +- .../cuda-driver/src/original_verify/sm120.rs | 2 +- .../src/qwen_dispatch/gdn_fused_t1.rs | 2 +- .../src/qwen_dispatch/gdn_native_batch.rs | 2 +- .../src/qwen_dispatch/moe_prefill_batch.rs | 2 +- .../src/original_prefill_schedule.rs | 2 +- .../src/conversation/golden/gen.sh | 22 - .../conversation/golden/gen_cache_golden.cpp | 333 --------- .../golden/gen_manager_golden.cpp | 423 ----------- .../conversation/golden/gen_state_golden.cpp | 274 -------- .../conversation/golden/stub/cuda_runtime.h | 16 - .../tests/stra161_reference/reference.py | 114 --- .../oracle/gen_cvec_golden.cpp | 161 ----- .../oracle/gen_cvec_golden.sh | 19 - .../experimental-ref/oracle/gen_kv_golden.cpp | 166 ----- .../experimental-ref/oracle/gen_kv_golden.sh | 35 - .../oracle/gen_remote_golden.cpp | 200 ------ .../oracle/gen_remote_golden.sh | 31 - .../oracle/gen_seal_additions.py | 45 -- .../oracle/gen_stream_golden.cpp | 63 -- .../oracle/gen_stream_golden.sh | 24 - .../oracle/stub/cuda_runtime.h | 3 - crates/experimental-ref/src/lib.rs | 2 +- crates/experimental-ref/tests/kv_golden.rs | 2 +- crates/experimental-ref/tests/literal_port.rs | 346 --------- crates/gateway-domain/src/reasoning_budget.rs | 2 +- .../model-format/src/gguf/read_index_file.rs | 4 +- .../examples/kernel_ab/cmd_alternate.rs | 2 +- crates/offline-tools/src/lib.rs | 2 +- crates/offline-tools/tests/oracle.rs | 2 +- crates/sampler-ref/oracle/build_oracle.sh | 15 - crates/sampler-ref/oracle/gen_fixtures.cpp | 507 -------------- .../sampler-ref/oracle/gen_sampling_keys.py | 78 --- crates/sampler-ref/oracle/stub/cuda_runtime.h | 38 - crates/sampler-ref/src/chain.rs | 2 +- crates/sampler-ref/src/coupled.rs | 4 +- crates/sampler-ref/src/lib.rs | 2 +- crates/sampler-ref/src/params.rs | 4 +- crates/sampler-ref/src/philox.rs | 2 +- crates/serving-policy/oracle/build_oracle.sh | 36 - .../oracle/gen_cvec_fixtures.cpp | 206 ------ .../oracle/gen_host_fixtures.cpp | 113 --- .../oracle/gen_vision_fixtures.cpp | 145 ---- crates/serving-policy/src/lib.rs | 2 +- crates/tokenizer/tests/oracle_differential.rs | 2 +- deploy/README.md | 17 +- engine/upstream.md | 20 +- limits.json | 2 +- scripts/build-cpu.sh | 29 - .../build-cuda-projection-family-oracle.sh | 25 - scripts/build-cuda-q5-oracle.sh | 22 - scripts/build-cuda-q6-oracle.sh | 22 - scripts/build-cuda-qsa-oracle.sh | 19 - scripts/build-original-verify-ptx.sh | 184 ----- scripts/build-static-cuda.sh | 87 --- scripts/check-keyless-gpu.sh | 20 - scripts/check-local.sh | 39 +- scripts/check_limits_test.py | 8 +- scripts/compare-real-tokenizer.py | 64 -- .../native_fixture.cu | 60 -- scripts/cuda-q5-oracle/README.md | 77 -- scripts/cuda-q5-oracle/native_fixture.cu | 46 -- scripts/cuda-q6-oracle/native_fixture.cu | 46 -- scripts/cuda-qsa-oracle/README.md | 58 -- scripts/cuda-qsa-oracle/host_theta.cpp | 6 - scripts/cuda-qsa-oracle/main.cu | 173 ----- scripts/cuda-qsa-oracle/oracle_attention.cu | 10 - scripts/cuda-qsa-oracle/oracle_index.cu | 5 - scripts/cuda-qsa-oracle/oracle_native.cu | 8 - scripts/cuda-qsa-oracle/oracle_rope.cu | 4 - scripts/cuda-qsa-oracle/oracle_select.cu | 8 - scripts/cuda-qsa-oracle/source.sha256 | 65 -- scripts/cuda-qsa-oracle/theta_probe.cu | 24 - scripts/cuda-stubs/check-cu.py | 194 ----- scripts/cuda-stubs/cooperative_groups.h | 25 - scripts/cuda-stubs/cublas_v2.h | 19 - scripts/cuda-stubs/cuda.h | 2 - scripts/cuda-stubs/cuda_bf16.h | 54 -- scripts/cuda-stubs/cuda_fp16.h | 105 --- scripts/cuda-stubs/cuda_fp4.h | 20 - scripts/cuda-stubs/cuda_fp8.h | 12 - scripts/cuda-stubs/cuda_runtime.h | 2 - scripts/cuda-stubs/cuda_runtime_api.h | 2 - scripts/cuda-stubs/cuda_stub.h | 609 ---------------- scripts/cuda-stubs/device_launch_parameters.h | 2 - scripts/cuda-stubs/literal_diff.py | 205 ------ scripts/cuda-stubs/mma.h | 20 - scripts/cuda-stubs/vector_types.h | 2 - scripts/decode-sm120/make_iq_prefix.py | 23 - scripts/dev/rename_strata_names.py | 4 +- .../build.sh | 25 - .../compare_outputs.inc | 115 --- .../microbench.cu | 356 ---------- .../ours-shim/strata/kernels/fused_gr.hpp | 24 - .../summarize.py | 87 --- .../upstream_down_launch.inc | 115 --- scripts/gpu-bringup/bringup_lib.py | 3 +- scripts/gpu-bringup/sm86_assets.py | 2 +- scripts/gpu-bringup/tests/test_gpu_bringup.py | 2 +- scripts/native-pack-fixture.py | 58 ++ scripts/offline/diff_chat_template.py | 194 ----- scripts/offline/diff_dequant.py | 115 --- scripts/offline/diff_gguf_header.py | 232 ------ scripts/offline/diff_mtp_fetch.py | 186 ----- scripts/offline/diff_native_pack.py | 512 -------------- scripts/offline/diff_tokenizer.py | 276 -------- scripts/offline/diff_tools.py | 302 -------- scripts/offline/gen_goldens.py | 469 ------------- scripts/offline/ggufgen.py | 53 -- scripts/prepare-keyless-routing.py | 185 ----- scripts/q8/rebuild_quantizer_ptx.sh | 39 -- scripts/smoke-controller-deployment.py | 2 +- scripts/smoke-mtp-pack.py | 181 ----- scripts/smoke-native-bootstrap.py | 2 +- scripts/smoke-native-pack.py | 167 ----- scripts/smoke-runtime-profile.py | 2 +- scripts/test-keyless-routing.py | 74 -- scripts/test-static-cuda-profile.py | 120 ---- tools/chain-probe/build.sh | 25 - tools/kernel-ab/README.md | 18 +- tools/kernel-ab/aa.sh | 144 ---- tools/kernel-ab/cpp/Makefile | 177 ----- tools/kernel-ab/cpp/avxvnni_probe.cpp | 10 - tools/kernel-ab/cpp/kab.cpp | 660 ------------------ tools/kernel-ab/cpp/kab_time.cpp | 489 ------------- tools/kernel-ab/smoke.sh | 85 --- tools/kernel-ab/time_smoke.sh | 63 -- 155 files changed, 156 insertions(+), 13452 deletions(-) delete mode 100644 control-plane/tests/golden/gen_goldens.py delete mode 100644 crates/context/tests/rope_plan_golden/gen_kv_pool_golden.cpp delete mode 100644 crates/context/tests/rope_plan_golden/gen_plan_golden.py delete mode 100755 crates/context/tests/rope_plan_golden/gen_plan_golden.sh delete mode 100644 crates/context/tests/rope_plan_golden/gen_rope_golden.cpp delete mode 100755 crates/context/tests/rope_plan_golden/gen_rope_golden.sh delete mode 100755 crates/cuda-driver/oracle/check_cu_syntax.sh delete mode 100644 crates/cuda-driver/oracle/drivers/prefill_ring_trace.cpp delete mode 100644 crates/cuda-driver/oracle/gen_prefill_ring_trace.py delete mode 100755 crates/engine-core/src/conversation/golden/gen.sh delete mode 100644 crates/engine-core/src/conversation/golden/gen_cache_golden.cpp delete mode 100644 crates/engine-core/src/conversation/golden/gen_manager_golden.cpp delete mode 100644 crates/engine-core/src/conversation/golden/gen_state_golden.cpp delete mode 100644 crates/engine-core/src/conversation/golden/stub/cuda_runtime.h delete mode 100644 crates/engine-qwen35-cuda/tests/stra161_reference/reference.py delete mode 100644 crates/experimental-ref/oracle/gen_cvec_golden.cpp delete mode 100755 crates/experimental-ref/oracle/gen_cvec_golden.sh delete mode 100644 crates/experimental-ref/oracle/gen_kv_golden.cpp delete mode 100755 crates/experimental-ref/oracle/gen_kv_golden.sh delete mode 100644 crates/experimental-ref/oracle/gen_remote_golden.cpp delete mode 100755 crates/experimental-ref/oracle/gen_remote_golden.sh delete mode 100644 crates/experimental-ref/oracle/gen_seal_additions.py delete mode 100644 crates/experimental-ref/oracle/gen_stream_golden.cpp delete mode 100755 crates/experimental-ref/oracle/gen_stream_golden.sh delete mode 100644 crates/experimental-ref/oracle/stub/cuda_runtime.h delete mode 100644 crates/experimental-ref/tests/literal_port.rs delete mode 100755 crates/sampler-ref/oracle/build_oracle.sh delete mode 100644 crates/sampler-ref/oracle/gen_fixtures.cpp delete mode 100644 crates/sampler-ref/oracle/gen_sampling_keys.py delete mode 100644 crates/sampler-ref/oracle/stub/cuda_runtime.h delete mode 100755 crates/serving-policy/oracle/build_oracle.sh delete mode 100644 crates/serving-policy/oracle/gen_cvec_fixtures.cpp delete mode 100644 crates/serving-policy/oracle/gen_host_fixtures.cpp delete mode 100644 crates/serving-policy/oracle/gen_vision_fixtures.cpp delete mode 100755 scripts/build-cpu.sh delete mode 100755 scripts/build-cuda-projection-family-oracle.sh delete mode 100755 scripts/build-cuda-q5-oracle.sh delete mode 100755 scripts/build-cuda-q6-oracle.sh delete mode 100755 scripts/build-cuda-qsa-oracle.sh delete mode 100644 scripts/build-original-verify-ptx.sh delete mode 100755 scripts/build-static-cuda.sh delete mode 100755 scripts/check-keyless-gpu.sh delete mode 100644 scripts/compare-real-tokenizer.py delete mode 100644 scripts/cuda-projection-family-oracle/native_fixture.cu delete mode 100644 scripts/cuda-q5-oracle/README.md delete mode 100644 scripts/cuda-q5-oracle/native_fixture.cu delete mode 100644 scripts/cuda-q6-oracle/native_fixture.cu delete mode 100644 scripts/cuda-qsa-oracle/README.md delete mode 100644 scripts/cuda-qsa-oracle/host_theta.cpp delete mode 100644 scripts/cuda-qsa-oracle/main.cu delete mode 100644 scripts/cuda-qsa-oracle/oracle_attention.cu delete mode 100644 scripts/cuda-qsa-oracle/oracle_index.cu delete mode 100644 scripts/cuda-qsa-oracle/oracle_native.cu delete mode 100644 scripts/cuda-qsa-oracle/oracle_rope.cu delete mode 100644 scripts/cuda-qsa-oracle/oracle_select.cu delete mode 100644 scripts/cuda-qsa-oracle/source.sha256 delete mode 100644 scripts/cuda-qsa-oracle/theta_probe.cu delete mode 100755 scripts/cuda-stubs/check-cu.py delete mode 100644 scripts/cuda-stubs/cooperative_groups.h delete mode 100644 scripts/cuda-stubs/cublas_v2.h delete mode 100644 scripts/cuda-stubs/cuda.h delete mode 100644 scripts/cuda-stubs/cuda_bf16.h delete mode 100644 scripts/cuda-stubs/cuda_fp16.h delete mode 100644 scripts/cuda-stubs/cuda_fp4.h delete mode 100644 scripts/cuda-stubs/cuda_fp8.h delete mode 100644 scripts/cuda-stubs/cuda_runtime.h delete mode 100644 scripts/cuda-stubs/cuda_runtime_api.h delete mode 100644 scripts/cuda-stubs/cuda_stub.h delete mode 100644 scripts/cuda-stubs/device_launch_parameters.h delete mode 100755 scripts/cuda-stubs/literal_diff.py delete mode 100644 scripts/cuda-stubs/mma.h delete mode 100644 scripts/cuda-stubs/vector_types.h delete mode 100644 scripts/decode-sm120/make_iq_prefix.py delete mode 100755 scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/build.sh delete mode 100644 scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/compare_outputs.inc delete mode 100644 scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/microbench.cu delete mode 100644 scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/ours-shim/strata/kernels/fused_gr.hpp delete mode 100644 scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/summarize.py delete mode 100644 scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/upstream_down_launch.inc create mode 100644 scripts/native-pack-fixture.py delete mode 100644 scripts/offline/diff_chat_template.py delete mode 100644 scripts/offline/diff_dequant.py delete mode 100644 scripts/offline/diff_gguf_header.py delete mode 100644 scripts/offline/diff_mtp_fetch.py delete mode 100644 scripts/offline/diff_native_pack.py delete mode 100644 scripts/offline/diff_tokenizer.py delete mode 100644 scripts/offline/diff_tools.py delete mode 100644 scripts/offline/gen_goldens.py delete mode 100644 scripts/offline/ggufgen.py delete mode 100644 scripts/prepare-keyless-routing.py delete mode 100644 scripts/q8/rebuild_quantizer_ptx.sh delete mode 100644 scripts/smoke-mtp-pack.py delete mode 100644 scripts/smoke-native-pack.py delete mode 100644 scripts/test-keyless-routing.py delete mode 100644 scripts/test-static-cuda-profile.py delete mode 100644 tools/chain-probe/build.sh delete mode 100755 tools/kernel-ab/aa.sh delete mode 100644 tools/kernel-ab/cpp/Makefile delete mode 100644 tools/kernel-ab/cpp/avxvnni_probe.cpp delete mode 100644 tools/kernel-ab/cpp/kab.cpp delete mode 100644 tools/kernel-ab/cpp/kab_time.cpp delete mode 100755 tools/kernel-ab/smoke.sh delete mode 100755 tools/kernel-ab/time_smoke.sh diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 8113053b..9fea4adb 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -6,23 +6,6 @@ on: tags: ['v*'] pull_request: workflow_dispatch: - inputs: - keyless_gpu: - description: Run synthetic Keyless CUDA tests on the private GPU runner - type: boolean - default: false - hosted_cuda_package: - description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact) - type: boolean - default: false - hosted_cuda_ple: - description: Build the hosted package with experimental KAR PLE compiled (serving remains explicit and off by default) - type: boolean - default: false - static_cuda_package: - description: Build and audit static CUDA toolkit linkage on the private Linux runner (no inference) - type: boolean - default: false permissions: contents: read @@ -41,296 +24,6 @@ jobs: - name: GPU-hidden fixed PTX assembly run: scripts/test-cuda-fixed-ptx.sh - keyless-cuda-gate: - if: gitea.event_name == 'workflow_dispatch' - runs-on: ubuntu-latest - outputs: - enabled: ${{ steps.select.outputs.enabled }} - steps: - - id: select - env: - KEYLESS_GPU: ${{ gitea.event.inputs.keyless_gpu }} - run: | - case "${KEYLESS_GPU:-false}" in - true) echo 'enabled=true' >> "$GITHUB_OUTPUT" ;; - false|'') echo 'enabled=false' >> "$GITHUB_OUTPUT" ;; - *) echo 'keyless_gpu must be a boolean input' >&2; exit 2 ;; - esac - - keyless-cuda: - needs: [verify, keyless-cuda-gate] - if: needs.keyless-cuda-gate.outputs.enabled == 'true' - runs-on: [self-hosted, linux, x64, strata-gpu] - steps: - - uses: actions/checkout@v4 - - name: Query-routing, streaming and snapshot GPU tests - run: scripts/check-keyless-gpu.sh - - name: Bounded KAR expert component GPU tests - run: scripts/check-kar-expert-gpu.sh - - static-cuda-package: - permissions: - contents: read - releases: write - if: gitea.event_name == 'workflow_dispatch' && gitea.event.inputs.static_cuda_package == 'true' && gitea.event.repository.private - needs: verify - runs-on: [self-hosted, linux, x64, strata-gpu] - steps: - - uses: actions/checkout@v4 - - name: Build and audit engine without GPU inference - env: - CUDA_VISIBLE_DEVICES: '' - BUILD_JOBS: '2' - STRATA_BUILD_DIR: ${{ runner.temp }}/strata-static-cuda-${{ github.run_id }} - run: nice -n 10 scripts/build-static-cuda.sh - - name: Install pinned Rust and musl target - run: | - scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl - command -v musl-gcc - - name: Assemble combined private package - run: | - engine="${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/strata" - python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \ - --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ - --build-features "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/BUILD-FEATURES.json" \ - --cargo-target-dir "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" \ - --output "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - - name: Build compatible private runtime image without GPU inference - run: | - package="${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - python3 scripts/build-runtime-image.py --package "$package" \ - --receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \ - > "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json")" - docker save --output "$package/runtime-image.tar" "$image" - cp "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" "$package/IMAGE-PROVENANCE.json" - (cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json > IMAGE-SHA256SUMS) - - name: Publish exact six-file static CUDA preview through Gitea - env: - GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} - run: | - python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \ - --repository "$GITHUB_REPOSITORY" --profile static-cuda \ - --tag "static-cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \ - --title "Static CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \ - --notes 'Private build-only six-file preview. No hosted compiler/license receipt, GPU or model qualification.' \ - --directory "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - - name: Remove uploaded package copy - if: always() - run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - - name: Remove owned runtime image - if: always() - run: | - receipt="${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" - if test -s "$receipt"; then - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")" - docker image rm "$image" - rm "$receipt" - fi - - name: Remove private build intermediates - if: always() - run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" - - hosted-cuda-package: - permissions: - contents: read - releases: write - if: gitea.event_name == 'workflow_dispatch' && (gitea.event.inputs.hosted_cuda_package == 'true' || gitea.event.inputs.hosted_cuda_ple == 'true') && gitea.event.repository.private - needs: verify - runs-on: ubuntu-latest - timeout-minutes: 150 - env: - CUDA_VISIBLE_DEVICES: '' - NVIDIA_VISIBLE_DEVICES: void - BUILD_JOBS: '1' - CARGO_BUILD_JOBS: '2' - CUDA_ARCHITECTURES: '120' - STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }} - steps: - - uses: actions/checkout@v4 - - name: Install compatible host tools (no drivers) - run: | - echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" - echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" - echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates musl-tools binutils docker.io python3 time - - name: Actual runtime-image loader boundary without GPU - run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-package-loader-container.py - - name: Assemble pinned build-only CUDA components - run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - - name: Build pinned GPU-hidden compiler image - env: - CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b - CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }} - run: | - context="$RUNNER_TEMP/strata-cuda-builder-context" - mkdir -p "$context" - cp deploy/Dockerfile.cuda-builder "$context/Dockerfile" - cp /etc/ssl/certs/ca-certificates.crt "$context/runner-ca-bundle.crt" - docker build --platform linux/amd64 --build-arg "BUILDER_BASE=$CUDA_BUILDER_BASE" \ - --tag "$CUDA_BUILDER_IMAGE" "$context" - docker image inspect --format '{{.Id}}' "$CUDA_BUILDER_IMAGE" > "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID" - - name: Record actual toolchain - env: - CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }} - CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b - run: | - "$CUDACXX" --version - docker run --rm --platform linux/amd64 --network none "$CUDA_BUILDER_IMAGE" g++-13 --version - df -h "$RUNNER_TEMP" - free -h - python3 - <<'PYTOOL' - import json, os, platform, subprocess - from pathlib import Path - info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text()) - packages=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none', - os.environ['CUDA_BUILDER_IMAGE'],'dpkg-query','-W','-f=${binary:Package}=${Version}'+chr(10), - 'binutils','ca-certificates','cmake','gcc-13','g++-13','git','make','python3'],text=True).splitlines() - gcc=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none', - os.environ['CUDA_BUILDER_IMAGE'],'g++-13','--version'],text=True) - info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(), - builder_base=os.environ['CUDA_BUILDER_BASE'], - builder_image_id=Path(os.environ['RUNNER_TEMP'],'CUDA-BUILDER-IMAGE-ID').read_text().strip(), - builder_packages=packages, - gcc=gcc, - nvcc=subprocess.check_output([os.environ['CUDACXX'],'--version'],text=True), - cuda_architectures=os.environ['CUDA_ARCHITECTURES'], driver_tested=False, model_tested=False) - (Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json').write_text(json.dumps(info,indent=2)+'\n') - PYTOOL - - name: Build actual static CUDA engine and audit without GPU - env: - CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }} - STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }} - run: | - mkdir -p "$STRATA_BUILD_DIR" - container="leleka-cuda-build-${GITHUB_RUN_ID}" - volume="leleka-cuda-build-${GITHUB_RUN_ID}" - source_archive="$RUNNER_TEMP/strata-cuda-source.tar" - cleanup() { - docker rm -f "$container" >/dev/null 2>&1 || true - docker volume rm "$volume" >/dev/null 2>&1 || true - rm -f -- "$source_archive" - } - trap cleanup EXIT - git -C "$GITHUB_WORKSPACE" archive --format=tar "$GITHUB_SHA" > "$source_archive" - docker volume create "$volume" >/dev/null - docker create --name "$container" --platform linux/amd64 --network bridge --read-only \ - --cap-drop ALL --security-opt no-new-privileges \ - --tmpfs /tmp:rw,nosuid,size=2g --mount "type=volume,src=$volume,dst=/work" \ - -e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \ - "$CUDA_BUILDER_IMAGE" /bin/bash -euc 'sleep infinity' >/dev/null - docker start "$container" >/dev/null - docker exec "$container" mkdir -p /work/workspace /work/toolkit /work/build - docker exec "$container" chmod 0777 /work/build - # Stage tracked source only. docker cp streams the archive from the - # runner container; bind mounts cannot use its path on the daemon host. - docker cp "$source_archive" "$container:/work/source.tar" - docker exec "$container" tar -xf /work/source.tar -C /work/workspace - docker exec "$container" rm /work/source.tar - docker cp "$CUDAToolkit_ROOT/." "$container:/work/toolkit/" - docker exec --user "$(id -u):$(id -g)" \ - -e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \ - -e CUDACXX=/work/toolkit/bin/nvcc -e CUDAToolkit_ROOT=/work/toolkit \ - -e CC=/usr/bin/gcc-13 -e CXX=/usr/bin/g++-13 -e CUDAHOSTCXX=/usr/bin/g++-13 \ - -e BUILD_JOBS="$BUILD_JOBS" -e CUDA_ARCHITECTURES="$CUDA_ARCHITECTURES" \ - -e STRATA_KAR_PLE="$STRATA_KAR_PLE" -e STRATA_BUILD_DIR=/work/build \ - -e SOURCE_REVISION="$GITHUB_SHA" \ - "$container" /bin/bash -euo pipefail -c ' - if compgen -G "/dev/nvidia*" >/dev/null; then - echo "NVIDIA devices unexpectedly visible in build container" >&2 - exit 1 - fi - cd /work/workspace - scripts/build-static-cuda.sh - ' - docker cp "$container:/work/build/strata" "$STRATA_BUILD_DIR/strata" - docker cp "$container:/work/build/BUILD-FEATURES.json" "$STRATA_BUILD_DIR/BUILD-FEATURES.json" - - name: Bind compile capability to CUDA toolchain provenance - run: | - python3 - <<'PYFEATURES' - import hashlib, json, os - from pathlib import Path - features_path=Path(os.environ['STRATA_BUILD_DIR'])/'BUILD-FEATURES.json' - features=json.loads(features_path.read_text()) - toolchain_path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json' - info=json.loads(toolchain_path.read_text()) - info['build_features']=features['features'] - info['build_features_sha256']=hashlib.sha256(features_path.read_bytes()).hexdigest() - toolchain_path.write_text(json.dumps(info,indent=2)+'\n') - PYFEATURES - - name: Install pinned Rust and musl target - run: | - scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl - - name: Assemble actual combined executable and runtime image - run: | - # Keep resource evidence even if the hosted runner terminates this job. - (while sleep 20; do - date -u - free -m - df -m "$RUNNER_TEMP" - test ! -r /sys/fs/cgroup/memory.events || cat /sys/fs/cgroup/memory.events - done) & - resource_sampler=$! - trap 'kill "$resource_sampler" 2>/dev/null || true; wait "$resource_sampler" 2>/dev/null || true' EXIT - engine="$STRATA_BUILD_DIR/strata" - package="$RUNNER_TEMP/strata-hosted-cuda-package" - /usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \ - --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ - --build-features "$STRATA_BUILD_DIR/BUILD-FEATURES.json" \ - --cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package" - python3 scripts/build-runtime-image.py --package "$package" \ - --receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \ - > "$RUNNER_TEMP/strata-hosted-image.json" - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$RUNNER_TEMP/strata-hosted-image.json")" - docker save --output "$package/runtime-image.tar" "$image" - cp "$RUNNER_TEMP/strata-hosted-image.json" "$package/IMAGE-PROVENANCE.json" - python3 - <<'PYBIND' - import hashlib, json, os - from pathlib import Path - package=Path(os.environ['RUNNER_TEMP'])/'strata-hosted-cuda-package' - receipt=json.loads((package/'PROVENANCE.json').read_text()) - image=json.loads((package/'IMAGE-PROVENANCE.json').read_text()) - path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json' - toolchain=json.loads(path.read_text()) - with (package/'runtime-image.tar').open('rb') as archive: - archive_sha=hashlib.file_digest(archive, 'sha256').hexdigest() - toolchain['docker_builder']={ - 'source_commit': os.environ['GITHUB_SHA'], - 'image_id': toolchain['builder_image_id'], - 'engine_sha256': receipt['engine']['sha256'], - 'build_features_sha256': receipt['build_features_sha256'], - 'runtime_image_id': image['image'], - 'runtime_archive_sha256': archive_sha} - path.write_text(json.dumps(toolchain,indent=2)+'\n') - PYBIND - cp "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$package/CUDA-TOOLCHAIN.json" - tar -C "$CUDAToolkit_ROOT" -cf "$package/CUDA-LICENSES.tar" licenses - (cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json CUDA-TOOLCHAIN.json CUDA-LICENSES.tar > IMAGE-SHA256SUMS) - - name: Publish exact eight-file hosted CUDA preview through Gitea - env: - GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} - run: | - python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \ - --repository "$GITHUB_REPOSITORY" --profile cuda \ - --tag "cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \ - --title "Hosted CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \ - --notes 'Private build-only preview. GPU-hidden loader identity and help passed; no GPU/model inference or performance qualification.' \ - --directory "$RUNNER_TEMP/strata-hosted-cuda-package" - - name: Remove uploaded package copy - if: always() - run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package" - - name: Remove owned intermediate image and build files - if: always() - run: | - receipt="$RUNNER_TEMP/strata-hosted-image.json" - if test -s "$receipt"; then - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")" - docker image rm "$image" - fi - rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-package-build" - docker image rm "leleka-cuda-builder:${GITHUB_RUN_ID}" 2>/dev/null || true - rm -rf -- "$RUNNER_TEMP/strata-cuda-builder-context" "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID" - linux-static-cli: permissions: contents: read @@ -387,12 +80,8 @@ jobs: run: python3 scripts/smoke-cuda-memory.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - name: Atomic pinned assets before native serving run: python3 scripts/smoke-asset-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - - name: Native GGUF pack preparation against upstream oracle - run: python3 scripts/smoke-native-pack.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - name: Native fetch prepare serve and verified offline reuse run: python3 scripts/smoke-native-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - - name: Pinned MTP structural preflight and native bootstrap - run: python3 scripts/smoke-mtp-pack.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - name: Native runtime profile metadata admission run: python3 scripts/smoke-runtime-profile.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - name: Native systemd unit syntax and path safety diff --git a/.github/workflows/port.yml b/.github/workflows/port.yml index 278bf5b2..2fc73abc 100644 --- a/.github/workflows/port.yml +++ b/.github/workflows/port.yml @@ -4,7 +4,8 @@ name: Rust port # weights or tokens. The existing "Linux" workflow is unchanged; the jobs below add the port-specific gates: # port-fast fmt, Clippy and tests on the host-buildable crates (scripts/check-local.sh --fast) # port-typecheck Linux-only crates (cuda-driver with the cuda-driver feature, leleka-runtime) type-checked, not run -# port-oracles CPU oracle differentials against the unmodified Python tools (needs pip and a pinned llama.cpp gguf-py) +# port-oracles the sampler host shim over the checked-in oracle fixtures (the live Python differentials and the oracle +# generators needed the vendored Strata tree, removed in STRA-406) # port-linux-tests Docker Linux harness (scripts/linux-tests/run.sh); optional until branch claude/port-linux-tests merges # Type-checking is not execution: nothing here runs the Linux-gated tests or any GPU smoke. @@ -54,45 +55,18 @@ jobs: cargo clippy --locked --target x86_64-unknown-linux-gnu --no-deps -p leleka-cuda-model -p leleka-cuda-driver --features cuda-driver -p leleka-engine-qwen35-cuda -p leleka-runtime --all-targets -- -D warnings port-oracles: - # CPU oracle differentials: the Rust side against the UNMODIFIED Python tools and the - # sampler host shim. Optional until it has run green on the hosted runner; the committed goldens are replayed by - # port-fast regardless. + # The sampler host shim over the checked-in oracle fixtures. Optional until it has run green on the hosted runner; + # the committed goldens are replayed by port-fast regardless. runs-on: ubuntu-latest continue-on-error: true steps: - uses: actions/checkout@v4 - name: Install build tools - run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential cmake git python3 python3-venv + run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential cmake git python3 - name: Install pinned Rust run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy - - name: Oracle Python environment (no model data) - # numpy 2.5.x needs Python >= 3.12 and the runner's distro Python is older, so the numpy pin follows the - # interpreter exactly as engine/strata/requirements.txt does (2.5.4 on 3.12+, 2.4.6 on 3.11, 2.2.6 below). - # The oracle differentials compare against recorded goldens with tolerances, not against a numpy build. - run: | - python3 -m venv "$RUNNER_TEMP/oracle-venv" - cat > "$RUNNER_TEMP/oracle-requirements.txt" <<'EOF' - numpy==2.5.4; python_version >= "3.12" - numpy==2.4.6; python_version == "3.11" - numpy==2.2.6; python_version < "3.11" - PyYAML==6.0.3 - tqdm==4.70.1 - Jinja2==3.1.6 - regex==2026.9.10 - EOF - "$RUNNER_TEMP/oracle-venv/bin/python" --version - "$RUNNER_TEMP/oracle-venv/bin/pip" install --disable-pip-version-check -r "$RUNNER_TEMP/oracle-requirements.txt" - - name: Fetch the pinned llama.cpp gguf-py - run: | - commit="$(sed -n 's/^LLAMA_CPP_COMMIT = "\(.*\)"$/\1/p' engine/strata/setup.py)" - test -n "$commit" - git init -q "$RUNNER_TEMP/llama.cpp" - git -C "$RUNNER_TEMP/llama.cpp" fetch --depth 1 https://github.com/ggml-org/llama.cpp "$commit" - git -C "$RUNNER_TEMP/llama.cpp" checkout -q FETCH_HEAD - - name: Port oracles (sampler shim and live Python differentials) + - name: Port oracles (sampler host shim over the checked-in fixtures) env: - OFFLINE_ORACLE_PYTHON: ${{ runner.temp }}/oracle-venv/bin/python - STRATA_GGUF_PY: ${{ runner.temp }}/llama.cpp/gguf-py SKIP_LINUX_TYPECHECK: '1' run: scripts/check-local.sh --port diff --git a/PORT-GAPS-MODE17.md b/PORT-GAPS-MODE17.md index 3a7c141e..749294f9 100644 --- a/PORT-GAPS-MODE17.md +++ b/PORT-GAPS-MODE17.md @@ -2,7 +2,7 @@ Read-only snapshot, 2026-10-12. Audit artifact only; no builds, tests, GPU, Strata, model or daemon execution. Paths below are relative to this source-port -tree or to the imported `engine/strata/`. Root integration remains mutable. +tree or to the Strata tree that was imported (removed, see `third_party/strata/UPSTREAM.md`). Root integration remains mutable. This is a bounded core-path ledger, not a whole-project completion certificate. ## Actionable remaining boundaries diff --git a/README.md b/README.md index 344ca216..cba5eba0 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ Leleka is a Rust/CUDA inference runtime for coding agents. Release **0.1** serves one model, **Qwen3.8-Flash-Next IQ3_S** (KAR level-2 PLE, MTP speculative decode), on **one RTX 5090 (32 GB)** at **262,144 tokens of context**, to Codex CLI and other clients over the Responses, Chat Completions and Messages APIs. -It is a Rust/CUDA port of the Original mode17 serve path of [Strata](https://github.com/Niko1221/Strata) (reference copy in `engine/strata/`, pinned at -upstream `41cf05a0`, see `third_party/strata/UPSTREAM.md`). Serving needs no Python and no CUDA toolkit on the host. +It is a Rust/CUDA port of the Original mode17 serve path of [Strata](https://github.com/Niko1221/Strata) (pinned at upstream `41cf05a0`; the vendored copy was removed, see +`third_party/strata/UPSTREAM.md`). Serving needs no Python and no CUDA toolkit on the host. **Status of 0.1.** It runs real Codex sessions to completion and decodes about 155 tok/s on the 245k-token benchmark of the 5090 server (section "Numbers"). It is **not a formally quality-gated profile**, only the RTX 5090 is supported, and the limits below are real. Release notes: `spec node release/RELEASE-NOTES-5090-v0.1.md`; @@ -76,7 +76,7 @@ What the service is doing, and why a request was slow or failed, is in its logs; - `crates/` — the runtime: `engine-qwen35-cuda` (the engine; `leleka-runtime` is its facade), `engine-core` (pure engine domain), `cuda-driver` (CUDA Driver API, sealed PTX), `leleka-memory` (memory governor), `obs` (logging), `deploy` (the `leleka` binary), model-format, tokenizer, sampler and CPU kernels. - `control-plane/`, `desktop-core/` — the HTTP/Responses gateway (`leleka-api`) and the engine/daemon processes. -- `engine/strata/` — the pinned upstream Strata, the reference (unmodified by Leleka). +- `third_party/strata/` — the Strata MIT licence texts, the pinned chat template and golden, and `UPSTREAM.md` (pin `41cf05a0`, local patches, where the removed vendored tree is in history). The Strata source tree itself is not in the repository. - `deploy/`, `scripts/` — profiles, service templates, release packager (`scripts/release/`), test and measurement tooling (Python is allowed there, never in serving). - `PROJECT_CHARTER.md`, the LeaseVibe spec (imported repository documentation) — requirements, provenance, decisions, gates and measurements. Architecture: spec node `architecture/hexagonal.md`. @@ -92,4 +92,4 @@ scripts/release/package-5090.sh check # the release gates; `package` buil ## Licence -MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `spec node release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`engine/strata/LICENSE`). +MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `spec node release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`third_party/strata/LICENSE`, printed by `leleka engine license`). diff --git a/control-plane/src/hardware_view.rs b/control-plane/src/hardware_view.rs index c2f04dc2..8405408f 100644 --- a/control-plane/src/hardware_view.rs +++ b/control-plane/src/hardware_view.rs @@ -1,5 +1,5 @@ //! The hardware half of `GET /metrics`, in the member names of the Python service's Monitor (`hardware`, -//! `hardware_static`, `history`; `engine/strata/serve/telemetry.py`), built from the engine's telemetry document +//! `hardware_static`, `history`; `Strata 41cf05a0, serve/telemetry.py`), built from the engine's telemetry document //! (`leleka-memory`'s `telemetry.rs`, copied here by the worker on its health tick). //! //! Units follow the Python service: memory in bytes, utilisation and CPU in percent, power in watts, temperature in diff --git a/control-plane/src/mcp.rs b/control-plane/src/mcp.rs index 6e18f304..aded0adc 100644 --- a/control-plane/src/mcp.rs +++ b/control-plane/src/mcp.rs @@ -1,5 +1,5 @@ //! MCP (Model Context Protocol) hub: tools from MCP servers, namespaced `__`, called -//! on behalf of an agent. Port of `engine/strata/serve/mcp.py`. +//! on behalf of an agent. Port of `Strata 41cf05a0, serve/mcp.py`. //! //! The operator lists servers in the run config (`mcp_servers`, or Claude Desktop's `mcpServers` //! block as is, or a separate `mcp_config_file`): a program Strata starts (`command`, `args`, diff --git a/control-plane/src/mtp_pack.rs b/control-plane/src/mtp_pack.rs index fcd3cfbe..c5d85cf2 100644 --- a/control-plane/src/mtp_pack.rs +++ b/control-plane/src/mtp_pack.rs @@ -8,10 +8,10 @@ use std::{ }; const INDEX_LIMIT: u64 = 64 * 1024; -// engine/strata/include/strata/kernels/cpu/expert.hpp: NE * BLOB. +// Strata 41cf05a0, include/strata/kernels/cpu/expert.hpp: NE * BLOB. const EXPERT_BYTES: u64 = 512 * 1_382_400; // Shapes from pinned upstream mtp-manifest.json, normalized by tools/mtp_rt.py. -// Consumer: engine/strata/src/core/mtp.cpp (N=2560, HC=4, NH=24, HD=256). +// Consumer: Strata 41cf05a0, src/core/mtp.cpp (N=2560, HC=4, NH=24, HD=256). const REQUIRED: &[(&str, &str, u64, u64)] = &[ ("fc_embedding.weight", "q8_0", 2560, 2560), ("fc_hidden.weight", "q8_0", 2560, 2560), diff --git a/control-plane/src/request_monitor.rs b/control-plane/src/request_monitor.rs index 0e1e2c16..5fd68621 100644 --- a/control-plane/src/request_monitor.rs +++ b/control-plane/src/request_monitor.rs @@ -1,5 +1,5 @@ //! The API request monitor: `GET /api/requests`, the opt-in inspection of the last requests' prompts and answers of the -//! Python service (`api_monitor` in its config; `engine/strata/serve/server.py` `begin_request` / `request_records`, +//! Python service (`api_monitor` in its config; `Strata 41cf05a0, serve/server.py` `begin_request` / `request_records`, //! tests in `serve/test_monitor.py`). //! //! It keeps the last [`RETENTION`] requests of the three generation dialects (`/v1/chat/completions`, `/v1/messages`, diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs index 35d414be..cb74c61c 100644 --- a/control-plane/src/server_api.rs +++ b/control-plane/src/server_api.rs @@ -1,4 +1,4 @@ -//! The operational HTTP surface of the Original's Python server (`engine/strata/serve/server.py`) +//! The operational HTTP surface of the Original's Python server (`Strata 41cf05a0, serve/server.py`) //! that is not an inference API: `GET /props`, `GET /slots`, `GET /v1/status`, `GET /api/health`, //! `GET|POST /settings`, `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload`, CORS and //! the own-page guard. Behaviour is checked against the real Python handlers in diff --git a/control-plane/tests/gguf_header_differential.rs b/control-plane/tests/gguf_header_differential.rs index ad505ffd..ad63fb8a 100644 --- a/control-plane/tests/gguf_header_differential.rs +++ b/control-plane/tests/gguf_header_differential.rs @@ -1,4 +1,4 @@ -//! GGUF header reader versus `engine/strata/tools/gguf_reader.py`. +//! GGUF header reader versus `Strata 41cf05a0, tools/gguf_reader.py`. //! //! `tests/fixtures/offline/gguf_headers.json` is generated by `scripts/offline/gen_goldens.py` from the unmodified //! Python reader: random GGUF v3 headers (all 13 metadata value types, arrays, unicode, alignment, split keys, diff --git a/control-plane/tests/golden/gen_goldens.py b/control-plane/tests/golden/gen_goldens.py deleted file mode 100644 index 330b670f..00000000 --- a/control-plane/tests/golden/gen_goldens.py +++ /dev/null @@ -1,617 +0,0 @@ -"""Offline golden generator for the control-plane serving surface (Python is allowed for fixtures only). - -Runs the REAL Python handlers of the pinned Strata (`engine/strata/serve/*.py`, mock engine, no GPU) over tables -of inputs and records what they answer. The Rust tests in `control-plane/tests/golden_*.rs` and the unit tests of -`crates/serving-policy` compare against these files. - - python3 -I control-plane/tests/golden/gen_goldens.py [section ...] - -Needs the packages in engine/strata/requirements.txt (jinja2, jsonschema, regex). The scratchpad venv has them. -Sections: gen_lines, shared, props_slots, cors, ... -""" -import json -import os -import queue -import sys -import threading - -HERE = os.path.dirname(os.path.abspath(__file__)) -REPO = os.path.normpath(os.path.join(HERE, "..", "..", "..")) -ENGINE = os.path.join(REPO, "engine", "strata") -sys.path.insert(0, ENGINE) -sys.path.insert(0, os.path.join(ENGINE, "tools")) - -OUT_CONTROL = os.path.join(HERE, "..", "fixtures", "golden") -OUT_POLICY = os.path.join(REPO, "crates", "serving-policy", "tests", "fixtures") - - -def write(name, obj, dest="control"): - out = OUT_POLICY if dest == "policy" else OUT_CONTROL - os.makedirs(out, exist_ok=True) - path = os.path.join(out, name + ".json") - with open(path, "w", encoding="utf-8") as f: - json.dump(obj, f, indent=1, ensure_ascii=False, sort_keys=False) - f.write("\n") - print("wrote", os.path.relpath(path, REPO), file=sys.stderr) - - -# ------------------------------------------------------------------------------------------------ gen_lines -def gen_lines(): - from serve.server import StrataEngine - - class Pipe: - def __init__(self): - self.sent = [] - - def write(self, text): - self.sent.append(text) - - def flush(self): - pass - - def capture(ids, max_new, sampling, embeddings=None): - eng = object.__new__(StrataEngine) - eng.proc = type("P", (), {"stdin": Pipe()})() - eng.lines = queue.Queue() - eng.lines.put("DONE 1 1 1.0 1.0 stop\n") - eng.can_stop = False - eng.progress = None - eng.prefill_tok_s_mean = None - eng.last = {} - list(eng.generate(ids, max_new, sampling, threading.Event(), embeddings=embeddings)) - return "".join(eng.proc.stdin.sent) - - cases = [] - sampling_tables = [ - {}, - {"temperature": 0.0}, - {"temperature": 0.7}, - {"temperature": 0.7, "top_p": 0.9}, - {"temperature": 1, "top_p": 1.0}, - {"temperature": 0.8, "top_k": 40, "min_p": 0.05}, - {"temperature": 0.8, "top_k": 0}, - {"temperature": 0.8, "top_k": 1000}, - {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.0}, - {"repetition_penalty": 1.1}, - {"repetition_penalty": 1.1, "penalty_last_n": 256}, - {"presence_penalty": 0.5, "frequency_penalty": 0.25}, - {"presence_penalty": -0.5}, - {"frequency_penalty": 1.5, "penalty_last_n": 0}, - {"temperature": 0.7, "seed": 42}, - {"temperature": 0.7, "seed": 0}, - {"temperature": 0.7, "seed": 18446744073709551615}, - {"temperature": 0.9, "top_p": 0.8, "top_k": 33, "min_p": 0.02, "repetition_penalty": 1.05, - "presence_penalty": 0.1, "frequency_penalty": 0.2, "penalty_last_n": 128, "seed": 7}, - {"strata_tune": {"pcie_frac": 0.0}}, - {"strata_tune": {"pcie_frac": 0.35, "spec_min_p": 0.2}}, - {"strata_tune": {"spec_min_p": 1.0}}, - {"experimental_speed_projection": True}, - {"experimental_speed_projection": False}, - {"temperature": 0.5, "strata_tune": {"pcie_frac": 0.5}, "experimental_speed_projection": False}, - ] - for ids, max_new, emb in (([1, 2, 3], 16, None), ([248045, 872, 198, 9707], 4096, None), - ([5, 248056, 248056, 6], 32, "/tmp/req-abc123.sve")): - for sampling in sampling_tables: - cases.append({"token_ids": ids, "max_new": max_new, "embeddings": emb, "sampling": sampling, - "line": capture(ids, max_new, sampling, emb)}) - write("gen_lines", {"source": "serve/server.py StrataEngine.generate (real code, fake pipe)", "cases": cases}) - - -# ------------------------------------------------------------------------------------------------ shared -def shared(): - from serve.server import clean_shared_defaults, sampling_defaults_from_config - - clean_cases = [ - None, {}, [], "x", 5, - {"temperature": 0.7}, {"temperature": 1}, {"temperature": 0}, {"temperature": 2}, {"temperature": 2.5}, - {"temperature": -0.1}, {"temperature": True}, {"temperature": "0.5"}, - {"top_p": 0.9}, {"top_p": 1}, {"top_p": 0}, {"top_p": 1.5}, {"top_p": False}, - {"top_k": 40}, {"top_k": 40.0}, {"top_k": 40.5}, {"top_k": 0}, {"top_k": 64}, {"top_k": 65}, {"top_k": "40"}, - {"seed": 7}, {"seed": 7.0}, {"seed": 0}, {"seed": -3}, {"seed": 1.5}, {"seed": 18446744073709551615}, - {"max_tokens": 512}, {"max_tokens": 0}, {"max_tokens": "10"}, - {"reasoning_effort": "none"}, {"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, - {"reasoning_effort": "high"}, {"reasoning_effort": "xhigh"}, {"reasoning_effort": 3}, - {"experimental_speed_projection": True}, {"experimental_speed_projection": False}, - {"experimental_speed_projection": 1}, - {"temperature": None, "top_p": "", "top_k": None}, {"unknown": 1}, {"unknown": None}, {"min_p": 0.1}, - {"temperature": 0.7, "top_p": 0.9, "top_k": 20, "seed": 11, "max_tokens": 100, - "reasoning_effort": "medium", "experimental_speed_projection": False}, - ] - clean = [] - for case in clean_cases: - try: - clean.append({"input": case, "ok": clean_shared_defaults(case)}) - except ValueError as e: - clean.append({"input": case, "error": str(e)}) - - config_cases = [ - None, {}, {"temperature": 0.7}, {"temperature": 0}, {"temperature": -1}, {"temperature": True}, - {"top_p": 0.95}, {"top_p": 0}, {"top_p": 1.01}, {"min_p": 0.05}, {"min_p": 0}, {"min_p": 2}, - {"top_k": 40}, {"top_k": 0}, {"top_k": 65}, {"top_k": 20.0}, {"top_k": 1.5}, - {"presence_penalty": 0.5}, {"presence_penalty": -0.5}, {"frequency_penalty": 0.25}, - {"frequency_penalty": -1}, {"repetition_penalty": 1.1}, {"repetition_penalty": 0}, - {"penalty_last_n": 128}, {"penalty_last_n": 0}, {"penalty_last_n": -2}, {"penalty_last_n": 1.5}, - {"seed": 5}, {"seed": 0}, {"seed": 5.5}, {"seed": "5"}, - {"experimental_speed_projection": True}, {"experimental_speed_projection": "yes"}, - {"temperature": None, "top_p": None}, {"nonsense": 3}, {"temperature": 0.6, "nonsense": 3}, - {"temperature": 0.6, "top_p": 0.9, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.1, - "frequency_penalty": 0.1, "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 9}, - ] - import contextlib - import io - config = [] - for case in config_cases: - out = io.StringIO() - try: - with contextlib.redirect_stdout(out): - ok = sampling_defaults_from_config({"sampling": case} if case is not None else {}) - config.append({"input": case, "ok": ok, "ignored": [ln for ln in out.getvalue().splitlines() - if "unknown key" in ln]}) - except SystemExit as e: - config.append({"input": case, "error": str(e)}) - write("shared", {"source": "serve/server.py clean_shared_defaults / sampling_defaults_from_config (real code)", - "clean": clean, "config": config}, dest="policy") - - -# ------------------------------------------------------------------------------------------------ reasoning -def reasoning(): - import random - from serve.frontend import OutputParser - from serve.server import Detokenizer, Service, ByteTokenizer - - class BytesTok: - """Token i's bytes are the table's entry; what Detokenizer needs from the real tokenizer.""" - def __init__(self, table): - self.table = table - - def token_bytes(self, t): - return self.table[t] - - pieces = [b"a", b"b", b" so ", b"think", b"", b"", b"", b"<", b"/", b"\n", - b"\xc3", b"\xa9", "\u65e5".encode()[:1], "\u65e5".encode()[1:], b"\xff", b"\xe2\x82", b"\xac", b"", b"x"] - rng = random.Random(1234) - seqs = [[0, 1, 2, 3], [4, 5], [6, 0, 1], [0, 4, 0, 1], [11, 12, 0, 0, 0], [13, 14, 0, 0], [16, 0, 0], [17, 18, 0], - [3, 4, 5, 3, 3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] - for _ in range(120): - seqs.append([rng.randrange(len(pieces)) for _ in range(rng.randrange(1, 14))]) - cases = [] - for seq in seqs: - row = {"pieces_hex": [pieces[i].hex() for i in seq], "wrap_at": {}} - for budget in (1, 2, 3, 5, 8): - parser = OutputParser(thinking=True, tools=None, stream_tools=True) - detok = Detokenizer(BytesTok(pieces)) - thought, wrap_at = 0, None - for i, t in enumerate(seq): - parser.feed(detok.push(t)) - if parser.state == "reasoning": - thought += 1 - if thought >= budget and not parser.buf and not detok.pending(): - wrap_at = i - break - row["wrap_at"][str(budget)] = wrap_at - cases.append(row) - - parse = [] - svc = Service.__new__(Service) - for req, default in [(None, 0), ({}, 0), ({"reasoning_budget_tokens": 20}, 0), ({"reasoning_budget_tokens": 20.0}, 0), - ({"reasoning_budget_tokens": 0}, 50), ({"reasoning_budget_tokens": -1}, 50), - ({}, 50), ({"reasoning_budget_tokens": None}, 50), ({"reasoning_budget_tokens": True}, 0), - ({"reasoning_budget_tokens": "5"}, 0), ({"reasoning_budget_tokens": 2.5}, 0), - ({"reasoning_budget_tokens": [1]}, 0), ({"reasoning_budget_tokens": 10000}, 0)]: - svc.reasoning_budget_tokens = default - try: - parse.append({"request": req, "default": default, "ok": svc.reasoning_budget(req)}) - except ValueError as e: - parse.append({"request": req, "default": default, "error": str(e)}) - from serve.server import REASONING_WRAP_UP - write("reasoning", {"source": "serve/server.py Service.reasoning_budget + Service.run budget branch (real " - "Detokenizer/OutputParser)", "wrap_up": REASONING_WRAP_UP, "cases": cases, - "parse": parse}, dest="policy") - - -# ------------------------------------------------------------------------------------------------ http -def http_surface(): - """The operational HTTP surface of the real Python server, scenario by scenario (fake resident engine).""" - import http.client - from pathlib import Path - from serve.frontend import ChatTemplate - from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve - - class Resident(StrataEngine): - def __init__(self, tok, loaded, max_context): - self.reply = MockEngine(tok, "Hello.", max_context=max_context) - self.max_context, self.info, self.last = max_context, {"version": "9.9.9"}, {} - self.loaded, self.unloaded, self.progress = loaded, not loaded, None - - def alive(self): - return self.loaded - - def exit_code(self): - return None - - def restart(self): - self.loaded, self.unloaded = True, False - - def close(self): - self.loaded = False - - def unload(self): - self.close() - self.unloaded = True - - def generate(self, *args, **kwargs): - yield from self.reply.generate(*args, **kwargs) - - def run(setup, steps): - tok = ByteTokenizer() - engine = Resident(tok, setup.get("loaded", True), setup.get("max_context", 4096)) - svc = Service(engine, tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"), - model_name=setup.get("model", "strata-test"), - sampling_defaults=setup.get("config_sampling") or {}) - svc.set_aliases(setup.get("aliases")) - svc.api_key = setup.get("api_key", "") - svc.cors_origins = setup.get("cors_origins", []) - svc.trusted_origins = setup.get("trusted_origins", []) - if setup.get("shared"): - svc.shared = dict(setup["shared"]) - svc.idle_unload_s = setup.get("idle_unload_s", 0) - for key, value in (setup.get("status") or {}).items(): - svc.status[key] = value - httpd = serve(svc, port=0) - port = httpd.server_address[1] - out = [] - try: - for step in steps: - conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10) - headers = dict(step.get("headers") or {}) - body = step.get("body") - if body is not None and not isinstance(body, str): - body = json.dumps(body) - headers.setdefault("Content-Type", "application/json") - if body is not None: - headers.setdefault("Content-Length", str(len(body.encode()))) - conn.request(step["method"], step["path"], body=body.encode() if body is not None else None, - headers=headers) - response = conn.getresponse() - raw = response.read().decode() - selected = {k.lower(): v for k, v in response.getheaders() - if k.lower().startswith("access-control-") or k.lower() == "vary"} - try: - parsed = json.loads(raw) if raw else None - except ValueError: - parsed = raw - out.append({"request": {"method": step["method"], "path": step["path"], - "headers": step.get("headers") or {}, "body": step.get("body")}, - "status": response.status, "headers": selected, "body": parsed, - "state": {"loaded": engine.loaded, "shared": svc.shared}}) - conn.close() - finally: - httpd.shutdown() - httpd.server_close() - return {"setup": setup, "steps": out} - - scenarios = {} - # ---- CORS - cors_steps = [ - {"method": "OPTIONS", "path": "/v1/chat/completions", - "headers": {"Origin": "https://a.example", "Access-Control-Request-Headers": "authorization,content-type"}}, - {"method": "OPTIONS", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}}, - {"method": "OPTIONS", "path": "/v1/models"}, - {"method": "OPTIONS", "path": "/health", "headers": {"Origin": "https://a.example"}}, - {"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://a.example/"}}, - {"method": "GET", "path": "/v1/status?x=1", "headers": {"Origin": "https://b.example"}}, - {"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}}, - {"method": "GET", "path": "/v1/models"}, - {"method": "GET", "path": "/health", "headers": {"Origin": "https://a.example"}}, - {"method": "GET", "path": "/props", "headers": {"Origin": "https://a.example"}}, - {"method": "GET", "path": "/v1/nothing", "headers": {"Origin": "https://a.example"}}, - ] - for name, origins in (("off", []), ("any", ["*"]), ("listed", ["https://a.example", "https://b.example"])): - scenarios[f"cors_{name}"] = run({"cors_origins": origins}, cors_steps) - # (an unknown path answers 404 before authentication in the Python server; the Rust server - # authenticates every path first, so that one step is left out here) - scenarios[f"cors_{name}_with_key"] = run({"cors_origins": origins, "api_key": "k" * 40}, cors_steps[:-1]) - # ---- own page - page = {"defaults": {"temperature": 0.5}} - own = [ - {"method": "POST", "path": "/settings", "body": page}, - {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "http://127.0.0.1:1"}}, - {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example"}}, - {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com/"}}, - {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com", - "Host": "proxy.internal"}}, - {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example", - "X-Forwarded-Host": "evil.example", - "CF-Ray": "1"}}, - {"method": "POST", "path": "/settings", "body": json.dumps(page), "headers": {"Content-Type": "text/plain"}}, - {"method": "POST", "path": "/settings", "body": json.dumps(page), - "headers": {"Content-Type": "application/x-www-form-urlencoded"}}, - {"method": "POST", "path": "/settings", "body": json.dumps(page), - "headers": {"Content-Type": "application/json; charset=utf-8"}}, - {"method": "GET", "path": "/settings"}, - ] - scenarios["own_page"] = run({"trusted_origins": ["https://strata.example.com"]}, own) - # ---- settings - settings = [ - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.7, "top_k": 40, "seed": 3}}}, - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 9}}}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"nonsense": 1}}}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"top_p": 0, "temperature": 1}}}, - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"max_tokens": 128, "reasoning_effort": "low", - "experimental_speed_projection": True}}}, - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": [1, 2]}, - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.5}}}, - {"method": "POST", "path": "/settings", "body": {}}, - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": {"defaults": 5}}, - ] - scenarios["settings"] = run({}, settings) - scenarios["settings_with_key"] = run({"api_key": "k" * 40}, [ - {"method": "GET", "path": "/settings"}, - {"method": "GET", "path": "/settings", "headers": {"Authorization": "Bearer " + "k" * 40}}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}}}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}}, - "headers": {"Authorization": "Bearer " + "k" * 40}}, - ]) - # ---- props, slots, health, status - reads = [ - {"method": "GET", "path": "/props"}, - {"method": "GET", "path": "/props?model=strata-test"}, - {"method": "GET", "path": "/props?model=alias-one"}, - {"method": "GET", "path": "/props?model=nope"}, - {"method": "GET", "path": "/props?model="}, - {"method": "GET", "path": "/slots"}, - {"method": "GET", "path": "/api/health"}, - {"method": "GET", "path": "/v1/status"}, - ] - scenarios["reads_loaded"] = run({"aliases": ["alias-one", "alias-two"]}, reads) - scenarios["reads_loaded_with_defaults"] = run( - {"config_sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.2, - "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 8}, - "shared": {"temperature": 0.9, "max_tokens": 256}, "max_context": 32768}, reads) - scenarios["reads_unloaded"] = run({"loaded": False, "aliases": ["alias-one"]}, reads) - scenarios["reads_busy"] = run({"status": {"busy": True, "queued": 2}}, [ - {"method": "GET", "path": "/slots"}, {"method": "GET", "path": "/v1/status"}]) - scenarios["reads_with_key"] = run({"api_key": "k" * 40}, [ - {"method": "GET", "path": "/props"}, {"method": "GET", "path": "/slots"}, - {"method": "GET", "path": "/v1/status"}, {"method": "GET", "path": "/api/health"}, - {"method": "GET", "path": "/health"}]) - # ---- load / unload - lifecycle = [ - {"method": "POST", "path": "/unload"}, - {"method": "POST", "path": "/unload"}, - {"method": "GET", "path": "/slots"}, - {"method": "POST", "path": "/load"}, - {"method": "POST", "path": "/load"}, - {"method": "POST", "path": "/v1/unload", "body": {}}, - {"method": "POST", "path": "/v1/unload", "body": {}}, - {"method": "POST", "path": "/v1/load", "body": {"model": "other-model"}}, - {"method": "POST", "path": "/v1/load", "body": {"model": "strata-test"}}, - {"method": "POST", "path": "/v1/load", "body": {}}, - {"method": "POST", "path": "/v1/load", "body": "{}", "headers": {"Content-Type": "text/plain"}}, - {"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Origin": "https://other.example"}}, - {"method": "POST", "path": "/v1/unload", "body": [1]}, - {"method": "POST", "path": "/v1/unload", "body": "not json", "headers": {"Content-Type": "application/json"}}, - {"method": "POST", "path": "/v1/unload", "body": {"model": None}}, - {"method": "GET", "path": "/props"}, - ] - scenarios["lifecycle"] = run({}, lifecycle) - scenarios["lifecycle_busy"] = run({"status": {"queued": 1}}, [ - {"method": "POST", "path": "/v1/unload", "body": {}}, - {"method": "POST", "path": "/v1/load", "body": {}}, - {"method": "POST", "path": "/unload"}, - {"method": "POST", "path": "/load"}, - ]) - scenarios["lifecycle_unloaded_then_busy"] = run({"loaded": False, "status": {"busy": True}}, [ - {"method": "POST", "path": "/v1/load", "body": {}}, - {"method": "POST", "path": "/unload"}, - {"method": "POST", "path": "/load"}, - ]) - scenarios["lifecycle_with_key"] = run({"api_key": "k" * 40}, [ - {"method": "POST", "path": "/unload"}, - {"method": "POST", "path": "/v1/unload", "body": {}}, - {"method": "POST", "path": "/v1/unload", "body": {}, - "headers": {"Authorization": "Bearer " + "k" * 40, "Origin": "https://other.example"}}, - {"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Authorization": "Bearer " + "k" * 40}}, - {"method": "POST", "path": "/load", "headers": {"x-api-key": "k" * 40}}, - ]) - write("http_surface", {"source": "serve/server.py Handler (real code, resident fake engine)", - "scenarios": scenarios}) - - -# ------------------------------------------------------------------------------------------------ timings -def timings(): - from serve.server import ByteTokenizer, MockEngine, Service, request_timings - from serve.frontend import ChatTemplate - from pathlib import Path - - cases = [] - lasts = [ - {"prompt_ms": 250.0, "decode_ms": 1000.0, "generated": 50, "reused": 60}, - {"prompt_ms": 0.0, "decode_ms": 0.0, "generated": 0, "reused": 0}, - {"prompt_ms": 12.34567, "decode_ms": 98.7654, "generated": 7, "reused": None}, - {"prompt_ms": 0.25, "decode_ms": 0.05, "generated": 3}, - {"prompt_ms": 2.675, "decode_ms": 1234.55, "generated": 11, "reused": 5, "drafts_offered": 20, "drafts_accepted": 15}, - {"prompt_ms": 100.0, "decode_ms": 333.3333, "generated": 0, "reused": 200}, - {"prompt_ms": 1e-9, "decode_ms": 5e-5, "generated": 9, "reused": 0, "drafts_offered": 0, "drafts_accepted": 0}, - {"prompt_ms": 12345.678, "decode_ms": 87654.321, "generated": 4096, "reused": 1}, - ] - for last in lasts: - for prompt_tokens, generated in ((300, last.get("generated") or 5), (10, 10), (0, 0), (50, 7)): - cases.append({"last": last, "prompt_tokens": prompt_tokens, "generated": generated, - "timings": request_timings(prompt_tokens, generated, last)}) - cases.append({"last": {}, "prompt_tokens": 5, "generated": 5, "timings": request_timings(5, 5, {})}) - aliases = [] - tok = ByteTokenizer() - for value in (None, [], ["a"], [" a ", "a", "", "m", "b"], "a, b ,a,,m", ["a", 1], 5, {"a": 1}, "", [""]): - svc = Service(MockEngine(tok, "x"), tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"), - model_name="m") - try: - svc.set_aliases(value) - aliases.append({"input": value, "ok": svc.aliases}) - except ValueError as e: - aliases.append({"input": value, "error": str(e)}) - write("timings", {"source": "serve/server.py request_timings + Service.set_aliases (real code)", - "timings": cases, "aliases": aliases}, dest="policy") - - -# ------------------------------------------------------------------------------------------------ vision -def vision(): - import base64 - import tempfile - from pathlib import Path - from serve.frontend import ChatTemplate, _image_source, images_of, openai_to_messages - from serve.server import IMAGE_PAD, VISION_START, ByteTokenizer, MockEngine, Service, Vision - - # base64 as Vision.load decodes data: URLs - b64 = [] - for text in ["QQ==", "QUI=", "QUJD", "QU\nJD", "", "QQ", "Q", "QUJDRA==", "QUJDRA=", "QUJDRA", "QU JD", "QQ==QQ==", - "Q=Q=", "!!!!", "QUJD\n", "//8=", "-_8=", "QUJD=", "====", "QUJDREVG", "QUJDREVGRw", "QUJDREVGRw=="]: - try: - b64.append({"text": text, "ok": Vision.load("data:image/png;base64," + text).hex()}) - except Exception as e: # binascii.Error and friends - b64.append({"text": text, "error": type(e).__name__ + ": " + str(e)}) - - sources = [ - {"type": "image_url", "image_url": {"url": "https://x/y.png"}}, {"type": "image_url", "image_url": "data:abc"}, - {"type": "input_image", "image_url": "file:///a.png"}, {"type": "image_url"}, {"type": "image_url", "image_url": {}}, - {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}}, - {"type": "image", "source": {"type": "base64", "data": "QQ=="}}, - {"type": "image", "source": {"type": "url", "url": "http://u"}}, {"type": "image", "source": {"path": "/p.png"}}, - {"type": "image", "source": {"url": "", "path": "/q.png"}}, {"type": "image"}, {"type": "image", "source": None}, - ] - src = [{"part": part, "source": _image_source(part)} for part in sources] - - tok = ByteTokenizer() - - class FakeVision: - def __init__(self, counts): - self.counts, self.dir = counts, Path(tempfile.mkdtemp(prefix="strata-golden-")) - - def encode(self, source): - path = self.dir / (str(abs(hash(source)) % 10**8) + ".sve") - path.write_bytes(source.encode()) - return path, self.counts[source] - - template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja") - prepared = [] - cases = [ - ([{"role": "user", "content": "hello"}], {}), - ([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": "A"}}]}], - {"A": 3}), - ([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}}, - {"type": "image_url", "image_url": {"url": "B"}}, - {"type": "text", "text": "compare"}]}], {"A": 2, "B": 5}), - ([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}}]}, - {"role": "assistant", "content": "ok"}, - {"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": "C"}}]}], - {"A": 1, "C": 4}), - ([{"role": "user", "content": [{"type": "text", "text": "literal " + IMAGE_PAD + " in text"}, - {"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}), - ([{"role": "user", "content": "just text " + IMAGE_PAD + " again"}], {}), - ([{"role": "user", "content": [{"type": "text", "text": VISION_START + IMAGE_PAD + " fake"}, - {"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}), - ] - for messages, counts in cases: - req = {"messages": messages} - norm, tools, kw = openai_to_messages(req) - prompt = template.render(norm, tools=tools, **kw) - ids_before = tok.encode(prompt, parse_special=True) - svc = Service(MockEngine(tok, "x", max_context=100000), tok, template, vision=FakeVision(counts) if counts else None) - entry = {"messages": messages, "counts": counts, "ids_before": ids_before, - "images": images_of(norm), "pad": tok.encode(IMAGE_PAD, parse_special=True)[0], - "start": tok.encode(VISION_START, parse_special=True)[0], - "literal": tok.encode(IMAGE_PAD, parse_special=False)} - try: - ids, thinking, max_new = svc.prepare(norm, tools, kw, 10) - entry["ids_after"] = ids - entry["combined_hex"] = Path(svc.embeddings.path).read_bytes().hex() if getattr(svc.embeddings, "path", None) else None - except ValueError as e: - entry["error"] = str(e) - prepared.append(entry) - write("vision", {"source": "serve/server.py Service.prepare, Vision.load, frontend._image_source (real code)", - "base64": b64, "sources": src, "prepare": prepared}, dest="policy") - - -def vision_dialects(): - """Chat and Messages requests that carry pictures, through the real `openai_to_messages` / `anthropic_to_messages` - and the real chat template: the prompt text and the picture sources in prompt order.""" - import base64 - from pathlib import Path - from serve.frontend import ChatTemplate, anthropic_to_messages, images_of, openai_to_messages - - template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja") - counter = iter(range(1, 250)) - - def url(): - # a PNG signature and one tag byte: the tests find the picture again by its last byte - return "data:image/png;base64," + base64.b64encode(b"\x89PNG\r\n\x1a\n" + bytes([next(counter)])).decode() - - def chat(messages): - return {"dialect": "chat", "request": {"messages": messages, "reasoning_effort": "none"}} - - def claude(messages, system=None): - request = {"messages": messages, "thinking": {"type": "disabled"}} - if system: - request["system"] = system - return {"dialect": "messages", "request": request} - - def b64(media="image/png"): - data = url().split(",", 1)[1] - return {"type": "image", "source": {"type": "base64", "media_type": media, "data": data}} - - cases = [ - chat([{"role": "user", "content": [{"type": "text", "text": "what is this?"}, - {"type": "image_url", "image_url": {"url": url(), "detail": "high"}}]}]), - chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]}]), - chat([{"role": "user", "content": [{"type": "image_url", "image_url": url()}, {"type": "text", "text": "after"}]}]), - chat([{"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "image_url", "image_url": {"url": url()}}, - {"type": "text", "text": "b"}, {"type": "image_url", "image_url": url()}, - {"type": "text", "text": "c"}]}]), - chat([{"role": "system", "content": "be brief"}, - {"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "x"}]}]), - chat([{"role": "user", "content": "first"}, {"role": "assistant", "content": "ok"}, - {"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": url()}}]}]), - chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]}, - {"role": "assistant", "content": "a cat"}, - {"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "and?"}]}]), - chat([{"role": "user", "content": [{"type": "text", "text": "the docs say <|image_pad|> marks an image"}, - {"type": "image_url", "image_url": {"url": url()}}]}]), - claude([{"role": "user", "content": [b64(), {"type": "text", "text": "describe"}]}]), - claude([{"role": "user", "content": [{"type": "text", "text": "describe"}, b64("image/jpeg")]}], system="be brief"), - claude([{"role": "user", "content": [b64(), b64(), {"type": "text", "text": "compare"}]}]), - claude([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image", "source": {"type": "url", "url": url()}}]}]), - claude([{"role": "user", "content": [{"type": "image", "source": {"type": "url", "url": url()}}]}]), - claude([{"role": "user", "content": "first"}, {"role": "assistant", "content": [{"type": "text", "text": "ok"}]}, - {"role": "user", "content": [b64(), {"type": "text", "text": "now this"}]}]), - ] - out = [] - for case in cases: - req = case["request"] - if case["dialect"] == "chat": - messages, tools, kw = openai_to_messages(req) - else: - messages, tools, kw = anthropic_to_messages(req) - out.append({**case, "prompt": template.render(messages, tools=tools, **kw), "images": images_of(messages)}) - write("vision_dialects", {"source": "serve/frontend.py openai_to_messages / anthropic_to_messages + chat_template.jinja", - "cases": out}) - - -SECTIONS = {"gen_lines": gen_lines, "shared": shared, "reasoning": reasoning, "http": http_surface, - "timings": timings, "vision": vision, "vision_dialects": vision_dialects} - - -def main(argv): - names = argv or list(SECTIONS) - for name in names: - SECTIONS[name]() - - -if __name__ == "__main__": - main(sys.argv[1:]) diff --git a/control-plane/tests/http_surface.rs b/control-plane/tests/http_surface.rs index 93ff5509..c2bc0d50 100644 --- a/control-plane/tests/http_surface.rs +++ b/control-plane/tests/http_surface.rs @@ -2,7 +2,7 @@ //! The operational HTTP surface (`/props`, `/slots`, `/settings`, `/load`, `/unload`, `/v1/load`, //! `/v1/unload`, `/v1/status`, `/api/health`, CORS, own-page guard) against the real Python //! handlers: every scenario in `tests/fixtures/golden/http_surface.json` was recorded from -//! `engine/strata/serve/server.py` by `tests/golden/gen_goldens.py http`, and is replayed here +//! `Strata 41cf05a0, serve/server.py` by `tests/golden/gen_goldens.py http`, and is replayed here //! against the Rust router with a real worker supervisor and the mock engine. //! //! Deliberate differences, skipped in the comparison: the chat template text, the build/version diff --git a/control-plane/tests/mcp_hub/main.rs b/control-plane/tests/mcp_hub/main.rs index fce9d816..f9136275 100644 --- a/control-plane/tests/mcp_hub/main.rs +++ b/control-plane/tests/mcp_hub/main.rs @@ -1,4 +1,4 @@ -//! The MCP hub against the Python fake server of the Original (`engine/strata/serve/mcp_fake_server.py`, +//! The MCP hub against the Python fake server of the Original (`mcp_fake_server.py` next to this test, from Strata 41cf05a0 `serve/`, //! standard library only; a test double, not part of serving): stdio and Streamable HTTP clients, //! paging, namespacing, errors as text, timeouts, the result cap, restart on demand, cancellation. //! The tests are skipped (with a message) when `python3` is not installed. diff --git a/control-plane/tests/mtp_fetch.rs b/control-plane/tests/mtp_fetch.rs index fb1e7413..e5e1e349 100644 --- a/control-plane/tests/mtp_fetch.rs +++ b/control-plane/tests/mtp_fetch.rs @@ -1,5 +1,5 @@ //! `mtp_fetch` against a local HTTP mirror of a fake checkpoint: the behavioural spec is -//! `engine/strata/tools/test_mtp_fetch.py` (#327), ported case for case. Nothing leaves the machine. +//! `Strata 41cf05a0, tools/test_mtp_fetch.py` (#327), ported case for case. Nothing leaves the machine. use std::{ collections::BTreeMap, fs, diff --git a/crates/context/src/rope_scaling.rs b/crates/context/src/rope_scaling.rs index acc69f35..f80d23a9 100644 --- a/crates/context/src/rope_scaling.rs +++ b/crates/context/src/rope_scaling.rs @@ -1,6 +1,6 @@ //! RoPE scaling (none / linear / YaRN) and the host-side cos/sin table builder. //! -//! Literal port of the Original (pinned Strata under `engine/strata/`): +//! Literal port of the Original (pinned Strata, upstream commit 41cf05a0): //! - `include/strata/kernels/rope_scaling.hpp` (`RopeScaling`, `rope_yarn_ramp`, `rope_scaled_angle`, //! `rope_scaling_invalid`, `RopeKernelArgs`), //! - `src/kernels/cuda/rope.cu` (`build_rope_table`, both overloads), diff --git a/crates/context/src/setup_policy.rs b/crates/context/src/setup_policy.rs index 0b20819d..84ee2294 100644 --- a/crates/context/src/setup_policy.rs +++ b/crates/context/src/setup_policy.rs @@ -1,4 +1,4 @@ -//! `engine/strata/setup.py`'s pure RAM / VRAM / context sizing rules, ported function for function. +//! `Strata 41cf05a0, setup.py`'s pure RAM / VRAM / context sizing rules, ported function for function. //! //! The rope half of `setup.py` (`derived_factor`, `resolve_rope`) lives in [`crate::rope_scaling`] //! (`derived_factor`, `setup_resolve_rope`); this module holds the rest: which contexts the RAM allows diff --git a/crates/context/tests/rope_plan_golden/gen_kv_pool_golden.cpp b/crates/context/tests/rope_plan_golden/gen_kv_pool_golden.cpp deleted file mode 100644 index 40d4643b..00000000 --- a/crates/context/tests/rope_plan_golden/gen_kv_pool_golden.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// gen_kv_pool_golden.cpp - prints the Original's `kv_pool_bytes` (src/core/layer.cpp, extracted verbatim by -// gen_plan_golden.py into kv_pool_bytes.inc) for every KV format on several shapes. Output: JSON array. -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/qsa.hpp" - -#include -#include - -using strata::kernels::QsaShapes; - -static bool g_without_key = false; // layer.cpp globals the extracted function reads -static bool g_kv_q4 = false; - -#include "kv_pool_bytes.inc" - -int main() { - struct Shape { int64_t kv, dim, page; }; - const Shape shapes[] = {{2, 256, 4}, {4, 128, 1}, {2, 256, 1}, {1, 64, 8}}; - const int64_t pages[] = {1, 7, 131072, 262144}; - struct Fmt { const char* name; bool without_key, q4, hybrid, int8; }; - // the flag combinations qsa_state_bytes passes: kv_pool_bytes(s, slots, g_kv_hybrid, g_kv_int8 || g_kv_hybrid) - const Fmt fmts[] = {{"fp16", false, false, false, false}, - {"int8", false, false, false, true}, - {"q4_0", false, true, false, false}, - {"k8v4", false, false, true, true}, - {"int8-keyless", true, false, false, true}}; - std::printf("["); - bool first = true; - for (const Shape& sh : shapes) { - QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head_kv = sh.kv; - s.head_dim = sh.dim; - s.page_size = sh.page; - for (const Fmt& f : fmts) { - g_without_key = f.without_key; - g_kv_q4 = f.q4; - for (int64_t p : pages) { - std::printf("%s\n {\"n_head_kv\": %lld, \"head_dim\": %lld, \"page_size\": %lld, \"format\": \"%s\", " - "\"pages\": %lld, \"bytes\": %llu}", - first ? "" : ",", (long long) sh.kv, (long long) sh.dim, (long long) sh.page, f.name, - (long long) p, (unsigned long long) kv_pool_bytes(s, p, f.hybrid, f.int8)); - first = false; - } - } - } - std::printf("\n]\n"); - return 0; -} diff --git a/crates/context/tests/rope_plan_golden/gen_plan_golden.py b/crates/context/tests/rope_plan_golden/gen_plan_golden.py deleted file mode 100644 index 11b011ad..00000000 --- a/crates/context/tests/rope_plan_golden/gen_plan_golden.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python3 -"""Offline fixture generator (Python is allowed for offline tooling, AGENTS.md): builds the Original's -`strata-plan` CLI (header-only) and the `kv_pool_bytes` harness, runs a table of configurations and writes -memory_plan_golden.json. Usage: gen_plan_golden.py .""" -import json, subprocess, sys, os, re - -out, strata, work = sys.argv[1:4] -cxx = os.environ.get("CXX", "clang++") -here = os.path.dirname(os.path.abspath(__file__)) -flags = ["-std=c++17", "-O2", "-I" + os.path.join(strata, "include"), "-I" + work] - -subprocess.check_call([cxx, *flags, os.path.join(strata, "src/plan/plan_main.cpp"), "-o", os.path.join(work, "strata-plan")]) -with open(os.path.join(strata, "src/core/layer.cpp")) as f: - src = f.read().split("\n") -start = next(i for i, l in enumerate(src) if l.startswith("uint64_t kv_pool_bytes(")) -end = next(i for i in range(start, len(src)) if src[i].startswith("}")) -with open(os.path.join(work, "kv_pool_bytes.inc"), "w") as f: - f.write("\n".join(src[start:end + 1]) + "\n") -subprocess.check_call([cxx, *flags, os.path.join(here, "gen_kv_pool_golden.cpp"), "-o", os.path.join(work, "kvgen")]) -kv_pool = json.loads(subprocess.check_output([os.path.join(work, "kvgen")])) - -G = 1000 ** 3 -GIB = 1024 ** 3 -state_default = 36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4) -cases = [] -def add(*args): cases.append([str(a) for a in args]) - -for ctx in (20480, 65536, 131072, 262144, 393216, 524288): - for vram in (12 * G, 16 * G, 24 * G, 32 * G, 32 * GIB, 48 * G): - add("--max-context", ctx, "--vram", vram) -# charter profiles with their state (x2 slots for 2x256K), on 32 GiB with and without resident weights -for (ctx, slots) in ((524288, 1), (524288, 2), (262144, 1), (262144, 2)): - st = state_default * slots - for vram in (16 * G, 24 * G, 32 * GIB): - add("--max-context", ctx, "--vram", vram, "--state", st) - add("--max-context", ctx, "--vram", vram, "--state", st, "--dense", 4 * G, "--embd", 500_000_000, "--workspace", 300_000_000) -# small cards: the planner must refuse -for ctx in (262144, 524288): - for vram in (3 * G, 4 * G, 6 * G, 7 * G): - add("--max-context", ctx, "--vram", vram) -# resident weights larger than the card: derived pool 0 falls back to the default pool -add("--max-context", 4096, "--vram", 5 * G, "--dense", 6 * G) -add("--max-context", 20480) # CLI defaults -add("--pool", 5943000000, "--max-context", 20480) -add("--pool", 3 * G, "--max-context", 100000) -add("--pool", 20 * G, "--max-context", 100000, "--dense", 5 * G, "--embd", G) # --pool still subtracts dense/embd -add("--max-context", 1000, "--vram", 1_000_000) # does not close -add("--max-context", 1, "--vram", 13056 + 117_669_888 + 1_382_399) # no room for one slot (default state) -add("--max-context", 1, "--vram", 13056 + 117_669_888 + 1_382_400) # exactly one slot -add("--max-context", 100, "--vram", 10 * G, "--state", 0) -add("--max-context", 100, "--vram", 10 * G, "--workspace", 123456789) -add("--help") -add("--bogus") -add("--max-context") - -runs = [] -for args in cases: - p = subprocess.run([os.path.join(work, "strata-plan"), *args], capture_output=True, text=True) - runs.append({"args": args, "exit": p.returncode, "stdout": p.stdout, "stderr": p.stderr}) - -json.dump({"generator": "strata-plan built from engine/strata/src/plan/plan_main.cpp (unmodified) + extracted layer.cpp kv_pool_bytes", - "state_bytes_default": state_default, "cli": runs, "kv_pool": kv_pool}, open(out, "w"), indent=1) diff --git a/crates/context/tests/rope_plan_golden/gen_plan_golden.sh b/crates/context/tests/rope_plan_golden/gen_plan_golden.sh deleted file mode 100755 index 65f76c9a..00000000 --- a/crates/context/tests/rope_plan_golden/gen_plan_golden.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -# Regenerates memory_plan_golden.json from the Original (macOS or Linux, any C++17 compiler + python3). -set -eu -here=$(cd "$(dirname "$0")" && pwd) -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -python3 -I "$here/gen_plan_golden.py" "$here/memory_plan_golden.json" "$here/../../../../engine/strata" "$work" diff --git a/crates/context/tests/rope_plan_golden/gen_rope_golden.cpp b/crates/context/tests/rope_plan_golden/gen_rope_golden.cpp deleted file mode 100644 index c0de014b..00000000 --- a/crates/context/tests/rope_plan_golden/gen_rope_golden.cpp +++ /dev/null @@ -1,196 +0,0 @@ -// gen_rope_golden.cpp - golden-fixture generator for the Rust rope port (leleka-runtime::rope_scaling). -// -// It links the ORIGINAL host-side code: `include/strata/kernels/rope_scaling.hpp` is included unmodified, and the -// two `build_rope_table` definitions are extracted VERBATIM from `src/kernels/cuda/rope.cu` by `gen_rope_golden.sh` -// into a generated include (`rope_table_original.inc`). Nothing from the Original is re-typed here. -// -// Every double/float is printed as its IEEE bit pattern in hex so the fixture is exact (serde_json's default -// float parser is not guaranteed correctly rounded). Tables are summarised by FNV-1a 64 over the little-endian -// f32 bytes of the whole cos table and of the whole sin table, plus full rows at selected positions. -#include "strata/kernels/rope_scaling.hpp" - -#include -#include -#include -#include -#include - -namespace strata::kernels { -// the engine's other definitions live in the .cu next to the extracted functions; only the table builders are needed -void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab); -void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab); -} // namespace strata::kernels - -namespace strata::kernels { -#include "rope_table_original.inc" -} // namespace strata::kernels - -using namespace strata::kernels; - -static std::string hex64(double d) { - uint64_t u; - std::memcpy(&u, &d, 8); - char b[32]; - std::snprintf(b, sizeof b, "0x%016llx", (unsigned long long) u); - return b; -} -static std::string hex32(float f) { - uint32_t u; - std::memcpy(&u, &f, 4); - char b[32]; - std::snprintf(b, sizeof b, "0x%08x", u); - return b; -} -static uint64_t fnv(const float* p, size_t n) { - uint64_t h = 0xcbf29ce484222325ull; - for (size_t i = 0; i < n; ++i) { - uint32_t u; - std::memcpy(&u, p + i, 4); - for (int k = 0; k < 4; ++k) { - h ^= (uint8_t) (u >> (8 * k)); - h *= 0x100000001b3ull; - } - } - return h; -} - -struct Case { - const char* name; - const char* desc; - int n_rot; - RopeScaling sc; - bool tables; // build the 524288-position tables (skipped for invalid configs) -}; - -static RopeScaling mk(RopeScalingType t, double fb, double factor, double fsi, double orig, double ext, double attn, - double bf, double bs) { - RopeScaling s; - s.type = t; - s.freq_base = fb; - s.factor = factor; - s.freq_scale_in = fsi; - s.orig_ctx = orig; - s.ext_factor = ext; - s.attn_factor = attn; - s.beta_fast = bf; - s.beta_slow = bs; - return s; -} - -int main() { - using T = RopeScalingType; - const double B = 1e7, O = 262144; - std::vector cases = { - {"none_default", "default-constructed RopeScaling (today's engine)", 64, RopeScaling{}, true}, - {"none_junk_knobs", "type none with every scaling knob set: knobs must be inert", 64, - mk(T::None, B, 4.0, 0.25, 4096, 1.0, 0.5, 20, 2), true}, - {"linear_2", "linear factor 2 (512K over 262144)", 64, mk(T::Linear, B, 2.0, 0, O, 0, 1.0, 32, 1), true}, - {"linear_1_5", "linear factor 1.5 (393216 over 262144)", 64, mk(T::Linear, B, 1.5, 0, O, 0, 1.0, 32, 1), true}, - {"linear_freq_scale_in", "linear with the raw ggml freq_scale 0.25 overriding 1/factor", 64, - mk(T::Linear, B, 2.0, 0.25, O, 0, 1.0, 32, 1), true}, - {"linear_attn_factor", "linear with attn_factor 0.9 and no correction: mscale = attn_factor", 64, - mk(T::Linear, B, 2.0, 0, O, 0, 0.9, 32, 1), true}, - {"yarn_2", "yarn factor 2 (setup.py default for 512K), ext 1, betas 32/1", 64, - mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, 1), true}, - {"yarn_1_5", "yarn factor 1.5 (setup.py default for 393216)", 64, - mk(T::YaRN, B, 1.5, 0, O, 1.0, 1.0, 32, 1), true}, - {"yarn_1", "yarn factor 1 (inside trained range): ramp active, mscale 1", 64, - mk(T::YaRN, B, 1.0, 0, O, 1.0, 1.0, 32, 1), true}, - {"yarn_4", "yarn factor 4 (1M context)", 64, mk(T::YaRN, B, 4.0, 0, O, 1.0, 1.0, 32, 1), true}, - {"yarn_2_betas", "yarn factor 2 with attn 1.1, betas 16/2", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.1, 16, 2), true}, - {"yarn_2_ext_half", "yarn factor 2 with ext_factor 0.5", 64, mk(T::YaRN, B, 2.0, 0, O, 0.5, 1.0, 32, 1), true}, - {"yarn_orig_131072", "yarn factor 4 against a 131072 trained context", 64, - mk(T::YaRN, B, 4.0, 0, 131072, 1.0, 1.0, 32, 1), true}, - {"yarn_ext0", "yarn type with ext_factor 0: correction off, behaves as linear", 64, - mk(T::YaRN, B, 2.0, 0, O, 0.0, 1.0, 32, 1), true}, - {"yarn_n_rot128", "yarn n_rot 128, base 1e6, orig 4096, factor 8", 128, - mk(T::YaRN, 1e6, 8.0, 0, 4096, 1.0, 1.0, 32, 1), true}, - {"yarn_n_rot4", "yarn n_rot 4: corr_dims clamps to n_rot-1", 4, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, 1), true}, - // invalid (finite) configurations: only the validity message and the scalar resolutions are recorded - {"bad_factor_below_1", "factor 0.5", 64, mk(T::Linear, B, 0.5, 0, O, 0, 1.0, 32, 1), false}, - {"bad_freq_base_1", "freq_base 1 (none)", 64, mk(T::None, 1.0, 1.0, 0, O, 0, 1.0, 32, 1), false}, - {"bad_orig_ctx_0", "orig_ctx 0", 64, mk(T::YaRN, B, 2.0, 0, 0.0, 1.0, 1.0, 32, 1), false}, - {"bad_ext_negative", "ext_factor -1", 64, mk(T::YaRN, B, 2.0, 0, O, -1.0, 1.0, 32, 1), false}, - {"bad_attn_0", "attn_factor 0", 64, mk(T::Linear, B, 2.0, 0, O, 0, 0.0, 32, 1), false}, - {"bad_beta_fast_0", "beta_fast 0", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 0, 1), false}, - {"bad_beta_slow_neg", "beta_slow -1", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, -1), false}, - {"bad_freq_scale_in_neg", "freq_scale_in -0.1", 64, mk(T::Linear, B, 2.0, -0.1, O, 0, 1.0, 32, 1), false}, - {"bad_mscale_negative", "freq_scale_in 1e6 with ext 1: the log term drives mscale negative", 64, - mk(T::YaRN, B, 2.0, 1e6, O, 1.0, 1.0, 32, 1), false}, - }; - - const int NMAX = 524288; - const int NS[2] = {262144, 524288}; - const int SAMPLE_POS[] = {0, 1, 2, 4095, 4096, 65535, 131071, 262143, 262144, 524287}; - const int AN_POS[] = {1, 4096, 262143, 524287}; - std::printf("{\n \"generator\": \"gen_rope_golden.cpp over rope_scaling.hpp + rope.cu build_rope_table (verbatim)\",\n"); - std::printf(" \"cases\": [\n"); - std::vector cs, sn; - for (size_t ci = 0; ci < cases.size(); ++ci) { - const Case& c = cases[ci]; - const RopeScaling& s = c.sc; - const int half = c.n_rot / 2; - std::printf(" {\n \"name\": \"%s\", \"desc\": \"%s\", \"n_rot\": %d,\n", c.name, c.desc, c.n_rot); - const char* tn = s.type == T::YaRN ? "yarn" : s.type == T::Linear ? "linear" : "none"; - std::printf(" \"type\": \"%s\",\n", tn); - std::printf(" \"freq_base\": \"%s\", \"factor\": \"%s\", \"freq_scale_in\": \"%s\", \"orig_ctx\": \"%s\",\n", - hex64(s.freq_base).c_str(), hex64(s.factor).c_str(), hex64(s.freq_scale_in).c_str(), - hex64(s.orig_ctx).c_str()); - std::printf(" \"ext_factor\": \"%s\", \"attn_factor\": \"%s\", \"beta_fast\": \"%s\", \"beta_slow\": \"%s\",\n", - hex64(s.ext_factor).c_str(), hex64(s.attn_factor).c_str(), hex64(s.beta_fast).c_str(), - hex64(s.beta_slow).c_str()); - const char* bad = rope_scaling_invalid(s); - if (bad) std::printf(" \"invalid\": \"%s\",\n", bad); - else std::printf(" \"invalid\": null,\n"); - std::printf(" \"freq_scale\": \"%s\", \"mscale\": \"%s\",\n", hex64(s.freq_scale()).c_str(), - hex64(s.mscale()).c_str()); - double cd[2]; - s.corr_dims(c.n_rot, cd); - std::printf(" \"corr_dims\": [\"%s\", \"%s\"],\n", hex64(cd[0]).c_str(), hex64(cd[1]).c_str()); - const RopeKernelArgs a = s.kernel_args(c.n_rot); - std::printf(" \"kernel_args\": {\"freq_scale\": \"%s\", \"corr_low\": \"%s\", \"corr_high\": \"%s\", " - "\"ext_factor\": \"%s\", \"attn_factor\": \"%s\"},\n", - hex32(a.freq_scale).c_str(), hex32(a.corr_low).c_str(), hex32(a.corr_high).c_str(), - hex32(a.ext_factor).c_str(), hex32(a.attn_factor).c_str()); - // analytic path (float32 rope_scaled_angle): theta_extrap = (float)(p * inv_i) - std::printf(" \"analytic\": ["); - bool first = true; - const int pairs[] = {0, 1, 7, 15, 16, 31}; - for (int pair : pairs) { - if (pair >= half) continue; - for (int p : AN_POS) { - const double inv = std::pow(s.freq_base, -2.0 * (double) pair / (double) c.n_rot); - const float te = (float) ((double) p * inv); - float co, si; - rope_scaled_angle(te, a.freq_scale, a.corr_low, a.corr_high, a.ext_factor, a.attn_factor, pair, co, si); - std::printf("%s\n {\"theta_extrap\": \"%s\", \"pair\": %d, \"cos\": \"%s\", \"sin\": \"%s\"}", - first ? "" : ",", hex32(te).c_str(), pair, hex32(co).c_str(), hex32(si).c_str()); - first = false; - } - } - std::printf("\n ]"); - if (c.tables) { - cs.assign((size_t) NMAX * half, 0.f); - sn.assign((size_t) NMAX * half, 0.f); - build_rope_table(c.n_rot, s, NMAX, cs.data(), sn.data()); - std::printf(",\n \"tables\": ["); - for (int k = 0; k < 2; ++k) - std::printf("%s\n {\"n_pos\": %d, \"cos_fnv1a64\": \"0x%016llx\", \"sin_fnv1a64\": \"0x%016llx\"}", - k ? "," : "", NS[k], (unsigned long long) fnv(cs.data(), (size_t) NS[k] * half), - (unsigned long long) fnv(sn.data(), (size_t) NS[k] * half)); - std::printf("\n ],\n \"rows\": ["); - for (size_t k = 0; k < sizeof SAMPLE_POS / sizeof *SAMPLE_POS; ++k) { - const int p = SAMPLE_POS[k]; - std::printf("%s\n {\"pos\": %d, \"cos\": [", k ? "," : "", p); - for (int i = 0; i < half; ++i) std::printf("%s\"%s\"", i ? "," : "", hex32(cs[(size_t) p * half + i]).c_str()); - std::printf("], \"sin\": ["); - for (int i = 0; i < half; ++i) std::printf("%s\"%s\"", i ? "," : "", hex32(sn[(size_t) p * half + i]).c_str()); - std::printf("]}"); - } - std::printf("\n ]"); - } - std::printf("\n }%s\n", ci + 1 < cases.size() ? "," : ""); - } - std::printf(" ]\n}\n"); - return 0; -} diff --git a/crates/context/tests/rope_plan_golden/gen_rope_golden.sh b/crates/context/tests/rope_plan_golden/gen_rope_golden.sh deleted file mode 100755 index 78b9b6d5..00000000 --- a/crates/context/tests/rope_plan_golden/gen_rope_golden.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -# Regenerates rope_golden.json from the Original's host code (macOS or Linux, any C++17 compiler). -# usage: gen_rope_golden.sh [extra compiler flags] -# The committed fixture is built with -O2 -ffp-contract=off (Rust never fuses multiply-adds) and -# -fno-builtin-sinf/-cosf: Apple clang otherwise merges a sinf+cosf pair into __sincosf_stret, whose sinf -# differs from a separate sinf call by 1-2 ULP, and Rust (like the CUDA device code) calls them separately. -# Only the float32 analytic path is affected; the float64 tables are identical either way. -set -eu -here=$(cd "$(dirname "$0")" && pwd) -strata="$here/../../../../engine/strata" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -# extract the two build_rope_table definitions from rope.cu verbatim (up to the next anonymous namespace) -awk '/^void build_rope_table\(int n_rot, double theta/ {on=1} on && /^namespace \{/ {exit} on {print}' \ - "$strata/src/kernels/cuda/rope.cu" > "$work/rope_table_original.inc" -test -s "$work/rope_table_original.inc" -${CXX:-clang++} -std=c++17 -O2 -ffp-contract=off -fno-builtin-sinf -fno-builtin-cosf "$@" -I"$strata/include" -I"$work" \ - "$here/gen_rope_golden.cpp" -o "$work/gen_rope_golden" -"$work/gen_rope_golden" > "$here/rope_golden.json" diff --git a/crates/cuda-driver/oracle/check_cu_syntax.sh b/crates/cuda-driver/oracle/check_cu_syntax.sh deleted file mode 100755 index 00318600..00000000 --- a/crates/cuda-driver/oracle/check_cu_syntax.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -# Syntax-check ported .cu files without nvcc. Superseded by the unified stub set under scripts/cuda-stubs/ (clang's CUDA -# frontend against stub headers; covers every .cu, not only the ones the host shim can execute). The EXECUTING emulation -# (shim/cuda_host_shim.h, run_shim_oracles.sh) is a different tool and stays. -# usage: check_cu_syntax.sh [file.cu ...] (no argument: every crates/cuda-driver/src/*.cu) -here=$(cd "$(dirname "$0")" && pwd) -exec python3 "$here/../../../scripts/cuda-stubs/check-cu.py" "$@" diff --git a/crates/cuda-driver/oracle/drivers/prefill_ring_trace.cpp b/crates/cuda-driver/oracle/drivers/prefill_ring_trace.cpp deleted file mode 100644 index 47368295..00000000 --- a/crates/cuda-driver/oracle/drivers/prefill_ring_trace.cpp +++ /dev/null @@ -1,463 +0,0 @@ -// GENERATED by oracle/gen_prefill_ring_trace.py from engine/strata/src/prefill/prefill.cpp -// (sha256 1d18288208debcf1d26021ed8bdfc2633db6dcbd88d899c76d1f628b57838c91). The code between the VERBATIM markers is copied from that file (lines 1170-1228, 1279-1287, 1692-1743, 1806-1853); -// everything else stubs the cuda* calls and records them. Issue is inline (STRATA_PREFILL_ISSUER=0): the threaded issuer -// makes the same copy-stream calls in the same order, gated by the same consumed + ring rule. -#include -#include -#include -#include -#include -#include -#include -#include -#include -using cudaStream_t = int; -using cudaEvent_t = int; -enum { cudaMemcpyHostToDevice = 1, cudaSuccess = 0 }; -constexpr int STAGE = 8, RING_MAX = 512, DQ = 2; -static std::vector g_ops; -static void op(const std::string& s) { g_ops.push_back(s); } -static const char* sname(cudaStream_t s) { return s == 1 ? "C" : "K"; } -static int slot_of_dev(const void* p) { return (int) (((uintptr_t) p - 0x10000000u) / 0x1000u); } -static std::string src_of_host(const void* p) { - const uintptr_t v = (uintptr_t) p; - if (v >= 0x40000000u) return "stage " + std::to_string((v - 0x40000000u) / 0x1000u); - return "blob " + std::to_string((v - 0x20000000u) / 0x10000u) + " " + std::to_string(((v - 0x20000000u) % 0x10000u) / 0x10u); -} -static int cudaMemcpyAsync(void* dst, const void* src, size_t, int, cudaStream_t s) { - op(std::string(sname(s)) + " h2d " + std::to_string(slot_of_dev(dst)) + " " + src_of_host(src)); - return 0; -} -static std::string ev_name(cudaEvent_t e) { - if (e >= 4000) return "ple_copied " + std::to_string(e - 4000); - if (e >= 3000) return "dma " + std::to_string(e - 3000); - return (e >= 2000 ? "used " + std::to_string(e - 2000) : "copied " + std::to_string(e - 1000)); -} -static int cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned) { op(std::string(sname(s)) + " wait " + ev_name(e)); return 0; } -static int cudaEventRecord(cudaEvent_t e, cudaStream_t s) { op(std::string(sname(s)) + " record " + ev_name(e)); return 0; } -struct Clock { struct time_point {}; static time_point now() { return {}; } }; -static double ms_since(Clock::time_point) { return 0.0; } -struct ExpertLayoutStub { size_t blob_bytes(int64_t) const { return 4096; } }; -namespace strata { namespace kernels { namespace cpu { -using ExpertLayout = ExpertLayoutStub; -inline const ExpertLayout& expert_layout() { static ExpertLayout l; return l; } -} } } -struct ModelGeom { int64_t n_expert; int64_t n_layers; }; -struct Scenario { - const char* name; - int n_layers, n_expert, lb, le, ring, stager_ring; - int64_t T; // rows of the chunk (stream_all needs T >= 1024) - std::vector> orders; // per layer in [lb, le): routed experts, ascending - int resident_mod, resident_rem; // cache-resident when e % mod == rem (mod 0: none) - bool cache_present; - int pinned_mod, transient_mod; // pinned: e % pinned_mod == 0; transient: (e+l) % transient_mod == 0 - int chunks; -}; -static const Scenario* g_sc = nullptr; -struct Src { - bool pinned(int64_t, int64_t e) const { return g_sc->pinned_mod != 0 && e % g_sc->pinned_mod == 0; } - bool transient(int64_t l, int64_t e) const { return !pinned(l, e) && g_sc->transient_mod != 0 && (e + l) % g_sc->transient_mod == 0; } - const uint8_t* blob(int64_t l, int64_t e) const { return (const uint8_t*) (0x20000000u + (uintptr_t) l * 0x10000u + (uintptr_t) e * 0x10u); } -}; -struct Stager { - struct Job { const uint8_t* src; size_t bytes; Src* from = nullptr; int32_t l = 0, e = 0; }; - int kRing = 16; - void start(std::vector&& js) { - if (js.empty()) return; // Stager::start - std::string d = "H stager_start"; - for (auto& j : js) d += j.from ? " T" + std::to_string(j.l) + "." + std::to_string(j.e) : " U"; - op(d + " n=" + std::to_string(js.size())); - } - const uint8_t* wait(int j) { op("H stager_wait " + std::to_string(j)); return (const uint8_t*) (0x40000000u + (uintptr_t) (j % kRing) * 0x1000u); } - void issued_one(int j, cudaStream_t copy) { cudaEventRecord(3000 + j % kRing, copy); } - void finish() { op("H stager_finish"); } -}; -struct Cache { const uint8_t* device_slot(int s) const { return (const uint8_t*) (0x50000000u + (uintptr_t) s * 0x1000u); } }; -struct Stats { int64_t experts_dma = 0, experts_streamed = 0, experts_resident = 0; double ms_experts_host = 0, ms_ple = 0; }; -constexpr int64_t N = 2560; -struct PT { void mark(int, cudaStream_t) {} }; -enum { kPfWaitCopy = 0, kPfDequant = 1 }; -inline int64_t stream_all_min() { return 1024; } -// ---- PLE read-ahead stubs -#include -static std::string ple_buf_of(const void* p, uintptr_t base) { return std::to_string(((uintptr_t) p - base) / 0x1000u); } -static int cudaMemcpyAsync(float* dst, const float* src, size_t, int, cudaStream_t) { - (void) dst; - op("K upload ple_emb " + ple_buf_of(src, 0x60000000u)); - return 0; -} -static int cudaEventSynchronize(cudaEvent_t e) { op("H sync ple_copied " + std::to_string(e - 4000)); return 0; } -template static std::future shim_async(F f) { op("H ple_async"); return std::async(std::launch::deferred, f); } -struct PleTable { - bool gather_batch_device(const uint32_t*, size_t, float*, cudaStream_t, std::string&) { op("K ple_gather_device"); return true; } -}; -struct PleState { PleTable* table; }; -struct SessionStub { struct { PleTable* table; } ple; }; -struct Impl { - Src* src = nullptr; const Cache* cache = nullptr; const int32_t* host_res = nullptr; const ModelGeom* g = nullptr; - int ring = STAGE; cudaStream_t cs = 2, copy = 1; - std::unique_ptr stager; - uint8_t* stage_dev[RING_MAX] = {}; - cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {}; - bool stage_live[RING_MAX] = {}; - float* ple_emb = nullptr; - float* ple_emb_host[2] = {}; - cudaEvent_t ple_copied[2] = {}; - std::vector ple_rows[2]; - int64_t T = 0; -}; - -static void run_scenario(const Scenario& sc) { - g_sc = ≻ - g_ops.clear(); - Impl m; - ModelGeom geom{sc.n_expert, sc.n_layers}; - const ModelGeom& g = geom; - Src src_obj; Cache cache_obj; - m.src = &src_obj; - m.g = &geom; - m.ring = sc.ring; - m.stager.reset(new Stager()); - m.stager->kRing = sc.stager_ring; - for (int i = 0; i < RING_MAX; ++i) { - m.stage_dev[i] = (uint8_t*) (0x10000000u + (uintptr_t) i * 0x1000u); - m.copied[i] = 1000 + i; m.used[i] = 2000 + i; - } - std::vector host_res_table((size_t) sc.n_layers * sc.n_expert, -1); - if (sc.cache_present) { - int next_slot = 0; - for (int l = 0; l < sc.n_layers; ++l) - for (int e = 0; e < sc.n_expert; ++e) - if (sc.resident_mod != 0 && e % sc.resident_mod == sc.resident_rem) host_res_table[(size_t) l * sc.n_expert + e] = next_slot++; - m.host_res = host_res_table.data(); - m.cache = &cache_obj; - } - Stats stats_; - PT pt; - cudaStream_t cs = m.cs; - const int64_t LB = sc.lb, LE = sc.le, T = sc.T; - std::string err; - for (int chunk = 0; chunk < sc.chunks; ++chunk) { - op("H chunk " + std::to_string(chunk)); - auto chunk_fn = [&]() -> bool { -// ---- VERBATIM prefill.cpp (sequence, issue_until) ---- - const strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout(); - const bool stream_all = m.ring > STAGE && T >= stream_all_min() && m.src != nullptr; - struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; }; - std::vector seq; - std::vector seq_start; - size_t issued = 0, consumed = 0; - if (stream_all) { - seq_start.assign((size_t) g.n_layers + 1, 0); - std::vector js; - for (int64_t l = LB; l < LE; ++l) { - seq_start[(size_t) l] = seq.size(); - for (int32_t e = 0; e < m.g->n_expert; ++e) { - if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue; - int job = -1; - const uint8_t* b = nullptr; - if (m.src->transient(l, e)) { // CS-T: copied by the source into the stager's buffer - job = (int) js.size(); - js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e}); - } else { - b = m.src->blob(l, e); - if (!b) { err = "prefill: expert source has no blob"; return false; } - if (!m.src->pinned(l, e)) { - job = (int) js.size(); - js.push_back({b, (size_t) lay0.blob_bytes(l)}); - } - } - seq.push_back({(int32_t) l, e, b, job}); - } - } - for (int64_t l = LE; l <= g.n_layers; ++l) seq_start[(size_t) l] = seq.size(); - m.stager->start(std::move(js)); - } - struct StagerDone { - Stager* st; - ~StagerDone() { if (st) st->finish(); } - } chunk_stager_done{stream_all ? m.stager.get() : nullptr}; - auto issue_until = [&](size_t limit) { - limit = std::min(limit, seq.size()); - while (issued < limit) { - const StreamEntry& en = seq[issued]; - const int sl = (int) (issued % (size_t) m.ring); - const auto th = Clock::now(); - const size_t bytes = (size_t) lay0.blob_bytes(en.l); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); - if (en.job < 0) { - cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy); - ++stats_.experts_dma; - } else { - const uint8_t* hb = m.stager->wait(en.job); - cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy); - m.stager->issued_one(en.job, m.copy); - } - cudaEventRecord(m.copied[sl], m.copy); - m.stage_live[sl] = true; - stats_.ms_experts_host += ms_since(th); - ++stats_.experts_streamed; - ++issued; - } - }; -// ---- end VERBATIM ---- - const bool threaded_issue = false; - std::atomic a_issued{0}, a_consumed{0}; -// ---- VERBATIM prefill.cpp (wait_issued, give_back) ---- - // the consumer's side: entry k's copy is on the copy stream (the thread issued it), then k is given back - auto wait_issued = [&](size_t k) { - if (!threaded_issue) return; - while (a_issued.load(std::memory_order_acquire) <= k) std::this_thread::yield(); - }; - auto give_back = [&](size_t upto) { - if (threaded_issue) a_consumed.store(upto, std::memory_order_release); - else issue_until(upto + (size_t) m.ring); - }; -// ---- end VERBATIM ---- - if (stream_all) issue_until((size_t) m.ring); // prefill.cpp: else if (stream_all) { issue_until((size_t) m.ring); } - for (int64_t l = LB; l < LE; ++l) { - const std::vector& order = sc.orders[(size_t) (l - LB)]; - op("H layer " + std::to_string(l)); - const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); -// ---- VERBATIM prefill.cpp (staging setup, stage_one) ---- - // Stage ahead: the copy stream moves blobs host -> device while the compute stream works. - int stage_next = 0; - std::vector stage_of(order.size(), -1); - // the unpinned ones are copied to pinned buffers by the stager's threads, in this order - std::vector job_of(order.size(), -1); - if (!stream_all) { - std::vector js; - for (size_t j = 0; j < order.size(); ++j) { - const int32_t e = order[j]; - if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue; - if (m.src->pinned(l, e)) continue; - job_of[j] = (int) js.size(); - if (m.src->transient(l, e)) { // CS-T: copied by the source - js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e}); - continue; - } - const uint8_t* b = m.src->blob(l, e); - if (!b) { err = "prefill: expert source has no blob"; return false; } - js.push_back({b, (size_t) lay.blob_bytes(l)}); - } - m.stager->start(std::move(js)); - } - StagerDone stager_done{stream_all ? nullptr : m.stager.get()}; - auto stage_one = [&](size_t j) -> bool { - const int32_t e = order[j]; - const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0; - if (resident) return true; - const int sl = stage_next; - stage_next = (stage_next + 1) % STAGE; - const auto th = Clock::now(); - const bool pinned = m.src->pinned(l, e); // pinned: never transient - const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr; - if (pinned && !b) { err = "prefill: expert source has no blob"; return false; } - if (pinned) { - // DMA straight from the page-locked arena: the copy stream only waits for the slot - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); - cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy); - ++stats_.experts_dma; - } else { - // copied to a pinned buffer by the stager (waits only if it is behind), then DMA - const uint8_t* hb = m.stager->wait(job_of[j]); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); - cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy); - m.stager->issued_one(job_of[j], m.copy); - } - cudaEventRecord(m.copied[sl], m.copy); - m.stage_live[sl] = true; - stage_of[j] = sl; - stats_.ms_experts_host += ms_since(th); - ++stats_.experts_streamed; - return true; - }; -// ---- end VERBATIM ---- - auto compute = [&](size_t j, const uint8_t*, int slot) -> bool { - op("K compute " + std::to_string(order[j]) + " " + (slot >= 0 ? std::to_string(slot) : std::string("-"))); - if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); // prefill.cpp: after the gather / dequant read of the blob - return true; - }; -// ---- VERBATIM prefill.cpp (the walks) ---- - if (!stream_all) { - size_t staged = 0; - const size_t lookahead = STAGE - 1; - for (size_t j = 0; j < order.size(); ++j) { - while (staged < order.size() && staged <= j + lookahead) { - if (!stage_one(staged)) return false; - ++staged; - } - const int32_t e = order[j]; - if (stage_of[j] < 0) { - ++stats_.experts_resident; - if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false; - } else { - pt.mark(kPfWaitCopy, cs); - cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0); - if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false; - } - } - } else { - // the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not - // pick only gives its slot back - size_t k = seq_start[(size_t) l]; - const size_t kend = seq_start[(size_t) l + 1]; - auto release_to = [&](int32_t e_stop) { - while (k < kend && seq[k].e < e_stop) { - cudaEventRecord(m.used[k % (size_t) m.ring], m.cs); - consumed = ++k; - give_back(consumed); - } - }; - for (size_t j = 0; j < order.size(); ++j) { - const int32_t e = order[j]; - release_to(e); - if (k < kend && seq[k].e == e) { - const int sl = (int) (k % (size_t) m.ring); - pt.mark(kPfWaitCopy, cs); - wait_issued(k); - cudaStreamWaitEvent(m.cs, m.copied[sl], 0); - if (!compute(j, m.stage_dev[sl], sl)) return false; - consumed = ++k; - give_back(consumed); - } else { - ++stats_.experts_resident; - if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false; - } - } - release_to(m.g->n_expert); - } -// ---- end VERBATIM ---- - op("K combine"); - } - return true; - }; - if (!chunk_fn()) { std::fprintf(stderr, "scenario %s failed: %s\n", sc.name, err.c_str()); std::exit(2); } - } - std::printf("{\"name\":\"%s\",\"p\":{\"n_layers\":%d,\"n_expert\":%d,\"lb\":%d,\"le\":%d,\"ring\":%d,\"stager_ring\":%d,\"rows\":%lld," - "\"resident_mod\":%d,\"resident_rem\":%d,\"cache_present\":%d,\"pinned_mod\":%d,\"transient_mod\":%d,\"chunks\":%d,\"orders\":[", - sc.name, sc.n_layers, sc.n_expert, sc.lb, sc.le, sc.ring, sc.stager_ring, (long long) T, sc.resident_mod, sc.resident_rem, - (int) sc.cache_present, sc.pinned_mod, sc.transient_mod, sc.chunks); - for (size_t li = 0; li < sc.orders.size(); ++li) { - std::printf("%s[", li ? "," : ""); - for (size_t k = 0; k < sc.orders[li].size(); ++k) std::printf("%s%d", k ? "," : "", sc.orders[li][k]); - std::printf("]"); - } - std::printf("]},\"stats\":[%lld,%lld,%lld],\"ops\":[", (long long) stats_.experts_dma, (long long) stats_.experts_streamed, (long long) stats_.experts_resident); - for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str()); - std::printf("]}"); -} - -struct PleScenario { const char* name; int64_t n, T; bool gpu_cache; }; -static void run_ple_scenario(const PleScenario& sc) { - g_ops.clear(); - Impl m; - m.T = sc.T; - PleTable table; - SessionStub ss; - ss.ple.table = &table; - for (int b = 0; b < 2; ++b) { m.ple_emb_host[b] = (float*) (0x60000000u + (uintptr_t) b * 0x1000u); m.ple_copied[b] = 4000 + b; m.ple_rows[b].assign(4, 0); } - m.ple_emb = (float*) 0x70000000u; - Stats stats_; - std::string err; - const int64_t n = sc.n; - const bool ple_on = true, ple_gpu_cache = sc.gpu_cache; - std::string ple_next_err; - std::future ple_next; - int ple_buf = 0; - auto ple_gather = [&](int64_t c0, int buf, std::string&) -> bool { op("H ple_gather " + std::to_string(c0) + " " + std::to_string(buf)); return true; }; - for (int64_t c0 = 0; c0 < n; c0 += m.T) { - const int64_t T = std::min(m.T, n - c0); - op("H ple_chunk " + std::to_string(c0)); - cudaStream_t cs = 2; (void) cs; - auto ple_fn = [&]() -> bool { -// ---- VERBATIM prefill.cpp (the PLE row read-ahead) ---- - if (ple_on) { - const auto tp = Clock::now(); - if (ple_gpu_cache) { - if (!ple_gather(c0, 0, err) || - !ss.ple.table->gather_batch_device(m.ple_rows[0].data(), (size_t) T, - m.ple_emb, m.cs, err)) return false; - } else if (!ple_next.valid()) { - if (!ple_gather(c0, ple_buf, err)) return false; - } else if (!ple_next.get()) { - err = ple_next_err; - return false; - } - if (!ple_gpu_cache) { - cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs); - cudaEventRecord(m.ple_copied[ple_buf], m.cs); - if (c0 + m.T < n) { - cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]); // the other buffer's upload (a chunk ago) is done - ple_next = shim_async( [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] { - return ple_gather(c1, b, ple_next_err); - }); - } - ple_buf ^= 1; - } - stats_.ms_ple += ms_since(tp); - } -// ---- end VERBATIM ---- - return true; - }; - if (!ple_fn()) { std::fprintf(stderr, "ple scenario failed\n"); std::exit(2); } - } - std::printf("{\"name\":\"%s\",\"ple\":[%lld,%lld,%d],\"ops\":[", sc.name, (long long) sc.n, (long long) sc.T, (int) sc.gpu_cache); - for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str()); - std::printf("]}"); -} - -// ---- the GR write fusion decision of one half -namespace strata { namespace kernels { struct CvecStub { bool cover; bool covers(int64_t) const { return cover; } }; inline CvecStub& cvec() { static CvecStub c; return c; } } } -static bool g_gr_unfused = false; -static bool gr_unfused() { return g_gr_unfused; } -static bool fuse_of(int64_t l, int half, int64_t LE, bool ple_on, bool unfused, bool cvec_covers) { - g_gr_unfused = unfused; - strata::kernels::cvec().cover = cvec_covers; - const int64_t nl = half == 0 ? l : l + 1; - const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && - !(half == 1 && strata::kernels::cvec().covers(l)); - return fuse; -} - -static std::vector iota_vec(int n, int step = 1, int from = 0) { - std::vector v; - for (int i = from; i < n; i += step) v.push_back(i); - return v; -} -int main() { - std::vector sc; - // fields: name, n_layers, n_expert, lb, le, ring, stager_ring, T, orders, resident_mod, resident_rem, cache_present, pinned_mod, transient_mod, chunks - sc.push_back({"stream_basic", 6, 24, 1, 4, 16, 16, 1024, - {iota_vec(24, 2), iota_vec(24, 3, 1), {0, 1, 2, 5, 23}}, 5, 0, true, 3, 4, 2}); - sc.push_back({"stream_ring_wrap", 4, 40, 0, 3, 16, 16, 2048, - {iota_vec(40), iota_vec(40), iota_vec(40, 7)}, 0, 0, true, 2, 0, 2}); - sc.push_back({"stream_no_cache_all_pinned", 3, 20, 0, 3, 16, 16, 1024, - {iota_vec(20), iota_vec(20, 2), {19}}, 0, 0, false, 1, 0, 1}); - sc.push_back({"stream_sparse_release", 5, 40, 1, 4, 16, 4, 4096, - {{39}, {0}, {5, 6, 7, 30}}, 0, 0, true, 5, 3, 2}); - sc.push_back({"staged_under_threshold", 4, 32, 0, 3, 384, 16, 512, - {iota_vec(32), iota_vec(32, 3), {2, 4}}, 4, 1, true, 3, 5, 2}); - sc.push_back({"staged_ring8", 3, 12, 0, 2, 8, 16, 4096, - {iota_vec(12), iota_vec(12, 2)}, 0, 0, false, 2, 3, 1}); - sc.push_back({"staged_few_experts", 3, 10, 0, 2, 16, 16, 100, - {{1, 3, 4}, {9}}, 3, 0, true, 0, 0, 1}); - std::printf("{\"ring\":["); - for (size_t i = 0; i < sc.size(); ++i) { if (i) std::printf(",\n"); run_scenario(sc[i]); } - std::printf("],\n"); - std::vector ples = {{"ple_two_chunks_gather", 2000, 1024, false}, {"ple_single_chunk", 100, 256, false}, - {"ple_gpu_cache", 3000, 1024, true}, {"ple_four_chunks", 4096, 1024, false}, - {"ple_exact_multiple", 2048, 1024, false}}; - std::printf("\"ple\":["); - for (size_t i = 0; i < ples.size(); ++i) { if (i) std::printf(",\n"); run_ple_scenario(ples[i]); } - std::printf("],\n\"fuse\":["); - bool first = true; - for (int le : {48, 16}) for (int ple_on = 0; ple_on < 2; ++ple_on) for (int unfused = 0; unfused < 2; ++unfused) - for (int cv = 0; cv < 2; ++cv) for (int l : {0, 1, 2, 14, 15, 46, 47}) for (int half = 0; half < 2; ++half) { - if (l >= le) continue; - std::printf("%s[%d,%d,%d,%d,%d,%d,%d]", first ? "" : ",", le, ple_on, unfused, cv, l, half, (int) fuse_of(l, half, le, ple_on != 0, unfused != 0, cv != 0)); - first = false; - } - std::printf("]}\n"); - return 0; -} diff --git a/crates/cuda-driver/oracle/gen_prefill_ring_trace.py b/crates/cuda-driver/oracle/gen_prefill_ring_trace.py deleted file mode 100644 index fe07b3da..00000000 --- a/crates/cuda-driver/oracle/gen_prefill_ring_trace.py +++ /dev/null @@ -1,321 +0,0 @@ -#!/usr/bin/env python3 -"""Builds drivers/prefill_ring_trace.cpp by EXTRACTING the expert-stream scheduling code of the Original -engine/strata/src/prefill/prefill.cpp (the sequence builder + issue_until, wait_issued / give_back, the staged -stage_one lambda, and the two per-layer expert walks) verbatim between textual markers, wrapped in a host harness whose -cuda* calls only append to a trace. usage: gen_prefill_ring_trace.py [prefill.cpp] > drivers/prefill_ring_trace.cpp -The trace line format is the golden-fixture format read by original_prefill_schedule.rs.""" -import hashlib, os, sys - -here = os.path.dirname(os.path.abspath(__file__)) -path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(here, '../../../engine/strata/src/prefill/prefill.cpp') -text = open(path).read() -lines = text.split('\n') - -def find(marker, start=0): - for i in range(start, len(lines)): - if marker in lines[i]: - return i - raise SystemExit('marker not found: ' + marker) - -def cut(first, last_exclusive, start=0): - a = find(first, start) - b = find(last_exclusive, a + 1) - return '\n'.join(lines[a:b]), a + 1, b - -seq_build, a1, b1 = cut('const strata::kernels::cpu::ExpertLayout& lay0', '// D-5: the stream is issued by its own host thread') -consumer, a2, b2 = cut("// the consumer's side:", 'host_setup_ms += ms_since(tsetup);') -staged, a3, b3 = cut('// Stage ahead: the copy stream moves blobs host -> device', "// one expert's products from its blob on the device") -w_first = find('auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool {') -a4 = find('if (!stream_all) {', w_first) -b4 = find('pt.mark(kPfCombine, cs);', a4) -walks = '\n'.join(lines[a4:b4]) -ple_a = find('// ---- the PLE rows of the whole chunk') -ple_first = find('if (ple_on) {', ple_a) -ple_last = find('for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1];', ple_first) -ple_block = '\n'.join(lines[ple_first:ple_last]) -assert 'std::async(std::launch::async,' in ple_block -ple_block = ple_block.replace('std::async(std::launch::async,', 'shim_async(') # the one documented edit: deferred, logged -fuse_a = find('const int64_t nl = half == 0 ? l : l + 1;') -fuse_b = find('const core::WeightRef* wnn = nullptr;', fuse_a) -fuse_block = '\n'.join(lines[fuse_a:fuse_b]) -digest = hashlib.sha256(text.encode()).hexdigest() - -template = r'''// GENERATED by oracle/gen_prefill_ring_trace.py from engine/strata/src/prefill/prefill.cpp -// (sha256 __DIGEST__). The code between the VERBATIM markers is copied from that file (lines __R1__, __R2__, __R3__, __R4__); -// everything else stubs the cuda* calls and records them. Issue is inline (STRATA_PREFILL_ISSUER=0): the threaded issuer -// makes the same copy-stream calls in the same order, gated by the same consumed + ring rule. -#include -#include -#include -#include -#include -#include -#include -#include -#include -using cudaStream_t = int; -using cudaEvent_t = int; -enum { cudaMemcpyHostToDevice = 1, cudaSuccess = 0 }; -constexpr int STAGE = 8, RING_MAX = 512, DQ = 2; -static std::vector g_ops; -static void op(const std::string& s) { g_ops.push_back(s); } -static const char* sname(cudaStream_t s) { return s == 1 ? "C" : "K"; } -static int slot_of_dev(const void* p) { return (int) (((uintptr_t) p - 0x10000000u) / 0x1000u); } -static std::string src_of_host(const void* p) { - const uintptr_t v = (uintptr_t) p; - if (v >= 0x40000000u) return "stage " + std::to_string((v - 0x40000000u) / 0x1000u); - return "blob " + std::to_string((v - 0x20000000u) / 0x10000u) + " " + std::to_string(((v - 0x20000000u) % 0x10000u) / 0x10u); -} -static int cudaMemcpyAsync(void* dst, const void* src, size_t, int, cudaStream_t s) { - op(std::string(sname(s)) + " h2d " + std::to_string(slot_of_dev(dst)) + " " + src_of_host(src)); - return 0; -} -static std::string ev_name(cudaEvent_t e) { - if (e >= 4000) return "ple_copied " + std::to_string(e - 4000); - if (e >= 3000) return "dma " + std::to_string(e - 3000); - return (e >= 2000 ? "used " + std::to_string(e - 2000) : "copied " + std::to_string(e - 1000)); -} -static int cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned) { op(std::string(sname(s)) + " wait " + ev_name(e)); return 0; } -static int cudaEventRecord(cudaEvent_t e, cudaStream_t s) { op(std::string(sname(s)) + " record " + ev_name(e)); return 0; } -struct Clock { struct time_point {}; static time_point now() { return {}; } }; -static double ms_since(Clock::time_point) { return 0.0; } -struct ExpertLayoutStub { size_t blob_bytes(int64_t) const { return 4096; } }; -namespace strata { namespace kernels { namespace cpu { -using ExpertLayout = ExpertLayoutStub; -inline const ExpertLayout& expert_layout() { static ExpertLayout l; return l; } -} } } -struct ModelGeom { int64_t n_expert; int64_t n_layers; }; -struct Scenario { - const char* name; - int n_layers, n_expert, lb, le, ring, stager_ring; - int64_t T; // rows of the chunk (stream_all needs T >= 1024) - std::vector> orders; // per layer in [lb, le): routed experts, ascending - int resident_mod, resident_rem; // cache-resident when e %% mod == rem (mod 0: none) - bool cache_present; - int pinned_mod, transient_mod; // pinned: e %% pinned_mod == 0; transient: (e+l) %% transient_mod == 0 - int chunks; -}; -static const Scenario* g_sc = nullptr; -struct Src { - bool pinned(int64_t, int64_t e) const { return g_sc->pinned_mod != 0 && e %% g_sc->pinned_mod == 0; } - bool transient(int64_t l, int64_t e) const { return !pinned(l, e) && g_sc->transient_mod != 0 && (e + l) %% g_sc->transient_mod == 0; } - const uint8_t* blob(int64_t l, int64_t e) const { return (const uint8_t*) (0x20000000u + (uintptr_t) l * 0x10000u + (uintptr_t) e * 0x10u); } -}; -struct Stager { - struct Job { const uint8_t* src; size_t bytes; Src* from = nullptr; int32_t l = 0, e = 0; }; - int kRing = 16; - void start(std::vector&& js) { - if (js.empty()) return; // Stager::start - std::string d = "H stager_start"; - for (auto& j : js) d += j.from ? " T" + std::to_string(j.l) + "." + std::to_string(j.e) : " U"; - op(d + " n=" + std::to_string(js.size())); - } - const uint8_t* wait(int j) { op("H stager_wait " + std::to_string(j)); return (const uint8_t*) (0x40000000u + (uintptr_t) (j %% kRing) * 0x1000u); } - void issued_one(int j, cudaStream_t copy) { cudaEventRecord(3000 + j %% kRing, copy); } - void finish() { op("H stager_finish"); } -}; -struct Cache { const uint8_t* device_slot(int s) const { return (const uint8_t*) (0x50000000u + (uintptr_t) s * 0x1000u); } }; -struct Stats { int64_t experts_dma = 0, experts_streamed = 0, experts_resident = 0; double ms_experts_host = 0, ms_ple = 0; }; -constexpr int64_t N = 2560; -struct PT { void mark(int, cudaStream_t) {} }; -enum { kPfWaitCopy = 0, kPfDequant = 1 }; -inline int64_t stream_all_min() { return 1024; } -// ---- PLE read-ahead stubs -#include -static std::string ple_buf_of(const void* p, uintptr_t base) { return std::to_string(((uintptr_t) p - base) / 0x1000u); } -static int cudaMemcpyAsync(float* dst, const float* src, size_t, int, cudaStream_t) { - (void) dst; - op("K upload ple_emb " + ple_buf_of(src, 0x60000000u)); - return 0; -} -static int cudaEventSynchronize(cudaEvent_t e) { op("H sync ple_copied " + std::to_string(e - 4000)); return 0; } -template static std::future shim_async(F f) { op("H ple_async"); return std::async(std::launch::deferred, f); } -struct PleTable { - bool gather_batch_device(const uint32_t*, size_t, float*, cudaStream_t, std::string&) { op("K ple_gather_device"); return true; } -}; -struct PleState { PleTable* table; }; -struct SessionStub { struct { PleTable* table; } ple; }; -struct Impl { - Src* src = nullptr; const Cache* cache = nullptr; const int32_t* host_res = nullptr; const ModelGeom* g = nullptr; - int ring = STAGE; cudaStream_t cs = 2, copy = 1; - std::unique_ptr stager; - uint8_t* stage_dev[RING_MAX] = {}; - cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {}; - bool stage_live[RING_MAX] = {}; - float* ple_emb = nullptr; - float* ple_emb_host[2] = {}; - cudaEvent_t ple_copied[2] = {}; - std::vector ple_rows[2]; - int64_t T = 0; -}; - -static void run_scenario(const Scenario& sc) { - g_sc = ≻ - g_ops.clear(); - Impl m; - ModelGeom geom{sc.n_expert, sc.n_layers}; - const ModelGeom& g = geom; - Src src_obj; Cache cache_obj; - m.src = &src_obj; - m.g = &geom; - m.ring = sc.ring; - m.stager.reset(new Stager()); - m.stager->kRing = sc.stager_ring; - for (int i = 0; i < RING_MAX; ++i) { - m.stage_dev[i] = (uint8_t*) (0x10000000u + (uintptr_t) i * 0x1000u); - m.copied[i] = 1000 + i; m.used[i] = 2000 + i; - } - std::vector host_res_table((size_t) sc.n_layers * sc.n_expert, -1); - if (sc.cache_present) { - int next_slot = 0; - for (int l = 0; l < sc.n_layers; ++l) - for (int e = 0; e < sc.n_expert; ++e) - if (sc.resident_mod != 0 && e %% sc.resident_mod == sc.resident_rem) host_res_table[(size_t) l * sc.n_expert + e] = next_slot++; - m.host_res = host_res_table.data(); - m.cache = &cache_obj; - } - Stats stats_; - PT pt; - cudaStream_t cs = m.cs; - const int64_t LB = sc.lb, LE = sc.le, T = sc.T; - std::string err; - for (int chunk = 0; chunk < sc.chunks; ++chunk) { - op("H chunk " + std::to_string(chunk)); - auto chunk_fn = [&]() -> bool { -// ---- VERBATIM prefill.cpp (sequence, issue_until) ---- -__SEQ_BUILD__ -// ---- end VERBATIM ---- - const bool threaded_issue = false; - std::atomic a_issued{0}, a_consumed{0}; -// ---- VERBATIM prefill.cpp (wait_issued, give_back) ---- -__CONSUMER__ -// ---- end VERBATIM ---- - if (stream_all) issue_until((size_t) m.ring); // prefill.cpp: else if (stream_all) { issue_until((size_t) m.ring); } - for (int64_t l = LB; l < LE; ++l) { - const std::vector& order = sc.orders[(size_t) (l - LB)]; - op("H layer " + std::to_string(l)); - const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); -// ---- VERBATIM prefill.cpp (staging setup, stage_one) ---- -__STAGED__ -// ---- end VERBATIM ---- - auto compute = [&](size_t j, const uint8_t*, int slot) -> bool { - op("K compute " + std::to_string(order[j]) + " " + (slot >= 0 ? std::to_string(slot) : std::string("-"))); - if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); // prefill.cpp: after the gather / dequant read of the blob - return true; - }; -// ---- VERBATIM prefill.cpp (the walks) ---- -__WALKS__ -// ---- end VERBATIM ---- - op("K combine"); - } - return true; - }; - if (!chunk_fn()) { std::fprintf(stderr, "scenario %%s failed: %%s\n", sc.name, err.c_str()); std::exit(2); } - } - std::printf("{\"name\":\"%%s\",\"p\":{\"n_layers\":%%d,\"n_expert\":%%d,\"lb\":%%d,\"le\":%%d,\"ring\":%%d,\"stager_ring\":%%d,\"rows\":%%lld," - "\"resident_mod\":%%d,\"resident_rem\":%%d,\"cache_present\":%%d,\"pinned_mod\":%%d,\"transient_mod\":%%d,\"chunks\":%%d,\"orders\":[", - sc.name, sc.n_layers, sc.n_expert, sc.lb, sc.le, sc.ring, sc.stager_ring, (long long) T, sc.resident_mod, sc.resident_rem, - (int) sc.cache_present, sc.pinned_mod, sc.transient_mod, sc.chunks); - for (size_t li = 0; li < sc.orders.size(); ++li) { - std::printf("%%s[", li ? "," : ""); - for (size_t k = 0; k < sc.orders[li].size(); ++k) std::printf("%%s%%d", k ? "," : "", sc.orders[li][k]); - std::printf("]"); - } - std::printf("]},\"stats\":[%%lld,%%lld,%%lld],\"ops\":[", (long long) stats_.experts_dma, (long long) stats_.experts_streamed, (long long) stats_.experts_resident); - for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%%s\"%%s\"", i ? "," : "", g_ops[i].c_str()); - std::printf("]}"); -} - -struct PleScenario { const char* name; int64_t n, T; bool gpu_cache; }; -static void run_ple_scenario(const PleScenario& sc) { - g_ops.clear(); - Impl m; - m.T = sc.T; - PleTable table; - SessionStub ss; - ss.ple.table = &table; - for (int b = 0; b < 2; ++b) { m.ple_emb_host[b] = (float*) (0x60000000u + (uintptr_t) b * 0x1000u); m.ple_copied[b] = 4000 + b; m.ple_rows[b].assign(4, 0); } - m.ple_emb = (float*) 0x70000000u; - Stats stats_; - std::string err; - const int64_t n = sc.n; - const bool ple_on = true, ple_gpu_cache = sc.gpu_cache; - std::string ple_next_err; - std::future ple_next; - int ple_buf = 0; - auto ple_gather = [&](int64_t c0, int buf, std::string&) -> bool { op("H ple_gather " + std::to_string(c0) + " " + std::to_string(buf)); return true; }; - for (int64_t c0 = 0; c0 < n; c0 += m.T) { - const int64_t T = std::min(m.T, n - c0); - op("H ple_chunk " + std::to_string(c0)); - cudaStream_t cs = 2; (void) cs; - auto ple_fn = [&]() -> bool { -// ---- VERBATIM prefill.cpp (the PLE row read-ahead) ---- -__PLE__ -// ---- end VERBATIM ---- - return true; - }; - if (!ple_fn()) { std::fprintf(stderr, "ple scenario failed\n"); std::exit(2); } - } - std::printf("{\"name\":\"%s\",\"ple\":[%lld,%lld,%d],\"ops\":[", sc.name, (long long) sc.n, (long long) sc.T, (int) sc.gpu_cache); - for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str()); - std::printf("]}"); -} - -// ---- the GR write fusion decision of one half -namespace strata { namespace kernels { struct CvecStub { bool cover; bool covers(int64_t) const { return cover; } }; inline CvecStub& cvec() { static CvecStub c; return c; } } } -static bool g_gr_unfused = false; -static bool gr_unfused() { return g_gr_unfused; } -static bool fuse_of(int64_t l, int half, int64_t LE, bool ple_on, bool unfused, bool cvec_covers) { - g_gr_unfused = unfused; - strata::kernels::cvec().cover = cvec_covers; -__FUSE__ - return fuse; -} - -static std::vector iota_vec(int n, int step = 1, int from = 0) { - std::vector v; - for (int i = from; i < n; i += step) v.push_back(i); - return v; -} -int main() { - std::vector sc; - // fields: name, n_layers, n_expert, lb, le, ring, stager_ring, T, orders, resident_mod, resident_rem, cache_present, pinned_mod, transient_mod, chunks - sc.push_back({"stream_basic", 6, 24, 1, 4, 16, 16, 1024, - {iota_vec(24, 2), iota_vec(24, 3, 1), {0, 1, 2, 5, 23}}, 5, 0, true, 3, 4, 2}); - sc.push_back({"stream_ring_wrap", 4, 40, 0, 3, 16, 16, 2048, - {iota_vec(40), iota_vec(40), iota_vec(40, 7)}, 0, 0, true, 2, 0, 2}); - sc.push_back({"stream_no_cache_all_pinned", 3, 20, 0, 3, 16, 16, 1024, - {iota_vec(20), iota_vec(20, 2), {19}}, 0, 0, false, 1, 0, 1}); - sc.push_back({"stream_sparse_release", 5, 40, 1, 4, 16, 4, 4096, - {{39}, {0}, {5, 6, 7, 30}}, 0, 0, true, 5, 3, 2}); - sc.push_back({"staged_under_threshold", 4, 32, 0, 3, 384, 16, 512, - {iota_vec(32), iota_vec(32, 3), {2, 4}}, 4, 1, true, 3, 5, 2}); - sc.push_back({"staged_ring8", 3, 12, 0, 2, 8, 16, 4096, - {iota_vec(12), iota_vec(12, 2)}, 0, 0, false, 2, 3, 1}); - sc.push_back({"staged_few_experts", 3, 10, 0, 2, 16, 16, 100, - {{1, 3, 4}, {9}}, 3, 0, true, 0, 0, 1}); - std::printf("{\"ring\":["); - for (size_t i = 0; i < sc.size(); ++i) { if (i) std::printf(",\n"); run_scenario(sc[i]); } - std::printf("],\n"); - std::vector ples = {{"ple_two_chunks_gather", 2000, 1024, false}, {"ple_single_chunk", 100, 256, false}, - {"ple_gpu_cache", 3000, 1024, true}, {"ple_four_chunks", 4096, 1024, false}, - {"ple_exact_multiple", 2048, 1024, false}}; - std::printf("\"ple\":["); - for (size_t i = 0; i < ples.size(); ++i) { if (i) std::printf(",\n"); run_ple_scenario(ples[i]); } - std::printf("],\n\"fuse\":["); - bool first = true; - for (int le : {48, 16}) for (int ple_on = 0; ple_on < 2; ++ple_on) for (int unfused = 0; unfused < 2; ++unfused) - for (int cv = 0; cv < 2; ++cv) for (int l : {0, 1, 2, 14, 15, 46, 47}) for (int half = 0; half < 2; ++half) { - if (l >= le) continue; - std::printf("%s[%d,%d,%d,%d,%d,%d,%d]", first ? "" : ",", le, ple_on, unfused, cv, l, half, (int) fuse_of(l, half, le, ple_on != 0, unfused != 0, cv != 0)); - first = false; - } - std::printf("]}\n"); - return 0; -} -''' -out = (template.replace('__DIGEST__', digest) - .replace('__R1__', f'{a1}-{b1}').replace('__R2__', f'{a2}-{b2}').replace('__R3__', f'{a3}-{b3}').replace('__R4__', f'{a4+1}-{b4}') - .replace('__SEQ_BUILD__', seq_build).replace('__CONSUMER__', consumer).replace('__STAGED__', staged).replace('__WALKS__', walks).replace('__PLE__', ple_block).replace('__FUSE__', fuse_block)) -out = out.replace('%%', '%') -sys.stdout.write(out) diff --git a/crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/physical_layout.rs b/crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/physical_layout.rs index b241d9c7..a2f75343 100644 --- a/crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/physical_layout.rs +++ b/crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/physical_layout.rs @@ -1,7 +1,7 @@ //! Physical `MtpDrafter::load` arena contract. //! //! The order below is the literal `Bump::take` order in -//! `engine/strata/src/core/mtp.cpp`. Keep this independent from the smaller +//! `Strata 41cf05a0, src/core/mtp.cpp`. Keep this independent from the smaller //! prefix and tail views: those views borrow spans of this one allocation. use super::{DeviceBuffer, Error, Result, Scratch}; use crate::ffi::BufferHandle; diff --git a/crates/cuda-driver/src/original_mtp_draft_vocab.rs b/crates/cuda-driver/src/original_mtp_draft_vocab.rs index 4a69047b..367bee0b 100644 --- a/crates/cuda-driver/src/original_mtp_draft_vocab.rs +++ b/crates/cuda-driver/src/original_mtp_draft_vocab.rs @@ -2,7 +2,7 @@ //! //! The Original drafts over the rows of the main native head listed in `rt/draft_vocab.bin` (int32 token ids, 106,299 //! of the 248,320 rows, English, code and every CJK token). Upstream Strata ships three smaller or different subsets -//! built with the same tool (`engine/strata/tools/draft_vocab.py`) and selects one with `--draft-vocab en|cyrillic|fr` +//! built with the same tool (`Strata 41cf05a0, tools/draft_vocab.py`) and selects one with `--draft-vocab en|cyrillic|fr` //! or //! `--mtp-draft-vocab FILE`. The English subset (`draft_vocab_en.bin`, 40,525 ids) drops 65,774 head rows from the //! draft: about 110 MiB less VRAM and a shorter draft LM-head GEMV, at the price that a token outside the subset can diff --git a/crates/cuda-driver/src/original_mtp_rt.rs b/crates/cuda-driver/src/original_mtp_rt.rs index d0ac9d04..4cb26875 100644 --- a/crates/cuda-driver/src/original_mtp_rt.rs +++ b/crates/cuda-driver/src/original_mtp_rt.rs @@ -1,7 +1,7 @@ //! Host half of Original `MtpDrafter::load` (core/mtp.cpp:143-205) and the file //! reads of `bind` (:380-415): the `tools/mtp_rt.py` runtime directory. //! -//! Directory layout (engine/strata/tools/mtp_rt.py): `dense.txt` one line per +//! Directory layout (Strata 41cf05a0, tools/mtp_rt.py): `dense.txt` one line per //! tensor `name kind rows cols offset bytes` (kind q8_0|bf16|f32), `dense.bin` //! every indexed tensor 256-aligned, `experts.bin` 512 routed expert blobs, //! optional `draft_vocab.bin` int32 token ids. diff --git a/crates/cuda-driver/src/original_verify/down.rs b/crates/cuda-driver/src/original_verify/down.rs index 1d9ec6ec..2e1bbd73 100644 --- a/crates/cuda-driver/src/original_verify/down.rs +++ b/crates/cuda-driver/src/original_verify/down.rs @@ -1,5 +1,5 @@ //! D1 `LELEKA_SM120_DOWN_SUB16`: the routed experts' down projection with upstream's group-strided sub8/sub16 kernel -//! (`native_down_multi_kernel`, `engine/strata/.../iq_kernels.cu:2130`), formats 20 and 42. +//! (`native_down_multi_kernel`, `Strata 41cf05a0, .../iq_kernels.cu:2130`), formats 20 and 42. //! //! `sm120_down_sub16.cu` computes the same floats as `window_moe_down_` of `original_verify_window_moe_experts.cu` //! (the model-free probe `tools/decode-sm120/sm120_probe.cpp down` compares them byte for byte), with 8 (IQ4_NL) or 16 diff --git a/crates/cuda-driver/src/original_verify/moe.rs b/crates/cuda-driver/src/original_verify/moe.rs index ba619f6c..967d0b40 100644 --- a/crates/cuda-driver/src/original_verify/moe.rs +++ b/crates/cuda-driver/src/original_verify/moe.rs @@ -1,5 +1,5 @@ //! MoE / FFN producers of the Verifier window (child of `original_verify`): the FFN half of -//! `pre` and `post` of `Verifier::record_window` (engine/strata/src/core/verify.cpp) as pure launch plans +//! `pre` and `post` of `Verifier::record_window` (Strata 41cf05a0, src/core/verify.cpp) as pure launch plans //! over sealed assets. //! //! ```text diff --git a/crates/cuda-driver/src/original_verify/sm120.rs b/crates/cuda-driver/src/original_verify/sm120.rs index 816d371d..231954d8 100644 --- a/crates/cuda-driver/src/original_verify/sm120.rs +++ b/crates/cuda-driver/src/original_verify/sm120.rs @@ -1,5 +1,5 @@ //! claude/decode-sm120-switches: the bitwise decode switches that Strata 0.2.6 turns on by default on a compute -//! capability 12.0 card (`engine/strata/include/strata/core/sm120_series.hpp`), as switches of the Original-literal +//! capability 12.0 card (`Strata 41cf05a0, include/strata/core/sm120_series.hpp`), as switches of the Original-literal //! verify window. //! //! Each switch replaces kernels of the window by upstream's faster kernels that compute every output byte as the diff --git a/crates/cuda-driver/src/qwen_dispatch/gdn_fused_t1.rs b/crates/cuda-driver/src/qwen_dispatch/gdn_fused_t1.rs index d2d39573..528bd936 100644 --- a/crates/cuda-driver/src/qwen_dispatch/gdn_fused_t1.rs +++ b/crates/cuda-driver/src/qwen_dispatch/gdn_fused_t1.rs @@ -6,7 +6,7 @@ //! `fused_gdn_ab` (BF16 alpha/beta GEMV + softplus/sigmoid epilogues), //! `fused_gdn_step_norm` (state update, readout, per-head RMS norm, ssm_norm weight, sigmoid(z) gate; state in //! place). -//! The kernels are the verbatim text of `engine/strata/src/kernels/cuda/fused_gdn.cu` (see +//! The kernels are the verbatim text of `Strata 41cf05a0, src/kernels/cuda/fused_gdn.cu` (see //! `offline_gdn_fused_t1_kernel.cu`). The pinned decode/T1 asset of `offline_gdn_kernel.cu` (decomposed //! `native_gdn = true / fused_gdn = false`) is NOT touched and keeps serving the decomposed path and MTP //! verification. diff --git a/crates/cuda-driver/src/qwen_dispatch/gdn_native_batch.rs b/crates/cuda-driver/src/qwen_dispatch/gdn_native_batch.rs index a10555c2..36dc7e85 100644 --- a/crates/cuda-driver/src/qwen_dispatch/gdn_native_batch.rs +++ b/crates/cuda-driver/src/qwen_dispatch/gdn_native_batch.rs @@ -5,7 +5,7 @@ //! BF16 alpha / beta GEMMs -> `gdn_gates` -> `gdn_conv` (+history) -> `gdn_l2` //! -> `gdn_rec_cols_pipe` -> `gdn_out_norm` (f32 `y` and half `y16`) -> native //! Out GEMM from `y16`. The kernels are the verbatim text of -//! `engine/strata/src/prefill/kernels.cu` (see `offline_gdn_prefill_kernel.cu`); +//! `Strata 41cf05a0, src/prefill/kernels.cu` (see `offline_gdn_prefill_kernel.cu`); //! the dequantizers are those of `dequant_bf16.cu`; the GEMMs are cuBLAS calls //! made by a closed adapter behind [`GdnGemm`]. This is NOT the pinned decode //! T1 arithmetic of `offline_gdn_kernel.cu`, which stays untouched for decode diff --git a/crates/cuda-driver/src/qwen_dispatch/moe_prefill_batch.rs b/crates/cuda-driver/src/qwen_dispatch/moe_prefill_batch.rs index aab1ce61..f06cf7f6 100644 --- a/crates/cuda-driver/src/qwen_dispatch/moe_prefill_batch.rs +++ b/crates/cuda-driver/src/qwen_dispatch/moe_prefill_batch.rs @@ -1,7 +1,7 @@ //! Closed batched MoE router + shared-expert program of the Strata PREFILL path //! (STRA-169, option B), whole micro-window of `T` rows per drain. //! -//! Original program (engine/strata/src/prefill/prefill.cpp, MoE half): +//! Original program (Strata 41cf05a0, src/prefill/prefill.cpp, MoE half): //! BF16 router GEMM over the whole window (`bf16_proj(wr, mixed_bf, logits)`, + lo pass when enabled) //! -> `route()` = `route_kernel<16>` (warp per token, plain `expf`) -> ids/weights //! -> shared expert: native gate / up (dequantized GGUF blocks -> FP16 GEMM from `mixed_h`), diff --git a/crates/cuda-model/src/original_prefill_schedule.rs b/crates/cuda-model/src/original_prefill_schedule.rs index 3fafe0e0..d25abe10 100644 --- a/crates/cuda-model/src/original_prefill_schedule.rs +++ b/crates/cuda-model/src/original_prefill_schedule.rs @@ -1,5 +1,5 @@ //! Pure, platform-independent port of the SCHEDULING half of the Original `Prefill::run` -//! (engine/strata/src/prefill/prefill.cpp, "bool Prefill::run"): the per-chunk expert-stream plan (sequence +//! (Strata 41cf05a0, src/prefill/prefill.cpp, "bool Prefill::run"): the per-chunk expert-stream plan (sequence //! builder, `issue_until`, `give_back`, the streamed and the staged per-layer walks), the PLE row read-ahead //! double buffer, the hyper-connection write fusion rule, the layer-split hand-off double buffer and `ring_slots`. //! diff --git a/crates/engine-core/src/conversation/golden/gen.sh b/crates/engine-core/src/conversation/golden/gen.sh deleted file mode 100755 index fd2d4d14..00000000 --- a/crates/engine-core/src/conversation/golden/gen.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh -# Rebuild the conversation golden fixtures from the pinned ORIGINAL C++ sources. -# Host-only: no CUDA, no model, no network. Needs clang++ or g++ with C++20. -set -eu -here=$(cd "$(dirname "$0")" && pwd) -root=$(cd "$here/../../../../.." && pwd) -strata="$root/engine/strata" -cxx=${CXX:-c++} -tmp=$(mktemp -d) -trap 'rm -rf "$tmp"' EXIT -stub="$here/stub" # minimal cuda_runtime.h so the CUDA-free state sources compile on a CUDA-less host -flags="-std=c++20 -O1 -I$strata/include -I$stub -I$strata/src/core" -$cxx $flags "$here/gen_cache_golden.cpp" "$strata/src/core/conversation_memory.cpp" -o "$tmp/gen_cache" -"$tmp/gen_cache" > "$here/cache_golden.json" -echo "wrote $here/cache_golden.json" -$cxx $flags "$here/gen_state_golden.cpp" "$strata/src/core/conversation_state.cpp" \ - "$strata/src/core/conversation_snapshot.cpp" -o "$tmp/gen_state" -"$tmp/gen_state" > "$here/state_golden.json" -echo "wrote $here/state_golden.json" -$cxx $flags "$here/gen_manager_golden.cpp" -o "$tmp/gen_manager" -"$tmp/gen_manager" > "$here/manager_golden.json" -echo "wrote $here/manager_golden.json" diff --git a/crates/engine-core/src/conversation/golden/gen_cache_golden.cpp b/crates/engine-core/src/conversation/golden/gen_cache_golden.cpp deleted file mode 100644 index d87f313c..00000000 --- a/crates/engine-core/src/conversation/golden/gen_cache_golden.cpp +++ /dev/null @@ -1,333 +0,0 @@ -// Golden-fixture generator for the Rust conversation cache port. -// -// Compiles the ORIGINAL host-side headers (conversation_buffer.hpp, -// conversation_cache.hpp, conversation_memory.cpp, program/conv_cache.hpp) -// unchanged and records deterministic operation traces together with every -// observable result. The Rust tests replay the same traces and compare. -// -// ./gen.sh # rebuilds cache_golden.json (no CUDA needed) -// -// No model data, prompts or captures are involved: token ids are synthetic. -#include "strata/core/conversation_cache.hpp" -#include "strata/core/conversation_memory.hpp" -#include "strata/program/conv_cache.hpp" - -#include -#include -#include -#include -#include - -using namespace strata::core; - -namespace { -struct Rng { - uint64_t s; - explicit Rng(uint64_t seed) : s(seed * 6364136223846793005ULL + 1442695040888963407ULL) {} - uint64_t next() { - s = s * 6364136223846793005ULL + 1442695040888963407ULL; - return s >> 33; - } - uint64_t below(uint64_t n) { return n ? next() % n : 0; } -}; - -template std::string arr(const std::vector& v) { - std::string out = "["; - for (size_t i = 0; i < v.size(); ++i) out += (i ? "," : "") + std::to_string(v[i]); - return out + "]"; -} - -std::string imgs_json(const std::vector& v) { - std::string out = "["; - for (size_t i = 0; i < v.size(); ++i) - out += (i ? "," : "") + std::string("[") + std::to_string(v[i].start) + "," + std::to_string(v[i].hash) + "]"; - return out + "]"; -} - -// ---- buffer traces ------------------------------------------------------------------------------------------- -void buffer_cases(std::string& out) { - out += "\"buffer_cases\":["; - const size_t seg = ConversationBuffer::segment_bytes; - for (int c = 0; c < 14; ++c) { - Rng rng(1000 + c); - ConversationBuffer buf; - std::string ops = "[", states = "["; - const int steps = 12 + (int) rng.below(10); - for (int i = 0; i < steps; ++i) { - size_t n; - switch (rng.below(6)) { - case 0: n = rng.below(200); break; - case 1: n = buf.size() + rng.below(70000); break; - case 2: n = buf.size() + 1 + rng.below(40); break; - case 3: n = seg + rng.below(5000); break; - case 4: n = rng.below(buf.size() + 1); break; - default: n = seg * 2 + rng.below(100000); break; - } - if (n > 3 * seg + 100000) n = 3 * seg + 100000; - const uint8_t value = (uint8_t) (rng.below(250) + 1); - std::vector probes = {buf.size(), n, n + 17, buf.size() + 99, seg + 1, 3 * seg, SIZE_MAX}; - std::string peaks = "["; - for (size_t p = 0; p < probes.size(); ++p) - peaks += (p ? "," : "") + std::string("[") + std::to_string(probes[p]) + "," + std::to_string(buf.allocation_peak(probes[p])) + "]"; - peaks += "]"; - const size_t peak = buf.allocation_peak(n); - buf.resize(n, value); - ops += (i ? "," : "") + std::string("[") + std::to_string(n) + "," + std::to_string(value) + "]"; - // sparse content probes: first, last and boundary bytes - std::vector at; - for (size_t b : {size_t(0), seg - 1, seg, seg + 1}) if (b < buf.size()) at.push_back(b); - if (buf.size()) at.push_back(buf.size() - 1); - std::string bytes_at = "["; - for (size_t k = 0; k < at.size(); ++k) { - uint8_t byte = 0; - buf.read(&byte, at[k], 1); - bytes_at += (k ? "," : "") + std::string("[") + std::to_string(at[k]) + "," + std::to_string(byte) + "]"; - } - bytes_at += "]"; - size_t segments = 0; - buf.visit(0, buf.size(), [&](const uint8_t*, size_t, size_t) { ++segments; return true; }); - states += (i ? "," : "") + std::string("{\"size\":") + std::to_string(buf.size()) + ",\"bytes\":" + std::to_string(buf.bytes()) + - ",\"peak\":" + std::to_string(peak) + ",\"peaks_before\":" + peaks + ",\"segments\":" + std::to_string(segments) + - ",\"bytes_at\":" + bytes_at + "}"; - } - out += (c ? "," : "") + std::string("{\"ops\":") + ops + "],\"states\":" + states + "]}"; - } - out += "]"; -} - -// ---- eviction ------------------------------------------------------------------------------------------------ -void eviction_cases(std::string& out) { - out += "\"eviction\":["; - Rng rng(77); - bool first = true; - for (int c = 0; c < 300; ++c) { - std::vector stamps(rng.below(9)); - for (auto& s : stamps) s = rng.below(12); - const int64_t cap = (int64_t) rng.below(9) - 1; - if (stamps.empty()) { - // C++ reads stamps[0..n): n == 0 returns 0 before touching memory - } - const size_t v = strata::program::conv_cache::eviction_victim(stamps.data(), stamps.size(), cap); - out += (first ? "" : ",") + std::string("{\"stamps\":") + arr(stamps) + ",\"cap\":" + std::to_string(cap) + - ",\"victim\":" + std::to_string(v) + "}"; - first = false; - } - out += "]"; -} - -// ---- meminfo ------------------------------------------------------------------------------------------------- -std::string esc(const std::string& s) { - std::string out = "\""; - for (char ch : s) { - if (ch == '\n') out += "\\n"; - else if (ch == '\t') out += "\\t"; - else if (ch == '\r') out += "\\r"; - else if (ch == '"') out += "\\\""; - else if (ch == '\\') out += "\\\\"; - else out += ch; - } - return out + "\""; -} -void memory_cases(std::string& out) { - out += "\"meminfo\":["; - const std::vector texts = { - "", "MemFree: 100 kB\n", "MemAvailable: -1 kB\n", "MemAvailable: +1 kB\n", "MemAvailable: 1 MB\n", - "MemAvailable: 1\n", "MemAvailable: 1x kB\n", "MemAvailable: 18446744073709551615 kB\n", - "MemAvailable: 18446744073709551616 kB\n", "MemAvailable: 1 kB trailing\n", - "MemAvailable: 1 kB\nMemAvailable: 2 kB\n", "MemTotal: 999999 kB\nMemAvailable: 12345 kB\nSwapFree: 777 kB\n", - "MemAvailable: 0 kB", "MemAvailable:\t7\tkB\r\n", "MemAvailableX: 5 kB\n", "MemAvailable: 007 kB\n", - " MemAvailable: 9 kB\n", "MemAvailable: 9 kB", "MemAvailable:\n", "MemAvailable: 9 KB\n", - "MemAvailable: 18014398509481983 kB\n", "MemAvailable: 18014398509481984 kB\n", "x\nMemAvailable: 5 kB\ny\n", - "MemAvailable: 1 kB\n\n\nfoo: 1 kB\n"}; - for (size_t i = 0; i < texts.size(); ++i) { - std::istringstream in(texts[i]); - const auto r = conversation_mem_available(in); - out += (i ? "," : "") + std::string("{\"text\":") + esc(texts[i]) + ",\"value\":" + (r ? std::to_string(*r) : "null") + "}"; - } - out += "],\"admit\":["; - Rng rng(5); - bool first = true; - const uint64_t M = UINT64_MAX; - std::vector pool = {0, 1, 59, 60, 99, 100, M / 2, M - 1, M}; - for (int c = 0; c < 200; ++c) { - const bool known = rng.below(5) != 0; - const uint64_t avail = pool[rng.below(pool.size())], alloc = pool[rng.below(pool.size())], floor = pool[rng.below(pool.size())]; - const bool ok = conversation_memory_admit(known ? std::optional(avail) : std::nullopt, alloc, floor); - out += (first ? "" : ",") + std::string("{\"known\":") + (known ? "true" : "false") + ",\"avail\":" + std::to_string(avail) + - ",\"alloc\":" + std::to_string(alloc) + ",\"floor\":" + std::to_string(floor) + ",\"ok\":" + (ok ? "true" : "false") + "}"; - first = false; - } - out += "]"; -} - -// ---- cache traces -------------------------------------------------------------------------------------------- -struct Spec { - std::vector ids; - std::vector imgs; - std::vector> checkpoints; - std::vector> cp_imgs; - size_t gdn = 0; - bool cvec = true; -}; - -SavedConversation build(const Spec& s) { - SavedConversation img; - img.live.ids = std::vector(s.ids.begin(), s.ids.end()); - img.live.imgs = std::vector(s.imgs.begin(), s.imgs.end()); - img.live.gdn = std::vector(s.gdn, 7); - img.cvec = s.cvec; - img.checkpoints.reserve(s.checkpoints.size()); - for (size_t i = 0; i < s.checkpoints.size(); ++i) { - ConversationCheckpoint c; - c.ids = std::vector(s.checkpoints[i].begin(), s.checkpoints[i].end()); - c.imgs = std::vector(s.cp_imgs[i].begin(), s.cp_imgs[i].end()); - c.gdn = std::vector(s.gdn / 4, 3); - img.checkpoints.push_back(std::move(c)); - } - return img; -} - -std::string spec_json(const Spec& s) { - std::string cps = "["; - for (size_t i = 0; i < s.checkpoints.size(); ++i) - cps += (i ? "," : "") + std::string("{\"ids\":") + arr(s.checkpoints[i]) + ",\"imgs\":" + imgs_json(s.cp_imgs[i]) + "}"; - cps += "]"; - return std::string("{\"ids\":") + arr(s.ids) + ",\"imgs\":" + imgs_json(s.imgs) + ",\"checkpoints\":" + cps + - ",\"gdn\":" + std::to_string(s.gdn) + ",\"cvec\":" + (s.cvec ? "true" : "false") + "}"; -} - -// A few synthetic conversation "families" so prefixes genuinely overlap. -struct World { - std::vector> roots; - explicit World(Rng& rng) { - for (int r = 0; r < 3; ++r) { - std::vector root; - const int len = 3 + (int) rng.below(5); - for (int i = 0; i < len; ++i) root.push_back((int32_t) (r * 100 + i + 1)); - roots.push_back(root); - } - } - std::vector extend(Rng& rng, const std::vector& base, int more) { - auto v = base; - for (int i = 0; i < more; ++i) v.push_back((int32_t) (500 + rng.below(4))); - return v; - } - Spec spec(Rng& rng) { - Spec s; - const auto& root = roots[rng.below(roots.size())]; - auto mid = extend(rng, root, (int) rng.below(4)); - s.ids = extend(rng, mid, 1 + (int) rng.below(4)); - if (rng.below(3)) { s.checkpoints.push_back(root); s.cp_imgs.push_back({}); } - if (rng.below(2) && mid.size() > root.size()) { s.checkpoints.push_back(mid); s.cp_imgs.push_back({}); } - if (rng.below(6) == 0) s.imgs.push_back({(int64_t) rng.below(s.ids.size()), rng.below(3)}); - for (auto& c : s.cp_imgs) for (const auto& k : s.imgs) if (k.start < (int64_t) 0) c.push_back(k); - // checkpoint images: those below its length (chain consistency) - for (size_t i = 0; i < s.checkpoints.size(); ++i) - for (const auto& k : s.imgs) if (k.start < (int64_t) s.checkpoints[i].size()) s.cp_imgs[i].push_back(k); - s.gdn = 16 + rng.below(200); - s.cvec = rng.below(8) != 0; - return s; - } - std::vector prompt(Rng& rng) { - const auto& root = roots[rng.below(roots.size())]; - return extend(rng, extend(rng, root, (int) rng.below(4)), 1 + (int) rng.below(5)); - } -}; - -void cache_traces(std::string& out) { - out += "\"cache_traces\":["; - for (int t = 0; t < 24; ++t) { - Rng rng(9000 + t); - World world(rng); - const size_t slots = 1 + rng.below(5); - const size_t one = build(world.spec(rng)).bytes(); - const size_t budget = rng.below(8) == 0 ? 0 : one * (1 + rng.below(6)) + rng.below(400); - ConversationCache cache(budget, slots); - std::string ops = "["; - const int steps = 32; - for (int i = 0; i < steps; ++i) { - std::string op, res; - const uint64_t kind = rng.below(12); - if (kind <= 3) { - Spec s = world.spec(rng); - const size_t held = rng.below(5) == 0 ? rng.below(one * 2 + 1) : 0; - const bool ok = cache.put(build(s), held); - op = "{\"op\":\"put\",\"spec\":" + spec_json(s) + ",\"held\":" + std::to_string(held) + "}"; - res = std::string("\"ok\":") + (ok ? "true" : "false"); - } else if (kind <= 6) { - auto p = world.prompt(rng); - std::vector im; - if (rng.below(8) == 0) im.push_back({(int64_t) rng.below(p.size()), rng.below(3)}); - const bool cv = rng.below(8) != 0; - const auto m = cache.best(std::vector(p.begin(), p.end()), im, cv); - op = "{\"op\":\"best\",\"prompt\":" + arr(p) + ",\"imgs\":" + imgs_json(im) + ",\"cvec\":" + (cv ? "true" : "false") + "}"; - res = "\"index\":" + std::to_string(m.index) + ",\"tokens\":" + std::to_string(m.tokens) + ",\"live\":" + (m.live ? "true" : "false"); - } else if (kind == 7) { - size_t idx = cache.size() ? rng.below(cache.size() + 1) : rng.below(2); - std::string taken = "null"; - if (idx < cache.size()) { - auto img = cache.take(idx); - taken = std::to_string(img.bytes()) + ",\"ids\":" + arr(img.live.ids); - taken = "{\"bytes\":" + taken + "}"; - } - op = "{\"op\":\"take\",\"index\":" + std::to_string(idx) + "}"; - res = "\"taken\":" + taken; - } else if (kind == 8) { - const size_t incoming = rng.below(one * 2 + 1), held = rng.below(4) == 0 ? rng.below(one + 1) : 0; - const bool fit = cache.can_fit(incoming, held); - const bool ok = cache.make_room(incoming, held); - op = "{\"op\":\"room\",\"incoming\":" + std::to_string(incoming) + ",\"held\":" + std::to_string(held) + "}"; - res = std::string("\"fit\":") + (fit ? "true" : "false") + ",\"ok\":" + (ok ? "true" : "false"); - } else if (kind == 9) { - std::vector layers; - const size_t n = 1 + rng.below(3); - layers.reserve(n); - std::vector sizes; - for (size_t l = 0; l < n; ++l) { - ConversationKv kv; - sizes.push_back(1 + rng.below(300)); - kv.k.resize(sizes.back()); - layers.push_back(std::move(kv)); - } - const int64_t tokens = (int64_t) (1 + rng.below(40)); - cache.retain(std::move(layers), tokens); - op = "{\"op\":\"retain\",\"sizes\":" + arr(sizes) + ",\"tokens\":" + std::to_string(tokens) + "}"; - res = "\"retained\":" + std::to_string(cache.retained_bytes()); - } else if (kind == 10) { - const int64_t dirty = (int64_t) rng.below(45); - cache.limit_reuse(dirty); - op = "{\"op\":\"limit\",\"dirty\":" + std::to_string(dirty) + "}"; - res = "\"retained\":" + std::to_string(cache.retained_bytes()); - } else { - auto reuse = cache.take_reuse(); - op = "{\"op\":\"take_reuse\"}"; - res = "\"layers\":" + std::to_string(reuse.kv.size()) + ",\"unchanged\":" + std::to_string(reuse.unchanged_tokens) + - ",\"captured\":" + std::to_string(reuse.captured_tokens); - } - ops += (i ? "," : "") + std::string("{\"call\":") + op + ",\"res\":{" + res + "},\"state\":{\"bytes\":" + - std::to_string(cache.bytes()) + ",\"size\":" + std::to_string(cache.size()) + ",\"evictions\":" + - std::to_string(cache.evictions()) + ",\"superseded\":" + std::to_string(cache.superseded()) + - ",\"retained\":" + std::to_string(cache.retained_bytes()) + "}}"; - } - out += (t ? "," : "") + std::string("{\"budget\":") + std::to_string(budget) + ",\"slots\":" + std::to_string(slots) + - ",\"ops\":" + ops + "]}"; - } - out += "]"; -} -} // namespace - -int main() { - std::string out = "{"; - out += "\"sizes\":{\"checkpoint\":" + std::to_string(sizeof(ConversationCheckpoint)) + ",\"kv\":" + std::to_string(sizeof(ConversationKv)) + - ",\"image_key\":" + std::to_string(sizeof(ConversationImageKey)) + "},"; - buffer_cases(out); - out += ","; - eviction_cases(out); - out += ","; - memory_cases(out); - out += ","; - cache_traces(out); - out += "}\n"; - std::fputs(out.c_str(), stdout); - return 0; -} diff --git a/crates/engine-core/src/conversation/golden/gen_manager_golden.cpp b/crates/engine-core/src/conversation/golden/gen_manager_golden.cpp deleted file mode 100644 index 552716a8..00000000 --- a/crates/engine-core/src/conversation/golden/gen_manager_golden.cpp +++ /dev/null @@ -1,423 +0,0 @@ -// Golden-fixture generator for the Rust conversation manager. -// -// The conversation block of generate.cpp (park_current, the resume choice at -// the head of a request, checkpoint_at, the periodic prompt checkpoint, the -// turn/root segment loop and the end-of-request live update) lives inside a -// 6,600-line CUDA translation unit and cannot be compiled on its own. Its -// statements are transliterated here VERBATIM in structure (same order, same -// conditions, same clock/LRU updates) against the real, unmodified -// ConversationCache, eviction_victim and memory admission, with a synthetic -// "device": snapshots carry fixed-size payloads and no CUDA is touched. The -// resulting per-request decisions and cache state are the oracle that the -// Rust ConversationManager must reproduce. -#include "strata/core/conversation_cache.hpp" -#include "strata/core/conversation_memory.hpp" -#include "strata/program/conv_cache.hpp" - -#include -#include -#include -#include -#include -#include - -using namespace strata::core; -using ImgKey = ConversationImageKey; -using ConvCheckpoint = ConversationCheckpoint; - -namespace { -struct Rng { - uint64_t s; - explicit Rng(uint64_t seed) : s(seed * 6364136223846793005ULL + 1442695040888963407ULL) {} - uint64_t next() { s = s * 6364136223846793005ULL + 1442695040888963407ULL; return s >> 33; } - uint64_t below(uint64_t n) { return n ? next() % n : 0; } -}; - -template std::string arr(const std::vector& v) { - std::string out = "["; - for (size_t i = 0; i < v.size(); ++i) out += (i ? "," : "") + std::to_string(v[i]); - return out + "]"; -} -// Token arrays are mostly consecutive runs: [start, length] pairs keep the fixture small. -std::string runs_json(const std::vector& v) { - std::string out = "["; - for (size_t i = 0; i < v.size();) { - size_t j = i + 1; - while (j < v.size() && v[j] == v[j - 1] + 1) ++j; - out += (i ? "," : "") + std::string("[") + std::to_string(v[i]) + "," + std::to_string(j - i) + "]"; - i = j; - } - return out + "]"; -} -std::string imgs_json(const std::vector& v) { - std::string out = "["; - for (size_t i = 0; i < v.size(); ++i) - out += (i ? "," : "") + std::string("[") + std::to_string(v[i].start) + "," + std::to_string(v[i].hash) + "]"; - return out + "]"; -} - -struct ConversationView { // the shape of conversation_snapshot.hpp's view, which needs CUDA headers - const std::vector& ids; - const std::vector& images; - const std::vector& checkpoints; - bool cvec; -}; - -constexpr size_t kPayload = 100; // synthetic running-state payload per checkpoint / live -constexpr int64_t kChunk = 256; // batched prompt chunk (request_capacity with an admitted capacity of 256) -constexpr int64_t kWindow = 4; // verify-window width (read_windows) -constexpr int64_t kShortRead = 64; // windows_ok: at most this many tokens go through the verify windows - -struct Options { - int prompt_cache = 6; - int64_t prompt_cache_every = 16384; - int64_t prompt_cache_root = 2048; - int turn_token = 7; - size_t cache_bytes = 0; - size_t cache_slots = 4; - uint64_t min_free = 0; - bool reread = false; - bool incremental = true; -}; - -// ---- the generate.cpp state ------------------------------------------------------------------------------------ -struct Serve { - Options o; - std::vector live; - std::vector live_imgs; - bool live_ok = false; - std::vector checks; - uint64_t check_clock = 0; - bool cvec_cached = true; - ConversationCache conversations; - int64_t pp_next_check = 0; - std::optional available; // injected telemetry - bool validate_fails = false; // injected: the next parked image is unusable - int parked_events = 0; - explicit Serve(const Options& opt) : o(opt), conversations(opt.prompt_cache > 0 ? opt.cache_bytes : 0, opt.cache_slots) {} - - // synthetic device --------------------------------------------------------------------------------------- - static SavedConversation image_of(const ConversationView& v) { - SavedConversation s; - s.live.ids = std::vector(v.ids.begin(), v.ids.end()); - s.live.imgs = std::vector(v.images.begin(), v.images.end()); - s.live.gdn = std::vector(kPayload, 1); - s.cvec = v.cvec; - s.checkpoints = v.checkpoints; - return s; - } - - // ---- park_current (generate.cpp:4415) --------------------------------------------------------------------- - void park_current(size_t held) { - if (!conversations.enabled() || !live_ok || live.empty()) return; - const ConversationView view{live, live_imgs, checks, cvec_cached}; - auto reuse = conversations.take_reuse(); - size_t estimate = image_of(view).bytes(); - const size_t fresh_estimate = estimate; - if (!reuse.kv.empty()) { reuse = {}; estimate = fresh_estimate; } // (the synthetic device never retains K/V) - conversations.drop_superseded(live, live_imgs, checks, cvec_cached); - if (!conversations.make_room(estimate, held)) return; - const uint64_t floor = o.min_free; - const size_t additional = estimate - reuse.bytes(); - if (!conversation_memory_admit(available, additional, floor)) return; - SavedConversation image = image_of(view); - if (!conversation_memory_admit(available, 0, floor)) return; - const bool stored = conversations.put(std::move(image), held); - if (stored) ++parked_events; - } - - static std::vector imgs_below(const std::vector& all, int64_t L) { - std::vector v; - for (const ImgKey& k : all) if (k.start < L) v.push_back(k); - return v; - } - - // ---- checkpoint_at (generate.cpp:4495) -------------------------------------------------------------------- - bool checkpoint_at(int64_t L, const std::vector& cur, const std::vector& req_imgs) { - if (o.prompt_cache <= 0 || L < 1) return true; - for (ConvCheckpoint& c : checks) - if ((int64_t) c.ids.size() == L) { c.used = ++check_clock; return true; } - ConvCheckpoint c; - c.ids.assign(cur.begin(), cur.begin() + L); - c.imgs = imgs_below(req_imgs, L); - c.gdn = std::vector(kPayload, 2); - c.used = ++check_clock; - checks.push_back(std::move(c)); - while ((int) checks.size() > o.prompt_cache) { - std::vector stamps; - for (const ConvCheckpoint& k : checks) stamps.push_back(k.used); - const size_t victim = strata::program::conv_cache::eviction_victim(stamps.data(), stamps.size(), o.prompt_cache); - checks.erase(checks.begin() + (std::ptrdiff_t) victim); - } - return true; - } -}; - -struct Request { - std::vector ids; - std::vector imgs; - bool cvec = true; - int gen = 1; - int stop_after = -1; // cancel before this prompt action (-1: never) - int64_t available = -1; // -1: unknown - bool validate_fails = false; -}; - -struct Outcome { - int64_t resume = 0; - bool from_live = false; - bool restored = false; - int64_t restored_tokens = 0; - bool restored_live = false; - int64_t reread_to = -1; - int64_t read_from = 0; - std::vector consumed; -}; - -// The request path from `cur = ids` to `finish` (generate.cpp:5013-5640, conversation parts only). -Outcome run_request(Serve& S, const Request& r) { - Outcome out; - S.available = r.available < 0 ? std::nullopt : std::optional((uint64_t) r.available); - S.validate_fails = r.validate_fails; - const std::vector& ids = r.ids; - const std::vector& req_imgs = r.imgs; - const int64_t n = (int64_t) ids.size(); - auto starts_with = [&](const std::vector& pre, const std::vector& pre_imgs) -> bool { - const int64_t L = (int64_t) pre.size(); - if (L < 1 || L > n - 1) return false; - for (int64_t i = 0; i < L; ++i) - if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false; - return Serve::imgs_below(req_imgs, L) == pre_imgs; - }; - const bool want_cvec = r.cvec; - int64_t resume = 0; - bool from_live = false; - if (S.o.prompt_cache > 0 && want_cvec == S.cvec_cached) { - if (S.live_ok && starts_with(S.live, S.live_imgs)) { resume = (int64_t) S.live.size(); from_live = true; } - for (const ConvCheckpoint& c : S.checks) - if ((int64_t) c.ids.size() > resume && starts_with(c.ids, c.imgs)) { - resume = (int64_t) c.ids.size(); - from_live = false; - } - } - const auto parked = S.conversations.best(ids, req_imgs, want_cvec); - std::optional incoming; - if (parked.tokens > resume) incoming.emplace(S.conversations.take(parked.index)); - if (incoming && S.validate_fails) incoming.reset(); - if ((!from_live || incoming)) S.park_current(incoming ? incoming->bytes() : 0); - if (incoming) { - S.live = std::move(incoming->live.ids); - S.live_imgs = std::move(incoming->live.imgs); - S.checks = std::move(incoming->checkpoints); - S.cvec_cached = incoming->cvec; - resume = parked.tokens; - from_live = parked.live; - if (S.o.incremental) S.conversations.retain(std::vector{}, int64_t(S.live.size())); - incoming.reset(); - out.restored = true; out.restored_tokens = resume; out.restored_live = from_live; - } - if (want_cvec != S.cvec_cached) { - S.live_ok = false; - S.checks.clear(); - S.cvec_cached = want_cvec; - } - S.checks.erase(std::remove_if(S.checks.begin(), S.checks.end(), [&](const ConvCheckpoint& c) { - return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs); - }), S.checks.end()); - S.live_ok = false; - int64_t reread_to = -1; - if (resume == 0) { - S.checks.clear(); - } else if (!from_live) { - ConvCheckpoint* c = nullptr; - for (ConvCheckpoint& k : S.checks) if ((int64_t) k.ids.size() == resume) c = &k; - if (c != nullptr) c->used = ++S.check_clock; - if (S.o.reread && c != nullptr) reread_to = resume; - } - const int64_t read_from = reread_to > 0 ? 0 : resume; - S.conversations.limit_reuse(read_from); - S.pp_next_check = reread_to > 0 ? INT64_MAX : resume + S.o.prompt_cache_every; - out.resume = resume; out.from_live = from_live; out.reread_to = reread_to; out.read_from = read_from; - - // ---- the prompt: segments up to the root / the last turn boundary / the last token ------------------------ - int64_t turn_at = -1; - if (S.o.prompt_cache > 0 && S.o.turn_token >= 0) - for (int64_t i = n - 1; i > resume; --i) - if (ids[(size_t) i] == S.o.turn_token) { turn_at = i; break; } - int64_t root_at = -1; - if (S.o.prompt_cache > 0 && S.o.turn_token >= 0 && S.o.prompt_cache_root > 0 && read_from == 0) - for (int64_t i = 1; i < turn_at; ++i) - if (ids[(size_t) i] == S.o.turn_token) { - if (i >= S.o.prompt_cache_root) root_at = i; - break; - } - int64_t at = read_from; - int actions = 0; - bool cancelled = false; - for (const int64_t to : {reread_to, root_at, turn_at, n - 1}) { - if (to <= at) continue; - const bool win = (to - at) <= kShortRead; - const int64_t width = win ? kWindow : kChunk; - while (at < to) { - if (r.stop_after >= 0 && actions == r.stop_after) { cancelled = true; break; } - const int64_t count = std::min(width, to - at); - at += count; - ++actions; - if (!win) { // sp.run's chunk callback - if (S.o.prompt_cache_every > 0 && at >= S.pp_next_check) { - S.checkpoint_at(at, ids, req_imgs); - S.pp_next_check = at + S.o.prompt_cache_every; - } - } - } - if (cancelled) break; - if (to == turn_at || to == root_at) S.checkpoint_at(to, ids, req_imgs); - } - // ---- the decode: consumed = ids[0..n-1) + the last prompt token + all generated tokens but the last ------- - if (!cancelled) { - std::vector consumed(ids.begin(), ids.end()); - for (int i = 0; i + 1 < r.gen; ++i) consumed.push_back(200000 + (int32_t) ids.size() * 10 + i); - out.consumed = consumed; - S.live.swap(consumed); - S.live_imgs = Serve::imgs_below(req_imgs, (int64_t) S.live.size()); - S.live_ok = S.o.prompt_cache > 0; - } - return out; -} - -std::string state_json(const Serve& S) { - std::string cps = "["; - for (size_t i = 0; i < S.checks.size(); ++i) - cps += (i ? "," : "") + std::string("[") + std::to_string(S.checks[i].ids.size()) + "," + std::to_string(S.checks[i].used) + "]"; - cps += "]"; - return "{\"live\":" + std::to_string(S.live.size()) + ",\"live_ok\":" + (S.live_ok ? "true" : "false") + ",\"cvec\":" + (S.cvec_cached ? "true" : "false") + - ",\"checks\":" + cps + ",\"clock\":" + std::to_string(S.check_clock) + ",\"pp_next\":" + std::to_string(S.pp_next_check) + - ",\"cache\":{\"size\":" + std::to_string(S.conversations.size()) + ",\"bytes\":" + std::to_string(S.conversations.bytes()) + - ",\"evictions\":" + std::to_string(S.conversations.evictions()) + ",\"superseded\":" + std::to_string(S.conversations.superseded()) + - ",\"retained\":" + std::to_string(S.conversations.retained_bytes()) + "},\"parks\":" + std::to_string(S.parked_events) + "}"; -} -} // namespace - -std::string options_json(const Options& o) { - return std::string("{\"prompt_cache\":") + std::to_string(o.prompt_cache) + ",\"every\":" + std::to_string(o.prompt_cache_every) + - ",\"root\":" + std::to_string(o.prompt_cache_root) + ",\"turn\":" + std::to_string(o.turn_token) + ",\"cache_bytes\":" + - std::to_string(o.cache_bytes) + ",\"slots\":" + std::to_string(o.cache_slots) + ",\"min_free\":" + std::to_string(o.min_free) + - ",\"reread\":" + (o.reread ? "true" : "false") + ",\"incremental\":" + (o.incremental ? "true" : "false") + "}"; -} - -// Run one request and emit it together with everything the Rust port must reproduce. -Outcome emit_request(Serve& S, const Request& r, std::string& reqs, bool first) { - const Outcome res = run_request(S, r); - reqs += (first ? "" : ",") + std::string("{\"ids\":") + runs_json(r.ids) + ",\"imgs\":" + imgs_json(r.imgs) + ",\"cvec\":" + (r.cvec ? "true" : "false") + - ",\"gen\":" + std::to_string(r.gen) + ",\"stop_after\":" + std::to_string(r.stop_after) + ",\"available\":" + std::to_string(r.available) + - ",\"validate_fails\":" + (r.validate_fails ? "true" : "false") + ",\"expect\":{\"resume\":" + std::to_string(res.resume) + - ",\"from_live\":" + (res.from_live ? "true" : "false") + ",\"restored\":" + - (res.restored ? "[" + std::to_string(res.restored_tokens) + "," + (res.restored_live ? "true" : "false") + "]" : std::string("null")) + - ",\"reread_to\":" + std::to_string(res.reread_to) + ",\"read_from\":" + std::to_string(res.read_from) + - ",\"consumed\":" + std::to_string(res.consumed.size()) + ",\"state\":" + state_json(S) + "}}"; - return res; -} - -// #342: MAIN conversation parked, then a sub-agent whose every turn re-renders the previous reply (so no turn -// continues the live session and each one parks a stale-tail copy of the one before). -std::string subagent_trace(const char* sep, size_t slots, size_t budget, int turns, bool with_main_return) { - Options o; - o.prompt_cache = 6; o.prompt_cache_every = 100000; o.prompt_cache_root = 8; o.cache_bytes = budget; o.cache_slots = slots; - Serve S(o); - std::string reqs = "["; - bool first = true; - auto emit = [&](std::vector ids, int gen) { - Request r; r.ids = std::move(ids); r.gen = gen; r.available = 1000000; - return emit_request(S, r, reqs, std::exchange(first, false)); - }; - auto block = [](int32_t base, int n) { std::vector v; for (int i = 0; i < n; ++i) v.push_back(base + i); return v; }; - auto cat = [](std::vector a, const std::vector& b) { a.insert(a.end(), b.begin(), b.end()); return a; }; - std::vector main_ids = cat(cat(cat({7}, block(100, 30)), cat({7}, block(1000, 20))), cat({7}, block(2000, 20))); - const auto main_run = emit(main_ids, 6); - std::vector rendered = cat({7}, block(5000, 24)); // the sub-agent's system prompt, rendered history so far - for (int t = 1; t <= turns; ++t) { - const std::vector ids = cat(cat(cat(rendered, {7}), block(6000 + 100 * t, 6)), {8, 8}); - emit(ids, 5); - rendered = cat(ids, block(7000 + 10 * t, 3)); // the reply, as the client re-renders it - } - if (with_main_return) { - emit(cat(main_run.consumed, cat({7}, block(9000, 5))), 4); - } - reqs += "]"; - return std::string(sep) + "{\"options\":" + options_json(o) + ",\"requests\":" + reqs + "}"; -} - -int main() { - std::string out = "{\"traces\":["; - for (int t = 0; t < 28; ++t) { - Rng rng(31000 + t); - Options o; - o.prompt_cache = 1 + (int) rng.below(7); - o.prompt_cache_every = rng.below(3) == 0 ? 0 : (rng.below(2) ? 100 + (int64_t) rng.below(300) : 100000); - const int64_t roots[] = {8, 40, 120, 2048, 0}; - o.prompt_cache_root = roots[rng.below(5)]; - o.cache_bytes = rng.below(6) == 0 ? 0 : (size_t) (6000 + rng.below(60000)); - o.cache_slots = 1 + rng.below(5); - o.min_free = rng.below(3) == 0 ? 1000 + rng.below(5000) : 0; - o.reread = rng.below(8) == 0; - o.incremental = rng.below(4) != 0; - Serve S(o); - // conversation family - std::vector> histories; - std::string reqs = "["; - const int steps = 30; - for (int step = 0; step < steps; ++step) { - Request r; - auto fresh_chat = [&](int sys_salt) { - std::vector v = {7}; - const int sys = 10 + (int) rng.below(120); - for (int i = 0; i < sys; ++i) v.push_back(100 + sys_salt * 1000 + i); - const int turns = 1 + (int) rng.below(3); - for (int tn = 0; tn < turns; ++tn) { - v.push_back(7); - const int len = 3 + (int) rng.below(90); - for (int i = 0; i < len; ++i) v.push_back((int32_t) (50000 + rng.below(3) * 10 + i + tn * 500)); - } - return v; - }; - const uint64_t pick = rng.below(7); - if (histories.empty() || pick == 0) { - r.ids = fresh_chat(rng.below(2) ? 0 : (int) (1 + rng.below(3))); - } else { - auto base = rng.below(5) < 3 ? histories.back() : histories[rng.below(histories.size())]; - const uint64_t how = rng.below(3); - if (how == 0) { - base.push_back(7); - const int len = 2 + (int) rng.below(60); - for (int i = 0; i < len; ++i) base.push_back(70000 + i); - r.ids = base; - } else if (how == 1) { - const size_t cut = 1 + rng.below(base.size() - 1); - base.resize(cut); - const int len = 2 + (int) rng.below(40); - for (int i = 0; i < len; ++i) base.push_back(80000 + i + (int32_t) rng.below(2)); - r.ids = base; - } else { - r.ids = base; - } - } - if (rng.below(12) == 0) r.imgs.push_back({(int64_t) rng.below(r.ids.size()), rng.below(2)}); - r.cvec = rng.below(8) != 0; - r.gen = 1 + (int) rng.below(10); - r.stop_after = rng.below(8) == 0 ? (int) rng.below(4) : -1; - r.available = rng.below(6) == 0 ? -1 : (int64_t) (rng.below(3) ? 1000000 : 3000); - r.validate_fails = rng.below(10) == 0; - const Outcome res = emit_request(S, r, reqs, step == 0); - if (!res.consumed.empty()) histories.push_back(res.consumed); - } - reqs += "]"; - out += (t ? "," : "") + std::string("{\"options\":") + options_json(o) + ",\"requests\":" + reqs + "}"; - } - // scripted #342 sub-agent traffic, with and without the MAIN conversation coming back - out += subagent_trace(",", 4, 1 << 20, 9, true); - out += subagent_trace(",", 3, 1 << 20, 7, true); - out += subagent_trace(",", 2, 1 << 20, 6, true); - out += subagent_trace(",", 4, 12000, 8, false); - out += "]}\n"; - std::fputs(out.c_str(), stdout); -} diff --git a/crates/engine-core/src/conversation/golden/gen_state_golden.cpp b/crates/engine-core/src/conversation/golden/gen_state_golden.cpp deleted file mode 100644 index 980944b3..00000000 --- a/crates/engine-core/src/conversation/golden/gen_state_golden.cpp +++ /dev/null @@ -1,274 +0,0 @@ -// Golden-fixture generator for the Rust conversation snapshot port. -// -// Links the ORIGINAL conversation_state.cpp / conversation_snapshot.cpp -// unchanged, with CUDA replaced by plain host memory (a stub cuda_runtime.h -// and memcpy-backed cudaMemcpy), and records sizes, layouts and content -// hashes of whole-session snapshots. The pools hold synthetic bytes only. -#include "strata/core/conversation_snapshot.hpp" -#include "strata/kernels/kv_q4.hpp" - -#include -#include -#include -#include -#include -#include - -using namespace strata::core; -using namespace strata::kernels; - -// ---- host stand-ins for the device runtime --------------------------------------------------------------------- -extern "C" cudaError_t cudaMemcpy(void* dst, const void* src, size_t n, cudaMemcpyKind) { - std::memcpy(dst, src, n); - return cudaSuccess; -} -extern "C" cudaError_t cudaDeviceSynchronize() { return cudaSuccess; } -extern "C" cudaError_t cudaGetLastError() { return cudaSuccess; } -namespace strata::kernels { -void kv_stream_reset(const KvStreamMap&, void*) {} -void kv_ring_restore(const QsaAttnPools&, const KvHostPools&, int, int64_t, int64_t, int64_t, const QsaShapes&, void*) {} -} // namespace strata::kernels -namespace strata::core { -strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState&) { return {}; } -} // namespace strata::core - -namespace { -std::string hash_hex(const std::vector& v) { - uint64_t h = 1469598103934665603ull; - for (uint8_t b : v) { h ^= b; h *= 1099511628211ull; } - char out[17]; - std::snprintf(out, sizeof out, "%016llx", (unsigned long long) h); - return out; -} -std::string hash_buf(const ConversationBuffer& b) { - std::vector v(b.size()); - if (!v.empty()) b.read(v.data(), 0, v.size()); - return hash_hex(v); -} -std::string q(const std::string& s) { return "\"" + s + "\""; } - -struct Storage { - std::deque> blocks; - template void alloc(T*& p, size_t n) { - if (!n) return; - blocks.emplace_back(n, 0); - p = reinterpret_cast(blocks.back().data()); - } -}; - -struct Fixture { - ModelGeometry g; - QsaState state; - Storage store; - std::array sources{}; - std::array sizes{}; - Fixture(int fmt, int mode) { - auto& st = state; - st.kv_mode = mode; st.without_key = fmt == kKvValueInt8; st.kv_int8 = fmt == kKvInt8 || st.without_key; - st.kv_q4 = fmt == kKvQ4; st.kv_hybrid = fmt == 3; - st.n_pages = 24; st.n_slots = mode ? 4 : st.n_pages; - st.max_cells = st.n_pages * 4; st.idx_pooled_rows = mode == 2 ? 2 : st.max_cells / 4 + 2; - const size_t per = fmt == kKvQ4 ? kv_q4_bytes_per_head((int) g.head_dim) : g.head_dim * ((st.kv_int8 || st.kv_hybrid) ? 1 : 2); - const size_t rows = st.max_cells * g.n_head_kv, slot_rows = st.n_slots * 4 * g.n_head_kv; - sizes = {rows * per, rows * per, (fmt == kKvInt8 || fmt == kKvValueInt8) ? rows * (g.head_dim / 64) * 2 : 0, - (fmt == kKvInt8 || fmt == kKvValueInt8) ? rows * (g.head_dim / 64) * 2 : 0, (size_t) st.idx_pooled_rows * g.idx_key_dim * 4}; - if (st.without_key) { sizes[0] = 0; sizes[2] = 0; } - if (fmt == 3) { - sizes = {rows * per, rows * kv_q4_bytes_per_head((int) g.head_dim), rows * (g.head_dim / 64) * 2, 0, - (size_t) st.idx_pooled_rows * g.idx_key_dim * 4}; - store.alloc(st.k_q, sizes[0]); store.alloc(st.v_q4, sizes[1]); store.alloc(st.k_scale, sizes[2]); - sources[0] = st.k_q; sources[1] = st.v_q4; sources[2] = st.k_scale; - } else if (fmt == kKvQ4) { - store.alloc(st.k_q4, slot_rows * per); store.alloc(st.v_q4, slot_rows * per); - if (mode) { store.alloc(st.host.k_q4, sizes[0]); store.alloc(st.host.v_q4, sizes[1]); } - sources[0] = mode ? st.host.k_q4 : st.k_q4; sources[1] = mode ? st.host.v_q4 : st.v_q4; - } else if (st.kv_int8) { - if (!st.without_key) store.alloc(st.k_q, slot_rows * per); - store.alloc(st.v_q, slot_rows * per); - if (!st.without_key) store.alloc(st.k_scale, slot_rows * (g.head_dim / 64) * 2); - store.alloc(st.v_scale, slot_rows * (g.head_dim / 64) * 2); - if (mode) { - store.alloc(st.host.k_q, sizes[0]); store.alloc(st.host.v_q, sizes[1]); - store.alloc(st.host.k_scale, sizes[2]); store.alloc(st.host.v_scale, sizes[3]); - } - sources[0] = mode ? st.host.k_q : st.k_q; sources[1] = mode ? st.host.v_q : st.v_q; - sources[2] = mode ? st.host.k_scale : st.k_scale; sources[3] = mode ? st.host.v_scale : st.v_scale; - } else { - store.alloc(st.k_pool, slot_rows * per); store.alloc(st.v_pool, slot_rows * per); - if (mode) { store.alloc(st.host.k_pool, sizes[0]); store.alloc(st.host.v_pool, sizes[1]); } - sources[0] = mode ? st.host.k_pool : st.k_pool; sources[1] = mode ? st.host.v_pool : st.v_pool; - } - store.alloc(st.idx_pooled, sizes[4]); sources[4] = st.idx_pooled; - store.alloc(st.page_table, st.n_pages * 4); - if (mode == 1) { - auto& m = st.map; - m.page_table = st.page_table; m.n_blocks = st.n_pages; m.n_slots = st.n_slots; - store.alloc(m.slot_block, st.n_slots * 4); store.alloc(m.slot_stamp, st.n_slots * 4); store.alloc(m.slot_ref, st.n_slots * 4); - store.alloc(m.miss_block, st.n_slots * 4); store.alloc(m.miss_slot, st.n_slots * 4); store.alloc(m.ctl, kKvCtlInts * 4); - } else if (mode == 2) { - // the ring table is device-initialized in the real tool; only its presence matters here - } - } - void fill(uint8_t salt) { - for (size_t i = 0; i < sources.size(); ++i) - for (size_t j = 0; j < sizes[i]; ++j) - static_cast(sources[i])[j] = (uint8_t) (salt + i * 31 + j * 7 + j / 257); - } -}; - -std::string kv_json(const ConversationKv& k) { - return "{\"format\":" + std::to_string(k.format) + ",\"cells\":" + std::to_string(k.cells) + ",\"heads\":" + std::to_string(k.heads) + - ",\"head_dim\":" + std::to_string(k.head_dim) + ",\"page_size\":" + std::to_string(k.page_size) + - ",\"pooled_rows\":" + std::to_string(k.pooled_rows) + ",\"idx_dim\":" + std::to_string(k.idx_dim) + - ",\"bytes\":" + std::to_string(k.bytes()) + ",\"sizes\":[" + std::to_string(k.k.size()) + "," + std::to_string(k.v.size()) + "," + - std::to_string(k.k_scale.size()) + "," + std::to_string(k.v_scale.size()) + "," + std::to_string(k.pooled.size()) + - "],\"hash\":[" + q(hash_buf(k.k)) + "," + q(hash_buf(k.v)) + "," + q(hash_buf(k.k_scale)) + "," + q(hash_buf(k.v_scale)) + "," + - q(hash_buf(k.pooled)) + "]}"; -} - -void state_cases(std::string& out) { - out += "\"state_cases\":["; - bool first = true; - auto emit = [&](const ModelGeometry& g, int64_t gdn_alloc, int64_t qsa_ord0, int64_t qsa_alloc, const char* what) { - ConversationStateSizes z; - std::string err; - const bool ok_whole = conversation_state_sizes(g, z, err); - SessionState ss; - ss.gdn_alloc = gdn_alloc; ss.qsa_ord0 = qsa_ord0; ss.qsa_alloc = qsa_alloc; - ConversationStateSizes zs; - const bool ok_session = conversation_session_sizes(g, ss, zs, err); - const auto k = std::array{g.n_embd, g.n_layers, g.qsa_interval, g.ssm_state_size, g.ssm_k_heads, g.ssm_v_heads, g.ssm_d_conv, - g.ssm_conv_channels, g.ssm_value_dim, g.n_head, g.n_head_kv, g.head_dim, g.idx_q_heads, g.idx_key_dim, - g.hc, g.hc_lr, g.n_expert, g.n_ff}; - std::string key = "["; - for (size_t i = 0; i < k.size(); ++i) key += (i ? "," : "") + std::to_string(k[i]); - key += "]"; - out += (first ? "" : ",") + std::string("{\"what\":") + q(what) + ",\"geometry\":" + key + ",\"gdn_alloc\":" + std::to_string(gdn_alloc) + - ",\"qsa_ord0\":" + std::to_string(qsa_ord0) + ",\"qsa_alloc\":" + std::to_string(qsa_alloc) + ",\"whole_ok\":" + (ok_whole ? "true" : "false") + - ",\"whole\":[" + std::to_string(ok_whole ? z.gdn : 0) + "," + std::to_string(ok_whole ? z.ple : 0) + "," + std::to_string(ok_whole ? z.tail : 0) + "," + - std::to_string(ok_whole ? z.dead : 0) + "," + std::to_string(ok_whole ? z.block_pos : 0) + "],\"session_ok\":" + (ok_session ? "true" : "false") + - ",\"session\":[" + std::to_string(ok_session ? zs.gdn : 0) + "," + std::to_string(ok_session ? zs.ple : 0) + "," + std::to_string(ok_session ? zs.tail : 0) + - "," + std::to_string(ok_session ? zs.dead : 0) + "," + std::to_string(ok_session ? zs.block_pos : 0) + "]}"; - first = false; - }; - ModelGeometry original; - emit(original, original.n_gdn_layers(), 0, original.n_qsa_layers(), "original whole model"); - emit(original, 3, 1, 1, "single stage carve"); - emit(original, 37, 0, 12, "gdn_alloc past rows"); - emit(original, 36, 0, 13, "qsa_alloc past ordinals"); - emit(original, 0, 12, 0, "empty tail carve"); - emit(original, -1, 0, 0, "negative gdn_alloc"); - emit(original, 36, 13, 0, "ord0 past last"); - ModelGeometry small = original; - small.n_layers = 8; small.ssm_state_size = 2; small.ssm_v_heads = 2; small.ssm_conv_channels = 8; small.n_head_kv = 1; small.head_dim = 64; small.idx_key_dim = 8; - emit(small, 6, 0, 2, "small whole"); - emit(small, 3, 1, 1, "small carve"); - small.n_layers = 3; - emit(small, 3, 0, 0, "zero QSA layers"); - ModelGeometry bad = original; bad.qsa_interval = 0; emit(bad, 0, 0, 0, "zero interval"); - bad = original; bad.ssm_state_size = INT64_MAX; emit(bad, 36, 0, 12, "overflow state"); - bad = original; bad.n_expert = 0; emit(bad, 36, 0, 12, "zero experts"); - bad = original; bad.n_layers = 0; emit(bad, 0, 0, 0, "zero layers"); - bad = original; bad.idx_key_dim = -1; emit(bad, 36, 0, 12, "negative idx"); - bad = original; bad.n_layers = 50; emit(bad, 38, 0, 12, "50 layers"); - bad = original; bad.ssm_d_conv = 1; emit(bad, 36, 0, 12, "conv width 1"); - out += "]"; -} - -void kv_cases(std::string& out) { - out += "\"kv_cases\":["; - bool first = true; - for (int fmt : std::array{kKvF16, kKvInt8, kKvQ4, 3, kKvValueInt8}) for (int mode : {0, 1, 2}) for (int rot : {0, 1}) { - if (fmt == 3 && mode != 0) continue; - Fixture f(fmt, mode); - f.state.kv_rot = rot != 0; - f.fill(13); - for (int64_t upto : {0, 1, 3, 4, 5, 63, 64, 65, 96, 97, -1}) { - const bool index = mode != 2; - ConversationKv a; - std::string err; - const size_t bytes = conversation_kv_bytes(f.state, f.g, upto, index); - const bool ok = conversation_kv_save(a, f.state, f.g, upto, index, err); - out += (first ? "" : ",") + std::string("{\"fmt\":") + std::to_string(fmt) + ",\"mode\":" + std::to_string(mode) + ",\"rot\":" + std::to_string(rot) + - ",\"upto\":" + std::to_string(upto) + ",\"bytes\":" + std::to_string(bytes) + ",\"ok\":" + (ok ? "true" : "false") + - ",\"image\":" + (ok ? kv_json(a) : "null") + "}"; - first = false; - } - } - out += "]"; -} - -// Mirrors conversation_snapshot_test.cpp full_session(): A captured, state overwritten, A restored, re-captured. -void session_cases(std::string& out) { - out += "\"session_cases\":["; - bool first = true; - for (int fmt : std::array{kKvF16, kKvInt8, kKvQ4, kKvValueInt8, 3}) for (int mode : {0, 1}) for (int experts : {256, 512}) { - if (fmt == 3 && mode != 0) continue; - Fixture main(fmt, mode), draft((fmt == 3 || fmt == kKvValueInt8) ? kKvInt8 : fmt, 2); - auto& g = main.g; - g.n_layers = 4; g.n_expert = experts; g.ssm_state_size = 2; g.ssm_v_heads = 2; g.ssm_conv_channels = 8; - SessionState ss; - ss.max_cells = 96; ss.qsa_states = &main.state; - ss.layer_hi = g.n_layers; ss.gdn_alloc = g.n_gdn_layers(); ss.qsa_alloc = g.n_qsa_layers(); - std::string err; - ConversationStateSizes sizes; - conversation_state_sizes(g, sizes, err); - main.store.alloc(ss.gdn_state, sizes.gdn); main.store.alloc(ss.ple_hist, sizes.ple); - main.store.alloc(main.state.idx_tail, sizes.tail); main.store.alloc(main.state.idx_dead, sizes.dead); - main.store.alloc(main.state.idx_block_pos, sizes.block_pos); - std::vector ids(65); - for (size_t i = 0; i < ids.size(); ++i) ids[i] = (int32_t) i + 1; - std::vector images; - std::vector checkpoints; - auto fill = [&](uint8_t salt) { - main.fill(salt); draft.fill(salt); - for (const auto& [p, n] : std::vector>{{ss.gdn_state, sizes.gdn}, {ss.ple_hist, sizes.ple}, - {main.state.idx_tail, sizes.tail}, {main.state.idx_dead, sizes.dead}, {main.state.idx_block_pos, sizes.block_pos}}) - std::memset(p, salt, n); - std::memcpy(main.state.idx_pooled + (ids.size() / 4) * g.idx_key_dim, main.state.idx_dead, sizes.dead); - }; - fill(13); - ConversationCheckpoint checkpoint; - checkpoint.ids.assign(ids.begin(), ids.begin() + 3); - conversation_checkpoint_save(checkpoint, ss, g, err); - checkpoint.used = 17; - checkpoints.push_back(std::move(checkpoint)); - const ConversationView view{ids, images, checkpoints, true}; - size_t estimate = 0; - conversation_snapshot_bytes(view, ss, g, draft.state, estimate, err); - SavedConversation a, b, restored; - conversation_snapshot_save(a, view, ss, g, draft.state, err); - fill(177); - conversation_snapshot_save(b, view, ss, g, draft.state, err); - const bool restored_ok = conversation_snapshot_restore(a, ss, g, draft.state, err) == ConversationRestore::restored; - conversation_snapshot_save(restored, view, ss, g, draft.state, err); - auto cp_json = [](const ConversationCheckpoint& c) { - return "{\"ids\":" + std::to_string(c.ids.size()) + ",\"used\":" + std::to_string(c.used) + ",\"bytes\":" + std::to_string(c.bytes()) + - ",\"hash\":[" + q(hash_hex(c.gdn)) + "," + q(hash_hex(c.ple)) + "," + q(hash_hex(c.tails)) + "," + q(hash_hex(c.dead)) + "," + - q(hash_hex(c.block_pos)) + "]}"; - }; - auto image_json = [&](const SavedConversation& s) { - std::string kv = "["; - for (size_t i = 0; i < s.kv.size(); ++i) kv += (i ? "," : "") + kv_json(s.kv[i]); - kv += "]"; - return "{\"bytes\":" + std::to_string(s.bytes()) + ",\"live\":" + cp_json(s.live) + ",\"checkpoint\":" + cp_json(s.checkpoints[0]) + ",\"kv\":" + kv + "}"; - }; - out += (first ? "" : ",") + std::string("{\"fmt\":") + std::to_string(fmt) + ",\"mode\":" + std::to_string(mode) + ",\"experts\":" + std::to_string(experts) + - ",\"estimate\":" + std::to_string(estimate) + ",\"a\":" + image_json(a) + ",\"b\":" + image_json(b) + ",\"restored_ok\":" + (restored_ok ? "true" : "false") + - ",\"restored\":" + image_json(restored) + ",\"ple_prev\":[" + std::to_string(ss.ple_prev[0]) + "," + std::to_string(ss.ple_prev[1]) + "]}"; - first = false; - } - out += "]"; -} -} // namespace - -int main() { - std::string out = "{"; - state_cases(out); - out += ","; - kv_cases(out); - out += ","; - session_cases(out); - out += "}\n"; - std::fputs(out.c_str(), stdout); -} diff --git a/crates/engine-core/src/conversation/golden/stub/cuda_runtime.h b/crates/engine-core/src/conversation/golden/stub/cuda_runtime.h deleted file mode 100644 index 486ffa19..00000000 --- a/crates/engine-core/src/conversation/golden/stub/cuda_runtime.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include -#include -#include -typedef int cudaError_t; -enum { cudaSuccess = 0, cudaErrorInvalidValue = 1, cudaErrorUnknown = 999 }; -typedef int cudaMemcpyKind; -enum { cudaMemcpyDefault = 4, cudaMemcpyHostToDevice = 1, cudaMemcpyDeviceToHost = 2, cudaMemcpyDeviceToDevice = 3 }; -typedef struct CUstream_st* cudaStream_t; -typedef struct CUevent_st* cudaEvent_t; -inline const char* cudaGetErrorString(cudaError_t) { return "stub"; } -extern "C" cudaError_t cudaMemcpy(void*, const void*, size_t, cudaMemcpyKind); -extern "C" cudaError_t cudaDeviceSynchronize(); -extern "C" cudaError_t cudaGetLastError(); -typedef struct CUgraphExec_st* cudaGraphExec_t; -typedef struct CUgraph_st* cudaGraph_t; diff --git a/crates/engine-qwen35-cuda/tests/stra161_reference/reference.py b/crates/engine-qwen35-cuda/tests/stra161_reference/reference.py deleted file mode 100644 index bb12a6da..00000000 --- a/crates/engine-qwen35-cuda/tests/stra161_reference/reference.py +++ /dev/null @@ -1,114 +0,0 @@ -"""Independent STRA161 offline integer/decode oracle; imports no candidate code.""" -import hashlib, json, re, struct -from pathlib import Path -ROOT=Path(__file__).resolve().parents[4] -OUT=Path(__file__).with_name('fixtures.json') -MULT=[23703573157769,20109073645365,8052911324071] -VOCAB=[20000003,20000023,20000033,20000047,20000059,20000063,20000069,20000077,20000081,20000093,20000107,20000147,20000153,20000159,20000161,20000171] -OFF=[0,20000003,40000026,60000059,80000106,100000165,120000228,140000297,160000374,180000455,200000548,220000655,240000802,260000955,280001114,300001275] -EOS=248044 -MASK=(1<<64)-1 -CODE=[-127,-104,-83,-65,-49,-35,-22,-10,1,13,25,38,53,69,89,113] -def mixed(ctx): - v=0 - for x,m in zip(ctx,MULT):v^=(x*m)&MASK - return v -def rows(token,prev): - ctx=[token];cut=False - for t in reversed(prev): - cut=cut or t<0 or t==EOS - ctx.append(EOS if cut else t) - return [(mixed(ctx[:2 if h<8 else 3])%VOCAB[h])+OFF[h] for h in range(16)] -def words(raw): - out=[] - for b in range(5): - d=struct.unpack('>4]))[0] for q in qs) - return out -# An independently generated original-source oracle predating this candidate. -inc=(ROOT/'engine/strata/src/kernels/ple_oracle_vectors.inc').read_text() -cases=[] -for c in range(6): - def arr(name):return [int(x) for x in re.search(r'case'+str(c)+'_'+name+r'\[\d+\] = \{(.*?)\};',inc,re.S).group(1).replace('\n','').split(',') if x.strip()] - ts,pv,want=arr('tokens'),arr('prev'),arr('rows') - for i,t in enumerate(ts): - # The retained source parity harness passes these original literal predecessor arrays unchanged. - prev=pv[2*i:2*i+2]; got=rows(t,prev) - assert got==want[16*i:16*i+16],(c,i,got,want[16*i:16*i+16]) - cases.append({'name':f'original-{c}-{i}','token':t,'prev_oldest_first':prev,'rows':got}) -for name,t,prev in [('zero',0,[0,0]),('oldest-null',8,[-1,7]),('newest-null',8,[7,-1]),('oldest-eos',9,[EOS,7]),('newest-eos',9,[7,EOS]),('tokenizer-eos-not-ple-eos',9,[7,248046]),('current-eos-keeps-context',EOS,[11,22]),('max-vocabulary',248319,[248318,248319])]:cases.append({'name':name,'token':t,'prev_oldest_first':prev,'rows':rows(t,prev)}) -# Finite synthetic encoded rows, no actual model payload. Exact dyadic scale*integer product. -decode=[] -for name,scales in [('split-nibbles',[0x3c00,0xbc00,0x3800,1,0x8000]),('scale-domains',[0,0x0400,0x7bff,0xfbff,0x3555])]: - raw=b''.join(struct.pack('0)-(s<0));return sigmoid(f32(sign*mag)) -def silu(v):return f32(v/f32(1.0+libm.expf(f32(-v)))) -def bf16(v): - i=word(v);return ((i+((i>>16)&1)+0x7fff)>>16)&0xffff -fp={'profile':'CPU source-ordered probes of default ple.cu(native_postops=false,native_bf16=false), NOT CUDA parity','host':platform.platform(),'libm':'current process C sqrtf/expf/fmaf via ctypes; Darwin libSystem','acceptance':{'integer_decode':{'abs':0,'rel':0,'ulp':0},'CPU_projection_norm_gate_broadcast_conv_residual':{'abs':0,'rel':0,'ulp':0,'scope':'exact frozen finite F32 words for these source-ordered CPU probes only; do not apply to a different reduction/libm/GPU backend'},'CUDA_floating_stages':'Unqualified: requires independently justified backend-specific bounds or source/order/compile equivalence; no guessed abs/rel/ULP'},'gate':[{'input_word':word(x),'expected_word':word(gate(x))} for x in [-1.,-1e-9,-0.,0.,1e-9,1.]],'bf16_round':[{'input_word':word(x),'expected_bf16':bf16(x)} for x in [0.,-0.,1.,1.+2**-8,1.+3*2**-8,-1.-2**-8]],'constant_norm':[],'conv':[],'residual_rival':{}} -for x,gamma in [(0.,1.),(1.,1.),(-1.,0.5),(0.25,-2.)]: - # 2560 repeated values: f32 square, double sum (exact on this fixture), - # double division, materialized F32 mean then F32 epsilon/sqrt/divide, - # source left-to-right x*scale*gamma. - mean=f32(float(f32(x*x))*2560/2560) - scale=f32(1.0/libm.sqrtf(f32(mean+f32(1e-6)))) - fp['constant_norm'].append({'input_word':word(x),'gamma_word':word(gamma),'mean_word':word(mean),'scale_word':word(scale),'expected_word':word(f32(f32(x*scale)*gamma)),'columns':2560}) -for h,current,taps in [([1.,2.,3.],4.,[0.5,-1.,2.,-0.25]),([-1.,0.,1.],-2.,[1.,0.5,-0.25,2.])]: - acc=0. - for x,w in zip(h+[current],taps):acc=libm.fmaf(w,x,acc) - fp['conv'].append({'history_rows':[0,3,6],'history_words':[word(x) for x in h],'current_word':word(current),'tap_words':[word(x) for x in taps],'tap_index':'k+4*channel','acc_word':word(acc),'silu_word':word(silu(acc))}) -a=silu(1.);R=16777216.;g=-16777216. -fp['residual_rival']={'R_word':word(R),'gated_word':word(g),'conv_word':word(a),'default_left_word':word(f32(f32(R+g)+a)),'native_right_word':word(f32(R+f32(g+a)))} - -def from_bf16(v):return struct.unpack(' -#include -#include -#include -#include -#include -#include -#include -#include - -// ---- stand-ins for what the extracted function touches -struct Options { - std::vector> cvec_files; - int cvec_first = -1, cvec_last = -1; - int cvec_mode = 1; - int cvec_single = -1; -}; -namespace strata::kernels { -struct Recorded { std::vector dir, s; int mode = -1, first = 0, last = 0; int64_t n_embd = 0, hc = 0; bool called = false; }; -inline Recorded g_recorded; -inline bool cvec_upload(const std::vector& dir, const std::vector& s, int mode, int first, int last, - int64_t n_embd, int64_t hc, std::string&) { - g_recorded = {dir, s, mode, first, last, n_embd, hc, true}; - return true; -} -} // namespace strata::kernels - -#include "fragment_load_control_vectors.inc" - -namespace { -uint64_t lcg_state = 77; -uint32_t next32() { lcg_state = lcg_state * 6364136223846793005ull + 1442695040888963407ull; return (uint32_t) (lcg_state >> 32); } -float value() { return (float) ((int32_t) (next32() >> 8) - (1 << 23)) / 8388608.0f * 2.0f; } -uint32_t bits(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; } - -void put_u32(std::string& b, uint32_t v) { b.append((const char*) &v, 4); } -void put_u64(std::string& b, uint64_t v) { b.append((const char*) &v, 8); } -void put_str(std::string& b, const std::string& s) { put_u64(b, s.size()); b += s; } -struct T { std::string name; std::vector data; uint32_t type = 0; }; -std::string gguf(const std::string& arch, const std::vector& ts, bool hint = false) { - std::string b; - put_u32(b, 0x46554747u); put_u32(b, 3); put_u64(b, ts.size()); put_u64(b, 1 + (hint ? 1 : 0)); - put_str(b, "general.architecture"); put_u32(b, 8); put_str(b, arch); - if (hint) { put_str(b, "controlvector.model_hint"); put_u32(b, 8); put_str(b, "qwen4exp"); } - uint64_t off = 0; - for (const T& t : ts) { - put_str(b, t.name); put_u32(b, 1); put_u64(b, t.data.size()); put_u32(b, t.type); put_u64(b, off); - off += (t.data.size() * 4 + 31) / 32 * 32; - } - while (b.size() % 32) b.push_back(0); - for (const T& t : ts) { - b.append((const char*) t.data.data(), t.data.size() * 4); - while (b.size() % 32) b.push_back(0); - } - return b; -} -std::string hex(const std::string& s) { - static const char* d = "0123456789abcdef"; - std::string o; - for (unsigned char c : s) { o += d[c >> 4]; o += d[c & 15]; } - return o; -} -std::vector vec(int n) { std::vector v(n); for (auto& x : v) x = value(); return v; } - -struct Case { std::string name; std::vector> files; std::vector contents; Options o; }; -} // namespace - -int main() { - const int L = 6, N = 40, HC = 4; - strata::core::ModelGeometry g; - g.n_layers = L; g.n_embd = N; g.hc = HC; - const std::string dir = std::string(getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp") + "/leleka_cvec_golden"; - std::system(("mkdir -p " + dir).c_str()); - - std::vector A = {gguf("controlvector", {{"direction.0", vec(N)}, {"direction.2", vec(N)}, {"direction.3", vec(N)}, {"direction.9", vec(N)}}, true), - gguf("controlvector", {{"direction.2", vec(N)}, {"direction.4", vec(N)}})}; - const std::string wrong_arch = gguf("llama", {{"direction.2", vec(N)}}); - const std::string wrong_shape = gguf("controlvector", {{"direction.2", vec(N + 1)}}); - const std::string wrong_type = gguf("controlvector", {{"direction.2", vec(N), 1}}); - const std::string no_dirs = gguf("controlvector", {{"other.2", vec(N)}}); - const std::string only_layer0 = gguf("controlvector", {{"direction.0", vec(N)}}); - const std::string zero_dir = gguf("controlvector", {{"direction.2", std::vector(N, 0.0f)}}); - const std::string truncated = A[0].substr(0, 60); - std::string bad_magic = A[0]; bad_magic[0] = 'X'; - std::string v2 = A[0]; v2[4] = 2; - - std::vector cases; - auto mk = [&](const std::string& name, std::vector> files, std::vector contents, Options o) { - cases.push_back({name, std::move(files), std::move(contents), o}); - }; - Options add; add.cvec_mode = 1; - Options proj; proj.cvec_mode = 0; - Options range = add; range.cvec_first = 2; range.cvec_last = 4; - Options proj_range = proj; proj_range.cvec_first = 2; proj_range.cvec_last = 5; - Options single = proj; single.cvec_single = 3; - Options single_missing = proj; single_missing.cvec_single = 5; - Options single_ignored_in_add = add; single_ignored_in_add.cvec_single = 5; - Options out_of_range = add; out_of_range.cvec_first = 5; out_of_range.cvec_last = 5; - Options wide = add; wide.cvec_last = 100; - mk("add_two_files", {{"a.gguf", 1.5f}, {"b.gguf", -0.5f}}, {A[0], A[1]}, add); - mk("add_range", {{"a.gguf", 1.0f}, {"b.gguf", 2.0f}}, {A[0], A[1]}, range); - mk("add_last_beyond_model", {{"a.gguf", 0.25f}}, {A[0]}, wide); - mk("project_two_files", {{"a.gguf", 1.0f}, {"b.gguf", 1.0f}}, {A[0], A[1]}, proj); - mk("project_range", {{"a.gguf", 0.75f}, {"b.gguf", 0.5f}}, {A[0], A[1]}, proj_range); - mk("project_single_layer", {{"a.gguf", 1.0f}}, {A[0]}, single); - mk("project_single_missing", {{"a.gguf", 1.0f}}, {A[0]}, single_missing); - mk("add_ignores_single", {{"a.gguf", 1.0f}}, {A[0]}, single_ignored_in_add); - mk("nothing_in_range", {{"a.gguf", 1.0f}}, {A[0]}, out_of_range); - mk("zero_scale_project", {{"a.gguf", 0.0f}}, {A[0]}, proj); - mk("zero_direction_project", {{"z.gguf", 1.0f}}, {zero_dir}, proj); - mk("wrong_architecture", {{"w.gguf", 1.0f}}, {wrong_arch}, add); - mk("wrong_shape", {{"s.gguf", 1.0f}}, {wrong_shape}, add); - mk("wrong_type", {{"t.gguf", 1.0f}}, {wrong_type}, add); - mk("no_direction_tensors", {{"n.gguf", 1.0f}}, {no_dirs}, add); - mk("only_layer_zero", {{"o.gguf", 1.0f}}, {only_layer0}, add); - mk("truncated", {{"x.gguf", 1.0f}}, {truncated}, add); - mk("bad_magic", {{"m.gguf", 1.0f}}, {bad_magic}, add); - mk("version_2", {{"v.gguf", 1.0f}}, {v2}, add); - - std::printf("{\"n_layers\":%d,\"n_embd\":%d,\"hc\":%d,\"cases\":[", L, N, HC); - for (size_t ci = 0; ci < cases.size(); ++ci) { - Case& c = cases[ci]; - Options o = c.o; - for (size_t i = 0; i < c.files.size(); ++i) { - const std::string path = dir + "/" + std::to_string(ci) + "_" + c.files[i].first; - std::ofstream(path, std::ios::binary).write(c.contents[i].data(), (std::streamsize) c.contents[i].size()); - o.cvec_files.push_back({path, c.files[i].second}); - } - strata::kernels::g_recorded = {}; - std::string summary, err; - const bool ok = load_control_vectors(o, g, summary, err); - // the error text names the temp path; record it with that prefix replaced by the file label - for (size_t i = 0; i < c.files.size(); ++i) { - const std::string path = dir + "/" + std::to_string(ci) + "_" + c.files[i].first; - for (size_t at; (at = err.find(path)) != std::string::npos;) err.replace(at, path.size(), c.files[i].first); - } - std::printf("%s\n{\"name\":\"%s\",\"options\":{\"first\":%d,\"last\":%d,\"mode\":%d,\"single\":%d},\"files\":[", ci ? "," : "", c.name.c_str(), - o.cvec_first, o.cvec_last, o.cvec_mode, o.cvec_single); - for (size_t i = 0; i < c.files.size(); ++i) - std::printf("%s{\"label\":\"%s\",\"scale\":%u,\"bytes\":\"%s\"}", i ? "," : "", c.files[i].first.c_str(), bits(c.files[i].second), hex(c.contents[i]).c_str()); - std::printf("],\"ok\":%d,\"error\":\"%s\"", ok ? 1 : 0, ok ? "" : err.c_str()); - if (ok) { - const auto& r = strata::kernels::g_recorded; - std::printf(",\"summary\":\"%s\",\"mode\":%d,\"first\":%d,\"last\":%d,\"dir\":[", summary.c_str(), r.mode, r.first, r.last); - for (size_t i = 0; i < r.dir.size(); ++i) std::printf("%s%u", i ? "," : "", bits(r.dir[i])); - std::printf("],\"s\":["); - for (size_t i = 0; i < r.s.size(); ++i) std::printf("%s%u", i ? "," : "", bits(r.s[i])); - std::printf("]"); - } - std::printf("}"); - } - std::printf("]}\n"); - std::system(("rm -rf " + dir).c_str()); - return 0; -} diff --git a/crates/experimental-ref/oracle/gen_cvec_golden.sh b/crates/experimental-ref/oracle/gen_cvec_golden.sh deleted file mode 100755 index 5849e650..00000000 --- a/crates/experimental-ref/oracle/gen_cvec_golden.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -# Regenerates tests/fixtures/cvec_golden.json from generate.cpp's own load_control_vectors (extracted verbatim) -# running on synthetic control-vector GGUF files. Host-only; `cvec_upload` is a recorder. -# crates/experimental-ref/oracle/gen_cvec_golden.sh -set -eu -here=$(cd "$(dirname "$0")" && pwd) -strata="$here/../../../engine/strata" -out="$here/../tests/fixtures" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -awk '/^bool load_control_vectors\(const Options& o, const strata::core::ModelGeometry& g, std::string& summary, std::string& err\) \{/ {on=1} on {print} on && /^}/ {exit}' \ - "$strata/src/program/generate.cpp" > "$work/fragment_load_control_vectors.inc" -test -s "$work/fragment_load_control_vectors.inc" -# -ffp-contract=off: the Original's host build has no FMA, `data += scale * src` is a multiply then an add -${CXX:-clang++} -std=c++17 -O1 -ffp-contract=off -Wno-unused-function -Wno-unused-variable -I"$strata/include" -I"$work" \ - "$here/gen_cvec_golden.cpp" -o "$work/gen_cvec" -mkdir -p "$out" -"$work/gen_cvec" > "$out/cvec_golden.json" -echo "wrote $out/cvec_golden.json" diff --git a/crates/experimental-ref/oracle/gen_kv_golden.cpp b/crates/experimental-ref/oracle/gen_kv_golden.cpp deleted file mode 100644 index e7d77e81..00000000 --- a/crates/experimental-ref/oracle/gen_kv_golden.cpp +++ /dev/null @@ -1,166 +0,0 @@ -// Golden fixtures for the Q4_0 / INT8 / FWHT arithmetic and the KV layout sizes, produced by the Original's own -// host code: the functions below are included VERBATIM (extracted by gen_kv_golden.sh with awk, never retyped) -// from engine/strata/src/kernels/kv_q4_parity.cpp (fwht256_host_reference, quantize_block_q4_0_host), -// kv_hybrid_parity.cpp (the INT8 K host reference) and the layer.cpp / kv_stream.cu size functions. -// usage: gen_kv_golden (the script builds it twice: -ffp-contract=off and =fast) -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/kv_stream.hpp" -#include "strata/kernels/qsa.hpp" - -#include -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; -using namespace strata::kernels; - -namespace { -bool g_without_key = false, g_kv_q4 = false; -#include "fragment_fwht_q4.inc" -#include "fragment_pool_bytes.inc" -} // namespace -namespace strata::kernels { -#include "fragment_block_bytes.inc" -} - -namespace { -uint64_t lcg_state = 0x9e3779b97f4a7c15ull; -uint32_t next32() { - lcg_state = lcg_state * 6364136223846793005ull + 1442695040888963407ull; - return (uint32_t) (lcg_state >> 32); -} -float uniform() { return (float) (next32() >> 8) / 16777216.0f; } // [0, 1) -float gauss() { // sum of 12 uniforms - 6 - float s = 0.0f; - for (int i = 0; i < 12; ++i) s += uniform(); - return s - 6.0f; -} -uint32_t bits(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; } -void print_u32(FILE* o, const float* v, int n) { - std::fprintf(o, "["); - for (int i = 0; i < n; ++i) std::fprintf(o, "%s%u", i ? "," : "", bits(v[i])); - std::fprintf(o, "]"); -} -} // namespace - -int main(int argc, char** argv) { - const std::string mode = argc > 1 ? argv[1] : "separate"; - // The fused build only needs the Q4_0 section (the one place a fused multiply-add changes a result); the - // other sections are generated identically in both builds so the LCG sequence stays aligned. - const bool full = mode == "separate"; - FILE* null_out = std::fopen("/dev/null", "w"); - FILE* o = full ? stdout : null_out; - std::fprintf(o, "{\"mode\":\"%s\",\n", mode.c_str()); - - // ---- FWHT rows (the Original's host reference, butterflies then 1/16) - std::fprintf(o, "\"fwht\":["); - for (int r = 0; r < 24; ++r) { - float in[256], out[256]; - const float scale = r < 8 ? 1.0f : (r < 16 ? 37.5f : 0.003f); - for (int i = 0; i < 256; ++i) in[i] = (r == 23 ? (i == 5 ? 1.0f : 0.0f) : gauss() * scale); - std::memcpy(out, in, sizeof in); - fwht256_host_reference(out); - std::fprintf(o, "%s{\"in\":", r ? ",\n" : "\n"); - print_u32(o, in, 256); - std::fprintf(o, ",\"out\":"); - print_u32(o, out, 256); - std::fprintf(o, "}"); - } - std::fprintf(o, "],\n"); - - // ---- Q4_0 groups (quantize_block_q4_0_host on separate or fused arithmetic, whatever this build does) - o = stdout; - if (!full) std::fprintf(o, "{\"mode\":\"%s\",\n", mode.c_str()); - std::fprintf(o, "\"q4\":["); - const int groups = 480 + 96; // the last 96 sit on the code boundaries where fused and separate evaluation differ - for (int g = 0; g < groups; ++g) { - float x[32]; - const int cls = g >= 480 ? 8 : g % 8; - const float M = 0.05f + uniform() * 9.0f; - for (int i = 0; i < 32; ++i) { - float v = gauss(); - switch (cls) { - case 1: v *= 0.01f; break; - case 2: v *= 300.0f; break; - case 3: v = (i % 2 ? 1.0f : -1.0f) * (float) (i / 2) * 0.25f; break; // exact multiples - case 4: v = (float) ((int) (next32() % 17) - 8) * 0.5f; break; // ties and boundaries - case 5: v = i == 7 ? 1e4f : v * 1e-3f; break; // one outlier - case 6: v = 0.0f; break; - case 7: v = v * 1e-8f; break; // fp16 subnormal scales - case 8: { // x on the half-multiples of d, +-1 ulp - v = i == 0 ? M : (float) ((double) M * ((double) (i % 8) + 0.5) / 8.0); - if (i > 0 && (next32() & 1)) v = nextafterf(v, 0.0f); - if (i > 0 && (next32() & 2)) v = nextafterf(v, 100.0f); - break; - } - default: break; - } - x[i] = v; - } - if (cls == 0 && g % 16 == 0) { x[3] = 2.0f; x[20] = -2.0f; } // tied magnitudes, opposite sign - k::block_q4_0 blk; - quantize_block_q4_0_host(x, blk); - unsigned char raw[18]; - std::memcpy(raw, &blk, 18); - std::fprintf(o, "%s{\"x\":", g ? ",\n" : "\n"); - print_u32(o, x, 32); - std::fprintf(o, ",\"block\":\""); - for (int i = 0; i < 18; ++i) std::fprintf(o, "%02x", raw[i]); - std::fprintf(o, "\"}"); - } - std::fprintf(o, "]"); - - // ---- INT8 K groups (kv_hybrid_parity.cpp's host reference for K) - if (!full) { std::fprintf(o, "}\n"); return 0; } - std::fprintf(o, ",\n"); - std::fprintf(o, "\"q8\":["); - { - const int cells = 12, H = 2, D = 256, G = D / k::KV_Q8_GROUP; - std::vector K((size_t) cells * H * D); - for (size_t i = 0; i < K.size(); ++i) K[i] = gauss() * ((i / 64) % 5 == 0 ? 0.0f : ((i / 64) % 5) * 0.4f); - std::vector rk((size_t) cells * H * D); - std::vector rk_s((size_t) cells * H * G); -#include "fragment_q8_k.inc" - for (int c = 0; c < cells; ++c) - for (int h = 0; h < H; ++h) - for (int g = 0; g < G; ++g) { - const size_t base = ((size_t) c * H + h) * D + (size_t) g * k::KV_Q8_GROUP; - std::fprintf(o, "%s{\"x\":", (c || h || g) ? ",\n" : "\n"); - print_u32(o, &K[base], 64); - std::fprintf(o, ",\"scale\":%u,\"codes\":[", (unsigned) rk_s[((size_t) c * H + h) * G + g]); - for (int t = 0; t < 64; ++t) std::fprintf(o, "%s%d", t ? "," : "", (int) rk[base + t]); - std::fprintf(o, "]}"); - } - } - std::fprintf(o, "],\n"); - - // ---- layout sizes: the Original's own functions - const k::QsaShapes s = k::qsa_real_shapes(); - std::fprintf(o, "\"per_cell\":{\"q8\":%llu,\"q4\":%llu},\n", (unsigned long long) k::kv_q8_bytes_per_cell(s), - (unsigned long long) k::kv_q4_bytes_per_cell(s)); - std::fprintf(o, "\"block_bytes\":{\"f16\":%llu,\"int8\":%llu,\"q4\":%llu,\"value_int8\":%llu},\n", - (unsigned long long) k::kv_block_bytes(s, k::kKvF16), (unsigned long long) k::kv_block_bytes(s, k::kKvInt8), - (unsigned long long) k::kv_block_bytes(s, k::kKvQ4), (unsigned long long) k::kv_block_bytes(s, k::kKvValueInt8)); - std::fprintf(o, "\"pool_bytes\":["); - bool first = true; - for (int64_t pages : {1, 5, 64, 5120, 131072}) { - struct Case { const char* name; bool without_key, q4, hybrid, int8; } cases[] = { - {"fp16", false, false, false, false}, {"int8", false, false, false, true}, {"q4_0", false, true, false, true}, - {"k8v4", false, false, true, true}, {"int8-keyless", true, false, false, true}}; - for (const Case& c : cases) { - g_without_key = c.without_key; - g_kv_q4 = c.q4; - std::fprintf(o, "%s{\"format\":\"%s\",\"pages\":%lld,\"bytes\":%llu}", first ? "\n" : ",\n", c.name, (long long) pages, - (unsigned long long) kv_pool_bytes(s, pages, c.hybrid, c.int8)); - first = false; - } - } - std::fprintf(o, "]}\n"); - return 0; -} diff --git a/crates/experimental-ref/oracle/gen_kv_golden.sh b/crates/experimental-ref/oracle/gen_kv_golden.sh deleted file mode 100755 index 646051c8..00000000 --- a/crates/experimental-ref/oracle/gen_kv_golden.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/sh -# Regenerates tests/fixtures/kv_golden_{separate,fused}.json from the Original's host code (macOS or Linux, any -# C++17 compiler, no CUDA). The reference functions are extracted verbatim from engine/strata with awk. -# crates/experimental-ref/oracle/gen_kv_golden.sh -# `separate` is compiled with -ffp-contract=off (every x * id + 8.5f is a multiply then an add), `fused` with -# -ffp-contract=fast (-mfma on x86; arm64 fuses natively), which is how nvcc compiles the same expression. -set -eu -here=$(cd "$(dirname "$0")" && pwd) -strata="$here/../../../engine/strata" -out="$here/../tests/fixtures" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -# 1. fwht256_host_reference + quantize_block_q4_0_host, up to the end of the anonymous namespace -awk '/^void fwht256_host_reference\(float\* x\) \{/ {on=1} on && /^} \/\/ namespace/ {exit} on {print}' \ - "$strata/src/kernels/kv_q4_parity.cpp" > "$work/fragment_fwht_q4.inc" -# 2. kv_pool_bytes of layer.cpp -awk '/^uint64_t kv_pool_bytes\(const QsaShapes& s, int64_t pages, bool hybrid, bool int8\) \{/ {on=1} on {print} on && /^}/ {exit}' \ - "$strata/src/core/layer.cpp" > "$work/fragment_pool_bytes.inc" -# 3. kv_block_bytes of kv_stream.cu -awk '/^uint64_t kv_block_bytes\(const QsaShapes& s, int fmt\) \{/ {on=1} on {print} on && /^}/ {exit}' \ - "$strata/src/kernels/cuda/kv_stream.cu" > "$work/fragment_block_bytes.inc" -# 4. the INT8 K host reference loop of kv_hybrid_parity.cpp (from after the rk_s declaration to Vrot's) -awk '/std::vector rk_s\(/ {skip=1; next} skip && /std::vector Vrot/ {exit} skip {print}' \ - "$strata/src/kernels/kv_hybrid_parity.cpp" > "$work/fragment_q8_k.inc" -for f in fragment_fwht_q4 fragment_pool_bytes fragment_block_bytes fragment_q8_k; do test -s "$work/$f.inc"; done -CXX=${CXX:-clang++} -FMA="" -case $(uname -m) in x86_64|amd64) FMA="-mfma" ;; esac -common="-std=c++17 -O1 -Wno-unused-function -I$strata/include -I$here/stub -I$work" -$CXX $common -ffp-contract=off -o "$work/gen_separate" "$here/gen_kv_golden.cpp" -$CXX $common -ffp-contract=fast $FMA -o "$work/gen_fused" "$here/gen_kv_golden.cpp" -mkdir -p "$out" -"$work/gen_separate" separate > "$out/kv_golden_separate.json" -"$work/gen_fused" fused > "$out/kv_golden_fused.json" -echo "wrote $out/kv_golden_separate.json and kv_golden_fused.json" diff --git a/crates/experimental-ref/oracle/gen_remote_golden.cpp b/crates/experimental-ref/oracle/gen_remote_golden.cpp deleted file mode 100644 index 3c529705..00000000 --- a/crates/experimental-ref/oracle/gen_remote_golden.cpp +++ /dev/null @@ -1,200 +0,0 @@ -// Golden fixtures for the second-GPU expert tier. The decision code of engine/strata/src/core/remote_experts.cpp -// (selection, slot sizing, claim bookkeeping, window guard + grouping, RemoteMeta packing, the result scatter) is -// included VERBATIM through the fragments extracted by gen_remote_golden.sh; the harness provides the members and -// recorder stand-ins for the cache and layout they touch. -#include -#include -#include -#include -#include -#include - -namespace strata::kernels::cpu { constexpr int64_t MAXT = 8; } -namespace { -constexpr int64_t H = 2560; -constexpr int64_t CAP = 8 * 10; -#include "f_struct.inc" - -struct Layout { - bool native = false; - uint64_t max_blob = 1382400; - std::vector blobs; - uint64_t blob_bytes(int64_t layer) const { return blobs[(size_t) layer]; } -}; -struct Cache { - std::vector> sel; - int32_t slot_of(int64_t layer, int64_t expert) const { - for (size_t i = 0; i < sel.size(); ++i) if (sel[i].first == layer && sel[i].second == expert) return (int32_t) i; - return -1; - } - uint64_t device_slot(int32_t slot) const { return 0x100000000ull + (uint64_t) slot * 0x200000ull; } -}; -struct Primary { - std::vector has; // layers * experts - int64_t experts = 0; - int32_t slot_of(int64_t layer, int64_t expert) const { return has[(size_t) (layer * experts + expert)] ? 3 : -1; } -}; - -struct Tier { - int device = 1; - int64_t n_expert_ = 0; - int device_ = 1; - Layout lay; - Cache cache_; - std::vector owned_ = std::vector(CAP, 0), layers_present_; - std::vector group_of_ = std::vector(CAP, -1), group_id_; - std::vector ptr_; - std::vector start_, dst_, tok_, original_row_; - uint64_t computed_ = 0; - unsigned char h_meta_[sizeof(RemoteMeta)] = {}; - const float* h_out_ = nullptr; - std::string err; - void close() {} - - // open() up to the memory check; returns selected.empty() == false - bool select(int slots, int64_t layers, int64_t experts, const std::vector>& ranked, - const Primary& primary, std::vector& claimed, std::vector>& selected_out, - uint64_t& needed_out) { - n_expert_ = experts; -#include "f_select.inc" - uint64_t needed_total = 0; - { -#include "f_needed.inc" - needed_total = needed; - } - layers_present_.assign((size_t) layers, 0); -#include "f_mark.inc" - selected_out = selected; - cache_.sel = selected; - needed_out = needed_total; - return true; - } - - bool begin(int64_t layer, const int32_t* ids, int64_t n_tok, int64_t k, const int32_t* kind, const int32_t* primary_res) { - const int64_t n = n_tok * k; -#include "f_begin.inc" - return true; - } - void pack(int64_t) { -#include "f_meta.inc" - } - void finish(float* out) { -#include "f_finish.inc" - } -}; - -uint64_t lcg_state = 4242; -uint32_t next32() { lcg_state = lcg_state * 6364136223846793005ull + 1442695040888963407ull; return (uint32_t) (lcg_state >> 32); } -uint32_t below(uint32_t n) { return next32() % n; } - -template void arr(const char* name, const std::vector& v, bool comma = true) { - std::printf("\"%s\":[", name); - for (size_t i = 0; i < v.size(); ++i) std::printf("%s%lld", i ? "," : "", (long long) v[i]); - std::printf("]%s", comma ? "," : ""); -} -} // namespace - -int main() { - std::printf("{\"open\":["); - const int L = 6, E = 24; - std::vector tiers; - std::vector primaries; - for (int c = 0; c < 40; ++c) { - Tier t; - Primary p; - p.experts = E; - p.has.assign((size_t) L * E, 0); - for (auto& h : p.has) h = below(5) == 0; - std::vector claimed((size_t) L * E, 0); - for (auto& v : claimed) v = below(6) == 0; - std::vector> ranked; - const int rn = 5 + (int) below(60); - for (int i = 0; i < rn; ++i) ranked.push_back({(int32_t) below(L + 2) - 1, (int32_t) below(E + 3) - 1}); - if (c % 5 == 3) ranked.insert(ranked.begin() + 1, ranked[0]); - t.lay.native = c % 2 == 1; - for (int l = 0; l < L; ++l) t.lay.blobs.push_back(100000 + below(900000)); - const int slots = 1 + (int) below(30); - const std::vector claimed_in = claimed; - std::vector> sel; - uint64_t needed = 0; - t.select(slots, L, E, ranked, p, claimed, sel, needed); - std::printf("%s{\"slots\":%d,\"native\":%d,", c ? "," : "", slots, t.lay.native ? 1 : 0); - arr("blobs", t.lay.blobs); - std::printf("\"max_blob\":%llu,", (unsigned long long) t.lay.max_blob); - arr("primary", p.has); - arr("claimed_in", claimed_in); - std::printf("\"ranked\":["); - for (size_t i = 0; i < ranked.size(); ++i) std::printf("%s[%d,%d]", i ? "," : "", ranked[i].first, ranked[i].second); - std::printf("],\"selected\":["); - for (size_t i = 0; i < sel.size(); ++i) std::printf("%s[%d,%d]", i ? "," : "", sel[i].first, sel[i].second); - std::printf("],\"needed\":%llu,", (unsigned long long) needed); - arr("layers_present", t.layers_present_); - arr("claimed_out", claimed, false); - std::printf("}"); - tiers.push_back(t); - primaries.push_back(p); - } - std::printf("],\"begin\":["); - int emitted = 0; - for (int c = 0; c < 200; ++c) { - Tier& t = tiers[(size_t) (c % tiers.size())]; - if (t.cache_.sel.empty()) continue; - const Primary& p = primaries[(size_t) (c % tiers.size())]; - const int64_t n_tok = c % 23 == 0 ? 9 : 1 + below(8); - int64_t k = c % 31 == 0 ? 9 : 10; - int64_t layer = c % 29 == 0 ? L : (int64_t) below(L); - // bias ids toward held experts so groups form - std::vector ids((size_t) (n_tok * k) + 1); - for (auto& id : ids) { - const uint32_t r = below(10); - if (r < 6) id = t.cache_.sel[below((uint32_t) t.cache_.sel.size())].second; - else if (r == 9) id = (int32_t) below(4) - 2 + (r == 9 ? E : 0); - else id = (int32_t) below(E); - } - const bool use_kind = c % 3 == 1, use_primary = c % 4 == 2; - std::vector kind(ids.size()), pres((size_t) L * E); - for (auto& v : kind) v = below(4) == 0 ? 2 : -1; - for (size_t i = 0; i < pres.size(); ++i) pres[i] = p.has[i] ? 1 : -1; - t.start_.clear(); t.dst_.clear(); t.tok_.clear(); t.original_row_.clear(); t.group_id_.clear(); t.ptr_.clear(); - t.computed_ = 0; - t.owned_.assign(CAP, 0); - const bool ok = t.begin(layer, ids.data(), n_tok, k, use_kind ? kind.data() : nullptr, use_primary ? pres.data() : nullptr); - std::printf("%s{\"layer\":%lld,\"n_tok\":%lld,\"k\":%lld,\"tier\":%d,", emitted++ ? "," : "", (long long) layer, (long long) n_tok, (long long) k, (int) (c % tiers.size())); - arr("ids", std::vector(ids.begin(), ids.begin() + (size_t) (n_tok * k))); - std::printf("\"use_kind\":%d,\"use_primary\":%d,", use_kind, use_primary); - arr("kind", std::vector(kind.begin(), kind.begin() + (size_t) (n_tok * k))); - std::printf("\"ok\":%d,", ok ? 1 : 0); - if (ok) { - arr("owned", t.owned_); - arr("group_id", t.group_id_); - arr("ptr", t.ptr_); - arr("start", t.start_); - arr("dst", t.dst_); - arr("tok", t.tok_); - arr("original_row", t.original_row_); - std::printf("\"computed\":%llu,", (unsigned long long) t.computed_); - if (!t.group_id_.empty()) { - std::memset(t.h_meta_, 0, sizeof t.h_meta_); - t.pack(n_tok); - std::printf("\"meta\":["); - for (size_t i = 0; i < sizeof t.h_meta_; ++i) std::printf("%s%u", i ? "," : "", t.h_meta_[i]); - std::printf("],"); - // finish: rows of 4 floats stand in for H (the verbatim loop uses H; use the real width on a sparse check) - std::vector compact(t.dst_.size() * H); - for (size_t i = 0; i < compact.size(); ++i) compact[i] = (float) (i / H) + 1.0f + (float) (i % H) * 0.0001f; - std::vector out((size_t) (n_tok * k) * H, -1.0f); - // run the verbatim scatter with the real width - t.h_out_ = compact.data(); - t.finish(out.data()); - std::printf("\"scatter_rows\":["); - for (size_t r = 0; r < (size_t) (n_tok * k); ++r) { - // row signature: first, middle, last element - std::printf("%s[%.7g,%.7g,%.7g]", r ? "," : "", out[r * H], out[r * H + H / 2], out[r * H + H - 1]); - } - std::printf("],"); - } - } - std::printf("\"end\":0}"); - } - std::printf("]}\n"); -} diff --git a/crates/experimental-ref/oracle/gen_remote_golden.sh b/crates/experimental-ref/oracle/gen_remote_golden.sh deleted file mode 100755 index 9aaebc7d..00000000 --- a/crates/experimental-ref/oracle/gen_remote_golden.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh -# Regenerates tests/fixtures/remote_golden.json from the Original's remote_experts.cpp: the expert selection of -# `open`, the grouping of `begin`, the RemoteMeta packing and `finish`'s scatter are extracted VERBATIM (awk) and -# compiled on the host against recorder stand-ins for the cache / layout. No CUDA involved. -# crates/experimental-ref/oracle/gen_remote_golden.sh -set -eu -here=$(cd "$(dirname "$0")" && pwd) -strata="$here/../../../engine/strata" -src="$strata/src/core/remote_experts.cpp" -out="$here/../tests/fixtures" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -# open(): rank filter ... "no unclaimed experts" check -awk '/^ std::vector> selected;$/ {on=1} on {print} on && /selected\.empty\(\)/ {exit}' "$src" > "$work/f_select.inc" -# open(): device bytes of the chosen slots -awk '/^ uint64_t needed = 0;$/ {on=1} on {print; n++} on && n==3 {exit}' "$src" > "$work/f_needed.inc" -# open(): claim bookkeeping -awk '{ if (hold != "" && index($0, "layers_present_[(size_t) pair.first] = 1;")) { print hold; on=1 } hold=$0 } on {print} on && /^ }$/ {exit}' "$src" > "$work/f_mark.inc" -# begin(): window guard ... group/start/dst/tok construction -awk '/^ if \(n <= 0 \|\| n > CAP/ {on=1} on {print} on && /^ start_\.push_back\(\(int32_t\) dst_\.size\(\)\);$/ {exit}' "$src" > "$work/f_begin.inc" -# begin(): metadata packing -awk '/auto\* meta = \(RemoteMeta\*\) h_meta_;/ {on=1} on {print} on && /meta->count = / {exit}' "$src" > "$work/f_meta.inc" -# finish(): scatter -awk '/^ for \(size_t i = 0; i < original_row_\.size\(\); \+\+i\)$/ {on=1} on {print; n++} on && n==2 {exit}' "$src" > "$work/f_finish.inc" -# struct RemoteMeta -awk '/^struct RemoteMeta \{/ {on=1} on {print} on && /^};/ {exit}' "$src" > "$work/f_struct.inc" -for f in select needed mark begin meta finish struct; do test -s "$work/f_$f.inc" || { echo "empty fragment $f" >&2; exit 1; }; done -${CXX:-clang++} -std=c++17 -O1 -ffp-contract=off -I"$work" "$here/gen_remote_golden.cpp" -o "$work/gen_remote" -mkdir -p "$out" -"$work/gen_remote" > "$out/remote_golden.json" -echo "wrote $out/remote_golden.json" diff --git a/crates/experimental-ref/oracle/gen_seal_additions.py b/crates/experimental-ref/oracle/gen_seal_additions.py deleted file mode 100644 index 2c05ec51..00000000 --- a/crates/experimental-ref/oracle/gen_seal_additions.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python3 -"""Regenerates crates/cuda-driver/seal-plans/cuda-seal-plan-additions-experimental.json (sha256 + bytes of the six experimental .cu assets -and their Rust consumers). Run from the repository root after any edit to those files: - python3 crates/experimental-ref/oracle/gen_seal_additions.py -Flags follow engine/strata/CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list and the -target sets only CUDA_STANDARD 17, so the build is precise, default -fmad.""" -import hashlib, json - -def sha(path): - data = open(path, "rb").read() - return {"sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data)} - -PROGRAMS = [ - ("kv_q4", "kv_q4.cu", "FWHT-256 + Q4_0 append (step/batched) + gather; Original kv_q4.cu precise (default flags, not in the fast-math list); K8V4's Q4_0 V half and rotated INT8's FWHT"), - ("kv_q8", "kv_q8.cu", "INT8 append (K+V, K8V4 K half, V-only) + gather; Original kv_q8.cu precise"), - ("kv_stream", "kv_stream.cu", "CLOCK residency resolver, block copy, ring table, u4 copy; Original kv_stream.cu precise; integer only"), - ("keyless", "keyless.cu", "per-head query routing (fmaf-ordered 256x256); Original keyless.cu precise"), - ("qsa_attn", "qsa_decode_attn.cu", "experimental attention modes 2/3/4 + merge; Original qsa_decode_attn.cu precise (expf/exp2f exact, not in the fast-math list)"), - ("cvec", "cvec.cu", "control-vector apply; Original cvec.cu default flags (its own __expf in sigmoidf_ is explicit in the source)"), -] -src = "crates/cuda-driver/src/" -assets = [] -for i, (name, original, policy) in enumerate(PROGRAMS): - assets.append({ - "cu": f"{src}experimental_{name}.cu", - "cu_pin": sha(f"{src}experimental_{name}.cu"), - "ptx": f"{src}experimental_{name}.ptx", - "flags": ["-ptx", "-O3", "-arch=sm_120", "-std=c++17"], - "policy": "EXPERIMENTAL, off by default (OptIn). " + policy, - "direct_original_headers": [], - "original": f"engine/strata/src/kernels/cuda/{original}", - "rust_consumers": {"experimental.rs": sha(src + "experimental.rs"), "experimental_gpu.rs": sha(src + "experimental_gpu.rs")}, - "rust_fields_to_fill": {"experimental.rs": [f"PINS[{i}].source_sha256", f"PINS[{i}].ptx_sha256"]}, - "encoding": "concat_include_str", - "seal_sha256": None, - "seal_length": None, - }) -doc = { - "schema": 1, - "note": "Additions for the experimental Strata modes. None of these six .cu files has been compiled; PINS in experimental.rs are all zero and admit_ptx refuses every asset until Root builds the PTX and freezes the digests. Flags follow engine/strata/CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list (native_* only) and the strata_kernels target adds no other CUDA flag besides CUDA_STANDARD 17, so the build is precise (no --use_fast_math) with default -fmad contraction.", - "assets": assets, -} -with open("crates/cuda-driver/seal-plans/cuda-seal-plan-additions-experimental.json", "w") as f: - json.dump(doc, f, indent=2) - f.write("\n") diff --git a/crates/experimental-ref/oracle/gen_stream_golden.cpp b/crates/experimental-ref/oracle/gen_stream_golden.cpp deleted file mode 100644 index dedfe0f2..00000000 --- a/crates/experimental-ref/oracle/gen_stream_golden.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// Golden fixtures for the KV streaming planner: `kv_plan`, `kv_pool_bytes`, `qsa_state_bytes`, `qsa_shapes`, -// `align_up16` and `qsa_kv_resident_min` of engine/strata/src/core/layer.cpp, included VERBATIM (extracted by -// gen_stream_golden.sh with awk, never retyped) and driven over a grid of formats, contexts, rings and -// --kv-resident values. Host-only: no CUDA symbol is needed. -#include "strata/core/layout.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/kv_stream.hpp" -#include "strata/kernels/qsa.hpp" - -#include -#include -#include -#include -#include - -namespace strata::core { -using strata::kernels::QsaShapes; -int64_t qsa_kv_resident_min(); -#include "fragment_flags.inc" -namespace { -#include "fragment_shapes.inc" -#include "fragment_streaming.inc" -} // namespace -#include "fragment_state_bytes.inc" -#include "fragment_resident_min.inc" - -void emit() { - const ModelGeometry g; - struct Fmt { const char* name; bool without_key, int8, q4, hybrid; } fmts[] = { - {"fp16", false, false, false, false}, {"int8", false, true, false, false}, {"q4_0", false, false, true, false}, - {"k8v4", false, false, false, true}, {"int8-keyless", true, true, false, false}}; - std::printf("{\"cases\":["); - bool first = true; - for (const Fmt& f : fmts) - for (int64_t max_cells : {4096ll, 32768ll, 262144ll, 524288ll}) - for (int64_t ring : {0ll, 256ll, -1ll}) - for (int64_t resident : {0ll, 1000ll, 20480ll, 65536ll}) - for (int rope = 0; rope < 2; ++rope) { - g_without_key = f.without_key; - g_kv_int8 = f.int8; - g_kv_q4 = f.q4; - g_kv_hybrid = f.hybrid; - g_kv_resident = resident; - const QsaShapes s = qsa_shapes(g); - const KvPlan p = kv_plan(s, max_cells, ring); - const uint64_t bytes = qsa_state_bytes(g, max_cells, rope != 0, ring); - std::printf("%s\n{\"format\":\"%s\",\"max_cells\":%lld,\"ring\":%lld,\"resident\":%lld,\"rope\":%d," - "\"mode\":%d,\"pages\":%lld,\"slots\":%lld,\"pooled_rows\":%lld,\"state_bytes\":%llu}", - first ? "" : ",", f.name, (long long) max_cells, (long long) ring, (long long) resident, rope, - p.mode, (long long) p.pages, (long long) p.slots, (long long) p.pooled_rows, - (unsigned long long) bytes); - first = false; - } - std::printf("],\"resident_min\":%lld,\"map_bytes_5120\":%llu}\n", (long long) qsa_kv_resident_min(), - (unsigned long long) strata::kernels::kv_stream_map_bytes(5120)); -} -} // namespace strata::core - -int main() { - strata::core::emit(); - return 0; -} diff --git a/crates/experimental-ref/oracle/gen_stream_golden.sh b/crates/experimental-ref/oracle/gen_stream_golden.sh deleted file mode 100755 index 71a271e1..00000000 --- a/crates/experimental-ref/oracle/gen_stream_golden.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/sh -# Regenerates tests/fixtures/stream_plan_golden.json from layer.cpp's own planner functions (extracted verbatim). -# crates/experimental-ref/oracle/gen_stream_golden.sh -set -eu -here=$(cd "$(dirname "$0")" && pwd) -strata="$here/../../../engine/strata" -out="$here/../tests/fixtures" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -layer="$strata/src/core/layer.cpp" -grep -m1 '^namespace { bool g_without_key' "$layer" | sed 's/^namespace {//; s/}$//' > "$work/fragment_flags.inc" -grep -m1 '^QsaShapes qsa_shapes(const ModelGeometry& g) {' "$layer" > "$work/fragment_shapes.inc" -grep -m1 '^uint64_t align_up16(uint64_t n) {' "$layer" >> "$work/fragment_shapes.inc" -# the streaming chunk: from the globals to the end of kv_pool_bytes (the anonymous namespace closes after it) -awk '/^int64_t g_kv_resident = 0;/ {on=1} on && /^} \/\/ namespace/ {exit} on {print}' "$layer" > "$work/fragment_streaming.inc" -awk '/^uint64_t qsa_state_bytes\(const ModelGeometry& g, int64_t max_cells, bool with_rope, int64_t ring_cells\) \{/ {on=1} on {print} on && /^}/ {exit}' \ - "$layer" > "$work/fragment_state_bytes.inc" -grep -m1 '^int64_t qsa_kv_resident_min()' "$layer" > "$work/fragment_resident_min.inc" -for f in fragment_flags fragment_shapes fragment_streaming fragment_state_bytes fragment_resident_min; do test -s "$work/$f.inc"; done -${CXX:-clang++} -std=c++17 -O1 -ffp-contract=off -Wno-unused-function -Wno-unused-variable -I"$strata/include" -I"$here/stub" -I"$work" \ - "$here/gen_stream_golden.cpp" -o "$work/gen_stream" -mkdir -p "$out" -"$work/gen_stream" > "$out/stream_plan_golden.json" -echo "wrote $out/stream_plan_golden.json" diff --git a/crates/experimental-ref/oracle/stub/cuda_runtime.h b/crates/experimental-ref/oracle/stub/cuda_runtime.h deleted file mode 100644 index 18d0d282..00000000 --- a/crates/experimental-ref/oracle/stub/cuda_runtime.h +++ /dev/null @@ -1,3 +0,0 @@ -// Host-only stand-in: the Original headers pulled in by the oracle harnesses need no CUDA symbol, only the -// include to resolve. Nothing here is ever linked or executed on a device. -#pragma once diff --git a/crates/experimental-ref/src/lib.rs b/crates/experimental-ref/src/lib.rs index 283b8044..2886c44b 100644 --- a/crates/experimental-ref/src/lib.rs +++ b/crates/experimental-ref/src/lib.rs @@ -1,5 +1,5 @@ //! CPU references, cell layouts and planners for the *experimental* modes of the Original Strata engine -//! (`engine/strata`), in safe Rust. Every mode here is lossy or otherwise unqualified and is therefore OFF by +//! (Strata 41cf05a0), in safe Rust. Every mode here is lossy or otherwise unqualified and is therefore OFF by //! default; callers must name the mode explicitly (see `leleka-cuda-driver::experimental`). //! //! * [`f16`], [`fwht`], [`q4_0`], [`kv_q8`] - the arithmetic of `f16_bits.hpp`, `kv_q4.cu`, `kv_q8.cu`. diff --git a/crates/experimental-ref/tests/kv_golden.rs b/crates/experimental-ref/tests/kv_golden.rs index 26dec0bd..0ea48e10 100644 --- a/crates/experimental-ref/tests/kv_golden.rs +++ b/crates/experimental-ref/tests/kv_golden.rs @@ -1,5 +1,5 @@ //! Golden tests: the Rust references against fixtures produced by the Original's own host code -//! (`oracle/gen_kv_golden.sh`; the reference functions are extracted verbatim from `engine/strata`). +//! (`oracle/gen_kv_golden.sh`; the reference functions are extracted verbatim from Strata 41cf05a0). use leleka_experimental_ref::{ fwht, kv_q8, diff --git a/crates/experimental-ref/tests/literal_port.rs b/crates/experimental-ref/tests/literal_port.rs deleted file mode 100644 index f43682d9..00000000 --- a/crates/experimental-ref/tests/literal_port.rs +++ /dev/null @@ -1,346 +0,0 @@ -//! Drift guard for the six CUDA ports: every line of every `__device__` / `__global__` function body of the -//! Original (`engine/strata/src/kernels/cuda/*.cu`) must still appear, whitespace-normalised, in the checked-in -//! port (`crates/cuda-driver/src/experimental_*.cu`). Signatures, host wrappers and error handling are the -//! documented deviations; kernel bodies are not allowed to differ. -//! -//! A device function of the Original that the port deliberately does not carry is named in that pair's -//! `EXCLUDED` list with its reason. The list is the only way past the guard, it is checked both ways (a name that -//! no longer exists in the Original fails, so the list cannot rot), and a NEW device function of the Original -//! that is neither in the port nor in the list fails the test: the upstream sync has to be looked at. -//! -//! History: the 2026-10-25 sync of `engine/strata` to upstream `41cf05a0` moved the Original kernels and the -//! ports were re-synced on 2026-11-03. - -use std::collections::HashSet; - -fn norm(line: &str) -> String { - line.split_whitespace().collect::>().join(" ") -} - -/// One `__global__` / `__device__` function of a source: its name and the normalised lines of its body. -#[derive(Debug)] -struct Body { - name: String, - lines: Vec, -} - -/// The function name of a signature (text between the `__global__` / `__device__` marker and the opening brace): -/// the identifier right before the first `(` once `__launch_bounds__(..)` is removed. -fn signature_name(signature: &str) -> String { - let mut text = signature.to_string(); - while let Some(i) = text.find("__launch_bounds__") { - let open = text[i..].find('(').map(|k| i + k); - let close = open.and_then(|o| text[o..].find(')').map(|k| o + k)); - match close { - Some(c) => text.replace_range(i..=c, " "), - None => break, - } - } - let head = match text.find('(') { - Some(i) => &text[..i], - None => &text[..], - }; - head.trim_end() - .rsplit(|c: char| !(c.is_alphanumeric() || c == '_')) - .next() - .unwrap_or("") - .to_string() -} - -/// Offset (from `after`) of the `}` that closes the `{` at `open`. -fn matching_brace(after: &str, open: usize) -> usize { - let mut depth = 0i32; - for (k, ch) in after[open..].char_indices() { - match ch { - '{' => depth += 1, - '}' => { - depth -= 1; - if depth == 0 { - return open + k; - } - } - _ => {} - } - } - panic!("unbalanced braces") -} - -/// The normalised, non-trivial lines of a function body. -fn body_lines(body: &str) -> Vec { - let mut lines = Vec::new(); - for line in body.lines() { - let l = norm(line); - if l.len() >= 6 && !l.starts_with("//") { - lines.push(l); - } - } - lines -} - -/// The first `__global__` / `__device__` marker of `rest`: its offset and length. -fn next_marker(rest: &str) -> Option<(usize, usize)> { - ["__global__", "__device__"] - .iter() - .filter_map(|m| rest.find(m).map(|i| (i, m.len()))) - .min() -} - -/// Bodies of all device functions (text between the first `{` after the `__global__` / `__device__` marker and its -/// matching `}`), signatures excluded. -fn device_bodies(source: &str) -> Vec { - let mut out = Vec::new(); - let text = source; - let mut search = 0; - while search < text.len() { - let Some((i, len)) = next_marker(&text[search..]) else { break }; - let from = search + i + len; - // a declaration like `__device__ int x;` has `;` before any `{` - let after = &text[from..]; - let (brace, semi) = (after.find('{'), after.find(';')); - match (brace, semi) { - (Some(b), Some(s)) if s < b => { - search = from + s; - continue; - } - (Some(b), _) => { - let end = matching_brace(after, b); - out.push(Body { - name: signature_name(&after[..b]), - lines: body_lines(&after[b + 1..end]), - }); - search = from + end; - } - _ => break, - } - } - out -} - -/// A device function of the Original that the port does not carry, and why. -type Excluded = (&'static str, &'static str); - -/// Every exclusion names a device function of the Original and carries a reason. -fn assert_exclusions_are_live(name: &str, names: &HashSet<&str>, excluded: &[Excluded]) { - for (function, reason) in excluded { - assert!( - names.contains(function), - "{name}: EXCLUDED names `{function}` ({reason}) but the Original has no such device \ - function; remove or rename the entry" - ); - assert!( - !reason.is_empty(), - "{name}: `{function}` is excluded without a reason" - ); - } -} - -/// The body lines that appear neither as a line of the port nor in its whitespace-flattened text. -fn missing_lines<'a>(lines: &[&'a String], have: &HashSet, flat: &str) -> Vec<&'a String> { - lines - .iter() - .copied() - .filter(|l| !have.contains(*l) && !flat.contains(l.as_str())) - .collect() -} - -fn check(name: &str, original: &str, port: &str, excluded: &[Excluded]) { - let have: HashSet = port.lines().map(norm).collect(); - let flat = norm(port); - let bodies = device_bodies(original); - let names: HashSet<&str> = bodies.iter().map(|b| b.name.as_str()).collect(); - assert_exclusions_are_live(name, &names, excluded); - let skip: HashSet<&str> = excluded.iter().map(|(f, _)| *f).collect(); - let kept: Vec<&Body> = bodies.iter().filter(|b| !skip.contains(b.name.as_str())).collect(); - let lines: Vec<&String> = kept.iter().flat_map(|b| b.lines.iter()).collect(); - assert!(lines.len() > 5, "{name}: found no device bodies"); - let missing = missing_lines(&lines, &have, &flat); - assert!( - missing.is_empty(), - "{name}: {} original kernel-body lines are not in the port:\n{}", - missing.len(), - missing - .iter() - .map(|l| l.as_str()) - .collect::>() - .join("\n") - ); - println!( - "{name}: {} kernel-body lines of {} device functions all present; {} functions excluded \ - with a reason", - lines.len(), - kept.len(), - excluded.len() - ); -} - -macro_rules! pair { - ($test:ident, $name:literal, $orig:literal, $port:literal, $excluded:expr) => { - #[test] - fn $test() { - check( - $name, - include_str!(concat!("../../../engine/strata/src/kernels/cuda/", $orig)), - include_str!(concat!("../../cuda-driver/src/", $port)), - $excluded, - ); - } - }; -} - -// kv_q8.cu: the 8-wide gather exists only in the experimental SM60 build of the Original (`#if -// defined(STRATA_EXPERIMENTAL_SM60)`, Pascal / Volta). The ready-made engine, and this port (sm_120, sm_86), run the -// 4-wide `kv_gather_q8_kernel`, which is ported. The Original states the wide kernel is bitwise the same. -const KV_Q8_EXCLUDED: &[Excluded] = &[ - ( - "q8_pair_to_f16x2", - "STRATA_EXPERIMENTAL_SM60 build only (sm_60/sm_70); compiled out of the ready-made engine", - ), - ( - "kv_gather_q8_wide_kernel", - "STRATA_EXPERIMENTAL_SM60 build only (sm_60/sm_70); bitwise the 4-wide gather, which is ported", - ), -]; - -// qsa_decode_attn.cu: the port carries the reference schedule of KV modes 2, 3 and 4 and the merge. The Original -// grew alternate schedules and batch variants of the same arithmetic, picked by architecture or environment, none -// of which the six closed programs expose as an entry. The Original proves the alternates bitwise equal to the -// reference schedule (its `qsa_merge_daily_parity` and `kv_hybrid_parity` harnesses, header comment of -// `qsa_decode_attn_chunks_only`); here the emulated reference schedule is compared with the Rust CPU reference -// (tests/emulated_kernels.rs). -const QSA_ATTN_EXCLUDED: &[Excluded] = &[ - ( - "attn_chunk_kernel", - "thin __global__ wrapper over attn_chunk_body; the extern \"C\" entries of the port are the equivalent \ - wrappers", - ), - ( - "attn_chunk_slots_kernel", - "same body over a per-query pool set (QsaAttnSlotPools kernel argument): engine batch slots, not an \ - experimental entry", - ), - ( - "attn_chunk_rows_kernel", - "same body over per-query pool rows (QsaAttnPoolsRows kernel argument): engine batch windows, not an \ - experimental entry", - ), - ( - "attn_chunk_q8_v3_kernel", - "INT8 (KV_MODE 1) Turing schedule; the port instantiates modes 2, 3 and 4 only", - ), - ( - "attn_chunk_kernel_pre75", - "alternate schedule of attn_chunk_body (NC cells per step, reduce12); bitwise the reference schedule per the \ - Original's parity harness; the Original selects it for pre-sm_75 cards and, by default, compute capability \ - 12.0 (STRATA_ATTN_DAILY)", - ), - ("shfl_x", "helper of attn_chunk_kernel_pre75 only"), - ("warp_sum_x", "helper of attn_chunk_kernel_pre75 only"), - ("warp_max_x", "helper of attn_chunk_kernel_pre75 only"), - ( - "reduce12", - "helper of attn_chunk_kernel_pre75 only (reduce12_gfx906 is the ported twin used by attn_chunk_body)", - ), - ( - "head_of_lane", - "helper of attn_chunk_kernel_pre75 only (reduce12_head_of_lane is the ported twin)", - ), - ("load_v1", "helper of attn_chunk_kernel_pre75 only"), - ("merge_max_block", "helper of attn_merge_v2_kernel only"), - ("merge_sum_block", "helper of attn_merge_v2_kernel only"), - ( - "attn_merge_v2_kernel", - "alternate merge (width-bounded, batched loads); bitwise attn_merge_kernel per the Original's parity harness; \ - follows STRATA_ATTN_DAILY", - ), -]; - -pair!( - kv_q4_bodies_are_literal, - "kv_q4", - "kv_q4.cu", - "experimental_kv_q4.cu", - &[] -); -pair!( - kv_q8_bodies_are_literal, - "kv_q8", - "kv_q8.cu", - "experimental_kv_q8.cu", - KV_Q8_EXCLUDED -); -pair!( - kv_stream_bodies_are_literal, - "kv_stream", - "kv_stream.cu", - "experimental_kv_stream.cu", - &[] -); -pair!( - keyless_bodies_are_literal, - "keyless", - "keyless.cu", - "experimental_keyless.cu", - &[] -); -pair!( - qsa_attn_bodies_are_literal, - "qsa_attn", - "qsa_decode_attn.cu", - "experimental_qsa_attn.cu", - QSA_ATTN_EXCLUDED -); -pair!( - cvec_bodies_are_literal, - "cvec", - "cvec.cu", - "experimental_cvec.cu", - &[] -); - -/// A synthetic Original: one kernel and one helper device function. -fn synthetic_original() -> &'static str { - concat!( - "__global__ void k(int a) {\n int x = a + 1;\n int y = x * 2;\n int u = y + x;\n", - " int v = u + y;\n int z = y - 3;\n int w = z;\n return;\n}\n", - "__device__ __forceinline__ float helper(float v) {\n", - " float s = v * 3.0f + 1.0f;\n return s * s;\n}\n" - ) -} - -fn check_panics(original: &str, port: &str, excluded: &[Excluded]) -> bool { - std::panic::catch_unwind(|| check("synthetic", original, port, excluded)).is_err() -} - -#[test] -fn the_guard_notices_a_changed_or_unlisted_device_function() { - let original = synthetic_original(); - let port_same = original.replace("__global__ void k(int a)", "__device__ void k_body(int a)"); - check("synthetic", original, &port_same, &[]); - let changed = port_same.replace("int y = x * 2;", "int y = x * 3;"); - assert!(check_panics(original, &changed, &[])); - let without_helper = port_same.replace("float s = v * 3.0f + 1.0f;", "float s = v;"); - assert!(check_panics(original, &without_helper, &[])); - // an exclusion lets the function go, a stale one is refused - check("synthetic", original, &without_helper, &[("helper", "test")]); - assert!(check_panics(original, &port_same, &[("gone", "test")])); -} - -#[test] -fn signature_names_survive_launch_bounds_and_templates() { - assert_eq!( - signature_name( - " void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float* q, int n)" - ), - "attn_chunk_kernel_pre75" - ); - assert_eq!( - signature_name(" __forceinline__ float warp_sum(float v)"), - "warp_sum" - ); - assert_eq!( - signature_name( - "\n__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p," - ), - "attn_chunk_body" - ); -} diff --git a/crates/gateway-domain/src/reasoning_budget.rs b/crates/gateway-domain/src/reasoning_budget.rs index 8dd2f094..742ceca9 100644 --- a/crates/gateway-domain/src/reasoning_budget.rs +++ b/crates/gateway-domain/src/reasoning_budget.rs @@ -1,6 +1,6 @@ //! `reasoning_budget_tokens` (#123): the most tokens a request may think before the thinking is closed for it. //! -//! Port of `Service.reasoning_budget` and of the budget part of `Service.run` in `engine/strata/serve/server.py`. +//! Port of `Service.reasoning_budget` and of the budget part of `Service.run` in `Strata 41cf05a0, serve/server.py`. //! The driver is generic over the engine and the tokenizer so the exact control flow (the clean-point rule, the //! wrap-up, the continuation prompt, the room check) is testable without a model; `tests/reasoning_budget_oracle.rs` //! replays cases produced by the unmodified Python `Service.run`. diff --git a/crates/model-format/src/gguf/read_index_file.rs b/crates/model-format/src/gguf/read_index_file.rs index 96efdd51..d6953f9f 100644 --- a/crates/model-format/src/gguf/read_index_file.rs +++ b/crates/model-format/src/gguf/read_index_file.rs @@ -15,9 +15,9 @@ pub(super) fn read_index_file(file: &mut File, size: u64, strict: bool) -> Resul /// (values per block, bytes per block) of each tensor kind. /// -/// Mirrors engine/strata/include/strata/artifact/gguf_reader.hpp at the +/// Mirrors Strata 41cf05a0, include/strata/artifact/gguf_reader.hpp at the /// upstream commit recorded in third_party/strata/UPSTREAM.md, plus the kinds -/// engine/strata/tools/gguf_reader.py BLOCK_GEOMETRY knows beyond it (Q8_K 15, +/// Strata 41cf05a0, tools/gguf_reader.py BLOCK_GEOMETRY knows beyond it (Q8_K 15, /// IQ1_S 19, F64 28, MXFP4 39, NVFP4 40). Geometry is only a byte count: a /// consumer that cannot decode a kind still refuses it at use. Differential: /// control-plane/tests/gguf_header_differential.rs. diff --git a/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate.rs index 67efa558..9f237c49 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate.rs @@ -80,7 +80,7 @@ fn alt_paths(a: &AltArgs) -> Result { let kab = kab_path(a); if !kab.is_file() { return Err(format!( - "the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)", + "the C++ driver {} does not exist (retired with the vendored Strata tree; pass --kab or set KAB)", kab.display() )); } diff --git a/crates/offline-tools/src/lib.rs b/crates/offline-tools/src/lib.rs index 8b919b43..8dd99d05 100644 --- a/crates/offline-tools/src/lib.rs +++ b/crates/offline-tools/src/lib.rs @@ -1,4 +1,4 @@ -//! Offline tooling ported from `engine/strata/tools/*.py`, byte for byte, with no Python at run time. +//! Offline tooling ported from `Strata 41cf05a0, tools/*.py`, byte for byte, with no Python at run time. //! //! | Rust module | Python oracle | what it writes | //! |--------------------|------------------------------|-------------------------------------------------------| diff --git a/crates/offline-tools/tests/oracle.rs b/crates/offline-tools/tests/oracle.rs index 6d9448d6..142da7e8 100644 --- a/crates/offline-tools/tests/oracle.rs +++ b/crates/offline-tools/tests/oracle.rs @@ -1,7 +1,7 @@ //! The ported tools against the Python originals' exact outputs. //! //! `tests/fixtures/tools_oracle.json` is written by `scripts/offline/gen_goldens.py tools_oracle`, which runs the -//! unmodified `engine/strata/tools/{embd_bf16_pack,ple_fp8_pack,draft_vocab,make_profile,mtp_rt}.py` on tiny +//! unmodified `Strata 41cf05a0, tools/{embd_bf16_pack,ple_fp8_pack,draft_vocab,make_profile,mtp_rt}.py` on tiny //! synthetic inputs. `scripts/offline/diff_tools.py` is the live differential over more cases. use std::{ fs, diff --git a/crates/sampler-ref/oracle/build_oracle.sh b/crates/sampler-ref/oracle/build_oracle.sh deleted file mode 100755 index 3bdc415d..00000000 --- a/crates/sampler-ref/oracle/build_oracle.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -# Rebuild the host oracle and regenerate the committed fixtures. macOS or Linux, clang++ or g++, no CUDA. -# crates/sampler-ref/oracle/build_oracle.sh [output_dir] -# -ffp-contract=off pins the host float evaluation to separate IEEE operations (no FMA), which is the -# contract the Rust reference documents. Compile flags are echoed into the fixture header. -set -eu -here=$(cd "$(dirname "$0")" && pwd) -root=$(cd "$here/../../.." && pwd) -out=${1:-"$here/../tests/fixtures"} -bin=${TMPDIR:-/tmp}/leleka_sampler_oracle.$$ -${CXX:-clang++} -std=c++17 -O1 -ffp-contract=off -fno-fast-math -Wno-unused-function -Wno-unused-variable \ - -I "$root/engine/strata/include" -I "$here/stub" "$here/gen_fixtures.cpp" -o "$bin" -mkdir -p "$out" -"$bin" "$out/sampler_oracle.json" -rm -f "$bin" diff --git a/crates/sampler-ref/oracle/gen_fixtures.cpp b/crates/sampler-ref/oracle/gen_fixtures.cpp deleted file mode 100644 index 73c24099..00000000 --- a/crates/sampler-ref/oracle/gen_fixtures.cpp +++ /dev/null @@ -1,507 +0,0 @@ -// Golden-fixture generator for the Rust CPU sampler reference (crates/sampler-ref). -// -// WHAT THIS RUNS. The Original's own host-side logic, not a re-implementation: -// * `engine/strata/src/kernels/sampler_parity.cpp` is #included UNMODIFIED (its `main` renamed, a -// header-only stub standing in for ) so that `host_philox_uniform`, -// `sampled_reference`, `mirror_select`, `mirror_pick`, `sampled_k` are the Original's code; -// * `strata/kernels/sampler.hpp` (`penalty_rows`) and `strata/core/coupled_draft.hpp` -// (`coupled_draft_cell/counter`, `coupled_hist_len/start`, `coupled_hist_base`) are the Original's headers. -// The only code written here is the case generator, the JSON writer and `coupled_ref` below, which -// transcribes the DEVICE-ONLY coupled kernels (`coupled_penalize_kernel`, `coupled_merge_kernel`, -// `sampled_tail_warp` in sampler.cu) because the Original has no host twin for them; it is -// cross-checked against the Original's `mirror_pick` on every case. -// -// Build/run: crates/sampler-ref/oracle/build_oracle.sh (compiles with -ffp-contract=off). -#define main original_sampler_parity_main -#include "../../../engine/strata/src/kernels/sampler_parity.cpp" -#undef main - -#include "strata/core/coupled_draft.hpp" - -#include -#include -#include - -namespace { - -using strata::kernels::SamplerParams; - -// ---- deterministic case source (splitmix64; no std::random distributions, which differ per stdlib) ---- -struct Rng { - uint64_t s; - uint64_t next() { - uint64_t z = (s += 0x9E3779B97F4A7C15ull); - z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; - z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; - return z ^ (z >> 31); - } - double uni() { return (double) (next() >> 11) * (1.0 / 9007199254740992.0); } - int below(int n) { return (int) (next() % (uint64_t) n); } - double normal() { return (uni() + uni() + uni() + uni() - 2.0) * 1.7; } - template T pick(std::initializer_list v) { return *(v.begin() + below((int) v.size())); } -}; - -uint32_t bits_of(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; } -float float_of(uint32_t u) { float f; std::memcpy(&f, &u, 4); return f; } -constexpr uint32_t kNaN = 0x7fc00000u, kNegNaN = 0xffc00000u, kInf = 0x7f800000u, kNegInf = 0xff800000u; - -FILE* out = nullptr; -bool first_item = true; -void comma() { if (!first_item) std::fputs(",", out); first_item = false; } - -void put_u32s(const std::vector& v) { - std::fputc('[', out); - for (size_t i = 0; i < v.size(); ++i) std::fprintf(out, i ? ",%u" : "%u", bits_of(v[i])); - std::fputc(']', out); -} -void put_ints(const std::vector& v) { - std::fputc('[', out); - for (size_t i = 0; i < v.size(); ++i) std::fprintf(out, i ? ",%d" : "%d", v[i]); - std::fputc(']', out); -} -void put_i32s(const std::vector& v) { put_ints(std::vector(v.begin(), v.end())); } -void put_params(const SamplerParams& p) { - std::fprintf(out, - "{\"top_k\":%d,\"top_p\":%u,\"min_p\":%u,\"temperature\":%u,\"min_keep\":%d,\"penalty_last_n\":%d," - "\"penalty_repeat\":%u,\"penalty_freq\":%u,\"penalty_present\":%u,\"seed\":%" PRIu64 - ",\"counter\":%" PRIu64 ",\"greedy\":%s}", - p.top_k, bits_of(p.top_p), bits_of(p.min_p), bits_of(p.temperature), p.min_keep, p.penalty_last_n, - bits_of(p.penalty_repeat), bits_of(p.penalty_freq), bits_of(p.penalty_present), p.seed, p.counter, - p.greedy ? "true" : "false"); -} - -std::vector window_of(const std::vector& hist, int penalty_last_n) { - // sampler.cu: hlen = min(penalty_last_n, history_len), clamped at 0; the window is the TAIL of the row - int hlen = std::min(penalty_last_n, (int) hist.size()); - if (hlen < 0) hlen = 0; - return std::vector(hist.end() - hlen, hist.end()); -} - -bool all_finite(const std::vector& l) { - for (float x : l) if (!std::isfinite(x)) return false; - return true; -} - -int mismatches = 0; -int n_cases = 0; - -// One chain case: either a dense logit vector or a sparse full-vocabulary description. -struct SparseLogits { - int n = 0; - float fill = 0; - std::vector> set; -}; - -void emit_chain_case(const char* name, const std::vector& logits, const SparseLogits* sparse, - const SamplerParams& p, int row, const std::vector& hist) { - const int nv = (int) logits.size(); - const std::vector window = window_of(hist, p.penalty_last_n); - const int k = sampled_k(p.top_k, nv); - const bool greedy = p.greedy || p.temperature <= 0.0f; - // the Original's own semantics for the row: greedy = the first entry of the k=1 selection - const SelList sel1 = mirror_select(logits.data(), nv, window, p, 1); - const SelList sel = greedy ? sel1 : mirror_select(logits.data(), nv, window, p, k); - const int token = greedy ? sel1.ids[0] : mirror_pick(sel, k, p, row); - // cross-check the two Original references on rows where they must agree (finite, sampled) - if (!greedy && all_finite(logits)) { - const int ref = sampled_reference(logits, window, p, row); - if (ref != token) { - ++mismatches; - std::fprintf(stderr, "reference disagreement in %s: mirror %d vs sampled_reference %d\n", name, token, ref); - } - } - comma(); - std::fprintf(out, "\n{\"name\":\"%s\",\"n_vocab\":%d,\"row\":%d,\"params\":", name, nv, row); - put_params(p); - if (sparse) { - std::fprintf(out, ",\"sparse\":{\"fill\":%u,\"set\":[", bits_of(sparse->fill)); - for (size_t i = 0; i < sparse->set.size(); ++i) - std::fprintf(out, i ? ",[%d,%u]" : "[%d,%u]", sparse->set[i].first, bits_of(sparse->set[i].second)); - std::fputs("]}", out); - } else { - std::fputs(",\"logits\":", out); - put_u32s(logits); - } - std::fputs(",\"history\":", out); - put_ints(hist); - std::fprintf(out, ",\"expect\":{\"token\":%d,\"sel_ids\":", token); - put_ints(sel.ids); - std::fputs(",\"sel_logits\":", out); - put_u32s(sel.logit); - if (!greedy) std::fprintf(out, ",\"u\":%u", bits_of(host_philox_uniform(p.seed, p.counter + (uint64_t) row))); - std::fputs("}}", out); - ++n_cases; -} - -std::vector make_logits(Rng& g, int nv, int mode) { - std::vector l((size_t) nv); - for (int v = 0; v < nv; ++v) { - double x = g.normal(); - switch (mode) { - case 0: l[(size_t) v] = (float) x; break; // plain - case 1: l[(size_t) v] = (float) (std::round(x * 2.0) / 2.0); break; // many exact ties - case 2: l[(size_t) v] = 1.25f; break; // all equal - case 3: { // non-finite mix - const int r = g.below(12); - l[(size_t) v] = r == 0 ? float_of(kNegInf) : r == 1 ? float_of(kNaN) : r == 2 ? float_of(kInf) - : r == 3 ? float_of(kNegNaN) : (float) x; - break; - } - case 4: l[(size_t) v] = (float) (x * 1e30); break; // huge magnitudes - case 5: l[(size_t) v] = (float) (x * 1e-40); break; // denormals - default: l[(size_t) v] = float_of(kNegInf); break; // all -inf - } - } - return l; -} - -SamplerParams make_params(Rng& g, bool allow_greedy) { - SamplerParams p; - p.top_k = g.pick({0, 1, 2, 5, 20, 20, 40, 63, 64, 65, 200, -3}); - p.top_p = g.pick({1.0f, 1.0f, 0.95f, 0.9f, 0.5f, 0.2f, 0.0f}); - p.min_p = g.pick({0.0f, 0.0f, 0.01f, 0.1f, 0.5f, 1.0f}); - p.temperature = g.pick({0.3f, 0.7f, 1.0f, 1.0f, 1.5f, 2.0f}); - if (allow_greedy && g.below(6) == 0) p.temperature = g.pick({0.0f, -1.0f}); - p.greedy = allow_greedy && g.below(12) == 0; - p.min_keep = g.pick({1, 1, 1, 2, 3}); - p.penalty_last_n = g.pick({0, 0, 4, 16, 64, 5000, -2}); - p.penalty_repeat = g.pick({1.0f, 1.1f, 1.5f, 2.0f, 0.8f}); - p.penalty_freq = g.pick({0.0f, 0.25f, 0.5f}); - p.penalty_present = g.pick({0.0f, 0.5f, 1.5f}); - p.seed = g.pick({0ull, 1ull, 42ull, 123456789ull, 0xFFFFFFFFull, 0x1FFFFFFFFull, 0xDEADBEEFCAFEF00Dull, - ~0ull}); - p.counter = g.pick({0ull, 1ull, 7ull, 1000ull, (1ull << 32) + 7ull, 0xFFFFFFFFull, ~0ull - 3ull}); - return p; -} - -std::vector make_history(Rng& g, int nv, int pln) { - int hl = g.pick({0, 8, 32, 80}); - if (pln > 0 && hl == 0) hl = 8; - std::vector h((size_t) hl); - for (auto& t : h) { - const int r = g.below(10); - t = r < 2 ? -1 : r == 2 ? nv + g.below(3) : g.below(std::min(nv + 1, 12)); - } - return h; -} - -// ---- the coupled draft, serial (TRANSCRIPTION of the device-only kernels; see the file header) ---- -struct CoupledResult { int id; float prob; int sub; }; - -CoupledResult coupled_ref(std::vector l, const std::vector& sub_to_id, const std::vector& id_to_sub, - int id_vocab, const SamplerParams& params, std::vector& ring, int cap, int j, - int step0, int& tail_pick_check) { - const int nv = (int) l.size(); - // coupled_penalize_kernel - const int h = strata::core::coupled_hist_len(params.penalty_last_n, cap); - if (h > 0) { - const int* hrow = ring.data() + strata::core::coupled_hist_start(cap, j, h); - std::vector seen((size_t) nv, 0); - for (int i = 0; i < h; ++i) { - const int v = hrow[i]; - if (v < 0 || v >= id_vocab) continue; - const int s = id_to_sub.empty() ? v : id_to_sub[(size_t) v]; - if (s < 0 || s >= nv) continue; - if (seen[(size_t) s]) continue; - seen[(size_t) s] = 1; - int c = 0; - for (int q = 0; q < h; ++q) c += hrow[q] == v; - float x = l[(size_t) s]; - if (c > 0) { - if (x <= 0.0f) x *= params.penalty_repeat; else x /= params.penalty_repeat; - x -= (float) c * params.penalty_freq + (c > 0 ? 1.0f : 0.0f) * params.penalty_present; - } - l[(size_t) s] = x; - } - } - // coupled_merge_kernel - SamplerParams p = params; - p.counter = strata::core::coupled_draft_counter((int64_t) step0); - const int k = sampled_k(p.top_k, nv); - SamplerParams none; // the split-part launch passes SamplerParams{} (no penalties) - const SelList sel = mirror_select(l.data(), nv, std::vector(), none, k); - int pick_idx = 0; - float prob = 1.0f; - if (p.greedy || p.temperature <= 0.0f) { - pick_idx = 0; - tail_pick_check = sel.ids[0]; - } else { - // sampled_tail_warp: top_p, min_p, temperature, draw, and the pick's probability - int n_keep = k; - float mx = sel.logit[0]; - for (int i = 1; i < k; ++i) mx = std::fmax(mx, sel.logit[(size_t) i]); - if (p.top_p < 1.0f) { - double sum = 0.0; - for (int i = 0; i < k; ++i) sum += std::exp((double) sel.logit[(size_t) i] - (double) mx); - double cum = 0.0; - int cut = k; - for (int i = 0; i < k; ++i) { - cum += std::exp((double) sel.logit[(size_t) i] - (double) mx) / sum; - if (cum >= (double) p.top_p) { cut = i + 1; break; } - } - if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; - n_keep = cut; - } - if (p.min_p > 0.0f) { - const float thresh = sel.logit[0] + std::log(p.min_p); - for (int i = 0; i < n_keep; ++i) - if (sel.logit[(size_t) i] < thresh) { n_keep = i; break; } - } - const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; - float smx = sel.logit[0] * inv_t; - for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, sel.logit[(size_t) i] * inv_t); - std::vector ex((size_t) std::max(n_keep, 1)); - for (int i = 0; i < n_keep; ++i) ex[(size_t) i] = std::exp((double) (sel.logit[(size_t) i] * inv_t) - (double) smx); - double sum = 0.0; - for (int i = 0; i < n_keep; ++i) sum += ex[(size_t) i]; - for (int i = 0; i < n_keep; ++i) ex[(size_t) i] = ex[(size_t) i] / sum; - const float u = host_philox_uniform(p.seed, p.counter + 0u); - double cum = 0.0; - pick_idx = n_keep > 0 ? n_keep - 1 : 0; - for (int i = 0; i < n_keep; ++i) { - cum += ex[(size_t) i]; - if ((double) u < cum) { pick_idx = i; break; } - } - prob = n_keep > 0 ? (float) ex[(size_t) pick_idx] : 1.0f; - tail_pick_check = mirror_pick(sel, k, p, 0); // the Original's own tail must agree - } - const int s = sel.ids[(size_t) pick_idx]; - const int id = sub_to_id.empty() ? s : sub_to_id[(size_t) s]; - ring[(size_t) (cap + j)] = id; - return {id, prob, s}; -} - -} // namespace - -int main(int argc, char** argv) { - if (argc < 2) { std::fprintf(stderr, "usage: %s out.json\n", argv[0]); return 2; } - out = std::fopen(argv[1], "w"); - if (!out) { std::perror("open"); return 2; } - Rng g{0x5A17E7E5ull}; - - std::fputs("{\n\"meta\":{\"generator\":\"crates/sampler-ref/oracle/gen_fixtures.cpp\"," - "\"oracle\":\"Original engine/strata sampler_parity.cpp host reference, included unmodified; " - "sampler.hpp + coupled_draft.hpp headers\"," - "\"compile\":\"-std=c++17 -O1 -ffp-contract=off -fno-fast-math\"," - "\"encoding\":\"floats are IEEE-754 binary32 bit patterns (u32)\"},\n", out); - - // ---------------- philox ---------------- - std::fputs("\"philox\":[", out); - first_item = true; - { - std::vector> pts = { - {0, 0}, {0, 1}, {1, 0}, {1, 1}, {42, 7}, {123, (1ull << 32) + 7}, {0xFFFFFFFFull, 0xFFFFFFFFull}, - {0x100000000ull, 0}, {0, 0x100000000ull}, {~0ull, ~0ull}, {0xDEADBEEFCAFEF00Dull, 12345678901234ull}}; - for (int i = 0; i < 80; ++i) pts.push_back({g.next(), g.next() >> (g.below(40))}); - for (auto& pr : pts) { - comma(); - std::fprintf(out, "\n[%" PRIu64 ",%" PRIu64 ",%u]", pr.first, pr.second, - bits_of(host_philox_uniform(pr.first, pr.second))); - } - } - std::fputs("\n],\n", out); - - // ---------------- chain ---------------- - std::fputs("\"chain\":[", out); - first_item = true; - { - int idx = 0; - char name[64]; - // random dense rows over several vocabularies and logit shapes - for (int nv : {1, 2, 5, 16, 33, 64, 65, 100, 257}) - for (int rep = 0; rep < (nv > 100 ? 2 : 14); ++rep) { - const int mode = rep % 7 == 6 ? 1 : (rep % 11 == 10 ? 2 : 0); - SamplerParams p = make_params(g, true); - const auto l = make_logits(g, nv, mode); - const auto h = make_history(g, nv, p.penalty_last_n); - std::snprintf(name, sizeof name, "rand-%d-%d", nv, rep); - emit_chain_case(name, l, nullptr, p, g.below(4), h); - ++idx; - } - // edge shapes: non-finite mix, huge, denormal, all -inf, ties, k larger than the finite count - for (int mode : {3, 3, 3, 3, 4, 4, 5, 5, 6, 1, 1, 2}) - for (int nv : {3, 12, 70}) { - SamplerParams p = make_params(g, true); - const auto l = make_logits(g, nv, mode); - const auto h = make_history(g, nv, p.penalty_last_n); - std::snprintf(name, sizeof name, "edge-m%d-%d-%d", mode, nv, idx++); - emit_chain_case(name, l, nullptr, p, g.below(3), h); - } - // penalties that matter: a clear head token repeatedly in the window - for (int rep = 0; rep < 16; ++rep) { - SamplerParams p = make_params(g, false); - p.penalty_last_n = 16; - p.penalty_repeat = g.pick({1.5f, 2.0f, 3.0f}); - p.penalty_freq = g.pick({0.0f, 0.5f, 0.25f}); - p.penalty_present = g.pick({0.0f, 1.0f, 0.5f}); - p.top_k = 8; - p.top_p = g.pick({1.0f, 0.9f}); - auto l = make_logits(g, 24, 0); - l[3] = 6.0f; l[9] = 5.5f; l[17] = -2.0f; - std::vector h = {-1, -1, 3, 3, 3, 9, 17, 17, 40, -1, 3, 9, 17, 5, 5, 3}; - std::snprintf(name, sizeof name, "penal-%d", rep); - emit_chain_case(name, l, nullptr, p, rep % 3, h); - } - // top_p lands EXACTLY on a cumulative boundary (equal logits: cum = 1/n, 2/n, ...), so `cum >= top_p` vs `>` is - // observable; 16 seeds per case so the draw reaches the entry that only the wrong comparison would keep - for (int n : {4, 8}) - for (int step = 1; step < n; ++step) - for (int sd = 0; sd < 6; ++sd) { - SamplerParams p; - p.top_k = n; p.top_p = (float) step / (float) n; p.temperature = 1.0f; p.min_p = 0.0f; - p.seed = 1000 + (uint64_t) sd * 7919; p.counter = (uint64_t) sd; - std::vector l((size_t) n + 2, 3.0f); - l[(size_t) n] = -20.0f; l[(size_t) n + 1] = -20.0f; - std::snprintf(name, sizeof name, "tp-boundary-%d-%d-%d", n, step, sd); - emit_chain_case(name, l, nullptr, p, 0, std::vector()); - } - // full-vocabulary sparse rows (the closed GPU op's geometry: 248,320 logits, up to 4,096 history slots) - for (int rep = 0; rep < 36; ++rep) { - SparseLogits sp; - sp.n = 248320; - sp.fill = g.pick({-5.0f, -9.5f, 0.0f}); - std::vector l((size_t) sp.n, sp.fill); - const int n_set = 6 + g.below(120); - for (int i = 0; i < n_set; ++i) { - const int at = g.below(sp.n); - const float val = (float) (g.normal() * 3.0 + 2.0); - sp.set.push_back({at, val}); - l[(size_t) at] = val; - } - if (rep % 4 == 1) - for (int i = 0; i < 8; ++i) { sp.set.push_back({1000 + 7 * i, 4.5f}); l[(size_t) (1000 + 7 * i)] = 4.5f; } // ties - if (rep % 13 == 12) { sp.set.push_back({5, float_of(kNegInf)}); l[5] = float_of(kNegInf); } - if (rep % 17 == 16) { sp.set.push_back({248319, float_of(kNaN)}); l[248319] = float_of(kNaN); } // last index: NaN is never picked - SamplerParams p = make_params(g, rep % 5 == 4); - if (rep % 3 == 0) { p.penalty_last_n = 64; } - std::vector h(rep == 2 ? 4096 : 64, -1); - for (size_t i = h.size() > 40 ? h.size() - 40 : 0; i < h.size(); ++i) - h[i] = sp.set.empty() ? 0 : sp.set[(size_t) g.below((int) sp.set.size())].first; - if (rep == 2) p.penalty_last_n = 4096; - if (p.penalty_last_n > 0 && h.empty()) h.assign(8, -1); - std::snprintf(name, sizeof name, "full-%d", rep); - emit_chain_case(name, l, &sp, p, 0, h); - } - } - std::fputs("\n],\n", out); - - // ---------------- ABI of strata::kernels::SamplerParams (the 64-byte blob every Original kernel takes by value) ---------------- - std::fprintf(out, "\"abi\":{\"size\":%zu,\"align\":%zu,\"offsets\":{", sizeof(SamplerParams), alignof(SamplerParams)); - std::fprintf(out, "\"top_k\":%zu,\"top_p\":%zu,\"min_p\":%zu,\"temperature\":%zu,\"min_keep\":%zu,\"penalty_last_n\":%zu," - "\"penalty_repeat\":%zu,\"penalty_freq\":%zu,\"penalty_present\":%zu,\"seed\":%zu,\"counter\":%zu,\"greedy\":%zu},\"samples\":[", - offsetof(SamplerParams, top_k), offsetof(SamplerParams, top_p), offsetof(SamplerParams, min_p), - offsetof(SamplerParams, temperature), offsetof(SamplerParams, min_keep), offsetof(SamplerParams, penalty_last_n), - offsetof(SamplerParams, penalty_repeat), offsetof(SamplerParams, penalty_freq), offsetof(SamplerParams, penalty_present), - offsetof(SamplerParams, seed), offsetof(SamplerParams, counter), offsetof(SamplerParams, greedy)); - first_item = true; - for (int rep = 0; rep < 12; ++rep) { - SamplerParams p = rep == 0 ? SamplerParams() : make_params(g, true); - alignas(SamplerParams) unsigned char raw[sizeof(SamplerParams)]; - std::memset(raw, 0, sizeof raw); - SamplerParams* q = new (raw) SamplerParams(); // default member initialisers, padding left as the memset made it - q->top_k = p.top_k; q->top_p = p.top_p; q->min_p = p.min_p; q->temperature = p.temperature; q->min_keep = p.min_keep; - q->penalty_last_n = p.penalty_last_n; q->penalty_repeat = p.penalty_repeat; q->penalty_freq = p.penalty_freq; - q->penalty_present = p.penalty_present; q->seed = p.seed; q->counter = p.counter; q->greedy = p.greedy; - comma(); - std::fputs("\n{\"params\":", out); put_params(p); - std::fputs(",\"bytes\":[", out); - for (size_t i = 0; i < sizeof raw; ++i) std::fprintf(out, i ? ",%u" : "%u", (unsigned) raw[i]); - std::fputs("]}", out); - } - std::fputs("\n]},\n", out); - - // ---------------- counters (coupled_draft.hpp, verbatim header functions) ---------------- - std::fputs("\"counters\":{\"cells\":[", out); - first_item = true; - for (int64_t p : {0ll, 1ll, 100ll, 4095ll, 1000000ll, (long long) 1 << 40}) - for (int a : {0, 1, 7}) - for (int j : {0, 1, 6}) { - comma(); - const int64_t cell = strata::core::coupled_draft_cell(p, a, j); - std::fprintf(out, "\n[%" PRId64 ",%d,%d,%" PRId64 ",%" PRIu64 "]", p, a, j, cell, - strata::core::coupled_draft_counter(cell)); - } - std::fputs("\n],\"hist_len\":[", out); - first_item = true; - for (int cap : {8, 64, strata::core::kCoupledHistCap}) - for (int pln : {-1, 0, 1, 7, 8, 9, 64, 4095, 4096, 4097, 100000}) { - comma(); - std::fprintf(out, "\n[%d,%d,%d]", pln, cap, strata::core::coupled_hist_len(pln, cap)); - } - std::fputs("\n],\"hist_start\":[", out); - first_item = true; - for (int cap : {8, 64, strata::core::kCoupledHistCap}) - for (int h : {1, 3, 8}) - for (int j : {0, 1, 6}) { - comma(); - std::fprintf(out, "\n[%d,%d,%d,%d]", cap, j, h, strata::core::coupled_hist_start(cap, j, h)); - } - std::fputs("\n]},\n", out); - - // ---------------- penalty_rows + coupled_hist_base (sampler.hpp / coupled_draft.hpp, verbatim) ---------------- - std::fputs("\"penalty_rows\":[", out); - first_item = true; - for (int rep = 0; rep < 60; ++rep) { - const int n_tail = g.pick({0, 1, 2, 5, 7, 20}); - const int T = 1 + g.below(8); - const int h = g.pick({1, 3, 8, 16}); - std::vector tail((size_t) n_tail), window((size_t) T), rows((size_t) T * (size_t) h); - for (auto& t : tail) t = g.below(1000); - for (auto& t : window) t = g.below(1000); - strata::kernels::penalty_rows(tail.data(), n_tail, window.data(), T, h, rows.data()); - comma(); - std::fputs("\n{\"tail\":", out); put_i32s(tail); - std::fputs(",\"window\":", out); put_i32s(window); - std::fprintf(out, ",\"h\":%d,\"rows\":", h); put_i32s(rows); - const int32_t next = g.below(1000); - std::vector base((size_t) h, 777777); - strata::core::coupled_hist_base(tail.data(), n_tail, next, h, base.data()); - std::fprintf(out, ",\"next\":%d,\"base\":", next); put_i32s(base); - std::fputs("}", out); - } - std::fputs("\n],\n", out); - - // ---------------- coupled draft sampling (transcribed kernels, cross-checked against mirror_pick) ---------------- - std::fputs("\"coupled\":[", out); - first_item = true; - for (int rep = 0; rep < 60; ++rep) { - const int nv = g.pick({7, 24, 70, 130}); - const bool subset = rep % 3 == 1; - const int id_vocab = subset ? nv * 3 : nv; - std::vector sub_to_id, id_to_sub; - if (subset) { - id_to_sub.assign((size_t) id_vocab, -1); - for (int s = 0; s < nv; ++s) { // subset s -> token id 3 s + 1 (an injective map) - sub_to_id.push_back(3 * s + 1); - id_to_sub[(size_t) (3 * s + 1)] = s; - } - } - SamplerParams p = make_params(g, false); - p.penalty_last_n = g.pick({0, 3, 8, 12, 20}); - auto l = make_logits(g, nv, rep % 9 == 8 ? 1 : 0); - const int cap = g.pick({16, 32}); - const int j = g.below(4); - std::vector ring((size_t) cap + 8, -1); - for (int i = 0; i < cap + j; ++i) - ring[(size_t) i] = g.below(5) == 0 ? -1 : (subset ? 3 * g.below(std::min(nv, 6)) + 1 : g.below(std::min(nv, 6))); - if (rep % 7 == 3) for (int i = 0; i < cap + j; ++i) if (g.below(4) == 0) ring[(size_t) i] = id_vocab + 1; // out of vocab - const int step0 = g.below(100000); - const std::vector ring_in = ring; - int check = -1; - const CoupledResult r = coupled_ref(l, sub_to_id, id_to_sub, id_vocab, p, ring, cap, j, step0, check); - if (check != r.sub) { ++mismatches; std::fprintf(stderr, "coupled tail disagreement in case %d\n", rep); } - comma(); - std::fprintf(out, "\n{\"cap\":%d,\"j\":%d,\"step0\":%d,\"id_vocab\":%d,\"logits\":", cap, j, step0, id_vocab); - put_u32s(l); - std::fputs(",\"params\":", out); put_params(p); - std::fputs(",\"sub_to_id\":", out); put_ints(sub_to_id); - std::fputs(",\"id_to_sub\":", out); put_ints(id_to_sub); - std::fputs(",\"ring\":", out); put_ints(ring_in); - std::fprintf(out, ",\"expect\":{\"id\":%d,\"sub\":%d,\"prob\":%u}}", r.id, r.sub, bits_of(r.prob)); - ++n_cases; - } - std::fputs("\n]\n}\n", out); - std::fclose(out); - std::fprintf(stderr, "wrote %d cases, %d oracle disagreements\n", n_cases, mismatches); - return mismatches == 0 ? 0 : 3; -} diff --git a/crates/sampler-ref/oracle/gen_sampling_keys.py b/crates/sampler-ref/oracle/gen_sampling_keys.py deleted file mode 100644 index 85a4a95c..00000000 --- a/crates/sampler-ref/oracle/gen_sampling_keys.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Offline fixture generator (Python is allowed for experiments/fixtures, never for serving). - -Runs the Original's `StrataEngine.sampling_keys` (engine/strata/serve/server.py) over a table of requests and -records the exact GEN key string it emits, plus the ranges `clean_shared_defaults` / -`sampling_defaults_from_config` enforce. Usage: - - python3 -I crates/sampler-ref/oracle/gen_sampling_keys.py crates/sampler-ref/tests/fixtures/sampling_keys.json - -The two pure functions are lifted verbatim from the Original's AST; nothing else of server.py is imported. -""" -import ast -import json -import os -import sys - -here = os.path.dirname(os.path.abspath(__file__)) -server_py = os.path.normpath(os.path.join(here, "..", "..", "..", "engine", "strata", "serve", "server.py")) - -# server.py imports the whole serving stack (jinja2, sockets, ...). The two functions under test are pure, so lift -# their source verbatim out of the AST instead of importing the module. -tree = ast.parse(open(server_py).read(), server_py) -engine = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "StrataEngine") -wanted = [n for n in engine.body if isinstance(n, ast.FunctionDef) and n.name in ("sampling_keys", "projection_key")] -assert {n.name for n in wanted} == {"sampling_keys", "projection_key"} -lifted = ast.Module(body=[ast.ClassDef(name="StrataEngine", bases=[], keywords=[], body=wanted, decorator_list=[])], - type_ignores=[]) -ast.fix_missing_locations(lifted) -ns = {} -exec(compile(lifted, server_py, "exec"), ns) - - -class server: # noqa: N801 - keeps the call below readable - StrataEngine = ns["StrataEngine"] - - -keys = server.StrataEngine.sampling_keys - -cases = [ - {}, - {"temperature": 0.0}, - {"temperature": 0.7}, - {"temperature": 1}, - {"temperature": 2.0}, - {"temperature": 0.1 + 0.2}, - {"temperature": 1e-7}, - {"temperature": 0.7, "top_p": 0.95}, - {"temperature": 0.7, "top_p": 1.0}, - {"top_p": 0.0}, - {"top_p": 0.5}, - {"top_k": 0}, {"top_k": 1}, {"top_k": 20}, {"top_k": 64}, {"top_k": 65}, {"top_k": 100000}, - {"min_p": 0.0}, {"min_p": 0.05}, {"min_p": 1.0}, {"min_p": 1e-5}, - {"repetition_penalty": 1.0}, - {"repetition_penalty": 1.1}, - {"repetition_penalty": 1.1, "penalty_last_n": 256}, - {"repetition_penalty": 1.1, "penalty_last_n": 0}, - {"repetition_penalty": 1.1, "penalty_last_n": 5000}, - {"frequency_penalty": 0.5}, - {"frequency_penalty": -0.5}, - {"presence_penalty": 0.25}, - {"presence_penalty": 1.5, "frequency_penalty": 0.5, "repetition_penalty": 1.05}, - {"presence_penalty": 0.0, "frequency_penalty": 0.0, "repetition_penalty": 1.0, "penalty_last_n": 33}, - {"penalty_last_n": 33}, - {"seed": 1}, {"seed": 42}, {"seed": 18446744073709551615}, - {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.02, "repetition_penalty": 1.1, - "presence_penalty": 0.5, "frequency_penalty": 0.25, "penalty_last_n": 128, "seed": 7}, - {"temperature": 1e16}, {"temperature": 1.5e-5}, -] -# the request-boundary rule (Rust) is stricter than the Original's silent skipping: those are tested in Rust only -out = { - "meta": {"generator": "crates/sampler-ref/oracle/gen_sampling_keys.py", - "oracle": "engine/strata/serve/server.py StrataEngine.sampling_keys"}, - "cases": [{"request": c, "keys": keys(dict(c))} for c in cases], -} -with open(sys.argv[1], "w") as f: - f.write('{"meta":' + json.dumps(out["meta"]) + ',\n"cases":[\n') - f.write(",\n".join(json.dumps(c) for c in out["cases"])) - f.write("\n]}\n") -print(f"wrote {len(cases)} cases") diff --git a/crates/sampler-ref/oracle/stub/cuda_runtime.h b/crates/sampler-ref/oracle/stub/cuda_runtime.h deleted file mode 100644 index 4a75f151..00000000 --- a/crates/sampler-ref/oracle/stub/cuda_runtime.h +++ /dev/null @@ -1,38 +0,0 @@ -// Host-only stand-in for so the Original's sampler_parity.cpp host reference -// (host_philox_uniform, sampled_reference, mirror_select, mirror_pick) can be compiled UNMODIFIED -// on a machine without CUDA. Nothing here is ever called by the fixture generator; every entry -// point aborts. The declarations only have to be enough for the file to parse. -#pragma once -#include -#include -#include - -typedef int cudaError_t; -typedef void* cudaStream_t; -typedef void* cudaEvent_t; -typedef void* cudaGraph_t; -typedef void* cudaGraphExec_t; -enum { cudaSuccess = 0 }; -enum cudaMemcpyKind { cudaMemcpyHostToDevice = 1, cudaMemcpyDeviceToHost = 2 }; -enum cudaStreamCaptureMode { cudaStreamCaptureModeThreadLocal = 1 }; - -[[noreturn]] inline void oracle_stub_abort() { std::fprintf(stderr, "cuda stub called\n"); std::abort(); } -inline const char* cudaGetErrorString(cudaError_t) { oracle_stub_abort(); } -template inline cudaError_t cudaMalloc(T**, size_t) { oracle_stub_abort(); } -inline cudaError_t cudaFree(void*) { oracle_stub_abort(); } -inline cudaError_t cudaMemcpy(void*, const void*, size_t, cudaMemcpyKind) { oracle_stub_abort(); } -inline cudaError_t cudaMemset(void*, int, size_t) { oracle_stub_abort(); } -inline cudaError_t cudaStreamCreate(cudaStream_t*) { oracle_stub_abort(); } -inline cudaError_t cudaStreamDestroy(cudaStream_t) { oracle_stub_abort(); } -inline cudaError_t cudaStreamSynchronize(cudaStream_t) { oracle_stub_abort(); } -inline cudaError_t cudaStreamBeginCapture(cudaStream_t, cudaStreamCaptureMode) { oracle_stub_abort(); } -inline cudaError_t cudaStreamEndCapture(cudaStream_t, cudaGraph_t*) { oracle_stub_abort(); } -inline cudaError_t cudaGraphInstantiate(cudaGraphExec_t*, cudaGraph_t, unsigned long long) { oracle_stub_abort(); } -inline cudaError_t cudaGraphLaunch(cudaGraphExec_t, cudaStream_t) { oracle_stub_abort(); } -inline cudaError_t cudaGraphDestroy(cudaGraph_t) { oracle_stub_abort(); } -inline cudaError_t cudaGraphExecDestroy(cudaGraphExec_t) { oracle_stub_abort(); } -inline cudaError_t cudaEventCreate(cudaEvent_t*) { oracle_stub_abort(); } -inline cudaError_t cudaEventDestroy(cudaEvent_t) { oracle_stub_abort(); } -inline cudaError_t cudaEventRecord(cudaEvent_t, cudaStream_t = nullptr) { oracle_stub_abort(); } -inline cudaError_t cudaEventSynchronize(cudaEvent_t) { oracle_stub_abort(); } -inline cudaError_t cudaEventElapsedTime(float*, cudaEvent_t, cudaEvent_t) { oracle_stub_abort(); } diff --git a/crates/sampler-ref/src/chain.rs b/crates/sampler-ref/src/chain.rs index d0279eda..7ee2e344 100644 --- a/crates/sampler-ref/src/chain.rs +++ b/crates/sampler-ref/src/chain.rs @@ -4,7 +4,7 @@ //! penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF pick //! ``` //! -//! Source of truth: `engine/strata/src/kernels/cuda/sampler.cu` +//! Source of truth: `Strata 41cf05a0, src/kernels/cuda/sampler.cu` //! (`sampler_greedy_kernel`, `sampler_kernel`, `sampler_one_block_kernel`, //! `sampled_tail_warp`) and the host mirrors `mirror_select` / `mirror_pick` //! in `sampler_parity.cpp`. The three sampled kernels of the Original (old, diff --git a/crates/sampler-ref/src/coupled.rs b/crates/sampler-ref/src/coupled.rs index d6df7784..db70c329 100644 --- a/crates/sampler-ref/src/coupled.rs +++ b/crates/sampler-ref/src/coupled.rs @@ -1,7 +1,7 @@ //! Coupled draft sampling arithmetic and the host penalty-history helpers. //! -//! Sources: `engine/strata/include/strata/core/coupled_draft.hpp` (cell / -//! counter / ring arithmetic), `engine/strata/include/strata/kernels/sampler.hpp` +//! Sources: `Strata 41cf05a0, include/strata/core/coupled_draft.hpp` (cell / +//! counter / ring arithmetic), `Strata 41cf05a0, include/strata/kernels/sampler.hpp` //! (`penalty_rows`) and the coupled kernels of `sampler.cu` //! (`coupled_penalize_kernel`, `coupled_merge_kernel`). //! diff --git a/crates/sampler-ref/src/lib.rs b/crates/sampler-ref/src/lib.rs index 36429cbe..6913283d 100644 --- a/crates/sampler-ref/src/lib.rs +++ b/crates/sampler-ref/src/lib.rs @@ -1,4 +1,4 @@ -//! CPU reference of the Original Strata sampler (`engine/strata`), in safe Rust. +//! CPU reference of the Original Strata sampler (Strata 41cf05a0), in safe Rust. //! //! This crate is a *literal transcription* of the Original host/device sampler //! logic, not a re-design: diff --git a/crates/sampler-ref/src/params.rs b/crates/sampler-ref/src/params.rs index 2168c73d..62331b1a 100644 --- a/crates/sampler-ref/src/params.rs +++ b/crates/sampler-ref/src/params.rs @@ -3,11 +3,11 @@ //! //! Sources of truth in the Original: //! -//! * `engine/strata/src/program/generate.cpp` (`GEN` key grammar and the +//! * `Strata 41cf05a0, src/program/generate.cpp` (`GEN` key grammar and the //! defaults an absent key keeps): greedy, `top_p = 1.0`, `top_k = 20`, //! `min_p = 0`, no penalties, `seed = 0` meaning "clock seed"; `min_p` is //! clamped to `[0, 1]` and `penalty_last_n` to `>= 0`. -//! * `engine/strata/serve/server.py` `StrataEngine.sampling_keys` (which keys are +//! * `Strata 41cf05a0, serve/server.py` `StrataEngine.sampling_keys` (which keys are //! emitted and how floats are printed) and `sampling_defaults_from_config` / //! `clean_shared_defaults` (the ranges the server enforces on configured //! defaults). diff --git a/crates/sampler-ref/src/philox.rs b/crates/sampler-ref/src/philox.rs index 2ea35ee1..bc9b99f0 100644 --- a/crates/sampler-ref/src/philox.rs +++ b/crates/sampler-ref/src/philox.rs @@ -1,7 +1,7 @@ //! The Original's counter-based uniform generator. //! //! Transcribed from `philox4x32_round` / `philox_uniform` in -//! `engine/strata/src/kernels/cuda/sampler.cu` (host twin: `host_philox_uniform` +//! `Strata 41cf05a0, src/kernels/cuda/sampler.cu` (host twin: `host_philox_uniform` //! in `sampler_parity.cpp`). NOTE: this is "Philox-shaped", not the textbook //! Philox4x32-10: the multipliers are the golden-ratio constants //! `0x9E3779B9` / `0xBB67AE85` and the round key is the bare round index diff --git a/crates/serving-policy/oracle/build_oracle.sh b/crates/serving-policy/oracle/build_oracle.sh deleted file mode 100755 index 3391284e..00000000 --- a/crates/serving-policy/oracle/build_oracle.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/sh -# Rebuild the host oracles and regenerate the committed fixtures. macOS or Linux, clang++ or g++, no CUDA. -# crates/serving-policy/oracle/build_oracle.sh [output_dir] -# The vision oracle compiles code EXTRACTED from the pinned generate.cpp (not retyped): the GENI embeddings / -# M-RoPE block and fnv1a, found by their text, so a change in the pinned source shows up as a failed extraction -# or a fixture diff. -set -eu -here=$(cd "$(dirname "$0")" && pwd) -root=$(cd "$here/../../.." && pwd) -engine="$root/engine/strata" -out=${1:-"$here/../tests/fixtures"} -work=${TMPDIR:-/tmp}/leleka_serving_oracle.$$ -mkdir -p "$work" "$out" -trap 'rm -rf "$work"' EXIT - -# ---- stride + watchdog -${CXX:-clang++} -std=c++17 -O1 -Wno-unused-function -I "$engine/include" "$here/gen_host_fixtures.cpp" -o "$work/host" -"$work/host" "$out/host_oracle.json" - -# ---- GENI embeddings block, verbatim -gen="$engine/src/program/generate.cpp" -awk '/^uint64_t fnv1a\(/ {p=1} p {print} p && /^}/ {exit}' "$gen" > "$work/fnv1a.inc" -awk '/if \(geni \|\| !mrope_identity\) \{/ {p=1} /tr\("positions built"/ {p=0} p {print}' "$gen" > "$work/generate_block.inc" -[ -s "$work/fnv1a.inc" ] && [ -s "$work/generate_block.inc" ] || { echo "could not extract the GENI block from $gen" >&2; exit 1; } -grep -q 'bad embeddings file' "$work/generate_block.inc" || { echo "extracted block is not the GENI embeddings code" >&2; exit 1; } -${CXX:-clang++} -std=c++20 -O1 -Wno-unused-function -Wno-unused-variable -I "$engine/include" -I "$work" \ - "$here/gen_vision_fixtures.cpp" -o "$work/vision" -"$work/vision" "$out/vision_oracle.json" - -# ---- control vector loader, verbatim -awk '/^bool load_control_vectors\(/ {p=1} p {print} p && /^}/ {exit}' "$gen" > "$work/load_control_vectors.inc" -[ -s "$work/load_control_vectors.inc" ] && grep -q 'no direction. tensors' "$work/load_control_vectors.inc" \ - || { echo "could not extract load_control_vectors from $gen" >&2; exit 1; } -${CXX:-clang++} -std=c++20 -O1 -ffp-contract=off -fno-fast-math -Wno-unused-function -Wno-unused-variable -I "$engine/include" -I "$work" \ - "$here/gen_cvec_fixtures.cpp" -o "$work/cvec" -"$work/cvec" "$out/cvec_oracle.json" diff --git a/crates/serving-policy/oracle/gen_cvec_fixtures.cpp b/crates/serving-policy/oracle/gen_cvec_fixtures.cpp deleted file mode 100644 index 2338d434..00000000 --- a/crates/serving-policy/oracle/gen_cvec_fixtures.cpp +++ /dev/null @@ -1,206 +0,0 @@ -// Host oracle for control vectors: `load_control_vectors` of src/program/generate.cpp INCLUDED VERBATIM -// (extracted by build_oracle.sh) with the Options / ModelGeometry / cvec_upload it needs stubbed, driven over -// small GGUF control-vector files this harness writes. The tables it would upload (dir, s) are recorded as -// raw float bits, so the Rust loader can be compared bit for bit (-ffp-contract=off pins the host arithmetic). -// -// Usage: gen_cvec_fixtures OUT.json -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "strata/artifact/gguf_reader.hpp" - -struct Options { - std::vector> cvec_files; - int cvec_first = -1, cvec_last = -1; - int cvec_mode = 1; - int cvec_single = -1; -}; -namespace strata::core { struct ModelGeometry { int64_t n_layers = 0, n_embd = 0, hc = 0; }; } -namespace strata::kernels { -struct Captured { std::vector dir, s; int mode = 0, first = 0, last = 0; bool called = false; }; -Captured g_up; -bool cvec_upload(const std::vector& dir, const std::vector& s, int mode, int first, int last, int64_t, int64_t, - std::string&) { - g_up = {dir, s, mode, first, last, true}; - return true; -} -} // namespace strata::kernels - -#include "load_control_vectors.inc" - -// ---- a minimal GGUF v3 writer --------------------------------------------------------------------------------- -struct Tensor { std::string name; uint32_t type; std::vector dims; std::vector data; }; -static void w32(std::string& s, uint32_t v) { s.append((const char*) &v, 4); } -static void w64(std::string& s, uint64_t v) { s.append((const char*) &v, 8); } -static void wstr(std::string& s, const std::string& v) { w64(s, v.size()); s += v; } -static std::string gguf(const std::vector>& kv, const std::vector& ts) { - std::string s = "GGUF"; - w32(s, 3); - w64(s, ts.size()); - w64(s, kv.size()); - for (const auto& [k, v] : kv) { wstr(s, k); w32(s, 8); wstr(s, v); } - uint64_t offset = 0; - std::vector offsets; - for (const Tensor& t : ts) { - wstr(s, t.name); - w32(s, (uint32_t) t.dims.size()); - for (uint64_t d : t.dims) w64(s, d); - w32(s, t.type); - w64(s, offset); - offsets.push_back(offset); - offset += (t.data.size() * 4 + 31) / 32 * 32; - } - while (s.size() % 32) s += '\0'; - for (const Tensor& t : ts) { - s.append((const char*) t.data.data(), t.data.size() * 4); - while (s.size() % 32) s += '\0'; - } - return s; -} -static std::string hex(const std::string& s) { - static const char* d = "0123456789abcdef"; - std::string o; - for (unsigned char c : s) { o += d[c >> 4]; o += d[c & 15]; } - return o; -} -static std::string jstr(const std::string& s) { - std::string o = "\""; - for (char c : s) { if (c == '"' || c == '\\') o += '\\'; o += c; } - return o + "\""; -} -static Tensor dir(const std::string& name, int64_t n, float seed, float step = 0.37f) { - Tensor t{name, 0, {(uint64_t) n}, {}}; - for (int64_t j = 0; j < n; ++j) t.data.push_back(seed + step * (float) j - (j % 3 == 0 ? 0.5f : 0.0f)); - return t; -} - -struct Case { - std::string name; - std::vector> files; // index into blobs, scale - int first, last, mode, single; -}; - -int main(int argc, char** argv) { - if (argc < 2) return 2; - constexpr int64_t L = 6, N = 5, HC = 2; - const std::string base = std::string(std::getenv("TMPDIR") ? std::getenv("TMPDIR") : "/tmp") + "/strata_cvec_oracle_" + std::to_string((long long) getpid()); - const std::vector> good = {{"general.architecture", "controlvector"}, {"controlvector.model_hint", "qwen4exp"}}; - std::vector blobs = { - // 0: directions for layers 1, 2, 4 (3 and 5 have none) - gguf(good, {dir("direction.1", N, 1.0f), dir("direction.2", N, -0.5f), dir("direction.4", N, 2.0f)}), - // 1: directions for 2, 3 - gguf(good, {dir("direction.2", N, 0.25f, 0.11f), dir("direction.3", N, 3.0f)}), - // 2: not a control vector - gguf({{"general.architecture", "llama"}}, {dir("direction.1", N, 1.0f)}), - // 3: no direction tensors - gguf(good, {dir("other.1", N, 1.0f)}), - // 4: wrong size - gguf(good, {dir("direction.1", N + 1, 1.0f)}), - // 5: wrong type (F16 id 1) - gguf(good, {Tensor{"direction.1", 1, {(uint64_t) N}, std::vector(3, 0.0f)}}), - // 6: layer 0, past the model, a non-number, a padded number: ignored / strtol semantics - gguf(good, {dir("direction.0", N, 9.0f), dir("direction.6", N, 9.0f), dir("direction.99", N, 9.0f), dir("direction.abc", N, 9.0f), - dir("direction.03", N, 0.75f)}), - // 7: all zeros - gguf(good, {Tensor{"direction.1", 0, {(uint64_t) N}, std::vector(N, 0.0f)}, Tensor{"direction.2", 0, {(uint64_t) N}, std::vector(N, 0.0f)}}), - // 8: another model's hint (a warning on stderr only) - gguf({{"general.architecture", "controlvector"}, {"controlvector.model_hint", "llama"}}, {dir("direction.1", N, 1.0f)}), - // 9: no hint at all - gguf({{"general.architecture", "controlvector"}}, {dir("direction.5", N, -1.0f)}), - }; - std::vector cases = { - {"add, one file, default range", {{"0", 1.0f}}, -1, -1, 1, -1}, - {"add, two files scaled and summed", {{"0", 0.5f}, {"1", -2.0f}}, -1, -1, 1, -1}, - {"project, one file", {{"0", 1.0f}}, -1, -1, 0, -1}, - {"project, two files", {{"0", 1.5f}, {"1", 1.0f}}, -1, -1, 0, -1}, - {"add, layer range 2..3", {{"0", 1.0f}, {"1", 1.0f}}, 2, 3, 1, -1}, - {"add, range past the model", {{"0", 1.0f}}, 1, 99, 1, -1}, - {"project, range first only", {{"0", 1.0f}}, 3, -1, 0, -1}, - {"project single:2", {{"0", 1.0f}}, -1, -1, 0, 2}, - {"project single:2 over a range", {{"0", 1.0f}, {"1", 1.0f}}, 2, 5, 0, 2}, - {"add ignores single", {{"0", 1.0f}}, -1, -1, 1, 2}, - {"project single without a direction", {{"0", 1.0f}}, -1, -1, 0, 3}, - {"project single past the model", {{"0", 1.0f}}, -1, -1, 0, 6}, - {"scale zero adds nothing but still counts as found", {{"0", 0.0f}}, -1, -1, 1, -1}, - {"scale zero in project mode steers nothing", {{"0", 0.0f}}, -1, -1, 0, -1}, - {"layers 0 / past-model / non-numeric ignored, 03 is layer 3", {{"6", 1.0f}}, -1, -1, 1, -1}, - {"not a control vector", {{"2", 1.0f}}, -1, -1, 1, -1}, - {"no direction tensors", {{"3", 1.0f}}, -1, -1, 1, -1}, - {"wrong tensor size", {{"4", 1.0f}}, -1, -1, 1, -1}, - {"wrong tensor type", {{"5", 1.0f}}, -1, -1, 1, -1}, - {"all-zero directions in project mode", {{"7", 1.0f}}, -1, -1, 0, -1}, - {"all-zero directions in add mode", {{"7", 1.0f}}, -1, -1, 1, -1}, - {"another model's hint still loads", {{"8", 1.0f}}, -1, -1, 1, -1}, - {"no hint", {{"9", 1.0f}}, -1, -1, 1, -1}, - {"second file bad", {{"0", 1.0f}, {"3", 1.0f}}, -1, -1, 1, -1}, - {"no steered layer in the range", {{"0", 1.0f}}, 5, 5, 1, -1}, - }; - std::FILE* f = std::fopen(argv[1], "w"); - if (!f) return 2; - std::fprintf(f, "{\n \"source\": \"src/program/generate.cpp load_control_vectors (verbatim) over GGUF files written by gen_cvec_fixtures.cpp\",\n" - " \"n_layers\": %lld, \"n_embd\": %lld, \"hc\": %lld,\n \"blobs\": [", (long long) L, (long long) N, (long long) HC); - for (size_t i = 0; i < blobs.size(); ++i) std::fprintf(f, "%s\"%s\"", i ? "," : "", hex(blobs[i]).c_str()); - std::fprintf(f, "],\n \"cases\": ["); - bool first = true; - for (const Case& c : cases) { - Options o; - o.cvec_first = c.first; - o.cvec_last = c.last; - o.cvec_mode = c.mode; - o.cvec_single = c.single; - std::vector> used; - for (size_t k = 0; k < c.files.size(); ++k) { - const int blob = std::atoi(c.files[k].first.c_str()); - const std::string path = base + "_" + std::to_string(blob) + ".gguf"; - std::FILE* w = std::fopen(path.c_str(), "wb"); - std::fwrite(blobs[(size_t) blob].data(), 1, blobs[(size_t) blob].size(), w); - std::fclose(w); - o.cvec_files.push_back({path, c.files[k].second}); - used.push_back({blob, c.files[k].second}); - } - strata::core::ModelGeometry g; - g.n_layers = L; g.n_embd = N; g.hc = HC; - strata::kernels::g_up = {}; - std::string summary, err; - const bool ok = load_control_vectors(o, g, summary, err); - // the temp paths carry this process's id: name the files by their blob instead - for (size_t k = 0; k < used.size(); ++k) { - const std::string path = o.cvec_files[k].first, label = "FILE" + std::to_string(used[k].first); - for (size_t at = err.find(path); at != std::string::npos; at = err.find(path)) err.replace(at, path.size(), label); - } - std::fprintf(f, "%s\n {\"name\": %s, \"files\": [", first ? "" : ",", jstr(c.name).c_str()); - for (size_t k = 0; k < used.size(); ++k) { - uint32_t bits; std::memcpy(&bits, &used[k].second, 4); - std::fprintf(f, "%s[%d, %u]", k ? "," : "", used[k].first, bits); - } - std::fprintf(f, "], \"first\": %d, \"last\": %d, \"mode\": \"%s\", \"single\": %d, \"ok\": %s, \"err\": %s, \"summary\": %s", - c.first, c.last, c.mode == 0 ? "project" : "add", c.single, ok ? "true" : "false", jstr(err).c_str(), jstr(summary).c_str()); - if (ok) { - std::fprintf(f, ", \"up\": {\"mode\": %d, \"first\": %d, \"last\": %d, \"dir_bits\": [", strata::kernels::g_up.mode, - strata::kernels::g_up.first, strata::kernels::g_up.last); - for (size_t i = 0; i < strata::kernels::g_up.dir.size(); ++i) { - uint32_t bits; std::memcpy(&bits, &strata::kernels::g_up.dir[i], 4); - std::fprintf(f, "%s%u", i ? "," : "", bits); - } - std::fprintf(f, "], \"s_bits\": ["); - for (size_t i = 0; i < strata::kernels::g_up.s.size(); ++i) { - uint32_t bits; std::memcpy(&bits, &strata::kernels::g_up.s[i], 4); - std::fprintf(f, "%s%u", i ? "," : "", bits); - } - std::fprintf(f, "]}"); - } - std::fprintf(f, "}"); - first = false; - for (const auto& [p, s] : o.cvec_files) { (void) s; std::remove(p.c_str()); } - } - std::fprintf(f, "\n ]\n}\n"); - std::fclose(f); - return 0; -} diff --git a/crates/serving-policy/oracle/gen_host_fixtures.cpp b/crates/serving-policy/oracle/gen_host_fixtures.cpp deleted file mode 100644 index 44f6675b..00000000 --- a/crates/serving-policy/oracle/gen_host_fixtures.cpp +++ /dev/null @@ -1,113 +0,0 @@ -// Host oracle for the serving policies that are plain C++ in the Original (no CUDA): -// * logits_selection.hpp - compiled UNMODIFIED from engine/strata/include; -// * the stall watchdog: core/progress.hpp (Progress, progress_now_ms) compiled unmodified, and the -// poll body of the watchdog thread in src/program/generate.cpp (the lines marked below) driven by an -// injected clock instead of sleep_for(1 s). -// Output: tests/fixtures/host_oracle.json (stride + watchdog scenarios). Usage: gen_host_fixtures OUT.json -#include -#include -#include -#include - -#include "strata/core/progress.hpp" -#include "strata/program/logits_selection.hpp" - -namespace ls = strata::program::logits_selection; - -static std::string esc(const std::string& s) { - std::string o; - for (char c : s) { - if (c == '"' || c == '\\') o += '\\'; - o += c; - } - return o; -} - -// ---- the watchdog thread of generate.cpp, with the clock and the counters passed in -------------------------- -struct Dog { - int limit; - uint64_t last; - uint64_t ticks_at; - int64_t since_ms; - Dog(int limit_s, int64_t now_ms, uint64_t beats, uint64_t ticks) - : limit(limit_s), last(beats), ticks_at(ticks), since_ms(now_ms) {} - // Returns -1 healthy, otherwise the "layers served since the last finished step" the report prints. - // The statements below are generate.cpp's loop body (lines "const uint64_t b = ..." to "std::abort()"). - int64_t poll(int64_t now_ms, uint64_t beats, bool busy, uint64_t ticks) { - if (limit <= 0) return -1; // `if (limit > 0) std::thread(...)`: no thread at all - const uint64_t b = beats; - if (!busy || b != last) { last = b; ticks_at = ticks; since_ms = now_ms; return -1; } - if (now_ms - since_ms < (int64_t) limit * 1000) return -1; - return (int64_t) (ticks - ticks_at); // stall_report(stderr, p.ticks.load() - ticks_at); abort - } -}; - -int main(int argc, char** argv) { - if (argc < 2) return 2; - std::FILE* f = std::fopen(argv[1], "w"); - if (!f) return 2; - std::fprintf(f, "{\n \"source\": \"include/strata/program/logits_selection.hpp + core/progress.hpp + the watchdog thread of src/program/generate.cpp (host build)\",\n"); - - // ---- stride - std::fprintf(f, " \"parse\": ["); - const char* texts[] = {"1", "2", "128", "9223372036854775807", "9223372036854775808", "0", "00", "007", "-1", "+1", - " 1", "1 ", "1x", "x", "", "1.5", "99999999999999999999", "12345678901234567890"}; - bool first = true; - for (const char* t : texts) { - int64_t v = -777; - const bool ok = ls::parse_stride(t, v); - std::fprintf(f, "%s\n {\"text\": \"%s\", \"ok\": %s, \"value\": %lld}", first ? "" : ",", esc(t).c_str(), ok ? "true" : "false", - (long long) (ok ? v : -777)); - first = false; - } - std::fprintf(f, "\n ],\n \"selected\": ["); - first = true; - const int64_t totals[] = {-1, 0, 1, 2, 5, 9, 10, 11, 64, 100}; - const int64_t strides[] = {-1, 0, 1, 2, 3, 4, 7, 10, 64, 1000}; - for (int64_t total : totals) - for (int64_t stride : strides) { - std::fprintf(f, "%s\n {\"total\": %lld, \"stride\": %lld, \"rows\": %lld, \"kept\": [", first ? "" : ",", (long long) total, - (long long) stride, (long long) ls::row_count(total, stride)); - bool kf = true; - for (int64_t p = -2; p < total + 2; ++p) - if (ls::selected(p, total, stride)) { - std::fprintf(f, "%s%lld", kf ? "" : ",", (long long) p); - kf = false; - } - std::fprintf(f, "]}"); - first = false; - } - std::fprintf(f, "\n ],\n"); - - // ---- watchdog scenarios: [limit_s, [[dt_ms, beats, busy, ticks], ...]] -> verdicts - struct Step { int64_t at_ms; uint64_t beats; bool busy; uint64_t ticks; }; - struct Scenario { int limit; std::vector steps; }; - std::vector sc = { - {3, {{1000, 0, true, 0}, {2000, 0, true, 5}, {2999, 0, true, 9}, {3000, 0, true, 9}, {4000, 0, true, 9}}}, - {2, {{1900, 1, true, 40}, {3800, 1, true, 40}, {3900, 1, true, 40}, {4000, 2, true, 41}, {5999, 2, true, 41}, {6000, 2, true, 80}}}, - {2, {{1000, 0, false, 1}, {2000, 0, false, 2}, {3000, 0, false, 3}, {100000, 0, true, 100}, {101999, 0, true, 100}, {102000, 0, true, 100}}}, - {0, {{1000, 0, true, 0}, {10000000, 0, true, 0}}}, - {-5, {{1000, 0, true, 0}, {10000000, 0, true, 0}}}, - {1, {{1000, 0, true, 3}, {2000, 0, true, 3}, {3000, 1, true, 3}, {3999, 1, true, 7}, {4000, 1, true, 7}}}, - {60, {{59000, 0, true, 0}, {59999, 0, true, 0}, {60000, 0, true, 12}, {61000, 5, false, 12}, {200000, 5, true, 12}}}, - }; - std::fprintf(f, " \"watchdog\": ["); - first = true; - for (const Scenario& s : sc) { - Dog dog(s.limit, 0, 0, 0); - std::fprintf(f, "%s\n {\"limit_s\": %d, \"steps\": [", first ? "" : ",", s.limit); - bool sf = true; - for (const Step& st : s.steps) { - const int64_t v = dog.poll(st.at_ms, st.beats, st.busy, st.ticks); - std::fprintf(f, "%s\n {\"at_ms\": %lld, \"beats\": %llu, \"busy\": %s, \"ticks\": %llu, \"layers_since\": %lld}", sf ? "" : ",", - (long long) st.at_ms, (unsigned long long) st.beats, st.busy ? "true" : "false", (unsigned long long) st.ticks, - (long long) v); - sf = false; - } - std::fprintf(f, "\n ]}"); - first = false; - } - std::fprintf(f, "\n ]\n}\n"); - std::fclose(f); - return 0; -} diff --git a/crates/serving-policy/oracle/gen_vision_fixtures.cpp b/crates/serving-policy/oracle/gen_vision_fixtures.cpp deleted file mode 100644 index 335a36e0..00000000 --- a/crates/serving-policy/oracle/gen_vision_fixtures.cpp +++ /dev/null @@ -1,145 +0,0 @@ -// Host oracle for the image-embeddings path of `--serve` (GENI): the SVE1 record reader and the M-RoPE -// position table of src/program/generate.cpp. -// -// The block between "if (geni || !mrope_identity) {" and "tr(\"positions built\"" is INCLUDED VERBATIM from the -// pinned generate.cpp (extracted by build_oracle.sh, see generate_block.inc) - not retyped - and so is `fnv1a`. -// Everything around it (the variables the block reads, a CUDA-free `put` target) is declared here. -// -// Usage: gen_vision_fixtures OUT.json (writes its scratch embedding files to $TMPDIR) -#include -#include -#include -#include -#include -#include -#include -#include - -#include "strata/core/conversation_cache.hpp" - -using ImgKey = strata::core::ConversationImageKey; - -#include "fnv1a.inc" - -struct Geometry { int64_t n_embd; }; - -struct Result { - std::string ve; - std::vector table; - std::vector row_offset; // float offset into img_rows per token, -1 = none - std::vector imgs; -}; - -constexpr int64_t kImagePad = 248056; - -static Result run(bool geni, const std::vector& ids, const std::string& emb_path, int64_t n_embd, int64_t cells, - bool mrope_identity) { - Geometry g{n_embd}; - const int64_t n = (int64_t) ids.size(); - std::vector req_imgs; - std::vector mrope_host((size_t) cells * 3); - for (int64_t c = 0; c < cells; ++c) mrope_host[(size_t) c * 3] = mrope_host[(size_t) c * 3 + 1] = mrope_host[(size_t) c * 3 + 2] = (int32_t) c; - std::vector img_rows; - std::vector row_ptr; - Result out; - { - // ---------------------------------------------------------------- verbatim from generate.cpp -#include "generate_block.inc" - out.ve = ve; - } // closes the `if (geni || !mrope_identity) {` that the block opens - } - out.table = mrope_host; - out.imgs = req_imgs; - for (const float* p : row_ptr) out.row_offset.push_back(p ? (int64_t) (p - img_rows.data()) : -1); - return out; -} - -// ---- SVE1 file builders --------------------------------------------------------------------------------------- -static void put_i32(std::string& s, int32_t v) { s.append((const char*) &v, 4); } -static std::string image(int32_t n, int32_t nx, int32_t ny, int32_t width, float seed, int32_t magic = 0x31455653) { - std::string s; - for (int32_t v : {magic, n, nx, ny, width}) put_i32(s, v); - for (int32_t i = 0; i < n * width; ++i) { - const float f = seed + (float) i * 0.5f; - s.append((const char*) &f, 4); - } - return s; -} - -static std::string hex(const std::string& s) { - static const char* d = "0123456789abcdef"; - std::string o; - for (unsigned char c : s) { o += d[c >> 4]; o += d[c & 15]; } - return o; -} - -static std::string jstr(const std::string& s) { - std::string o = "\""; - for (char c : s) { if (c == '"' || c == '\\') o += '\\'; o += c; } - return o + "\""; -} - -int main(int argc, char** argv) { - if (argc < 2) return 2; - const char* tmp = std::getenv("TMPDIR"); - const std::string scratch = std::string(tmp ? tmp : "/tmp") + "/strata_sve_oracle_" + std::to_string((long long) getpid()) + ".sve"; - std::FILE* f = std::fopen(argv[1], "w"); - if (!f) return 2; - std::fprintf(f, "{\n \"source\": \"src/program/generate.cpp GENI embeddings block + fnv1a (verbatim, host build)\",\n \"cases\": ["); - - struct Case { const char* name; bool geni; std::vector ids; std::string file; int64_t n_embd; int64_t cells; bool identity; }; - const int64_t P = kImagePad; - const std::string i1 = image(1, 1, 1, 4, 1.0f), i6 = image(6, 3, 2, 4, 10.0f), i8 = image(8, 2, 4, 4, 20.0f), i25 = image(25, 5, 5, 4, 30.0f); - std::vector cases = { - {"text identity after an image request", false, {5, 6, 7}, "", 4, 32, false}, - {"text only with no file", true, {5, 6, 7, 8}, "", 4, 32, true}, - {"one 1x1 image", true, {1, 2, P, 3, 4}, i1, 4, 32, true}, - {"one 3x2 image", true, {1, P, P, P, P, P, P, 9, 10}, i6, 4, 40, true}, - {"one 2x4 image (tall: ny > nx)", true, {7, P, P, P, P, P, P, P, P, 8}, i8, 4, 40, true}, - {"two images in order", true, {1, P, P, P, P, P, P, 2, P, P, P, P, P, P, P, P, 3}, i6 + i8, 4, 64, true}, - {"5x5 image then text", true, {1, 2, 3, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, 4, 5}, i25, 4, 64, true}, - {"adjacent images", true, {P, P, P, P, P, P, P, P, P, P, P, P, P, P, 1}, i6 + i8, 4, 40, true}, - {"image at the start", true, {P, 4}, i1, 4, 16, true}, - {"identity request after (not geni, not identity)", false, {1, 2}, "", 4, 16, false}, - // errors - {"prompt ends in an image", true, {1, P, P, P, P, P, P}, i6, 4, 32, true}, - {"more images in the prompt than the file", true, {1, P, 2, P, 3}, i1, 4, 32, true}, - {"more images in the file than the prompt", true, {1, P, 2, 3}, i1 + i1, 4, 32, true}, - {"fewer image_pad tokens than rows", true, {1, P, P, 2, 3, 4, 5, 6, 7}, i6, 4, 32, true}, - {"bad magic", true, {1, P, 2}, image(1, 1, 1, 4, 1.0f, 0x12345678), 4, 32, true}, - {"wrong width", true, {1, P, 2}, image(1, 1, 1, 8, 1.0f), 4, 32, true}, - {"grid does not multiply", true, {1, P, 2}, image(6, 3, 3, 4, 1.0f), 4, 32, true}, - {"zero rows", true, {1, P, 2}, image(0, 0, 0, 4, 1.0f), 4, 32, true}, - {"short header", true, {1, P, 2}, i1.substr(0, 12), 4, 32, true}, - {"short data", true, {1, P, 2}, i1.substr(0, i1.size() - 3), 4, 32, true}, - {"second record truncated", true, {1, P, 2, P, 3}, i1 + i1.substr(0, 25), 4, 32, true}, - }; - bool first = true; - for (const Case& c : cases) { - if (!c.file.empty() || c.geni) { - std::FILE* w = std::fopen(scratch.c_str(), "wb"); - std::fwrite(c.file.data(), 1, c.file.size(), w); - std::fclose(w); - } - // "no file": point at a path that does not exist - const std::string path = c.file.empty() && c.geni ? std::string("/nonexistent/embeddings.sve") : scratch; - const Result r = run(c.geni, c.ids, path, c.n_embd, c.cells, c.identity); - std::fprintf(f, "%s\n {\"name\": %s, \"geni\": %s, \"mrope_identity\": %s, \"n_embd\": %lld, \"cells\": %lld, \"file_hex\": \"%s\", \"ids\": [", - first ? "" : ",", jstr(c.name).c_str(), c.geni ? "true" : "false", c.identity ? "true" : "false", - (long long) c.n_embd, (long long) c.cells, hex(c.file).c_str()); - for (size_t i = 0; i < c.ids.size(); ++i) std::fprintf(f, "%s%lld", i ? "," : "", (long long) c.ids[i]); - std::fprintf(f, "], \"ve\": %s, \"table\": [", jstr(r.ve).c_str()); - for (size_t i = 0; i < r.table.size(); ++i) std::fprintf(f, "%s%d", i ? "," : "", r.table[i]); - std::fprintf(f, "], \"row_offset\": ["); - for (size_t i = 0; i < r.row_offset.size(); ++i) std::fprintf(f, "%s%lld", i ? "," : "", (long long) r.row_offset[i]); - std::fprintf(f, "], \"imgs\": ["); - for (size_t i = 0; i < r.imgs.size(); ++i) - std::fprintf(f, "%s[%lld,\"%016llx\"]", i ? "," : "", (long long) r.imgs[i].start, (unsigned long long) r.imgs[i].hash); - std::fprintf(f, "]}"); - first = false; - } - std::remove(scratch.c_str()); - std::fprintf(f, "\n ]\n}\n"); - std::fclose(f); - return 0; -} diff --git a/crates/serving-policy/src/lib.rs b/crates/serving-policy/src/lib.rs index 1799d354..4aa55e38 100644 --- a/crates/serving-policy/src/lib.rs +++ b/crates/serving-policy/src/lib.rs @@ -1,4 +1,4 @@ -//! Pure Rust ports of the Original Strata serving-layer policies (`engine/strata/serve/*.py` and the +//! Pure Rust ports of the Original Strata serving-layer policies (`Strata 41cf05a0, serve/*.py` and the //! host-side parts of `src/program/generate.cpp`). No I/O, no async runtime, no `unsafe`. //! //! Each module cites the Original code it transcribes and is tested against fixtures produced by running diff --git a/crates/tokenizer/tests/oracle_differential.rs b/crates/tokenizer/tests/oracle_differential.rs index 7c86760e..8de555f1 100644 --- a/crates/tokenizer/tests/oracle_differential.rs +++ b/crates/tokenizer/tests/oracle_differential.rs @@ -1,4 +1,4 @@ -//! Tokenizer versus `engine/strata/tools/strata_tokenizer.py` (the unmodified oracle, regex 2026.9.10). +//! Tokenizer versus `Strata 41cf05a0, tools/strata_tokenizer.py` (the unmodified oracle, regex 2026.9.10). //! //! `tests/fixtures/tokenizer_oracle.json` is produced by `scripts/offline/gen_goldens.py tokenizer_oracle`: a //! synthetic byte-level BPE vocabulary (256-byte alphabet, 300 trained merges that reach past the 64-symbol heap diff --git a/deploy/README.md b/deploy/README.md index f53ad557..878be948 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -606,6 +606,9 @@ libraries. HIP and non-Linux/GNU configurations reject this option. On a Linux builder with the toolkit and CMake already installed: +> **Retired (STRA-406).** `scripts/build-static-cuda.sh` built the engine from the vendored Strata tree, which was removed from the repository +> (`third_party/strata/UPSTREAM.md`). Build the engine from an upstream checkout at the pin and pass the binary to `scripts/build-linux-package.py`. + ```sh export CUDACXX=/absolute/path/to/cuda/bin/nvcc export CUDAToolkit_ROOT=/absolute/path/to/cuda @@ -762,12 +765,10 @@ fail without publishing a pack. `conversions.json` records the changes and source tensor hashes; `source.json` records the verified shard identities; the receipt lists the optional files that are present. -`scripts/smoke-native-pack.py` compares dense bytes, index rows and the complete -v3/v4 expert table against the unmodified pinned `tools/iq_pack.py` oracle on -small single/split GGUF fixtures, including per-role shard offsets. Numerical -and byte tolerance is zero. `scripts/offline/diff_native_pack.py` extends this to -thousands of generated cases plus the full CLI with `--compat-bf16`, `--base` and -`--experts-bin` (see `spec node offline-port.md`). Python/numpy are test-only dependencies. This does +The pack bytes (dense bytes, index rows and the complete v3/v4 expert table) were compared against the unmodified pinned `tools/iq_pack.py` oracle +on small single/split GGUF fixtures, including per-role shard offsets, with zero numerical and byte tolerance (`scripts/smoke-native-pack.py` and +`scripts/offline/diff_native_pack.py`, retired with the vendored Strata tree in STRA-406; the Rust tests and the checked-in goldens remain; see +`spec node offline-port.md`). Python/numpy are test-only dependencies. This does not establish full-model GPU readiness: real-model pack parity and clean-node GPU startup still require their separate gates. Automatic fetch/prepare/start orchestration remains a subsequent integration step. @@ -895,7 +896,7 @@ readiness**. It neither converts a raw MTP GGUF nor quantizes new weights. The existing offline `mtp_rt.py` conversion remains separate; its dense Q8 conversion must not be described as lossless. MTP activation stays explicit and real-model qualification is still required. CPU verification: -`python3 scripts/smoke-mtp-pack.py /path/to/leleka-api` (synthetic sparse layout). +`scripts/smoke-mtp-pack.py` (synthetic sparse layout; retired with the vendored Strata tree in STRA-406, the Rust tests of `mtp_pack` remain). `scripts/smoke-native-bootstrap.py` verifies real HTTP acquisition, exact pack @@ -989,6 +990,8 @@ separate qualification step. On a Linux x86_64 build host with the CUDA toolkit, GNU toolchain, `musl-gcc`, Python 3.11+, `readelf`, and the pinned Rust toolchain/target installed: +> `scripts/build-static-cuda.sh` is retired (STRA-406, see above): produce the engine binary and `BUILD-FEATURES.json` from an upstream build. + ```sh scripts/build-static-cuda.sh engine="$PWD/artifacts/build-static-cuda/strata" diff --git a/engine/upstream.md b/engine/upstream.md index e27a68f8..9d041723 100644 --- a/engine/upstream.md +++ b/engine/upstream.md @@ -1,6 +1,6 @@ # Strata upstream provenance -**Status:** `engine/strata/` was brought to upstream `41cf05a0` (engine 0.1.50, app 0.2.5) on 2026-10-25 on branch +**Status:** `Strata 41cf05a0 ` was brought to upstream `41cf05a0` (engine 0.1.50, app 0.2.5) on 2026-10-25 on branch `claude/upstream-sync`, with the local patches re-applied. The previous pin (`d9ab8435`, engine 0.1.35) is kept below and in Git history (`570201a:engine/strata`). Nothing was pushed. The quality-gate reference build (`stra169-ladder` Original) stays a build of the OLD pin plus the old local patches; the new subtree is not that reference (see "What this does to the quality reference"). @@ -14,7 +14,7 @@ OLD pin plus the old local patches; the new subtree is not that reference (see " | Upstream commit date | 2026-10-25 11:35 +0100 ("README (all 7 languages): models in the order Qwen3.8-Flash-Next, Qwen3.6-35B-A3B, DeepSeek V4.1-Flash") | | Upstream version at the pin | engine and Control 0.1.50, Terminal and app 0.2.5 (`1aff6d14`, 2026-10-24) | | Upstream tree object of the pin | not recorded (the subtree is the pin plus local patches and omissions; the exact differences are listed below) | -| Local repository path | `engine/strata/` | +| Local repository path | `Strata 41cf05a0 ` | | Update date | 2026-10-25 | | Update method | documented tree replacement: 3-way `git merge-tree` of the old subtree against the new upstream, base = the old pin (see "How this update was made") | | Hosted project repository URL | https://github.com/paveldhq/leleka-api (private) | @@ -24,8 +24,8 @@ OLD pin plus the old local patches; the new subtree is not that reference (see " | Pin | Upstream commit | Date | Engine | In this repository | | --- | --- | --- | --- | --- | -| 1 (initial import) | `d9ab8435f654c368c586340d490915f6addf56a3` | 2026-10-02 | 0.1.35 | `engine/strata/` up to `570201a` (git subtree merge `c4e2137` of squash `906afc5de9dd` in the pre-squash history; later squashed into `4013e0c`) | -| 2 (this update) | `41cf05a06a25dd29103b7b27a2279a3f60c21876` | 2026-10-25 | 0.1.50 | `engine/strata/` on `claude/upstream-sync` | +| 1 (initial import) | `d9ab8435f654c368c586340d490915f6addf56a3` | 2026-10-02 | 0.1.35 | `Strata 41cf05a0 ` up to `570201a` (git subtree merge `c4e2137` of squash `906afc5de9dd` in the pre-squash history; later squashed into `4013e0c`) | +| 2 (this update) | `41cf05a06a25dd29103b7b27a2279a3f60c21876` | 2026-10-25 | 0.1.50 | `Strata 41cf05a0 ` on `claude/upstream-sync` | **Upstream rewrote its history.** `d9ab8435` is not an ancestor of upstream `origin/main` (`git merge-base --is-ancestor` fails). Its tree is identical (`git diff` is empty, tree `487c4cc0`) to upstream commit `5b734e42` ("Engine 0.1.35", same date), which is an @@ -44,7 +44,7 @@ so `git subtree pull` has nothing to anchor on. The update therefore used a tree the local patches), `theirs` = upstream `41cf05a0`. 2. `git merge-tree --write-tree --merge-base= `; conflicts were resolved by hand (below); the result was checked by listing every blob that differs from upstream `41cf05a0` (only the 21 patched files, the 4 added files and the left-out files differ). -3. The result tree went into `engine/strata/` with `git read-tree --prefix=engine/strata/ -u` (`core.autocrlf=false`, LF kept), then the +3. The result tree went into `Strata 41cf05a0 ` with `git read-tree --prefix=Strata 41cf05a0 -u` (`core.autocrlf=false`, LF kept), then the left-out files were removed from the index and the working tree. 4. `docs/upstream/local-patches-on-0.1.35.patch` is the patch that was re-applied (old pin to old subtree, 25 files); `docs/upstream/local-patches-on-0.1.50.patch` is the same patches as they stand on the new pin (new pin to new subtree, 25 files). @@ -62,7 +62,7 @@ All of them are default-off or build-profile only. None changes the default beha | Keyless V-only QSA arm (`a8411b5`; failed its quality gate, see `docs/experiments/2026-10-04-keyless-runtime.md`, `docs/keyless-runtime.md`) | `include/strata/core/keyless.hpp`, `src/core/keyless.cpp`, `src/kernels/cuda/keyless.cu`, `src/kernels/keyless_parity.cpp` (new files), plus `layer.cpp/.hpp`, `verify.cpp/.hpp`, `prefill.cpp`, `src/prefill/kernels.cu`, `kv_q8.cu`, `kv_stream.cu/.hpp`, `qsa_decode_attn.cu/.hpp`, `kv_stream_parity.cpp`, `conversation_snapshot.cpp/_test.cpp`, `mtp.cpp`, `generate.cpp` | Re-applied by hand (see conflicts). Needs `STRATA_KEYLESS_ROUTING` and `--kv int8`; refuses K8V4 and the new fused norm+rope; no slots / rows attention variant (falls back to per-query calls) | | Mode bits | `setup.sh` | The 0644 mode our 2026-10-14 snapshot (`7f896a8`) set on `setup.sh` and `docker-entrypoint.sh` is not carried: `setup.sh` is 0755 as upstream; upstream deleted `docker-entrypoint.sh` (it is `docker/entrypoint.sh` now) | -Other commits that touched `engine/strata` in the pre-squash history (`b1da05f` first-window logits capture, `78e92d5` telemetry) are +Other commits that touched Strata 41cf05a0, in the pre-squash history (`b1da05f` first-window logits capture, `78e92d5` telemetry) are either not part of the tracked snapshot at `570201a` or are the telemetry line listed above; `git grep` for the capture finds nothing in `570201a:engine/strata`, so nothing was lost by this update. @@ -90,7 +90,7 @@ Content conflicts (15 files, 44 hunks) and one modify/delete. Everything else in ### What this does to the quality reference -`engine/strata/` on this branch is a different engine from the one the `stra169-ladder` Original was built from: with default flags it +`Strata 41cf05a0 ` on this branch is a different engine from the one the `stra169-ladder` Original was built from: with default flags it behaves differently from the old pin (upstream flipped defaults on: route tail skip, PcieAuto, sm_120 and sm_86 kernel sets, fused int8 prompt experts, auto conversation cache; see `docs/upstream-digest-2026-10-25.md`). Do not use a build of this subtree for the greedy/tensor baselines of `docs/quality-gate.md`. The old pin remains reproducible from `git show 570201a:engine/strata` and from the upstream tree @@ -124,12 +124,12 @@ upstream's instructions for its product and do not apply to work in this reposit | Check | Result | | --- | --- | -| Tree identity: every blob of `engine/strata/` compared with upstream `41cf05a0` | identical except the 21 patched files + 4 new files (and the left-out files) | +| Tree identity: every blob of `Strata 41cf05a0 ` compared with upstream `41cf05a0` | identical except the 21 patched files + 4 new files (and the left-out files) | | `git diff --stat` for line-ending churn | none (LF kept, `core.autocrlf=false`; the nested `.gitattributes` of the subtree sets `eol=crlf` for `*.bat/*.cmd/*.ps1` as upstream does) | | `scripts/build-cpu.sh` in WSL Ubuntu 24.04, GCC 13.3, CMake 3.31.6 | 16 of 16 ctest tests pass (the script's target list had to be extended: upstream registers 11 more CPU tests than the old pin; `Not Run` otherwise) | | CUDA compile (sm_86 only, `nvcc` 13.2, no GPU use) of the patched translation units: `kv_q8.cu`, `kv_stream.cu`, `qsa_decode_attn.cu`, `keyless.cu`, `prefill/kernels.cu`, `prefill.cpp`, `layer.cpp`, `verify.cpp`, `expert_source.cpp`, `mtp.cpp`, `conversation_snapshot.cpp`, `keyless.cpp`, `ngram.cpp`, `generate.cpp`, `kv_stream_parity.cpp`, `keyless_parity.cpp` | all 17 objects compile (warnings only) in the default configuration; the 7 objects that depend on the KAR/PLE macros (`ngram.cpp`, `expert_source.cpp`, `prefill.cpp`, `generate.cpp`, `kar_ple_cache.cu`, `kar_expert.cu`, `kar_expert_miss.cpp`) also compile with `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`, `STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=ON`, `STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON`. The compile found one error a textual merge cannot (a duplicate `trace_h_` member in `verify.hpp`), fixed by renaming ours to `kl_trace_*`. Not built: link, the `strata` binary, the parity tests, the sm_120 PTX | | GPU parity, quality gate, any model run | not run (by instruction); the keyless, KAR and PLE arms are default off and unexercised | -| Port crates that `include_str!` files from `engine/strata` | none of those files changed upstream (`LICENSE`, `serve/chat_template.jinja`, `serve/chat_golden.json`, `tests/data/native_experts/*.txt`, `serve/mcp_fake_server.py`, `tools/mtp_rt.py`) | +| Port crates that `include_str!` files from Strata 41cf05a0 | none of those files changed upstream (`LICENSE`, `serve/chat_template.jinja`, `serve/chat_golden.json`, `tests/data/native_experts/*.txt`, `serve/mcp_fake_server.py`, `tools/mtp_rt.py`) | ## Local CUDA validation, 2026-10-04 @@ -171,7 +171,7 @@ quality arm, not full compressed-model residency or a qualified speedup. The Leleka runtime under `crates/`, `desktop-core/` and `control-plane/` is a Rust/CUDA port of the Original mode17 serve path written for this project; it shares the model artifacts and the algorithms (not the C++ code) with Strata. The Original used as the quality reference and for the vanilla baselines is a separate build of the OLD pin (`d9ab8435` / `5b734e42`, engine 0.1.35) plus the local -patches that were in `engine/strata/` before this update; `engine/strata/` itself is no longer that source. The agreement of the port +patches that were in `Strata 41cf05a0 ` before this update; `Strata 41cf05a0 ` itself is no longer that source. The agreement of the port with the Original is measured in `docs/quality-gate.md`; the request-end prefix checkpoints (`docs/prefix-cache.md`) and the chain kernels (`docs/chain-kernels.md`) are port-side additions with their own gates. diff --git a/limits.json b/limits.json index 5cb53f03..ca1b834d 100644 --- a/limits.json +++ b/limits.json @@ -2,7 +2,7 @@ "_comment": "Policy of scripts/check-limits.py (STRA-367, lawbook chapter 301). The limits apply to new and changed code (diff gate) and to the whole tree as a falling census. See spec node architecture/limits-gate.md.", "limits": {"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120, "params": 5}, "tab_width": 4, - "exclude": ["engine/strata/", "target/", ".git/"], + "exclude": ["third_party/strata/", "target/", ".git/"], "python_include": [ "scripts/limits/", "scripts/archcheck/", "scripts/check-limits.py", "scripts/check_limits_test.py", "scripts/check-architecture.py", "scripts/check_architecture_test.py" diff --git a/scripts/build-cpu.sh b/scripts/build-cpu.sh deleted file mode 100755 index 11acddaf..00000000 --- a/scripts/build-cpu.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -build_dir="${STRATA_BUILD_DIR:-${repo_root}/artifacts/build-cpu}" -jobs="${BUILD_JOBS:-4}" - -if ! command -v cmake >/dev/null 2>&1; then - printf 'CMake 3.24 or newer is required.\n' >&2 - exit 1 -fi - -cmake -S "${repo_root}/engine/strata" -B "${build_dir}" \ - -DSTRATA_ENABLE_CUDA=OFF \ - -DSTRATA_ENABLE_HIP=OFF \ - -DSTRATA_BUILD_TESTS=OFF \ - -DSTRATA_BUILD_CONVERSATION_TESTS=ON - -# The standalone CPU tests ctest registers under STRATA_BUILD_CONVERSATION_TESTS. Upstream 0.1.50 registers eleven more than -# the 0.1.35 pin did; a registered test whose binary is not built shows up as "Not Run" and fails ctest, so every one is listed. -cmake --build "${build_dir}" --parallel "${jobs}" --target \ - strata-gguf strata-dequant strata-plan \ - conversation_cache_test conversation_memory_test \ - conv_cache_test coupled_draft_test bf16_bits_test \ - conversation_split_failure_test conversation_file_test session_save_reclaim_test message_boundary_test \ - split_ring_test draft_kv_plan_test spec_prob_test draft_cap_test batch_rows_test batch_groups_test \ - nvfp4_avx512_parity - -ctest --test-dir "${build_dir}" --output-on-failure diff --git a/scripts/build-cuda-projection-family-oracle.sh b/scripts/build-cuda-projection-family-oracle.sh deleted file mode 100755 index a4b02b86..00000000 --- a/scripts/build-cuda-projection-family-oracle.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env bash -# Test-only bounded native reference; no serving/model build or GPU execution. -# TOOLKIT must be the verified deploy/cuda-toolkit.lock.json 13.0.88 distribution. -set -euo pipefail -[[ $# == 2 ]] || { echo 'Usage: build-cuda-projection-family-oracle.sh TOOLKIT PRIVATE_OUTPUT' >&2; exit 2; } -root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -toolkit="$(cd "$1" && pwd)" -output="$2" -[[ ! -e "$output" && -f "$toolkit/TOOLKIT-PROVENANCE.json" ]] -"$toolkit/bin/nvcc" --version | grep 'V13.0.88' -python3 - "$toolkit/TOOLKIT-PROVENANCE.json" "$root/deploy/cuda-toolkit.lock.json" <<'PY' -import json,sys -assert json.load(open(sys.argv[1]))['lock']==json.load(open(sys.argv[2])) -PY -# Exact native source identity is an oracle gate, not caller-selected reference. -echo 'f2fc636e5e8f6db9bbb8146fbf2b78a717c0e0076bf8c72ac2b784df7b3f455f engine/strata/src/kernels/cuda/native_mmvq.cu' | (cd "$root" && sha256sum --check) -echo '07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537 engine/strata/src/kernels/cuda/iq_kernels.cu' | (cd "$root" && sha256sum --check) -echo '0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c engine/strata/third_party/ggml/ggml-common.h' | (cd "$root" && sha256sum --check) -sha256sum "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" "$root/scripts/cuda-projection-family-oracle/native_fixture.cu" -"$toolkit/bin/nvcc" -std=c++17 -O3 -arch=sm_120 --use_fast_math \ - -Xcompiler=-ffunction-sections,-fdata-sections -Xlinker=--gc-sections \ - -I"$root/engine/strata/include" -I"$root/engine/strata/third_party/ggml" "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" \ - "$root/engine/strata/src/kernels/cuda/iq_kernels.cu" \ - "$root/scripts/cuda-projection-family-oracle/native_fixture.cu" -ldl -o "$output" -sha256sum "$output" diff --git a/scripts/build-cuda-q5-oracle.sh b/scripts/build-cuda-q5-oracle.sh deleted file mode 100755 index e3a4afa5..00000000 --- a/scripts/build-cuda-q5-oracle.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -# Test-only bounded native reference; no serving/model build or GPU execution. -# TOOLKIT must be the verified deploy/cuda-toolkit.lock.json 13.0.88 distribution. -set -euo pipefail -[[ $# == 2 ]] || { echo 'Usage: build-cuda-q5-oracle.sh TOOLKIT PRIVATE_OUTPUT' >&2; exit 2; } -root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -toolkit="$(cd "$1" && pwd)" -output="$2" -[[ ! -e "$output" && -f "$toolkit/TOOLKIT-PROVENANCE.json" ]] -"$toolkit/bin/nvcc" --version | grep 'V13.0.88' -python3 - "$toolkit/TOOLKIT-PROVENANCE.json" "$root/deploy/cuda-toolkit.lock.json" <<'PY' -import json,sys -assert json.load(open(sys.argv[1]))['lock']==json.load(open(sys.argv[2])) -PY -# Exact native source identity is an oracle gate, not caller-selected reference. -echo 'f2fc636e5e8f6db9bbb8146fbf2b78a717c0e0076bf8c72ac2b784df7b3f455f engine/strata/src/kernels/cuda/native_mmvq.cu' | (cd "$root" && sha256sum --check) -sha256sum "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" "$root/scripts/cuda-q5-oracle/native_fixture.cu" -"$toolkit/bin/nvcc" -std=c++17 -O3 -arch=sm_120 --use_fast_math \ - -Xcompiler=-ffunction-sections,-fdata-sections -Xlinker=--gc-sections \ - -I"$root/engine/strata/include" "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" \ - "$root/scripts/cuda-q5-oracle/native_fixture.cu" -ldl -o "$output" -sha256sum "$output" diff --git a/scripts/build-cuda-q6-oracle.sh b/scripts/build-cuda-q6-oracle.sh deleted file mode 100755 index 054ba140..00000000 --- a/scripts/build-cuda-q6-oracle.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -# Test-only bounded native reference; no serving/model build or GPU execution. -# TOOLKIT must be the verified deploy/cuda-toolkit.lock.json 13.0.88 distribution. -set -euo pipefail -[[ $# == 2 ]] || { echo 'Usage: build-cuda-q6-oracle.sh TOOLKIT PRIVATE_OUTPUT' >&2; exit 2; } -root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -toolkit="$(cd "$1" && pwd)" -output="$2" -[[ ! -e "$output" && -f "$toolkit/TOOLKIT-PROVENANCE.json" ]] -"$toolkit/bin/nvcc" --version | grep 'V13.0.88' -python3 - "$toolkit/TOOLKIT-PROVENANCE.json" "$root/deploy/cuda-toolkit.lock.json" <<'PY' -import json,sys -assert json.load(open(sys.argv[1]))['lock']==json.load(open(sys.argv[2])) -PY -# Exact native source identity is an oracle gate, not caller-selected reference. -echo 'f2fc636e5e8f6db9bbb8146fbf2b78a717c0e0076bf8c72ac2b784df7b3f455f engine/strata/src/kernels/cuda/native_mmvq.cu' | (cd "$root" && sha256sum --check) -sha256sum "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" "$root/scripts/cuda-q6-oracle/native_fixture.cu" -"$toolkit/bin/nvcc" -std=c++17 -O3 -arch=sm_120 --use_fast_math \ - -Xcompiler=-ffunction-sections,-fdata-sections -Xlinker=--gc-sections \ - -I"$root/engine/strata/include" "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" \ - "$root/scripts/cuda-q6-oracle/native_fixture.cu" -ldl -o "$output" -sha256sum "$output" diff --git a/scripts/build-cuda-qsa-oracle.sh b/scripts/build-cuda-qsa-oracle.sh deleted file mode 100755 index 3b3c7a6b..00000000 --- a/scripts/build-cuda-qsa-oracle.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env bash -# New test-only harness; never launches a GPU or rebuilds the server. -set -euo pipefail -[[ $# == 1 ]] || { echo 'Usage: build-cuda-qsa-oracle.sh PRIVATE_OUTPUT_DIRECTORY' >&2; exit 2; } -root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -out="$1" -mkdir -p "$out" -nvcc --version | tee "$out/compiler.txt" -grep 'V12.8.93' "$out/compiler.txt" -(cd "$root" && sha256sum --check scripts/cuda-qsa-oracle/source.sha256) -common=(-std=c++17 -O3 -arch=sm_120 -Xcompiler=-ffunction-sections,-fdata-sections -I"$root/engine/strata/include") -for part in native rope index; do - nvcc "${common[@]}" --use_fast_math -c "$root/scripts/cuda-qsa-oracle/oracle_$part.cu" -o "$out/$part.o" -done -for part in select attention; do - nvcc "${common[@]}" --fmad=true --ftz=false -c "$root/scripts/cuda-qsa-oracle/oracle_$part.cu" -o "$out/$part.o" -done -nvcc "${common[@]}" --fmad=false --ftz=false "$root/scripts/cuda-qsa-oracle/main.cu" "$out/"{native,rope,index,select,attention}.o -Xlinker=--gc-sections -L/usr/local/cuda/lib64/stubs -lcuda -o "$out/qsa_oracle" -sha256sum "$out/qsa_oracle" "$out/"*.o > "$out/binary.sha256" diff --git a/scripts/build-original-verify-ptx.sh b/scripts/build-original-verify-ptx.sh deleted file mode 100644 index 51f592ed..00000000 --- a/scripts/build-original-verify-ptx.sh +++ /dev/null @@ -1,184 +0,0 @@ -#!/usr/bin/env bash -# Produce the fixed CUDA Driver assets consumed by OriginalVerifyBank, direct prompt, and MTP paths. -# -# This is an offline compilation step for the Linux CPU Docker runner. It does -# not load libcuda, expose a GPU, start a model, or run an inference request. -set -euo pipefail - -[[ $# == 1 ]] || { - echo "Usage: scripts/build-original-verify-ptx.sh PINNED_CUDA_TOOLKIT" >&2 - exit 2 -} - -root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -toolkit="$(cd "$1" && pwd)" -lock="$root/deploy/cuda-toolkit.lock.json" - -[[ -f "$toolkit/TOOLKIT-PROVENANCE.json" ]] || { - echo "missing pinned toolkit provenance" >&2 - exit 2 -} -"$toolkit/bin/nvcc" --version | grep -F 'V13.0.88' >/dev/null -python3 - "$toolkit/TOOLKIT-PROVENANCE.json" "$lock" <<'PY' -import json, sys -if json.load(open(sys.argv[1], encoding='utf-8'))['lock'] != json.load(open(sys.argv[2], encoding='utf-8')): - raise SystemExit('toolkit provenance does not match deploy/cuda-toolkit.lock.json') -PY - -stage="$(mktemp -d "$root/crates/cuda-driver/src/.original-verify-ptx.XXXXXX")" -trap 'rm -rf "$stage"' EXIT - -compile() { - local source="$1" output="$2" - "$toolkit/bin/nvcc" --ptx -std=c++17 -O3 -arch=sm_120 \ - --fmad=true --ftz=false -I"$root/engine/strata/include" -I"$root/engine/strata/third_party/ggml" -I"$root/crates/cuda-driver/src/third_party/llamacpp/ggml-cuda" -I"$root/crates/cuda-driver/src/third_party/llamacpp/ggml-include" -I"$root/crates/cuda-driver/src/third_party/llamacpp/ggml-src" "$source" -o "$output" -} - -compile "$root/crates/cuda-driver/src/original_verify.cu" "$stage/original_verify.ptx" -compile "$root/crates/cuda-driver/src/original_verify_qsa.cu" "$stage/original_verify_qsa.ptx" -compile "$root/crates/cuda-driver/src/qsa_prompt_device_gate.cu" "$stage/qsa_prompt_device_gate.ptx" -compile "$root/crates/cuda-driver/src/ple_prompt_device.cu" "$stage/ple_prompt_device.ptx" -compile "$root/crates/cuda-driver/src/gr_prompt_device.cu" "$stage/gr_prompt_device.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_tail.cu" "$stage/mtp_original_tail.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_kv.cu" "$stage/mtp_original_kv.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_prefill.cu" "$stage/mtp_original_prefill.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_prefill_embedding.cu" "$stage/mtp_original_prefill_embedding.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_prefill_quant.cu" "$stage/mtp_original_prefill_quant.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_prefill_mmq.cu" "$stage/mtp_original_prefill_mmq.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_prefill_fixup.cu" "$stage/mtp_original_prefill_fixup.ptx" -# Full MTP forward: every asset is compiled from its matching direct CUDA source. -compile "$root/crates/cuda-driver/src/mtp_original_full_s2.cu" "$stage/mtp_original_full_s2.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_quant80.cu" "$stage/mtp_original_full_quant80.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_shared.cu" "$stage/mtp_original_full_shared.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_router.cu" "$stage/mtp_original_full_router.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_router_legacy.cu" "$stage/mtp_original_full_router_legacy.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_combine.cu" "$stage/mtp_original_full_combine.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_bf16.cu" "$stage/mtp_original_full_bf16.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_gr_norm.cu" "$stage/mtp_original_full_gr_norm.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_gr_post.cu" "$stage/mtp_original_full_gr_post.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_gr_write.cu" "$stage/mtp_original_full_gr_write.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_element.cu" "$stage/mtp_original_full_element.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_qsa_gate.cu" "$stage/mtp_original_full_qsa_gate.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_verify.cu" "$stage/mtp_original_full_verify.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_head_native.cu" "$stage/mtp_original_full_head_native.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_head_iq.cu" "$stage/mtp_original_full_head_iq.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_head_sampler.cu" "$stage/mtp_original_full_head_sampler.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_qnorm.cu" "$stage/mtp_original_full_qnorm.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_fused_gr.cu" "$stage/mtp_original_full_fused_gr.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_checks.cu" "$stage/mtp_original_full_checks.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_attention.cu" "$stage/mtp_original_full_attention.ptx" -compile "$root/crates/cuda-driver/src/mtp_original_full_coupled.cu" "$stage/mtp_original_full_coupled.ptx" - -python3 - "$stage/original_verify.ptx" "$stage/original_verify_qsa.ptx" "$stage/qsa_prompt_device_gate.ptx" "$stage/ple_prompt_device.ptx" "$stage/gr_prompt_device.ptx" "$stage/mtp_original_tail.ptx" "$stage/mtp_original_kv.ptx" "$stage/mtp_original_prefill.ptx" "$stage/mtp_original_prefill_embedding.ptx" "$stage/mtp_original_prefill_quant.ptx" "$stage/mtp_original_prefill_mmq.ptx" "$stage/mtp_original_prefill_fixup.ptx" "$stage/mtp_original_full_s2.ptx" "$stage/mtp_original_full_quant80.ptx" "$stage/mtp_original_full_shared.ptx" "$stage/mtp_original_full_router.ptx" "$stage/mtp_original_full_router_legacy.ptx" "$stage/mtp_original_full_combine.ptx" "$stage/mtp_original_full_bf16.ptx" "$stage/mtp_original_full_gr_norm.ptx" "$stage/mtp_original_full_gr_post.ptx" "$stage/mtp_original_full_gr_write.ptx" "$stage/mtp_original_full_element.ptx" "$stage/mtp_original_full_qsa_gate.ptx" "$stage/mtp_original_full_verify.ptx" "$stage/mtp_original_full_head_native.ptx" "$stage/mtp_original_full_head_iq.ptx" "$stage/mtp_original_full_head_sampler.ptx" "$stage/mtp_original_full_qnorm.ptx" "$stage/mtp_original_full_fused_gr.ptx" "$stage/mtp_original_full_checks.ptx" "$stage/mtp_original_full_attention.ptx" "$stage/mtp_original_full_coupled.ptx" <<'PY' -import sys -from pathlib import Path - -required = { - 'original_verify.ptx': ( - 'verify_gdn_conv_l2_multi_kernel', 'verify_gdn_conv_commit_kernel', - 'verify_gdn_ab_multi_kernel', 'verify_gdn_step_norm_multi_kernel', - 'verify_embedding_gather_dev_kernel', 'verify_broadcast_streams_kernel', - 'verify_copy_indexed_kernel', 'verify_fetch_blobs_kernel', - 'verify_rebase_ptrs_kernel', 'verify_add_streams_broadcast_kernel', - 'verify_ident_hits_kernel', 'verify_gather_rows_16', 'verify_gather_rows_4', - 'verify_gather_rows_1', 'verify_map_ids_kernel', 'verify_row_top_prob_kernel', - 'verify_mtp_select_kernel', 'verify_dense_steps_kernel', 'verify_window_ids_kernel', - 'verify_wait_flag_ge_kernel', 'verify_resident_plan_kernel', - 'verify_wait_flag_ge_or_kernel', 'verify_copy_i32_unless_kernel', - 'verify_copy_or_zero_kernel', 'verify_gpu_stamp_kernel', - 'verify_copy_from_mapped_kernel', 'verify_copy_rows_from_mapped_kernel', - 'verify_doorbell_publish_kernel', 'verify_copy_i32_from_mapped_kernel', - 'verify_clear_status', 'verify_scan_logits', - ), - 'original_verify_qsa.ptx': ( - 'verify_qsa_append_analytic', 'verify_qsa_append_table', - ), - 'qsa_prompt_device_gate.ptx': ( - 'qsa_prompt_device_gate', - ), - 'ple_prompt_device.ptx': ( - 'ple_rms', 'ple_gate', 'ple_broadcast', 'ple_conv', 'ple_history', 'ple_finite', - ), - 'gr_prompt_device.ptx': ( - 'gr_norm_rs_kernel', 'gr_silu_kernel', 'gr_mix_r_kernel', 'gr_write_kernel', 'gr_scan', - 'gr_norm_scan', 'gr_silu_scan', 'gr_product_scan', 'gr_write_norm_rs_kernel', - ), - 'mtp_original_tail.ptx': ( - 'mtp_original_quantize', 'mtp_original_q80_1', 'mtp_original_q80_2', 'mtp_original_q80_3', - 'mtp_original_q80_4', 'mtp_original_q80_5', 'mtp_original_q80_6', 'mtp_original_q80_7', - 'mtp_original_q80_8', 'mtp_original_knorm', 'mtp_original_krope', 'mtp_original_finite', 'mtp_original_q8_guard', - ), - 'mtp_original_kv.ptx': ( - 'mtp_original_append', 'mtp_original_ring_table', 'mtp_original_window_ids', 'mtp_original_encoded_guard', - ), - 'mtp_original_prefill.ptx': ( - 'mtp_prefill_rms', 'mtp_prefill_gr_norm', 'mtp_prefill_gr_silu', 'mtp_prefill_gr_mix', - 'mtp_prefill_broadcast', 'mtp_prefill_embedding', 'mtp_prefill_rope', 'mtp_prefill_append', - 'mtp_prefill_finite', 'mtp_prefill_iota', 'mtp_prefill_encoded', 'mtp_prefill_zero', - 'mtp_prefill_gr_norm_scan', 'mtp_prefill_gr_silu_scan', 'mtp_prefill_bf16_scan', - 'mtp_prefill_gr_product_scan', 'mtp_prefill_q8_scan', - ), - 'mtp_original_prefill_embedding.ptx': ('mtp_prefill_native_embedding',), - 'mtp_original_prefill_quant.ptx': ('mtp_prefill_q8',), - 'mtp_original_prefill_mmq.ptx': ( - '_Z9mul_mat_qIL9ggml_type8ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - '_Z9mul_mat_qIL9ggml_type8ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - '_Z9mul_mat_qIL9ggml_type8ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - '_Z9mul_mat_qIL9ggml_type8ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - '_Z9mul_mat_qIL9ggml_type8ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - '_Z9mul_mat_qIL9ggml_type8ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - '_Z9mul_mat_qIL9ggml_type8ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - '_Z9mul_mat_qIL9ggml_type8ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - '_Z9mul_mat_qIL9ggml_type8ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - '_Z9mul_mat_qIL9ggml_type8ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - '_Z9mul_mat_qIL9ggml_type8ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_', - ), - 'mtp_original_prefill_fixup.ptx': ( - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - '_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_', - ), - 'mtp_original_full_coupled.ptx': ( - 'sampler_split_part_kernel', 'coupled_stage_kernel', 'coupled_penalize_kernel', 'coupled_merge_kernel', - ), -} - -symbols = (Path.cwd() / 'crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/full_forward/symbols.rs').read_text(encoding='utf-8') -for asset, exports in __import__('re').findall(r'include_bytes!\(\"([^\"]+\.ptx)\"\).*?&\[(.*?)\]\)', symbols, __import__('re').S): - required[asset] = tuple(__import__('re').findall(r'c\"([^\"]+)\"', exports)) - -for raw in map(Path, sys.argv[1:]): - body = raw.read_bytes() - if not (0 < len(body) <= 16 * 1024 * 1024) or b'\0' in body or not body.isascii(): - raise SystemExit(f'{raw.name}: invalid PTX encoding or size') - text = body.decode('ascii') - missing = [name for name in required[raw.name] if f'.entry {name}' not in text] - if missing: - raise SystemExit(f'{raw.name}: missing exports: {", ".join(missing)}') - if 'UNSEALED' in text: - raise SystemExit(f'{raw.name}: unsealed marker') -PY - -for name in original_verify.ptx original_verify_qsa.ptx qsa_prompt_device_gate.ptx ple_prompt_device.ptx gr_prompt_device.ptx; do - install -m 0644 "$stage/$name" "$root/crates/cuda-driver/src/.$name.new" - mv -f "$root/crates/cuda-driver/src/.$name.new" "$root/crates/cuda-driver/src/$name" - sha256sum "$root/crates/cuda-driver/src/$name" -done - -# MTP FFI loads include_bytes! assets directly and requires precisely one -# terminal NUL. Validate generated ASCII raw PTX above, then append only that -# terminator during atomic installation. -for name in mtp_original_tail.ptx mtp_original_kv.ptx mtp_original_prefill.ptx mtp_original_prefill_embedding.ptx mtp_original_prefill_quant.ptx mtp_original_prefill_mmq.ptx mtp_original_prefill_fixup.ptx mtp_original_full_s2.ptx mtp_original_full_quant80.ptx mtp_original_full_shared.ptx mtp_original_full_router.ptx mtp_original_full_router_legacy.ptx mtp_original_full_combine.ptx mtp_original_full_bf16.ptx mtp_original_full_gr_norm.ptx mtp_original_full_gr_post.ptx mtp_original_full_gr_write.ptx mtp_original_full_element.ptx mtp_original_full_qsa_gate.ptx mtp_original_full_verify.ptx mtp_original_full_head_native.ptx mtp_original_full_head_iq.ptx mtp_original_full_head_sampler.ptx mtp_original_full_qnorm.ptx mtp_original_full_fused_gr.ptx mtp_original_full_checks.ptx mtp_original_full_attention.ptx mtp_original_full_coupled.ptx; do - python3 -c 'import sys; from pathlib import Path; raw=Path(sys.argv[1]).read_bytes(); assert raw and raw.isascii() and b"\0" not in raw; Path(sys.argv[2]).write_bytes(raw+b"\0")' "$stage/$name" "$root/crates/cuda-driver/src/.$name.new" - chmod 0644 "$root/crates/cuda-driver/src/.$name.new" - mv -f "$root/crates/cuda-driver/src/.$name.new" "$root/crates/cuda-driver/src/$name" - sha256sum "$root/crates/cuda-driver/src/$name" -done diff --git a/scripts/build-static-cuda.sh b/scripts/build-static-cuda.sh deleted file mode 100755 index 970e77d6..00000000 --- a/scripts/build-static-cuda.sh +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -build_dir="${STRATA_BUILD_DIR:-${repo_root}/artifacts/build-static-cuda}" -jobs="${BUILD_JOBS:-2}" -[[ "$(uname -s)" == Linux ]] || { echo 'Static CUDA engine builds require Linux.' >&2; exit 1; } - -if [[ ${STRATA_KAR_PLE+x} ]]; then - kar_ple="${STRATA_KAR_PLE}" -else - kar_ple=0 -fi -case "${kar_ple}" in - 0) cmake_kar_ple=OFF ;; - 1) cmake_kar_ple=ON ;; - *) echo 'STRATA_KAR_PLE must be exactly 0 or 1.' >&2; exit 2 ;; -esac - -if [[ ${SOURCE_REVISION+x} ]]; then - source_revision="${SOURCE_REVISION}" -else - source_revision="$(git -C "${repo_root}" rev-parse HEAD)" -fi -if [[ ! "${source_revision}" =~ ^[0-9a-f]{40}$ ]]; then - echo 'SOURCE_REVISION must be an exact lowercase 40-character Git commit.' >&2 - exit 2 -fi - -# CUDACXX/CUDAToolkit_ROOT select an existing toolkit; STRATA_GGML_DIR avoids fetching GGML. -cmake_args=( - -S "${repo_root}/engine/strata" -B "${build_dir}" - -DSTRATA_ENABLE_CUDA=ON -DSTRATA_ENABLE_HIP=OFF -DSTRATA_CUDA_STATIC=ON \ - -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES="${CUDA_ARCHITECTURES:-120}" \ - -DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE="${cmake_kar_ple}" \ - -DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=OFF \ - -DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE=OFF \ - -DSTRATA_NEXT_KAR_DIR="${repo_root}/gpu/kar" \ - -DSTRATA_BUILD_TESTS=OFF -DSTRATA_NATIVE_EXPERTS=ON \ - -DSTRATA_PORTABLE=ON -) -if [[ -n "${STRATA_GGML_DIR:-}" ]]; then - cmake_args+=("-DSTRATA_GGML_DIR=${STRATA_GGML_DIR}") -fi -cmake "${cmake_args[@]}" -cmake --build "${build_dir}" --parallel "${jobs}" --target strata -python3 "${repo_root}/scripts/check-static-cuda-elf.py" "${build_dir}/strata" -# generate.cpp handles --help before any model or GPU initialization. -env -u LD_LIBRARY_PATH CUDA_VISIBLE_DEVICES= "${build_dir}/strata" --help - -# This records compile capability only. The runtime still requires an explicit -# model/profile selection; PLE is experimental and defaults off at serving time. -python3 - "${build_dir}/BUILD-FEATURES.json" "${kar_ple}" "${CUDA_ARCHITECTURES:-120}" "${source_revision}" <<'PYFEATURES' -import json -import os -from pathlib import Path -import sys -import tempfile - -destination, ple, architectures, revision = sys.argv[1:] -record = { - 'schema_version': 1, - 'source_revision': revision, - 'cuda_architectures': architectures, - 'features': { - 'cuda': True, - 'cuda_static_runtime': True, - 'cxx_static_runtime': True, - 'kar_ple': ple == '1', - 'kar_experts': False, - 'ple_trace': False, - }, -} -path = Path(destination) -path.parent.mkdir(parents=True, exist_ok=True) -fd, temporary = tempfile.mkstemp(prefix='.BUILD-FEATURES-', dir=path.parent) -try: - with os.fdopen(fd, 'w') as output: - json.dump(record, output, sort_keys=True, indent=2) - output.write('\n') - output.flush() - os.fsync(output.fileno()) - os.replace(temporary, path) -finally: - if os.path.exists(temporary): - os.unlink(temporary) -PYFEATURES diff --git a/scripts/check-keyless-gpu.sh b/scripts/check-keyless-gpu.sh deleted file mode 100755 index 4a31ccec..00000000 --- a/scripts/check-keyless-gpu.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -build_dir="${STRATA_KEYLESS_BUILD_DIR:-${repo_root}/artifacts/build-keyless-gpu}" -# A separate CUDA test context must fit; never stop the user's serving process. -used="$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | head -n 1)" -if (( used > 1024 )); then - printf 'GPU is occupied; run keyless validation after unloading the model.\n' >&2 - exit 1 -fi -cmake -S "${repo_root}/engine/strata" -B "${build_dir}" \ - -DSTRATA_ENABLE_CUDA=ON -DSTRATA_ENABLE_HIP=OFF \ - -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_BUILD_TESTS=OFF \ - -DSTRATA_BUILD_CONVERSATION_TESTS=ON \ - -DCMAKE_CUDA_ARCHITECTURES="${STRATA_CUDA_ARCHITECTURES:-native}" -cmake --build "${build_dir}" --parallel "${BUILD_JOBS:-4}" --target \ - keyless_parity keyless_stream_parity conversation_snapshot_test -ctest --test-dir "${build_dir}" --output-on-failure \ - -R '^(keyless_parity|keyless_stream_parity|conversation_snapshot_test)$' diff --git a/scripts/check-local.sh b/scripts/check-local.sh index 2f54eac9..996914ea 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -14,8 +14,6 @@ # Environment: # STRICT_DEBT=1 fail on the known format/Clippy debt listed below instead of warning # SKIP_LINUX_TYPECHECK=1 skip the x86_64-unknown-linux-gnu type-check (needs `rustup target add` otherwise) -# OFFLINE_ORACLE_PYTHON, STRATA_GGUF_PY -# enable the live Python-oracle differentials # LELEKA_LINUX_TESTS=1 also run scripts/linux-tests/run.sh (Docker Linux harness, branch claude/port-linux-tests) # # No model weights, tokens or network access to model hosts are used by any step. @@ -66,8 +64,6 @@ fast_path() { debt cargo fmt -p leleka-model-format -p leleka-experimental-ref --check cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-experimental-ref --all-targets --no-deps -- -D warnings debt cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-model-format --all-targets --no-deps -- -D warnings - # leleka-experimental-ref includes tests/literal_port.rs, the drift guard between engine/strata/src/kernels/cuda and the checked-in - # experimental ports (re-synced to the upstream 41cf05a0 kernels on 2026-11-03). cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-experimental-ref -p leleka-model-format } @@ -90,24 +86,8 @@ port_oracles() { # Pure-host tests of the Linux-only sampler files, against fixtures built from the unmodified Original host code. "${repo_root}/crates/sampler-ref/oracle/run_port_host_tests.sh" # Golden fixtures built from the Original C++/Python (rope, memory plan, serving policy, conversation, experimental - # references, offline tools, tokenizer) are replayed by the cargo tests above. Live Python differentials follow. - offline_oracles -} - -# Live differentials against the unmodified Python oracle. Opt in with a venv that has -# numpy, pyyaml, tqdm, jinja2 and regex, and the pinned llama.cpp gguf-py: -# OFFLINE_ORACLE_PYTHON=/venv/bin/python STRATA_GGUF_PY=/llama.cpp/gguf-py scripts/check-local.sh -offline_oracles() { - if [[ -n "${OFFLINE_ORACLE_PYTHON:-}" && -n "${STRATA_GGUF_PY:-}" ]]; then - cargo build --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-control-plane --bin leleka-api - local strata_next="${CARGO_TARGET_DIR:-${repo_root}/target}/debug/leleka-api" - local oracle - for oracle in native_pack gguf_header tokenizer dequant tools mtp_fetch chat_template; do - "${OFFLINE_ORACLE_PYTHON}" "${repo_root}/scripts/offline/diff_${oracle}.py" "${strata_next}" - done - else - echo "== live Python oracle differentials skipped (set OFFLINE_ORACLE_PYTHON and STRATA_GGUF_PY)" - fi + # references, offline tools, tokenizer) are checked in and replayed by the cargo tests above. The generators and the live + # Python differentials needed the vendored Strata tree, which was removed (third_party/strata/UPSTREAM.md, STRA-406). } linux_harness() { @@ -210,20 +190,18 @@ port_oracles linux_harness [[ "${mode}" == port ]] && exit 0 -python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py" +python3 -m py_compile "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py" python3 "${repo_root}/scripts/test-benchmark-harness.py" python3 "${repo_root}/scripts/test-native-service.py" python3 "${repo_root}/scripts/test-native-api.py" python3 "${repo_root}/scripts/test-native-menu.py" python3 "${repo_root}/scripts/test-model-switch.py" python3 "${repo_root}/scripts/test-cuda-bootstrap.py" -python3 "${repo_root}/scripts/test-static-cuda-profile.py" python3 "${repo_root}/scripts/test-static-cuda-elf.py" python3 "${repo_root}/scripts/test-linux-package.py" python3 "${repo_root}/scripts/test-runtime-image.py" python3 "${repo_root}/scripts/test-ple-config-parity.py" python3 "${repo_root}/scripts/test-gitea-release.py" -python3 "${repo_root}/scripts/test-keyless-routing.py" # leleka-cuda-driver and leleka-runtime build only for Linux; on other hosts the type-check above is the check. if [[ "${host_os}" == Linux ]]; then @@ -238,19 +216,8 @@ if [[ "${host_os}" == Linux ]]; then else echo "== Linux-only crate tests skipped on ${host_os}" fi -# every ported .cu parses against the CUDA stub headers (no nvcc needed; see scripts/cuda-stubs/cuda_stub.h) -# (verified on macOS/Apple clang; on other hosts libstdc++'s math headers may need stub additions, so it is advisory there) -if command -v clang++ >/dev/null 2>&1; then - if [ "$(uname -s)" = Darwin ]; then - python3 "${repo_root}/scripts/cuda-stubs/check-cu.py" - else - # glibc/libstdc++ hosts: clang's CUDA frontend needs macOS-only stub overloads, so the C++-only pass (--plain) is the advisory check here - python3 "${repo_root}/scripts/cuda-stubs/check-cu.py" --plain || echo "warning: cuda stub syntax check failed (advisory off macOS)" >&2 - fi -fi cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check cargo clippy --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --all-targets --no-deps -- -D warnings cargo test --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked replay="$(cargo run --quiet --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --bin replay-responses -- --sse "${repo_root}/benchmarks/fixtures/responses/structured-tool.json")" [[ "${replay}" == *"event: response.completed"* ]] -"${repo_root}/scripts/build-cpu.sh" diff --git a/scripts/check_limits_test.py b/scripts/check_limits_test.py index 1fd65f0c..f759c448 100755 --- a/scripts/check_limits_test.py +++ b/scripts/check_limits_test.py @@ -19,7 +19,7 @@ from limits import allow, baseline, census, cli, clippy_ratchet, diffs, files, g from limits import model, policy, pyscan, rscan # noqa: E402 POLICY = policy.Policy({"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120, "params": 5}, 4, - ("engine/strata/",), + ("third_party/strata/",), ("scripts/limits/",), ("claude/hexagonal-integ", "main")) LIMITS = POLICY.limits @@ -298,7 +298,7 @@ class TempRepo(unittest.TestCase): self.root = pathlib.Path(self.tmp.name) git(self.root, "init", "-q", "-b", "main") (self.root / "limits.json").write_text(json.dumps({ - "limits": LIMITS, "tab_width": 4, "exclude": ["engine/strata/"], "python_include": [], + "limits": LIMITS, "tab_width": 4, "exclude": ["third_party/strata/"], "python_include": [], "base_candidates": ["claude/hexagonal-integ", "main"]}), encoding="utf-8") self.write("old.rs", LONG) git(self.root, "add", "-A") @@ -344,7 +344,7 @@ class GateOnARepository(TempRepo): self.assertEqual(self.run_gate(), 1) def test_excluded_paths_are_ignored(self): - self.write("engine/strata/x.rs", LONG) + self.write("third_party/strata/x.rs", LONG) self.assertEqual(self.run_gate(), 0) def test_base_resolution(self): @@ -393,7 +393,7 @@ class BaselineRatchet(unittest.TestCase): class Policy(unittest.TestCase): def test_scope_of_files(self): self.assertEqual(policy.language(POLICY, "crates/x/src/a.rs"), "rust") - self.assertIsNone(policy.language(POLICY, "engine/strata/src/a.rs")) + self.assertIsNone(policy.language(POLICY, "third_party/strata/src/a.rs")) self.assertIsNone(policy.language(POLICY, "crates/x/target/debug/build.rs")) self.assertEqual(policy.language(POLICY, "scripts/limits/cli.py"), "python") self.assertIsNone(policy.language(POLICY, "scripts/other.py")) diff --git a/scripts/compare-real-tokenizer.py b/scripts/compare-real-tokenizer.py deleted file mode 100644 index 8c428138..00000000 --- a/scripts/compare-real-tokenizer.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python3 -"""Compare native token IDs and roundtrips with the pinned upstream Python oracle. - -Offline evaluation only. Requires `regex` for engine/strata/tools/strata_tokenizer.py. -The real GGUF and extracted tokenizer assets must stay outside Git. -""" - -import argparse -import json -import pathlib -import subprocess -import sys - - -CORPUS = ( - "Hello world!", - "Привіт, світе! Як справи?", - "e\u0301 café — naïve", - "😀👨‍👩‍👧‍👦", - "空白 漢字\n数字123", - "\t\r\nTwo spaces\x00end", - "<|im_start|>user\nSay hi<|im_end|>", - '{"name":"calc","arguments":{"x":1}}', - "a" * 70 + " next", - "print(1 + 2) # ✓", -) - - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--binary", type=pathlib.Path, required=True) - parser.add_argument("--gguf", type=pathlib.Path, required=True) - parser.add_argument("--assets", type=pathlib.Path, required=True) - args = parser.parse_args() - binary = args.binary.resolve(strict=True) - gguf = args.gguf.resolve(strict=True) - assets = args.assets.resolve(strict=True) - sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "engine/strata/tools")) - from strata_tokenizer import Tokenizer # pylint: disable=import-outside-toplevel - - oracle = Tokenizer.from_gguf(gguf) - for special in (False, True): - for number, value in enumerate(CORPUS): - command = [binary, "model", "tokenize", assets, "--stdin"] - if special: - command.append("--special") - native = json.loads(subprocess.run( - command, input=value, text=True, capture_output=True, check=True, - ).stdout) - expected = oracle.encode(value, parse_special=special) - if native != expected: - raise ValueError(f"token IDs differ for case {number}, special={special}") - decoded = json.loads(subprocess.run( - [binary, "model", "detokenize", assets, ",".join(map(str, native))], - text=True, capture_output=True, check=True, - ).stdout) - if decoded != value or oracle.decode(expected) != value: - raise ValueError(f"roundtrip differs for case {number}, special={special}") - print(json.dumps({"cases": len(CORPUS) * 2, "vocab": len(oracle.tokens), - "merges": len(oracle.ranks), "result": "exact native/upstream parity"})) - - -if __name__ == "__main__": - main() diff --git a/scripts/cuda-projection-family-oracle/native_fixture.cu b/scripts/cuda-projection-family-oracle/native_fixture.cu deleted file mode 100644 index e1a85bad..00000000 --- a/scripts/cuda-projection-family-oracle/native_fixture.cu +++ /dev/null @@ -1,60 +0,0 @@ -// Independent test-only runner. Compile the ORIGINAL native_mmvq.cu unchanged. -// Does not decode native weights, share candidate scratch, or select arbitrary entries. -#include "strata/kernels/native_mmvq.hpp" -#include "strata/kernels/iq_kernels.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -static void ck(cudaError_t e){if(e!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(e));} -static void dc(CUresult e){if(e!=CUDA_SUCCESS)throw std::runtime_error("Driver test fixture status "+std::to_string(e));} -template static T sym(void* lib,const char* name){void* p=dlsym(lib,name);if(!p)throw std::runtime_error(name);return reinterpret_cast(p);} -int main(int argc,char**argv) try { - if(argc!=4)throw std::runtime_error("Usage: native_fixture INPUT OUTPUT TRUSTED_COMMON_QUANTIZER_PTX"); - std::ifstream in(argv[1],std::ios::binary);uint32_t h[4];in.read(reinterpret_cast(h),sizeof h); - if(!in||h[0]!=0x31464b51||h[1]>9||h[2]<1||h[2]>10240||h[3]<32||h[3]>6144||h[3]%32)throw std::runtime_error("bounded synthetic geometry"); - const auto mode=h[1],m=h[2],n=h[3]; - static const unsigned be[]={32,256,256,256,256,32,32,256,256,64}; - static const unsigned bb[]={34,144,98,110,82,18,18,136,136,18}; - if(n%be[mode])throw std::runtime_error("format block geometry"); - size_t wb=size_t(m)*(n/be[mode])*bb[mode],qb=size_t(n/32)*36; - std::vectorw(wb),q(qb),fresh(qb),candidate(qb);std::vectorx(n),y(m); - in.read(reinterpret_cast(w.data()),wb);in.read(reinterpret_cast(x.data()),n*4);if(!in||in.peek()!=EOF)throw std::runtime_error("fixture length"); - // Invalid activation is tested in Rust/candidate admission; never feed it into - // the original unchecked native float-to-integer quantizer. - for(float v:x)if(!std::isfinite(v))throw std::runtime_error("native fixture requires finite input"); - ck(cudaSetDevice(0));cudaStream_t stream;ck(cudaStreamCreate(&stream));void *dw,*dx,*dq,*df,*dcq,*dy,*ds; - ck(cudaMalloc(&dw,wb));ck(cudaMalloc(&dx,n*4));ck(cudaMalloc(&dq,qb));ck(cudaMalloc(&df,qb));ck(cudaMalloc(&dcq,qb));ck(cudaMalloc(&dy,m*4));ck(cudaMalloc(&ds,4)); - ck(cudaMemcpy(dw,w.data(),wb,cudaMemcpyHostToDevice));ck(cudaMemcpy(dx,x.data(),n*4,cudaMemcpyHostToDevice)); - strata::kernels::native_quantize_q8_1(static_cast(dx),dq,n,1,stream);ck(cudaStreamSynchronize(stream));ck(cudaMemcpy(q.data(),dq,qb,cudaMemcpyDeviceToHost)); - // Composition independently quantizes a second fresh native scratch allocation. - strata::kernels::native_quantize_q8_1(static_cast(dx),df,n,1,stream); - strata::kernels::iq_set_old_kernels(true); // exact original row_dot, not grouped expert combine - switch(mode){ - case 0:strata::kernels::native_q8_0_f32(dw,static_cast(dx),df,static_cast(dy),n,m,1,stream);break; - case 1:strata::kernels::native_q4_k_f32(dw,static_cast(dx),df,static_cast(dy),n,m,1,stream);break; - case 5:strata::kernels::native_iq4_nl_f32(dw,static_cast(dx),df,static_cast(dy),n,m,1,stream);break; - case 7:strata::kernels::native_iq4_xs_f32(dw,static_cast(dx),df,static_cast(dy),n,m,1,stream);break; - default:{static const int tag[]={8,12,18,21,22,20,20,23,23,42}; - strata::kernels::iq_mmvq(tag[mode],dw,df,static_cast(dy),n,m,1,stream);break;} - }ck(cudaStreamSynchronize(stream)); - ck(cudaMemcpy(fresh.data(),df,qb,cudaMemcpyDeviceToHost));ck(cudaMemcpy(y.data(),dy,m*4,cudaMemcpyDeviceToHost));if(q!=fresh)throw std::runtime_error("fresh native quantization disagrees"); - std::ifstream pt(argv[3],std::ios::binary);std::string ptx((std::istreambuf_iterator(pt)),{});if(ptx.empty()||ptx.size()>262144||ptx.find(char(0))!=std::string::npos)throw std::runtime_error("bounded trusted test asset");for(unsigned char c:ptx)if(c>127)throw std::runtime_error("trusted PTX must be ASCII");ptx.push_back(0); - void* lib=dlopen("libcuda.so.1",RTLD_NOW|RTLD_LOCAL);if(!lib)throw std::runtime_error("installed Driver missing"); - auto load=sym(lib,"cuModuleLoadData");auto get=sym(lib,"cuModuleGetFunction"); - auto launch=sym(lib,"cuLaunchKernel");auto unload=sym(lib,"cuModuleUnload"); - CUmodule mod;CUfunction f;dc(load(&mod,ptx.data()));dc(get(&f,mod,"leleka_quantize_q8_1"));ck(cudaMemset(ds,0,4)); - CUdeviceptr px=reinterpret_cast(dx),pq=reinterpret_cast(dcq),ps=reinterpret_cast(ds);uint32_t cols=n;void*args[]={&px,&pq,&ps,&cols}; - dc(launch(f,(n+255)/256,1,1,256,1,1,0,reinterpret_cast(stream),args,nullptr));ck(cudaStreamSynchronize(stream)); - uint32_t status;ck(cudaMemcpy(&status,ds,4,cudaMemcpyDeviceToHost));ck(cudaMemcpy(candidate.data(),dcq,qb,cudaMemcpyDeviceToHost));dc(unload(mod));dlclose(lib); - std::ofstream out(argv[2],std::ios::binary);uint32_t oh[]={0x31464f51,mode,m,n,status};out.write(reinterpret_cast(oh),sizeof oh);out.write(reinterpret_cast(q.data()),qb);out.write(reinterpret_cast(candidate.data()),qb);out.write(reinterpret_cast(y.data()),m*4);if(!out)throw std::runtime_error("output write"); - for(void*p:{dw,dx,dq,df,dcq,dy,ds})ck(cudaFree(p));ck(cudaStreamDestroy(stream));ck(cudaDeviceReset()); - std::cout<<"NATIVE_ORACLE rows="< -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -static void ck(cudaError_t e){if(e!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(e));} -static void dc(CUresult e){if(e!=CUDA_SUCCESS)throw std::runtime_error("Driver test fixture status "+std::to_string(e));} -template static T sym(void* lib,const char* name){void* p=dlsym(lib,name);if(!p)throw std::runtime_error(name);return reinterpret_cast(p);} -int main(int argc,char**argv) try { - if(argc!=4)throw std::runtime_error("Usage: native_fixture INPUT OUTPUT TRUSTED_Q5_PTX"); - std::ifstream in(argv[1],std::ios::binary);uint32_t h[3];in.read(reinterpret_cast(h),sizeof h); - if(!in||h[0]!=0x35314b51||h[1]<1||h[1]>640||h[2]<256||h[2]>6144||h[2]%256)throw std::runtime_error("bounded synthetic geometry"); - const auto m=h[1],n=h[2];size_t wb=size_t(m)*(n/256)*176,qb=size_t(n/32)*36; - std::vectorw(wb),q(qb),fresh(qb),candidate(qb);std::vectorx(n),y(m); - in.read(reinterpret_cast(w.data()),wb);in.read(reinterpret_cast(x.data()),n*4);if(!in||in.peek()!=EOF)throw std::runtime_error("fixture length"); - // Invalid activation is tested in Rust/candidate admission; never feed it into - // the original unchecked native float-to-integer quantizer. - for(float v:x)if(!std::isfinite(v))throw std::runtime_error("native fixture requires finite input"); - ck(cudaSetDevice(0));cudaStream_t stream;ck(cudaStreamCreate(&stream));void *dw,*dx,*dq,*df,*dcq,*dy,*ds; - ck(cudaMalloc(&dw,wb));ck(cudaMalloc(&dx,n*4));ck(cudaMalloc(&dq,qb));ck(cudaMalloc(&df,qb));ck(cudaMalloc(&dcq,qb));ck(cudaMalloc(&dy,m*4));ck(cudaMalloc(&ds,4)); - ck(cudaMemcpy(dw,w.data(),wb,cudaMemcpyHostToDevice));ck(cudaMemcpy(dx,x.data(),n*4,cudaMemcpyHostToDevice)); - strata::kernels::native_quantize_q8_1(static_cast(dx),dq,n,1,stream);ck(cudaStreamSynchronize(stream));ck(cudaMemcpy(q.data(),dq,qb,cudaMemcpyDeviceToHost)); - // Composition independently quantizes a second fresh native scratch allocation. - strata::kernels::native_q5_k_f32(dw,static_cast(dx),df,static_cast(dy),n,m,1,stream);ck(cudaStreamSynchronize(stream)); - ck(cudaMemcpy(fresh.data(),df,qb,cudaMemcpyDeviceToHost));ck(cudaMemcpy(y.data(),dy,m*4,cudaMemcpyDeviceToHost));if(q!=fresh)throw std::runtime_error("fresh native quantization disagrees"); - std::ifstream pt(argv[3],std::ios::binary);std::string ptx((std::istreambuf_iterator(pt)),{});if(ptx.empty()||ptx.size()>262144)throw std::runtime_error("bounded trusted test asset");ptx.push_back(0); - void* lib=dlopen("libcuda.so.1",RTLD_NOW|RTLD_LOCAL);if(!lib)throw std::runtime_error("installed Driver missing"); - auto load=sym(lib,"cuModuleLoadData");auto get=sym(lib,"cuModuleGetFunction"); - auto launch=sym(lib,"cuLaunchKernel");auto unload=sym(lib,"cuModuleUnload"); - CUmodule mod;CUfunction f;dc(load(&mod,ptx.data()));dc(get(&f,mod,"leleka_quantize_q8_1"));ck(cudaMemset(ds,0,4)); - CUdeviceptr px=reinterpret_cast(dx),pq=reinterpret_cast(dcq),ps=reinterpret_cast(ds);uint32_t cols=n;void*args[]={&px,&pq,&ps,&cols}; - dc(launch(f,(n+255)/256,1,1,256,1,1,0,reinterpret_cast(stream),args,nullptr));ck(cudaStreamSynchronize(stream)); - uint32_t status;ck(cudaMemcpy(&status,ds,4,cudaMemcpyDeviceToHost));ck(cudaMemcpy(candidate.data(),dcq,qb,cudaMemcpyDeviceToHost));dc(unload(mod));dlclose(lib); - std::ofstream out(argv[2],std::ios::binary);uint32_t oh[]={0x35314f51,m,n,status};out.write(reinterpret_cast(oh),sizeof oh);out.write(reinterpret_cast(q.data()),qb);out.write(reinterpret_cast(candidate.data()),qb);out.write(reinterpret_cast(y.data()),m*4);if(!out)throw std::runtime_error("output write"); - for(void*p:{dw,dx,dq,df,dcq,dy,ds})ck(cudaFree(p));ck(cudaStreamDestroy(stream));ck(cudaDeviceReset()); - std::cout<<"NATIVE_ORACLE rows="< -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -static void ck(cudaError_t e){if(e!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(e));} -static void dc(CUresult e){if(e!=CUDA_SUCCESS)throw std::runtime_error("Driver test fixture status "+std::to_string(e));} -template static T sym(void* lib,const char* name){void* p=dlsym(lib,name);if(!p)throw std::runtime_error(name);return reinterpret_cast(p);} -int main(int argc,char**argv) try { - if(argc!=4)throw std::runtime_error("Usage: native_fixture INPUT OUTPUT TRUSTED_Q6_PTX"); - std::ifstream in(argv[1],std::ios::binary);uint32_t h[3];in.read(reinterpret_cast(h),sizeof h); - if(!in||h[0]!=0x36314b51||h[1]<1||h[1]>10240||h[2]<256||h[2]>6144||h[2]%256)throw std::runtime_error("bounded synthetic geometry"); - const auto m=h[1],n=h[2];size_t wb=size_t(m)*(n/256)*210,qb=size_t(n/32)*36; - std::vectorw(wb),q(qb),fresh(qb),candidate(qb);std::vectorx(n),y(m); - in.read(reinterpret_cast(w.data()),wb);in.read(reinterpret_cast(x.data()),n*4);if(!in||in.peek()!=EOF)throw std::runtime_error("fixture length"); - // Invalid activation is tested in Rust/candidate admission; never feed it into - // the original unchecked native float-to-integer quantizer. - for(float v:x)if(!std::isfinite(v))throw std::runtime_error("native fixture requires finite input"); - ck(cudaSetDevice(0));cudaStream_t stream;ck(cudaStreamCreate(&stream));void *dw,*dx,*dq,*df,*dcq,*dy,*ds; - ck(cudaMalloc(&dw,wb));ck(cudaMalloc(&dx,n*4));ck(cudaMalloc(&dq,qb));ck(cudaMalloc(&df,qb));ck(cudaMalloc(&dcq,qb));ck(cudaMalloc(&dy,m*4));ck(cudaMalloc(&ds,4)); - ck(cudaMemcpy(dw,w.data(),wb,cudaMemcpyHostToDevice));ck(cudaMemcpy(dx,x.data(),n*4,cudaMemcpyHostToDevice)); - strata::kernels::native_quantize_q8_1(static_cast(dx),dq,n,1,stream);ck(cudaStreamSynchronize(stream));ck(cudaMemcpy(q.data(),dq,qb,cudaMemcpyDeviceToHost)); - // Composition independently quantizes a second fresh native scratch allocation. - strata::kernels::native_q6_k_f32(dw,static_cast(dx),df,static_cast(dy),n,m,1,stream);ck(cudaStreamSynchronize(stream)); - ck(cudaMemcpy(fresh.data(),df,qb,cudaMemcpyDeviceToHost));ck(cudaMemcpy(y.data(),dy,m*4,cudaMemcpyDeviceToHost));if(q!=fresh)throw std::runtime_error("fresh native quantization disagrees"); - std::ifstream pt(argv[3],std::ios::binary);std::string ptx((std::istreambuf_iterator(pt)),{});if(ptx.empty()||ptx.size()>262144)throw std::runtime_error("bounded trusted test asset");ptx.push_back(0); - void* lib=dlopen("libcuda.so.1",RTLD_NOW|RTLD_LOCAL);if(!lib)throw std::runtime_error("installed Driver missing"); - auto load=sym(lib,"cuModuleLoadData");auto get=sym(lib,"cuModuleGetFunction"); - auto launch=sym(lib,"cuLaunchKernel");auto unload=sym(lib,"cuModuleUnload"); - CUmodule mod;CUfunction f;dc(load(&mod,ptx.data()));dc(get(&f,mod,"leleka_quantize_q8_1"));ck(cudaMemset(ds,0,4)); - CUdeviceptr px=reinterpret_cast(dx),pq=reinterpret_cast(dcq),ps=reinterpret_cast(ds);uint32_t cols=n;void*args[]={&px,&pq,&ps,&cols}; - dc(launch(f,(n+255)/256,1,1,256,1,1,0,reinterpret_cast(stream),args,nullptr));ck(cudaStreamSynchronize(stream)); - uint32_t status;ck(cudaMemcpy(&status,ds,4,cudaMemcpyDeviceToHost));ck(cudaMemcpy(candidate.data(),dcq,qb,cudaMemcpyDeviceToHost));dc(unload(mod));dlclose(lib); - std::ofstream out(argv[2],std::ios::binary);uint32_t oh[]={0x36314f51,m,n,status};out.write(reinterpret_cast(oh),sizeof oh);out.write(reinterpret_cast(q.data()),qb);out.write(reinterpret_cast(candidate.data()),qb);out.write(reinterpret_cast(y.data()),m*4);if(!out)throw std::runtime_error("output write"); - for(void*p:{dw,dx,dq,df,dcq,dy,ds})ck(cudaFree(p));ck(cudaStreamDestroy(stream));ck(cudaDeviceReset()); - std::cout<<"NATIVE_ORACLE rows="< -#include -#include -#include -int main(){volatile float base=10000000.0f;const float x=powf(base,-2.0f/64);uint32_t word;std::memcpy(&word,&x,4);std::printf("original_runtime_host_theta=%08x value=%.9g\n",word,x);} diff --git a/scripts/cuda-qsa-oracle/main.cu b/scripts/cuda-qsa-oracle/main.cu deleted file mode 100644 index b7c3005c..00000000 --- a/scripts/cuda-qsa-oracle/main.cu +++ /dev/null @@ -1,173 +0,0 @@ -// Independent test caller: candidate PTX is never an expected-value oracle. -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -extern "C" void oracle_norm(const float*,const float*,float*,int,int,cudaStream_t); -extern "C" void oracle_gate(const float*,const float*,float*,cudaStream_t); -extern "C" void oracle_rope(const float*,float*,int,int,const int*,cudaStream_t); -extern "C" void oracle_index(const float*,const float*,const int*,float*,float*,float*,int*,cudaStream_t); -extern "C" void oracle_scores(const float*,const float*,const float*,const int*,int64_t,float*,cudaStream_t); -extern "C" void oracle_topk(const float*,const int*,int64_t,int*,cudaStream_t); -extern "C" void oracle_pack(const float*,const float*,uint16_t*,uint16_t*,const int*,cudaStream_t); -extern "C" void oracle_attention(const float*,const uint16_t*,const uint16_t*,const int*,float*,cudaStream_t); -static std::string output; -static std::string retained; -static uint64_t words=0; -static unsigned cases=0; -static void rt(cudaError_t e){if(e!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(e));} -static void drv(CUresult e){if(e!=CUDA_SUCCESS){const char*s=nullptr;cuGetErrorString(e,&s);throw std::runtime_error(s?s:"driver failure");}} -template struct Buffer { - T*p=nullptr;size_t n; - explicit Buffer(size_t count):n(count){rt(cudaMalloc(&p,n*sizeof(T)));rt(cudaMemset(p,0,n*sizeof(T)));} - explicit Buffer(const std::vector&v):Buffer(v.size()){set(v);} - ~Buffer(){if(p)cudaFree(p);} - void set(const std::vector&v){if(v.size()!=n)throw std::runtime_error("fixture extent");rt(cudaMemcpy(p,v.data(),n*sizeof(T),cudaMemcpyHostToDevice));} - std::vector get(){std::vectorv(n);rt(cudaMemcpy(v.data(),p,n*sizeof(T),cudaMemcpyDeviceToHost));return v;} - Buffer(const Buffer&)=delete; -}; -static void raw(const std::string&name,const void*p,size_t n){std::ofstream f(output+"/"+name,std::ios::binary);f.write(static_cast(p),n);if(!f)throw std::runtime_error("proof write");} -template static void exact(const std::string&name,const std::vector&want,const std::vector&got){ - raw(name+".want",want.data(),want.size()*sizeof(T));raw(name+".got",got.data(),got.size()*sizeof(T)); - if(want.size()!=got.size())throw std::runtime_error(name+": extent"); - for(size_t i=0;i values(size_t n,int salt){std::vectorv(n);for(size_t i=0;i norm_weights(size_t n){std::vectorv(n);for(size_t i=0;i step(unsigned p){return {int(p),int(p+1),int((p+1)/4),int(std::min(p+1,2051u))};} -static cudaStream_t stream; -static CUmodule modules[4]; -static void launch(int m,const char*name,unsigned gx,unsigned gy,unsigned bx,unsigned shared,std::vectorargs){ - CUfunction f;drv(cuModuleGetFunction(&f,modules[m],name)); - drv(cuLaunchKernel(f,gx,gy,1,bx,1,1,shared,reinterpret_cast(stream),args.data(),nullptr)); - rt(cudaStreamSynchronize(stream)); -} -static void norms(){for(int mode=0;mode<3;++mode){int c=mode==2?128:256,n=mode==0?24:mode==1?2:4; - Bufferx(values(c*n,mode+1)),g(norm_weights(c)),w(c*n),y(c*n); - oracle_norm(x.p,g.p,w.p,c,n,stream);rt(cudaStreamSynchronize(stream)); - const char*names[]={"leleka_qsa_norm_q","leleka_qsa_norm_k","leleka_qsa_norm_index_q"}; - launch(0,names[mode],n,1,256,0,{&x.p,&g.p,&y.p});exact(std::string("norm_")+std::to_string(mode),w.get(),y.get()); -}} -static void ropes(bool repair=false){for(int mode=0;mode<3;++mode){int c=mode==2?128:256,n=mode==0?24:mode==1?2:4; - const char*names[]={"leleka_qsa_rope_q","leleka_qsa_rope_k","leleka_qsa_rope_index_q"}; - for(unsigned p:{0u,1u,4u,7u,262143u}){ - if(repair&&mode==0&&p==0)continue; // Exact Q position0 proof is already retained. - auto input=values(c*n,mode+4);Bufferx(input),w(c*n),y(c*n);Bufferpositions(std::vector(n,int(p))); - oracle_rope(x.p,w.p,c,n,positions.p,stream);rt(cudaStreamSynchronize(stream)); - launch(0,names[mode],1,n,128,0,{&x.p,&p,&y.p});auto got=y.get(); - exact("rope_"+std::to_string(mode)+"_"+std::to_string(p),w.get(),got); - for(int row=0;rowx(full),q(6144),g(6144); - launch(0,"leleka_qsa_split_q_gate",24,1,256,0,{&x.p,&q.p,&g.p}); - std::vectorwq(6144),wg(6144);for(int h=0;h<24;++h)for(int d=0;d<256;++d){wq[h*256+d]=full[h*512+d];wg[h*256+d]=full[h*512+256+d];} - exact("split_q",wq,q.get());exact("split_gate",wg,g.get()); - const uint32_t bits[]={0,0x80000000u,0x3f800000u,0x3f801000u,0x3f803000u,0xbf801000u,0x33800000u,0x33000000u,0x477fe000u,0xc77fe000u}; - const uint16_t half[]={0,0x8000,0x3c00,0x3c00,0x3c02,0xbc00,1,0,0x7bff,0xfbff}; - std::vectorkv(512);std::vectorwant(512);for(int i=0;i<512;++i){std::memcpy(&kv[i],&bits[i%10],4);want[i]=half[i%10];} - Bufferk(kv),v(kv);Bufferkh(512),vh(512),wk(512),wv(512);Bufferst(step(0)); - oracle_pack(k.p,v.p,wk.p,wv.p,st.p,stream);rt(cudaStreamSynchronize(stream)); - launch(0,"leleka_qsa_pack_kv",2,1,256,0,{&k.p,&v.p,&kh.p,&vh.p}); - exact("pack_original_k",wk.get(),kh.get());exact("pack_literal_k",want,kh.get());exact("pack_original_v",wv.get(),vh.get()); -} -static void indexer(){ - Bufferg(norm_weights(128)),tail(384),dead(128),pool(384);Bufferbpos(1); - std::vectorprior(512,0.0f); - for(unsigned p=0;p<8;++p){auto input=values(128,p+9);Bufferx(input),old(prior),next(640);Bufferposition(std::vector{int(p)}); - oracle_index(x.p,g.p,position.p,tail.p,dead.p,pool.p,bpos.p,stream);rt(cudaStreamSynchronize(stream)); - launch(0,"leleka_qsa_index_append",1,1,256,0,{&x.p,&g.p,&old.p,&next.p,&p}); - auto got=next.get(),wt=tail.get(),wd=dead.get(),wp=pool.get();std::vectorwant=wt;want.insert(want.end(),wd.begin(),wd.end()); - size_t row=p==0?0:p%4==3?p/4+0:(p+1)/4; - want.insert(want.end(),wp.begin()+row*128,wp.begin()+(row+1)*128); - exact("index_append_"+std::to_string(p),want,got);prior.assign(got.begin(),got.begin()+512); - }} -static std::vector retained_words(const std::string&name){ - std::vectorv(640);std::ifstream f(retained+"/"+name,std::ios::binary); - f.read(reinterpret_cast(v.data()),2560);if(!f||f.peek()!=std::ifstream::traits_type::eof())throw std::runtime_error("retained fixture extent");return v; -} -static void repaired_indexer(){ - // Restore the independently proven prior at6; no operator0..6 is relaunched. - auto previous=retained_words("index_append_6.want"),first_block=retained_words("index_append_3.want"); - std::vectorold(previous.begin(),previous.begin()+512),tail_words(old.begin(),old.begin()+384),dead_words(old.begin()+384,old.end()),pool_words(384,0); - std::copy(first_block.begin()+512,first_block.end(),pool_words.begin());std::copy(dead_words.begin(),dead_words.end(),pool_words.begin()+128); - Bufferg(norm_weights(128)),tail(tail_words),dead(dead_words),pool(pool_words),x(values(128,16)),prior(old),next(640); - Bufferbpos(1),position(std::vector{7});unsigned p=7; - oracle_index(x.p,g.p,position.p,tail.p,dead.p,pool.p,bpos.p,stream);rt(cudaStreamSynchronize(stream)); - launch(0,"leleka_qsa_index_append",1,1,256,0,{&x.p,&g.p,&prior.p,&next.p,&p}); - auto want=tail.get(),wd=dead.get(),wp=pool.get();want.insert(want.end(),wd.begin(),wd.end());want.insert(want.end(),wp.begin()+128,wp.begin()+256); - exact("index_append_7_repaired",want,next.get()); -} -static std::vector cpu_ids(const std::vector&scores,unsigned n){ - std::vectorids(n);std::iota(ids.begin(),ids.end(),0); - std::stable_sort(ids.begin(),ids.end(),[&](int a,int b){float x=scores[a/4],y=scores[b/4];return x==y?ay;}); - ids.resize(std::min(n,2051u));std::sort(ids.begin(),ids.end());return ids; -} -static void selection(){for(unsigned n:{1u,4u,7u,2051u,2052u,2053u,4096u,262144u}){unsigned p=n-1;size_t blocks=n/4+1; - Bufferk(values(blocks*128,3)),dead(values(128,7)),q(values(512,19)),w(blocks),y(blocks);Bufferst(step(p)),wid(2051),id(2051); - oracle_scores(k.p,dead.p,q.p,st.p,blocks,w.p,stream);rt(cudaStreamSynchronize(stream)); - launch(1,"leleka_qsa_block_scores",256,1,256,0,{&k.p,&dead.p,&q.p,&y.p,&p});auto scores=y.get(); - exact("scores_"+std::to_string(n),w.get(),scores); - oracle_topk(w.p,st.p,blocks,wid.p,stream);rt(cudaStreamSynchronize(stream)); - launch(1,"leleka_qsa_block_topk",1,1,256,0,{&y.p,&id.p,&p});auto got=id.get(),want=wid.get();got.resize(std::min(n,2051u));want.resize(got.size()); - exact("topk_source_"+std::to_string(n),want,got);exact("topk_independent_"+std::to_string(n),cpu_ids(scores,n),got); - // Literal all-equal block scores force lowest-ID ties even at the truncation boundary. - std::vectorties(blocks,0.0f);y.set(ties);launch(1,"leleka_qsa_block_topk",1,1,256,0,{&y.p,&id.p,&p});got=id.get();got.resize(std::min(n,2051u)); - std::vectorliteral(got.size());std::iota(literal.begin(),literal.end(),0);exact("topk_literal_tie_"+std::to_string(n),literal,got); - }} -static double half_double(uint16_t x){return double(__half2float(__ushort_as_half(x)));} -static void attention(){for(unsigned width:{1u,7u,257u,2051u}){ - auto query=values(6144,11);std::vectork(size_t(width)*512),v(k.size()); - const uint16_t kb[]={0x0000,0x3400,0xb800,0x3a00,0xbc00,0x3800}; - const uint16_t vb[]={0x3c00,0xbc00,0x4000,0xb800,0x3400,0x4200}; - for(size_t i=0;iq(query),w(6144),y(6144);Bufferdk(k),dv(v);Bufferst(step(width-1)); - oracle_attention(q.p,dk.p,dv.p,st.p,w.p,stream);rt(cudaStreamSynchronize(stream)); - launch(2,"leleka_qsa_attend",24,1,256,(2051+32)*4,{&q.p,&dk.p,&dv.p,&y.p,&width});auto got=y.get();exact("attention_source_"+std::to_string(width),w.get(),got); - std::vectorreference(6144),scores(width); - for(int h=0;h<24;++h){int kv=h/12; - for(unsigned j=0;j1e-5)throw std::runtime_error("attention double tolerance");++cases; - }} -static void gate(){ - const float literals[]={-1000,-100,-1,-0.0f,0.0f,1,100,1000};auto a=values(6144,21);std::vectorgate(6144),full(12288,777); - for(int h=0;h<24;++h)for(int d=0;d<256;++d){float x=literals[(h+d)%8];gate[h*256+d]=x;full[h*512+256+d]=x;} - Bufferx(a),g(gate),f(full),w(6144),y(6144); - oracle_gate(x.p,f.p,w.p,stream);rt(cudaStreamSynchronize(stream));launch(3,"leleka_qsa_gate_f32",24,1,256,0,{&x.p,&g.p,&y.p});exact("gate_native_f32_saturation",w.get(),y.get()); -} -static void invalid(){ - auto a=values(6144,2);a[0]=std::numeric_limits::quiet_NaN();Bufferx(a),g(norm_weights(256)),y(6144); - launch(0,"leleka_qsa_norm_q",24,1,256,0,{&x.p,&g.p,&y.p});auto out=y.get();for(int d=0;d<256;++d)if(!std::isnan(out[d]))throw std::runtime_error("norm NaN hidden");++cases;std::puts("PASS invalid_norm_row_nan"); - auto gate=values(6144,3);gate[19]=std::numeric_limits::infinity();Buffergg(gate); - launch(3,"leleka_qsa_gate_f32",24,1,256,0,{&x.p,&gg.p,&y.p});out=y.get();if(!std::isnan(out[0])||!std::isnan(out[19]))throw std::runtime_error("gate invalid hidden");++cases;std::puts("PASS invalid_gate_nan_inf"); -} -int main(int argc,char**argv){try{ - if(argc<3||argc>5)throw std::runtime_error("Usage: qsa_oracle ASSET_DIRECTORY PRIVATE_OUTPUT_DIRECTORY [group [RETAINED_PROOF_DIRECTORY]]");output=argv[2];std::string group=argc>=4?argv[3]:"all"; - if(group=="repair"){if(argc!=5)throw std::runtime_error("repair requires retained prior-proof directory");retained=argv[4];} - rt(cudaSetDevice(0));rt(cudaFree(nullptr));drv(cuInit(0));rt(cudaStreamCreate(&stream)); - const char*asset[]={"qwen_qsa_native.ptx","qwen_qsa_select.ptx","qwen_qsa_attention.ptx","qwen_qsa_attention_native.ptx"}; - for(int i=0;i<4;++i)drv(cuModuleLoad(&modules[i],(std::string(argv[1])+"/"+asset[i]).c_str())); - cudaDeviceProp prop;rt(cudaGetDeviceProperties(&prop,0));int driver=0;rt(cudaDriverGetVersion(&driver));std::printf("DEVICE %s cc=%d.%d driver=%d\n",prop.name,prop.major,prop.minor,driver); - auto enabled=[&](const char*s){return group=="all"||group==s;}; - if(enabled("norm"))norms();if(enabled("rope"))ropes();if(enabled("pack"))split_pack();if(enabled("index"))indexer();if(enabled("select"))selection();if(enabled("attention"))attention();if(enabled("gate"))gate();if(enabled("invalid"))invalid(); - if(group=="repair"){ropes(true);repaired_indexer();} - for(auto m:modules)drv(cuModuleUnload(m));rt(cudaStreamDestroy(stream));std::printf("RESULT PASS cases=%u exact_words=%llu\n",cases,(unsigned long long)words);return 0; - }catch(const std::exception&e){std::fprintf(stderr,"RESULT FAIL %s\n",e.what());return 1;}} diff --git a/scripts/cuda-qsa-oracle/oracle_attention.cu b/scripts/cuda-qsa-oracle/oracle_attention.cu deleted file mode 100644 index bd0a4e5c..00000000 --- a/scripts/cuda-qsa-oracle/oracle_attention.cu +++ /dev/null @@ -1,10 +0,0 @@ -#include "../../engine/strata/src/kernels/cuda/qsa.cu" -extern "C" void oracle_pack(const float*k,const float*v,uint16_t*kp,uint16_t*vp,const int*step,cudaStream_t s) { - // One-page geometry makes original cache append a contiguous two-head pack. - int*table; cudaMalloc(&table,4); const int zero=0; cudaMemcpy(table,&zero,4,cudaMemcpyHostToDevice); - strata::kernels::kv_append_kernel<<<2,256,0,s>>>(kp,vp,table,step,k,v,2,256,1,{}); - cudaStreamSynchronize(s); cudaFree(table); -} -extern "C" void oracle_attention(const float*q,const uint16_t*k,const uint16_t*v,const int*step,float*y,cudaStream_t s) { - strata::kernels::qsa_attend_kernel<<<24,256,(2051+32)*4,s>>>(q,k,v,step,24,2,256,y,nullptr); -} diff --git a/scripts/cuda-qsa-oracle/oracle_index.cu b/scripts/cuda-qsa-oracle/oracle_index.cu deleted file mode 100644 index 37b3fbbd..00000000 --- a/scripts/cuda-qsa-oracle/oracle_index.cu +++ /dev/null @@ -1,5 +0,0 @@ -#include "../../engine/strata/src/kernels/cuda/native_qsa_indexer.cu" -extern "C" void oracle_index(const float*x,const float*g,const int*p,float*tail,float*dead,float*pool,int*bpos,cudaStream_t s) { - strata::kernels::QsaIndexerBuffers b{tail,dead,pool,bpos}; - strata::kernels::native_qsa_indexer_append(x,p,0,g,1e-6f,b,strata::kernels::qsa_real_shapes(),8,strata::kernels::RopeScaling{},s); -} diff --git a/scripts/cuda-qsa-oracle/oracle_native.cu b/scripts/cuda-qsa-oracle/oracle_native.cu deleted file mode 100644 index 9f71b910..00000000 --- a/scripts/cuda-qsa-oracle/oracle_native.cu +++ /dev/null @@ -1,8 +0,0 @@ -// Test only: the original implementation is an independent translation unit. -#include "../../engine/strata/src/kernels/cuda/native_qsa.cu" -extern "C" void oracle_norm(const float*x,const float*g,float*y,int c,int n,cudaStream_t s) { - strata::kernels::native_qsa_rms_norm_weighted(x,g,y,c,n,1e-6f,s); -} -extern "C" void oracle_gate(const float*x,const float*full,float*y,cudaStream_t s) { - strata::kernels::native_qsa_gate_apply(x,full,y,24,256,s); -} diff --git a/scripts/cuda-qsa-oracle/oracle_rope.cu b/scripts/cuda-qsa-oracle/oracle_rope.cu deleted file mode 100644 index 44ea53d7..00000000 --- a/scripts/cuda-qsa-oracle/oracle_rope.cu +++ /dev/null @@ -1,4 +0,0 @@ -#include "../../engine/strata/src/kernels/cuda/native_rope.cu" -extern "C" void oracle_rope(const float*x,float*y,int c,int n,const int*p,cudaStream_t s) { - strata::kernels::native_rope_apply(x,y,n,c,64,strata::kernels::RopeScaling{},p,s); -} diff --git a/scripts/cuda-qsa-oracle/oracle_select.cu b/scripts/cuda-qsa-oracle/oracle_select.cu deleted file mode 100644 index 3afea2b0..00000000 --- a/scripts/cuda-qsa-oracle/oracle_select.cu +++ /dev/null @@ -1,8 +0,0 @@ -#include "../../engine/strata/src/kernels/cuda/qsa_select.cu" -extern "C" void oracle_scores(const float*k,const float*d,const float*q,const int*step,int64_t blocks,float*y,cudaStream_t s) { - // Select exactly the original deterministic multi-query warp path, nq=1. - strata::kernels::block_scores_multi_kernel<<<256,256,0,s>>>(k,d,q,step,1,blocks,y); -} -extern "C" void oracle_topk(const float*x,const int*step,int64_t blocks,int*y,cudaStream_t s) { - strata::kernels::block_topk_kernel<<<1,256,0,s>>>(x,step,blocks,2051,y); -} diff --git a/scripts/cuda-qsa-oracle/source.sha256 b/scripts/cuda-qsa-oracle/source.sha256 deleted file mode 100644 index f42cc172..00000000 --- a/scripts/cuda-qsa-oracle/source.sha256 +++ /dev/null @@ -1,65 +0,0 @@ -101eec0eba8c5afff046d5040c6d5044f7aaf82ceae5c19832925e070a1c8e01 crates/engine-qwen35-cuda/src/model_binding/weight_binding/qsa.rs -ed281c74a39e07f58d23a22be195fffce4a8840840dc767a0bef2ff0b7683b6c crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs -cc996a7f1a0f56adbbcd6d514fe6ba4a4d06c3ce5c244f24b4acc11bf0a0214c crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs -78ab8d9240963876e2a1578f845894cd38af148a37242a2dfc9a8668afeb1bc6 crates/cuda-driver/assets/qwen_qsa_attention.cu -91219cfbc1a77c4bb66661060ac939a50dc4c4d7d4db8d50bc59fbcd167562b2 crates/cuda-driver/assets/qwen_qsa_attention.ptx -6b90b748df610f26a40b82ebbacdebd15d35252c3feb76ea1aaad0ed519db22a crates/cuda-driver/assets/qwen_qsa_attention_native.cu -7772e4e75d78a9910144ca108551800fd4296955781540afb65f53d612d7e1f3 crates/cuda-driver/assets/qwen_qsa_attention_native.ptx -35e3672926fe27fed13f9e560163d7a4cf89e827c6256a3ede71f487c7f85ab5 crates/cuda-driver/assets/qwen_qsa_native.cu -d60489fb70ce4370047bf54fae8dd46dfb53bb73b1618c58942932a789d064c5 crates/cuda-driver/assets/qwen_qsa_native.ptx -03df9d4d42cf742e4e06068d30bfc30bf7303fee188fad456b53a0788c4f1a7f crates/cuda-driver/assets/qwen_qsa_select.cu -e094e10f84cca612ca28596aa394ee999e33fe7bc84b359bfab6da0730d4a519 crates/cuda-driver/assets/qwen_qsa_select.ptx -a9f47aa583e656757e4b81830143e05cac1a8266fb22cee085663732d5c6948a engine/strata/src/kernels/cuda/native_qsa.cu -21cc2bc7c84254811fc0ff66c8b995d2c3a5abf91260068f7ae6767d5e217ab2 engine/strata/src/kernels/cuda/native_rope.cu -bc46a3a289a4decc400fe1db05b54879dac4c3cd1a91634c18a08dbd2f71360a engine/strata/src/kernels/cuda/native_qsa_indexer.cu -b579d6f9e3829407b9f31153790b11bba3186ec687a27d81d0c32e65ce429894 engine/strata/src/kernels/cuda/qsa_select.cu -dc7ff0992355ec744bcdcb919f50cf8925a340438e0c5209ae917177d938295a engine/strata/src/kernels/cuda/qsa.cu -5e7c6b5fed22f8681e96203d42ca9c9368b9075c8568e5144c5811d5c9d997a3 engine/strata/src/kernels/qsa_parity.cpp -813b51f17c5c264d642f4d77b3d6e5f35e7ea7310ba87b18b3a2a5bc9185198f engine/strata/include/strata/kernels/bf16_bits.hpp -402538e5405d93e6617997ffa45561e259e01bf3d7b00ffca5379721ff4a71f3 engine/strata/include/strata/kernels/bf16_gemv.hpp -34e0a44c41392634451d4d676a0035623b205cf2952685aa1946b4df78dd5a65 engine/strata/include/strata/kernels/cvec.hpp -6b49ba8f050e6684caa57879f14657c5453078a3ccb8f963432ea3049a4178ca engine/strata/include/strata/kernels/dequant_bf16.hpp -d8f3aa8d610887451f177f05ada1135d52daf21b95a8c2c58686c07403c8013d engine/strata/include/strata/kernels/dequant_s2.hpp -05404993da1f077653a1dbf2dc54278b03821dfc3fe31ae1b963d30e94e95cf9 engine/strata/include/strata/kernels/dp4a.hpp -2f57555de85d267391036e2693f215cd3ec3b1b4af243654120781ca640a86df engine/strata/include/strata/kernels/elementwise.hpp -0f74e6dd832da427b681c9971265a0af1a91198694fdef3654d860b98863fc8c engine/strata/include/strata/kernels/f16_bits.hpp -595205dcf531d8fb758bcd7b2d3ac4e4158bd06f20160199e592824d530e2078 engine/strata/include/strata/kernels/fused_gdn.hpp -0506a16f95e4f0ab05dab62619d642598282677a126efa05303a8b278b712360 engine/strata/include/strata/kernels/fused_gr.hpp -f44626e3f52813b9be289aee72f708e9ad61aa9b3a0e43037ba5ff8b358fc638 engine/strata/include/strata/kernels/gdn.hpp -2a5bbba0ea74752dceba2e14bcf5e7c470dd69dd74e533a3e2e9aa76804ef74e engine/strata/include/strata/kernels/gr.hpp -2b8f5a08be7c7a501e8af7103d7d3ce412295c4467bbfd08b8dc0d02cea7c70d engine/strata/include/strata/kernels/iq_kernels.hpp -c7624d5567d464edd0e5e99951dca08f8a748545af2f0be4f18398a011c8ab89 engine/strata/include/strata/kernels/kv_q4.hpp -8917232c10900e85a6193012d2cc56138c7ab000c01d964bc9d296cf2b2e4bb6 engine/strata/include/strata/kernels/kv_q8.hpp -1ba39fb94fd3425cdaaa86b62e659567b8d09c8d190b8a1cfd832bc5f0ef0de6 engine/strata/include/strata/kernels/kv_stream.hpp -92d153fcedd6fcb747fee61fb0e01c3adb0c36e205154255b81e4337cb782402 engine/strata/include/strata/kernels/mrope.hpp -6cc7bb288fc263ee800f5b5329bcc8d139ddde7e31a022364850cf80b1e5f7ff engine/strata/include/strata/kernels/native_flash_attn.hpp -2b65e1b5b689c06d099bc061d746d606dcc5b974a7bffe0820ce01e7295d1971 engine/strata/include/strata/kernels/native_gdn.hpp -7533d8464b6ae8e2800e43ee3036d23f21181c2472c069d19bacf115beeafc69 engine/strata/include/strata/kernels/native_gdn_preprocess.hpp -520230cbf749a13c4f91687da31c0136fdcb2f14d4e4f956c38334d0e2cf742c engine/strata/include/strata/kernels/native_gr_norm.hpp -572867fecf55294f99251e679b934bb6ce63e2162f9c5c0e27bcec167a74d0f6 engine/strata/include/strata/kernels/native_gr_postops.hpp -283d882a96e1f22d97ee170bd0c8bca5cc226ab5f82fa1df133c8fd901efe487 engine/strata/include/strata/kernels/native_mmvq.hpp -b8400379c2f0deea4f440a2aeb343d45377f4a334bf4b1c8eb8aa933eaace51f engine/strata/include/strata/kernels/native_moe.hpp -eeeec9650c6e19402dcec9c4c807ff5a62f0b64b4a3ad86e6a286489ee7af091 engine/strata/include/strata/kernels/native_ple_postops.hpp -ef43d79914eb433458e2b212a9733e6a0e15be115aa156675d18a8d012c66387 engine/strata/include/strata/kernels/native_qsa.hpp -d040ccbef7943f16c7ce99d8070979b555a8c740950a6f53945b7199226d3fc3 engine/strata/include/strata/kernels/native_qsa_indexer.hpp -d57ba2509e97093ed2bfa3cbe73886407211a5d476a0b629ed925dd992369354 engine/strata/include/strata/kernels/native_qsa_score.hpp -550e8640263e0fbf2319e0d26426371b917eb34b6a24d3d672d502ff94717040 engine/strata/include/strata/kernels/native_rope.hpp -e5e0a529c11235080ec541cdc65a1ac1c0dba8eb994cf5373609fc8985311502 engine/strata/include/strata/kernels/native_router.hpp -b77415af3194a3181b7491bcbe22f4660b4f59d54d061edc486e6da4f10a9996 engine/strata/include/strata/kernels/ngram.hpp -d658e7186f1e81a8b183a583b5fa6bfaf228042cda4e88aa1c41ada260db6b12 engine/strata/include/strata/kernels/ple.hpp -87c02222284f842fcecb46a422b119af769c72c3914edc8da5b2ee782456dc74 engine/strata/include/strata/kernels/qsa.hpp -9450de49e491cdf59f315bbdd2abfbe7b0b761d4638c224339913626709e3485 engine/strata/include/strata/kernels/qsa_decode_attn.hpp -c49066bcb4e9d84ca7e374680c453e226cdc2efa2ec02262561a5f8f228bc35f engine/strata/include/strata/kernels/qsa_prompt_attn.hpp -eb3d61f08249db03c9d2212082c285de954c34f58d711e8cd8f6dce9d259e2a8 engine/strata/include/strata/kernels/qsa_select.hpp -baad6fe6c691f8f5aee2d6dbbb3513eead12c754b485ee41af4618d5035772f7 engine/strata/include/strata/kernels/quantize_act.hpp -bd9094c0f0f761971a6760fde2b84a5660c934ce9a654dc287c686acd284a65a engine/strata/include/strata/kernels/rope.hpp -05a8dcf57c9b12a23128f22e4bef01445c3a37991df5e1ffacd01d077c46595d engine/strata/include/strata/kernels/rope_scaling.hpp -cd0d8e91e702bfa2cfd681d4ccf4f6c4c62af2cd612d2d109e5369845ddf362d engine/strata/include/strata/kernels/router_top10.hpp -74802f312c20daa90b7fbacba4a3357c8e94c7ecdab75f402be507dd303a8193 engine/strata/include/strata/kernels/s2_expert_grouped.hpp -cc146b9c652f1ee0c89be65ce179ea4cb31d4b4d32366c07f06b45644bbb8eb0 engine/strata/include/strata/kernels/s2_gemv.hpp -5c2ccbdc5b3f3a66b9afef5bc799ae2a83bcb2103b258bb84e8d82aad06b4eb1 engine/strata/include/strata/kernels/s2_gemv_q8.hpp -369ab6cc010b49ac1d82bb680246e93b4c10f4f7081f56a325f6c7138ab1c3fb engine/strata/include/strata/kernels/s_gemv.hpp -89f0889563938cb12aa75744f6342e22de3f4d641c2e645ea5a8b609f062f841 engine/strata/include/strata/kernels/sampler.hpp -9f49d44286650219f488dea3fbe0474b009498e88921cc3ef806e87c372da8e2 engine/strata/include/strata/kernels/shared_expert.hpp -54e349fe4ab994f57a15ae8c15f81c3778652aa881ce6d25aa4136670bfa9ba7 engine/strata/include/strata/kernels/verify_kernels.hpp -eb3df4efe89642f069420e0f68ec526b33d4cc66f9a6b26de0583492b5758a77 engine/strata/include/strata/core/emulate.hpp diff --git a/scripts/cuda-qsa-oracle/theta_probe.cu b/scripts/cuda-qsa-oracle/theta_probe.cu deleted file mode 100644 index 43af35af..00000000 --- a/scripts/cuda-qsa-oracle/theta_probe.cu +++ /dev/null @@ -1,24 +0,0 @@ -// Diagnostic only. Same powf word through a runtime parameter or fixed literal; -// compare CUDA12.8 cubin and driver PTX JIT without changing either oracle. -#include -#include -#include -#include -#include -#include -__device__ void report(float scale,float*out){ - float log=__log2f(scale),power=powf(scale,3.0f),angle=power; - out[0]=scale;out[1]=log;out[2]=power;out[3]=cosf(angle);out[4]=sinf(angle); -} -extern "C" __global__ void probe_dynamic(float scale,float*out){report(scale,out);} -extern "C" __global__ void probe_literal(float*out){report(__uint_as_float(0x3f1ab32bu),out);} -int main(int argc,char**argv){ - if(argc!=2)return 2;cudaSetDevice(0);cudaFree(nullptr);cudaStream_t stream;cudaStreamCreate(&stream); - float*output;cudaMalloc(&output,20);float scale;uint32_t word=0x3f1ab32bu;std::memcpy(&scale,&word,4);float values[5]; - auto print=[&](const char*name){cudaDeviceSynchronize();cudaMemcpy(values,output,20,cudaMemcpyDeviceToHost);std::printf("%s",name);for(float x:values){uint32_t b;std::memcpy(&b,&x,4);std::printf(" %08x",b);}std::puts("");}; - probe_dynamic<<<1,1,0,stream>>>(scale,output);print("cubin_dynamic");probe_literal<<<1,1,0,stream>>>(output);print("cubin_literal"); - CUmodule module;if(cuModuleLoad(&module,argv[1])!=CUDA_SUCCESS)return 3;CUfunction f; - cuModuleGetFunction(&f,module,"probe_dynamic");void*dynamic[]={&scale,&output};cuLaunchKernel(f,1,1,1,1,1,1,0,reinterpret_cast(stream),dynamic,nullptr);print("jit_dynamic"); - cuModuleGetFunction(&f,module,"probe_literal");void*literal[]={&output};cuLaunchKernel(f,1,1,1,1,1,1,0,reinterpret_cast(stream),literal,nullptr);print("jit_literal"); - cudaFree(output);cuModuleUnload(module);cudaStreamDestroy(stream);return cudaGetLastError()==cudaSuccess?0:4; -} diff --git a/scripts/cuda-stubs/check-cu.py b/scripts/cuda-stubs/check-cu.py deleted file mode 100755 index ddc40d30..00000000 --- a/scripts/cuda-stubs/check-cu.py +++ /dev/null @@ -1,194 +0,0 @@ -#!/usr/bin/env python3 -"""Syntax / semantics check of the ported CUDA sources on a host without nvcc. - -usage: scripts/cuda-stubs/check-cu.py [-j N] [-v] [--fast-math] [--keep DIR] [file.cu ...] - (no file: every crates/cuda-driver/src/*.cu except third_party) - -Pipeline per file: clang++ -E (stub headers first on the include path, then the nvcc -I set of -scripts/build-original-verify-ptx.sh) -> every `asm volatile(...)` replaced by cuda_stub_asm() -(operand expressions stay type-checked, PTX text is not examined) -> clang++ -fsyntax-only -std=c++17. -Exit status 1 when any file fails. See cuda_stub.h for what a pass does and does not prove. -""" -import argparse, concurrent.futures, os, re, subprocess, sys, tempfile - -ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) -STUBS = os.path.join(ROOT, 'scripts', 'cuda-stubs') -SRC = os.path.join(ROOT, 'crates', 'cuda-driver', 'src') -INCLUDES = [ - STUBS, - os.path.join(ROOT, 'engine', 'strata', 'include'), - os.path.join(ROOT, 'engine', 'strata', 'src', 'kernels', 'cuda'), # sm120_iq_prefix.cuh includes "s26_tsum.cuh" from the Original - os.path.join(ROOT, 'engine', 'strata', 'third_party', 'ggml'), - os.path.join(SRC, 'third_party', 'llamacpp', 'ggml-cuda'), - os.path.join(SRC, 'third_party', 'llamacpp', 'ggml-include'), - os.path.join(SRC, 'third_party', 'llamacpp', 'ggml-src'), -] -COMMON = ['-std=c++17', '-D__NVCC__=1', '-D__CUDACC_RELAXED_CONSTEXPR__=1', '-D__CUDACC_EXTENDED_LAMBDA__=1'] -WARN = ['-Wall', '-Wno-unknown-pragmas', '-Wno-unused-function', '-Wno-unused-variable', '-Wno-unused-but-set-variable', - '-Wno-unused-local-typedef', '-Wno-pass-failed', '-Wno-missing-braces', '-Wno-sign-compare', '-Wno-unused-value', - '-Wno-unused-const-variable', '-Wno-deprecated-declarations', '-Wno-unknown-attributes', '-Wno-macro-redefined', - '-Wno-pragma-once-outside-header', '-Wno-ignored-attributes', '-Wno-unused-lambda-capture', '-Wno-tautological-compare', - '-Wno-unused-parameter', '-Wno-unused-command-line-argument', '-Wno-sometimes-uninitialized', '-Wno-undefined-internal', '-Wno-uninitialized'] -ASM_RE = re.compile(r'\b(?:__asm__|__asm|asm)\b\s*(?:__volatile__|volatile)?\s*(?:goto\s*)?\(') - -def scan_string(s, i): - q = s[i]; i += 1 - while i < len(s): - if s[i] == '\\': i += 2; continue - if s[i] == q: return i + 1 - i += 1 - return i - -def match_paren(s, i): - """s[i] == '(' ; return index after the matching ')'.""" - depth = 0 - while i < len(s): - c = s[i] - if c in '"\'': i = scan_string(s, i); continue - if c == '(': depth += 1 - elif c == ')': - depth -= 1 - if depth == 0: return i + 1 - i += 1 - raise ValueError('unbalanced asm') - -def split_top(body, sep): - parts, depth, cur, i = [], 0, [], 0 - while i < len(body): - c = body[i] - if c in '"\'': - j = scan_string(body, i); cur.append(body[i:j]); i = j; continue - if c in '([{': depth += 1 - elif c in ')]}': depth -= 1 - if c == sep and depth == 0 and not (sep == ':' and (body[i + 1:i + 2] == ':' or body[i - 1:i] == ':')): - parts.append(''.join(cur)); cur = [] - else: - cur.append(c) - i += 1 - parts.append(''.join(cur)) - return parts - -OPERAND_RE = re.compile(r'(?:\[\s*\w+\s*\]\s*)?"[^"]*"\s*\(') - -def operands(section): - out, i = [], 0 - while True: - m = OPERAND_RE.search(section, i) - if not m: return out - end = match_paren(section, m.end() - 1) - out.append(section[m.end():end - 1]) - i = end - -def rewrite_asm(text): - out, pos = [], 0 - while True: - m = ASM_RE.search(text, pos) - if not m: - out.append(text[pos:]); break - before = text[:m.start()].rstrip() - # only asm STATEMENTS: an asm label on a declaration (Darwin's __DARWIN_ALIAS) follows a declarator, never ; { } or a linemarker - if not (re.search(r'\bvolatile|__volatile__', m.group(0)) or before[-1:] in ('', ';', '{', '}') or re.search(r'^#.*$', before.split('\n')[-1])): - out.append(text[pos:m.end()]); pos = m.end(); continue - out.append(text[pos:m.start()]) - end = match_paren(text, m.end() - 1) - body = text[m.end():end - 1] - parts = split_top(body, ':') - ops = [] - for sec in parts[1:3]: - ops += operands(sec) - out.append('cuda_stub_asm(' + ', '.join('(' + o.replace('\n', ' ') + ')' for o in ops) + ')' + '\n' * body.count('\n')) - pos = end - return ''.join(out) - -PRINTF_CALL = re.compile(r'(?<=[;{}):,(])(\s*)printf(\s*\()') - -def rewrite_printf(text): - """clang only lowers device printf when it compiles the device side; a host-only pass sees a call to a host function.""" - return PRINTF_CALL.sub(r'\1cuda_stub_printf\2', text) - -def rewrite_launches(text): - """K<<>>(args) -> (cuda_stub_cfg(a, b, c, d), K(args))""" - while True: - i = text.find('<<<') - if i < 0: return text - j = text.index('>>>', i) - cfg = text[i + 3:j] - k = i - while k > 0 and text[k - 1] in ' \t\n': k -= 1 - end_name = k - if text[k - 1] == '>': # explicit template arguments - depth = 0 - while k > 0: - k -= 1 - if text[k] == '>': depth += 1 - elif text[k] == '<': - depth -= 1 - if depth == 0: break - while k > 0 and (text[k - 1].isalnum() or text[k - 1] in '_:'): k -= 1 - name = text[k:end_name] - a = j + 3 - while text[a] in ' \t\n': a += 1 - b = match_paren(text, a) - text = text[:k] + '(cuda_stub_cfg(' + cfg.replace('\n', ' ') + '), ' + name + text[a:b] + ')' + text[b:] - -SHARED_INIT_RE = re.compile(r'__shared__[^;{}()]*?\b\w+(?:\[[^\]]*\])*\s*=[^=]') - -def lint(path): - """nvcc rejects a __shared__ variable with an initializer; the stub cannot see that (it erases __shared__).""" - msgs = [] - for n, line in enumerate(open(path, encoding='utf-8', errors='replace'), 1): - code = line.split('//')[0] - if SHARED_INIT_RE.search(code) and 'static_assert' not in code: - msgs.append(f'{path}:{n}: error: __shared__ variable with an initializer (nvcc: "initializer not allowed for __shared__ variable")') - return msgs - -def check(path, fast_math, keep, cuda=True): - inc = [] - for d in INCLUDES: inc += ['-I', d] - extra = ['-D__USE_FAST_MATH__=1'] if fast_math else [] - lang = ['-x', 'cuda', '--cuda-host-only', '-nocudainc', '-nocudalib'] if cuda else ['-x', 'c++'] - pre = subprocess.run(['clang++', '-E'] + lang + ['-include', 'cuda_runtime.h'] + COMMON + extra + inc + [path], capture_output=True, text=True) - if pre.returncode != 0: - return path, False, pre.stderr, 0 - src = rewrite_asm(pre.stdout) - if cuda: src = rewrite_printf(src) - if not cuda: src = rewrite_launches(src) - fd, tmp = tempfile.mkstemp(suffix='.ii', dir=keep) - os.write(fd, src.encode()); os.close(fd) - try: - r = subprocess.run(['clang++', '-fsyntax-only'] + (['-x', 'cuda-cpp-output', '--cuda-host-only', '-nocudainc', '-nocudalib'] if cuda else ['-x', 'c++-cpp-output']) + COMMON + WARN + [tmp], capture_output=True, text=True) - finally: - if not keep: os.unlink(tmp) - nwarn = r.stderr.count('warning:') - lm = lint(path) - return path, r.returncode == 0 and not lm, r.stderr + '\n'.join(lm), nwarn - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument('files', nargs='*') - ap.add_argument('-j', type=int, default=os.cpu_count() or 4) - ap.add_argument('-v', action='store_true', help='print diagnostics of passing files too') - ap.add_argument('--fast-math', action='store_true') - ap.add_argument('--plain', action='store_true', help='C++-only pass (qualifiers erased) instead of clang\'s CUDA frontend') - ap.add_argument('--keep', help='directory to keep the rewritten translation units in') - ap.add_argument('--max-errors', type=int, default=12) - a = ap.parse_args() - files = a.files or sorted(os.path.join(SRC, f) for f in os.listdir(SRC) if f.endswith('.cu')) - bad = 0 - with concurrent.futures.ThreadPoolExecutor(a.j) as ex: - for path, ok, err, nwarn in ex.map(lambda p: check(os.path.abspath(p), a.fast_math, a.keep, not a.plain), files): - name = os.path.relpath(path, ROOT) - if ok: - print(f'ok {name}' + (f' ({nwarn} warnings)' if nwarn else '')) - if a.v and err: print(err) - else: - bad += 1 - print(f'FAIL {name}') - errs = [l for l in err.splitlines() if 'error:' in l] - print('\n'.join(' ' + l for l in errs[:a.max_errors]) or err[:2000]) - if len(errs) > a.max_errors: print(f' ... {len(errs) - a.max_errors} more errors') - print(f'{len(files) - bad}/{len(files)} files pass') - return 1 if bad else 0 - -if __name__ == '__main__': - sys.exit(main()) diff --git a/scripts/cuda-stubs/cooperative_groups.h b/scripts/cuda-stubs/cooperative_groups.h deleted file mode 100644 index 9ab0b355..00000000 --- a/scripts/cuda-stubs/cooperative_groups.h +++ /dev/null @@ -1,25 +0,0 @@ -// Stub of : thread_block / tiled_partition / this_thread_block / reduce. -#pragma once -#include "cuda_stub.h" -#if defined(__CUDA__) -#pragma clang force_cuda_host_device begin -#endif -namespace cooperative_groups { -struct thread_block { - void sync() const; unsigned thread_rank() const; unsigned size() const; dim3 group_index() const; uint3 thread_index() const; dim3 group_dim() const; -}; -inline thread_block this_thread_block() { return thread_block{}; } -template struct thread_block_tile { - void sync() const; unsigned thread_rank() const; unsigned size() const; unsigned meta_group_rank() const; unsigned meta_group_size() const; - template T shfl(T, int) const; template T shfl_down(T, unsigned) const; template T shfl_up(T, unsigned) const; - template T shfl_xor(T, unsigned) const; int any(int) const; int all(int) const; unsigned ballot(int) const; -}; -template thread_block_tile tiled_partition(const thread_block&) { return {}; } -template struct plus { template T operator()(T a, T b) const { return a + b; } }; -template struct maximum { T operator()(T a, T b) const { return a > b ? a : b; } }; -template struct less { T operator()(T a, T b) const { return a < b ? a : b; } }; -template T reduce(const G&, T v, Op) { return v; } -} -#if defined(__CUDA__) -#pragma clang force_cuda_host_device end -#endif diff --git a/scripts/cuda-stubs/cublas_v2.h b/scripts/cuda-stubs/cublas_v2.h deleted file mode 100644 index 05ef928d..00000000 --- a/scripts/cuda-stubs/cublas_v2.h +++ /dev/null @@ -1,19 +0,0 @@ -// Stub of : only the handle and status names ggml-cuda/common.cuh mentions. -#pragma once -#include "cuda_stub.h" -#if defined(__CUDA__) -#pragma clang force_cuda_host_device begin -#endif -typedef void* cublasHandle_t; -typedef int cublasStatus_t; -typedef int cublasComputeType_t; -typedef int cudaDataType_t; -enum { CUBLAS_STATUS_SUCCESS = 0 }; -#define CUBLAS_TF32_TENSOR_OP_MATH 3 -cublasStatus_t cublasCreate(cublasHandle_t*); -cublasStatus_t cublasDestroy(cublasHandle_t); -cublasStatus_t cublasSetStream(cublasHandle_t, cudaStream_t); -cublasStatus_t cublasSetMathMode(cublasHandle_t, int); -#if defined(__CUDA__) -#pragma clang force_cuda_host_device end -#endif diff --git a/scripts/cuda-stubs/cuda.h b/scripts/cuda-stubs/cuda.h deleted file mode 100644 index 23af62ab..00000000 --- a/scripts/cuda-stubs/cuda.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include "cuda_stub.h" diff --git a/scripts/cuda-stubs/cuda_bf16.h b/scripts/cuda-stubs/cuda_bf16.h deleted file mode 100644 index a5106750..00000000 --- a/scripts/cuda-stubs/cuda_bf16.h +++ /dev/null @@ -1,54 +0,0 @@ -// Stub of (class shape and intrinsics only; numerics are NOT modelled). -#pragma once -#include "cuda_stub.h" -#ifndef LELEKA_CUDA_STUB_BF16 -#define LELEKA_CUDA_STUB_BF16 -#if defined(__CUDA__) -#pragma clang force_cuda_host_device begin -#endif -struct __nv_bfloat16_raw { unsigned short x; }; -struct __nv_bfloat162_raw { unsigned short x, y; }; -struct __nv_bfloat16 { - unsigned short __x; - __nv_bfloat16() = default; - __nv_bfloat16(const __nv_bfloat16_raw& r) : __x(r.x) {} - __nv_bfloat16(float); __nv_bfloat16(double); __nv_bfloat16(short); __nv_bfloat16(unsigned short); - __nv_bfloat16(int); __nv_bfloat16(unsigned int); __nv_bfloat16(long long); __nv_bfloat16(unsigned long long); - operator __nv_bfloat16_raw() const { return __nv_bfloat16_raw{__x}; } - operator float() const; operator short() const; operator unsigned short() const; operator int() const; operator unsigned int() const; - operator long long() const; operator unsigned long long() const; operator char() const; operator signed char() const; operator unsigned char() const; - explicit operator bool() const; - __nv_bfloat16& operator=(float); -}; -typedef __nv_bfloat16 nv_bfloat16; -struct __attribute__((aligned(4))) __nv_bfloat162 { - __nv_bfloat16 x, y; - __nv_bfloat162() = default; - __nv_bfloat162(const __nv_bfloat16& a, const __nv_bfloat16& b) : x(a), y(b) {} -}; -typedef __nv_bfloat162 nv_bfloat162; -__nv_bfloat16 operator+(const __nv_bfloat16&, const __nv_bfloat16&); __nv_bfloat16 operator-(const __nv_bfloat16&, const __nv_bfloat16&); -__nv_bfloat16 operator*(const __nv_bfloat16&, const __nv_bfloat16&); __nv_bfloat16 operator/(const __nv_bfloat16&, const __nv_bfloat16&); -__nv_bfloat16 operator-(const __nv_bfloat16&); -bool operator==(const __nv_bfloat16&, const __nv_bfloat16&); bool operator!=(const __nv_bfloat16&, const __nv_bfloat16&); -bool operator<(const __nv_bfloat16&, const __nv_bfloat16&); bool operator>(const __nv_bfloat16&, const __nv_bfloat16&); -bool operator<=(const __nv_bfloat16&, const __nv_bfloat16&); bool operator>=(const __nv_bfloat16&, const __nv_bfloat16&); -__nv_bfloat16 __float2bfloat16(float); __nv_bfloat16 __float2bfloat16_rn(float); __nv_bfloat16 __float2bfloat16_rz(float); -__nv_bfloat16 __double2bfloat16(double); -float __bfloat162float(__nv_bfloat16); -__nv_bfloat162 __float2bfloat162_rn(float); __nv_bfloat162 __floats2bfloat162_rn(float, float); __nv_bfloat162 __halves2bfloat162(__nv_bfloat16, __nv_bfloat16); -float2 __bfloat1622float2(__nv_bfloat162); __nv_bfloat162 __float22bfloat162_rn(float2); -float __low2float(__nv_bfloat162); float __high2float(__nv_bfloat162); __nv_bfloat16 __low2bfloat16(__nv_bfloat162); __nv_bfloat16 __high2bfloat16(__nv_bfloat162); -__nv_bfloat162 __low2bfloat162(__nv_bfloat162); __nv_bfloat162 __high2bfloat162(__nv_bfloat162); -unsigned short __bfloat16_as_ushort(__nv_bfloat16); short __bfloat16_as_short(__nv_bfloat16); -__nv_bfloat16 __ushort_as_bfloat16(unsigned short); __nv_bfloat16 __short_as_bfloat16(short); -__nv_bfloat16 __hadd(__nv_bfloat16, __nv_bfloat16); __nv_bfloat16 __hsub(__nv_bfloat16, __nv_bfloat16); -__nv_bfloat16 __hmul(__nv_bfloat16, __nv_bfloat16); __nv_bfloat16 __hfma(__nv_bfloat16, __nv_bfloat16, __nv_bfloat16); -__nv_bfloat16 __hneg(__nv_bfloat16); __nv_bfloat16 __habs(__nv_bfloat16); -__nv_bfloat162 __hadd2(__nv_bfloat162, __nv_bfloat162); __nv_bfloat162 __hmul2(__nv_bfloat162, __nv_bfloat162); -__nv_bfloat162 __hfma2(__nv_bfloat162, __nv_bfloat162, __nv_bfloat162); -struct __nv_bfloat16_raw __nv_cvt_e8m0_to_bf16raw(unsigned char); -#if defined(__CUDA__) -#pragma clang force_cuda_host_device end -#endif -#endif diff --git a/scripts/cuda-stubs/cuda_fp16.h b/scripts/cuda-stubs/cuda_fp16.h deleted file mode 100644 index 2096e14a..00000000 --- a/scripts/cuda-stubs/cuda_fp16.h +++ /dev/null @@ -1,105 +0,0 @@ -// Stub of : the class shape of the real __half / __half2 (implicit float conversions, so the same -// overload ambiguities as nvcc), the conversion and arithmetic intrinsics the sources use. Numerics are NOT modelled. -#pragma once -#include "cuda_stub.h" -#ifndef LELEKA_CUDA_STUB_FP16 -#define LELEKA_CUDA_STUB_FP16 -#if defined(__CUDA__) -#pragma clang force_cuda_host_device begin -#endif -struct __half_raw { unsigned short x; }; -struct __half2_raw { unsigned short x, y; }; -struct __half { - unsigned short __x; - __half() = default; - __half(const __half_raw& r) : __x(r.x) {} - __half(float f); - __half(double f); - __half(short v); - __half(unsigned short v); - __half(int v); - __half(unsigned int v); - __half(long long v); - __half(unsigned long long v); - operator __half_raw() const { return __half_raw{__x}; } - operator float() const; - operator short() const; - operator unsigned short() const; - operator int() const; - operator unsigned int() const; - operator long long() const; - operator unsigned long long() const; - operator char() const; - operator signed char() const; - operator unsigned char() const; - explicit operator bool() const; - __half& operator=(const __half_raw& r) { __x = r.x; return *this; } - __half& operator=(float f); - __half& operator=(double f); - __half& operator=(short v); - __half& operator=(unsigned short v); - __half& operator=(int v); - __half& operator=(unsigned int v); - __half& operator=(long long v); - __half& operator=(unsigned long long v); - __half& operator+=(const __half&); __half& operator-=(const __half&); __half& operator*=(const __half&); __half& operator/=(const __half&); - __half& operator++(); __half& operator--(); __half operator++(int); __half operator--(int); -}; -typedef __half half; -struct __attribute__((aligned(4))) __half2 { - __half x, y; - __half2() = default; - __half2(const __half& a, const __half& b) : x(a), y(b) {} - __half2(const __half2_raw& r); - operator __half2_raw() const; - __half2& operator=(const __half2_raw&); - __half2& operator+=(const __half2&); __half2& operator-=(const __half2&); __half2& operator*=(const __half2&); __half2& operator/=(const __half2&); -}; -typedef __half2 half2; -__half operator+(const __half&, const __half&); __half operator-(const __half&, const __half&); -__half operator*(const __half&, const __half&); __half operator/(const __half&, const __half&); -__half operator+(const __half&); __half operator-(const __half&); -bool operator==(const __half&, const __half&); bool operator!=(const __half&, const __half&); -bool operator<(const __half&, const __half&); bool operator>(const __half&, const __half&); -bool operator<=(const __half&, const __half&); bool operator>=(const __half&, const __half&); -__half2 operator+(const __half2&, const __half2&); __half2 operator-(const __half2&, const __half2&); -__half2 operator*(const __half2&, const __half2&); __half2 operator/(const __half2&, const __half2&); - -__half __float2half(float); __half __float2half_rn(float); __half __float2half_rz(float); __half __float2half_rd(float); __half __float2half_ru(float); -__half __double2half(double); -float __half2float(__half); -__half2 make_half2(__half, __half); -__half2 __float2half2_rn(float); __half2 __floats2half2_rn(float, float); __half2 __halves2half2(__half, __half); -float2 __half22float2(__half2); __half2 __float22half2_rn(float2); -float __low2float(__half2); float __high2float(__half2); __half __low2half(__half2); __half __high2half(__half2); -__half2 __low2half2(__half2); __half2 __high2half2(__half2); __half2 __lows2half2(__half2, __half2); __half2 __highs2half2(__half2, __half2); -__half2 __half2half2(__half); __half2 __lowhigh2highlow(__half2); -short __half2short_rn(__half); int __half2int_rn(__half); int __half2int_rz(__half); unsigned __half2uint_rn(__half); -__half __int2half_rn(int); __half __short2half_rn(short); __half __uint2half_rn(unsigned); -short __half_as_short(__half); unsigned short __half_as_ushort(__half); -__half __short_as_half(short); __half __ushort_as_half(unsigned short); -int __half2_as_int(__half2); unsigned __half2_as_uint(__half2); __half2 __int_as_half2(int); __half2 __uint_as_half2(unsigned); -__half __hadd(__half, __half); __half __hsub(__half, __half); __half __hmul(__half, __half); __half __hdiv(__half, __half); -__half __hadd_rn(__half, __half); __half __hmul_rn(__half, __half); __half __hsub_rn(__half, __half); __half __hadd_sat(__half, __half); -__half __hfma(__half, __half, __half); __half __hfma_rn(__half, __half, __half); __half __hneg(__half); __half __habs(__half); -__half __hmax(__half, __half); __half __hmin(__half, __half); -bool __heq(__half, __half); bool __hne(__half, __half); bool __hlt(__half, __half); bool __hle(__half, __half); -bool __hgt(__half, __half); bool __hge(__half, __half); bool __hisnan(__half); bool __hisinf(__half); -__half2 __hadd2(__half2, __half2); __half2 __hsub2(__half2, __half2); __half2 __hmul2(__half2, __half2); __half2 __h2div(__half2, __half2); -__half2 __hfma2(__half2, __half2, __half2); __half2 __hneg2(__half2); __half2 __habs2(__half2); -__half2 __hadd2_rn(__half2, __half2); __half2 __hmul2_rn(__half2, __half2); __half2 __hsub2_rn(__half2, __half2); -__half2 __hmax2(__half2, __half2); __half2 __hmin2(__half2, __half2); -bool __hbeq2(__half2, __half2); bool __hbne2(__half2, __half2); -__half2 __heq2(__half2, __half2); __half2 __hlt2(__half2, __half2); -__half hexp(__half); __half hlog(__half); __half hsqrt(__half); __half hrsqrt(__half); __half hrcp(__half); -__half hexp2(__half); __half hsin(__half); __half hcos(__half); __half hfloor(__half); __half hceil(__half); __half htrunc(__half); __half hrint(__half); -__half2 h2exp(__half2); __half2 h2sqrt(__half2); __half2 h2rsqrt(__half2); __half2 h2rcp(__half2); __half2 h2exp2(__half2); -__half __shfl_sync(unsigned, __half, int, int = 32); -__half2 __shfl_sync(unsigned, __half2, int, int = 32); -__half2 __ldg(const __half2*); __half __ldg(const __half*); -void atomicAdd(__half*, __half); -__half2 atomicAdd(__half2*, __half2); -#if defined(__CUDA__) -#pragma clang force_cuda_host_device end -#endif -#endif diff --git a/scripts/cuda-stubs/cuda_fp4.h b/scripts/cuda-stubs/cuda_fp4.h deleted file mode 100644 index f092e6a5..00000000 --- a/scripts/cuda-stubs/cuda_fp4.h +++ /dev/null @@ -1,20 +0,0 @@ -// Stub of (CUDA >= 12.8 FP4 E2M1 types, used by the Blackwell MMA path of ggml-cuda/quantize.cu). -#pragma once -#include "cuda_stub.h" -#if defined(__CUDA__) -#pragma clang force_cuda_host_device begin -#endif -#include "cuda_fp16.h" -#include "cuda_bf16.h" -typedef unsigned char __nv_fp4_storage_t; -typedef unsigned char __nv_fp4x2_storage_t; -typedef unsigned short __nv_fp4x4_storage_t; -enum __nv_fp4_interpretation_t { __NV_E2M1 }; -struct __nv_fp4_e2m1 { __nv_fp4_storage_t __x; __nv_fp4_e2m1() = default; __nv_fp4_e2m1(float); operator float() const; }; -struct __nv_fp4x2_e2m1 { __nv_fp4x2_storage_t __x; __nv_fp4x2_e2m1() = default; __nv_fp4x2_e2m1(float2); __nv_fp4x2_e2m1(__half2); operator float2() const; }; -struct __nv_fp4x4_e2m1 { __nv_fp4x4_storage_t __x; __nv_fp4x4_e2m1() = default; __nv_fp4x4_e2m1(float4); __nv_fp4x4_e2m1(float2, float2); __nv_fp4x4_e2m1(__half2, __half2); }; -__half2_raw __nv_cvt_fp4x2_to_halfraw2(__nv_fp4x2_storage_t, __nv_fp4_interpretation_t); -__nv_fp4x2_storage_t __nv_cvt_float2_to_fp4x2(float2, __nv_fp4_interpretation_t, int); -#if defined(__CUDA__) -#pragma clang force_cuda_host_device end -#endif diff --git a/scripts/cuda-stubs/cuda_fp8.h b/scripts/cuda-stubs/cuda_fp8.h deleted file mode 100644 index 22b88a37..00000000 --- a/scripts/cuda-stubs/cuda_fp8.h +++ /dev/null @@ -1,12 +0,0 @@ -// Stub of . -#pragma once -#include "cuda_stub.h" -#if defined(__CUDA__) -#pragma clang force_cuda_host_device begin -#endif -typedef unsigned char __nv_fp8_storage_t; -struct __nv_fp8_e4m3 { __nv_fp8_storage_t __x; __nv_fp8_e4m3() = default; __nv_fp8_e4m3(float); __nv_fp8_e4m3(double); __nv_fp8_e4m3(int); operator float() const; }; -struct __nv_fp8_e5m2 { __nv_fp8_storage_t __x; __nv_fp8_e5m2() = default; __nv_fp8_e5m2(float); __nv_fp8_e5m2(double); operator float() const; }; -#if defined(__CUDA__) -#pragma clang force_cuda_host_device end -#endif diff --git a/scripts/cuda-stubs/cuda_runtime.h b/scripts/cuda-stubs/cuda_runtime.h deleted file mode 100644 index 23af62ab..00000000 --- a/scripts/cuda-stubs/cuda_runtime.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include "cuda_stub.h" diff --git a/scripts/cuda-stubs/cuda_runtime_api.h b/scripts/cuda-stubs/cuda_runtime_api.h deleted file mode 100644 index 23af62ab..00000000 --- a/scripts/cuda-stubs/cuda_runtime_api.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include "cuda_stub.h" diff --git a/scripts/cuda-stubs/cuda_stub.h b/scripts/cuda-stubs/cuda_stub.h deleted file mode 100644 index 7840874d..00000000 --- a/scripts/cuda-stubs/cuda_stub.h +++ /dev/null @@ -1,609 +0,0 @@ -// Host-only CUDA stand-in for SYNTAX / SEMANTICS checking of the ported .cu sources on a machine without nvcc. -// -// scripts/cuda-stubs/check-cu.py [--list] [file.cu ...] (default: every crates/cuda-driver/src/*.cu) -// -// What this proves: the file parses as C++17 and every identifier, overload, template argument and operand type that the -// device code uses resolves against a CUDA-shaped API (dim3/threadIdx, the vector types, __half/__nv_bfloat16, warp -// shuffle / vote, atomics, fast-math and rounding intrinsics, __dp4a and the SIMD-in-register family, cooperative -// groups, cp.async helpers, cudaFuncSetAttribute ...). Inline PTX (`asm volatile`) is NOT parsed: check-cu.py rewrites -// every asm statement into a call that still type-checks the operand expressions. -// What it does NOT prove: that nvcc accepts it (real __half has stricter conversion rules, texture/driver APIs and -// template deduction corner cases differ), PTX validity, register/smem limits, or any numerics. A pass here is -// necessary, not sufficient. -#pragma once -#ifndef LELEKA_CUDA_STUB_H -#define LELEKA_CUDA_STUB_H - -// What really drags in; the sources must name every other standard header themselves. -#include -#include -#include -#include -#include -#include // cuda_fp16.hpp/cuda_bf16.hpp and crt/*.h pull in transitively on every supported host -#include -#include -#include -#include - -#ifndef __CUDA_ARCH__ -#define __CUDA_ARCH__ 1200 // the device-compilation pass of -arch=sm_120 (the code the PTX is generated from) -#endif -#ifndef __CUDACC__ -#define __CUDACC__ 1 -#endif -#define __CUDACC_VER_MAJOR__ 13 -#define __CUDACC_VER_MINOR__ 0 -#define CUDART_VERSION 13000 -#define CUDA_VERSION 13000 -#define __CUDA_ARCH_LIST__ 1200 - -// ---------------------------------------------------------------------------------------------------- qualifiers -#if defined(__CUDA__) -// clang's CUDA frontend (check-cu.py --cuda): the qualifiers are real, so host/device call legality, __shared__ rules and -// the <<<>>> syntax are checked by the compiler itself. Everything below is declared __host__ __device__ (the region ends -// at the bottom of this file); the builtin variables and the libm overloads are __device__. -#define __global__ __attribute__((global)) -#define __device__ __attribute__((device)) -#define __host__ __attribute__((host)) -#define __shared__ __attribute__((shared)) -#define __constant__ __attribute__((constant)) -#define __managed__ __attribute__((managed)) -#define __forceinline__ __inline__ __attribute__((always_inline)) -#define __launch_bounds__(...) __attribute__((launch_bounds(__VA_ARGS__))) -#define __grid_constant__ __attribute__((grid_constant)) -#define CUDA_STUB_DEVVAR __device__ -#else -#define __global__ -#define __device__ -#define __host__ -#define __forceinline__ inline -#define __noinline__ -#define __shared__ -#define __constant__ -#define __managed__ -#define __launch_bounds__(...) -#define __grid_constant__ -#define CUDA_STUB_DEVVAR -#endif -#define __restrict__ __restrict -#define __align__(n) __attribute__((aligned(n))) -#define __builtin_align__(n) __attribute__((aligned(n))) -#define __maxnreg__(n) -#define __cluster_dims__(...) -#define __builtin_assume(x) ((void) 0) -#if defined(__CUDA__) -#pragma clang force_cuda_host_device begin -#endif - -// ---------------------------------------------------------------------------------------------------- vector types -#define CUDA_STUB_VEC1(T, N) struct N##1 { T x; }; static inline N##1 make_##N##1(T x) { return N##1{x}; } -#define CUDA_STUB_VEC2(T, N) struct N##2 { T x, y; }; static inline N##2 make_##N##2(T x, T y) { return N##2{x, y}; } -#define CUDA_STUB_VEC3(T, N) struct N##3 { T x, y, z; }; static inline N##3 make_##N##3(T x, T y, T z) { return N##3{x, y, z}; } -#define CUDA_STUB_VEC4(T, N) struct alignas(16) N##4 { T x, y, z, w; }; static inline N##4 make_##N##4(T x, T y, T z, T w) { return N##4{x, y, z, w}; } -#define CUDA_STUB_VEC_ALL(T, N) CUDA_STUB_VEC1(T, N) CUDA_STUB_VEC3(T, N) -CUDA_STUB_VEC_ALL(signed char, char) -CUDA_STUB_VEC_ALL(unsigned char, uchar) -CUDA_STUB_VEC_ALL(short, short) -CUDA_STUB_VEC_ALL(unsigned short, ushort) -CUDA_STUB_VEC_ALL(int, int) -CUDA_STUB_VEC_ALL(unsigned int, uint) -CUDA_STUB_VEC_ALL(long, long) -CUDA_STUB_VEC_ALL(unsigned long, ulong) -CUDA_STUB_VEC_ALL(long long, longlong) -CUDA_STUB_VEC_ALL(unsigned long long, ulonglong) -CUDA_STUB_VEC_ALL(float, float) -CUDA_STUB_VEC_ALL(double, double) -struct alignas(2) char2 { signed char x, y; }; -static inline char2 make_char2(signed char x, signed char y) { return char2{x, y}; } -struct alignas(4) char4 { signed char x, y, z, w; }; -static inline char4 make_char4(signed char x, signed char y, signed char z, signed char w) { return char4{x, y, z, w}; } -struct alignas(2) uchar2 { unsigned char x, y; }; -static inline uchar2 make_uchar2(unsigned char x, unsigned char y) { return uchar2{x, y}; } -struct alignas(4) uchar4 { unsigned char x, y, z, w; }; -static inline uchar4 make_uchar4(unsigned char x, unsigned char y, unsigned char z, unsigned char w) { return uchar4{x, y, z, w}; } -struct alignas(4) short2 { short x, y; }; -static inline short2 make_short2(short x, short y) { return short2{x, y}; } -struct alignas(8) short4 { short x, y, z, w; }; -static inline short4 make_short4(short x, short y, short z, short w) { return short4{x, y, z, w}; } -struct alignas(4) ushort2 { unsigned short x, y; }; -static inline ushort2 make_ushort2(unsigned short x, unsigned short y) { return ushort2{x, y}; } -struct alignas(8) ushort4 { unsigned short x, y, z, w; }; -static inline ushort4 make_ushort4(unsigned short x, unsigned short y, unsigned short z, unsigned short w) { return ushort4{x, y, z, w}; } -struct alignas(8) int2 { int x, y; }; -static inline int2 make_int2(int x, int y) { return int2{x, y}; } -struct alignas(16) int4 { int x, y, z, w; }; -static inline int4 make_int4(int x, int y, int z, int w) { return int4{x, y, z, w}; } -struct alignas(8) uint2 { unsigned x, y; }; -static inline uint2 make_uint2(unsigned x, unsigned y) { return uint2{x, y}; } -struct alignas(16) uint4 { unsigned x, y, z, w; }; -static inline uint4 make_uint4(unsigned x, unsigned y, unsigned z, unsigned w) { return uint4{x, y, z, w}; } -struct alignas(16) long2 { long x, y; }; -struct alignas(16) ulong2 { unsigned long x, y; }; -struct alignas(16) longlong2 { long long x, y; }; -static inline longlong2 make_longlong2(long long x, long long y) { return longlong2{x, y}; } -struct alignas(16) ulonglong2 { unsigned long long x, y; }; -static inline ulonglong2 make_ulonglong2(unsigned long long x, unsigned long long y) { return ulonglong2{x, y}; } -struct alignas(8) float2 { float x, y; }; -static inline float2 make_float2(float x, float y) { return float2{x, y}; } -struct alignas(16) float4 { float x, y, z, w; }; -static inline float4 make_float4(float x, float y, float z, float w) { return float4{x, y, z, w}; } -struct alignas(16) double2 { double x, y; }; -static inline double2 make_double2(double x, double y) { return double2{x, y}; } -#undef CUDA_STUB_VEC1 -#undef CUDA_STUB_VEC2 -#undef CUDA_STUB_VEC3 -#undef CUDA_STUB_VEC4 -#undef CUDA_STUB_VEC_ALL - -// ---------------------------------------------------------------------------------------------------- builtin variables -struct dim3 { - unsigned int x, y, z; - constexpr dim3(unsigned int vx = 1, unsigned int vy = 1, unsigned int vz = 1) : x(vx), y(vy), z(vz) {} - constexpr dim3(uint3 v) : x(v.x), y(v.y), z(v.z) {} - constexpr operator uint3() const { return uint3{x, y, z}; } -}; -extern CUDA_STUB_DEVVAR const uint3 threadIdx; -extern CUDA_STUB_DEVVAR const uint3 blockIdx; -extern CUDA_STUB_DEVVAR const dim3 blockDim; -extern CUDA_STUB_DEVVAR const dim3 gridDim; -extern CUDA_STUB_DEVVAR const int warpSize; - -// ---------------------------------------------------------------------------------------------------- errors / runtime API -typedef int cudaError_t; -typedef void* cudaStream_t; -typedef void* cudaEvent_t; -typedef void* cudaGraph_t; -typedef void* cudaGraphExec_t; -typedef void* CUstream; -typedef void* CUfunction; -typedef void* CUmodule; -typedef int CUresult; -enum { cudaSuccess = 0, cudaErrorInvalidValue = 1 }; -enum cudaMemcpyKind { cudaMemcpyHostToHost, cudaMemcpyHostToDevice, cudaMemcpyDeviceToHost, cudaMemcpyDeviceToDevice, cudaMemcpyDefault }; -enum cudaFuncAttribute { cudaFuncAttributeMaxDynamicSharedMemorySize = 8, cudaFuncAttributePreferredSharedMemoryCarveout = 9 }; -enum cudaFuncCache { cudaFuncCachePreferNone, cudaFuncCachePreferShared, cudaFuncCachePreferL1 }; -struct cudaFuncAttributes { size_t sharedSizeBytes; size_t constSizeBytes; size_t localSizeBytes; int maxThreadsPerBlock; int numRegs; int ptxVersion; int binaryVersion; int maxDynamicSharedSizeBytes; }; -enum cudaLaunchAttributeID { cudaLaunchAttributeProgrammaticStreamSerialization = 5 }; -union cudaLaunchAttributeValue { int programmaticStreamSerializationAllowed; }; -struct cudaLaunchAttribute { cudaLaunchAttributeID id; cudaLaunchAttributeValue val; }; -struct cudaLaunchConfig_t { dim3 gridDim, blockDim; size_t dynamicSmemBytes; cudaStream_t stream; cudaLaunchAttribute* attrs; unsigned numAttrs; }; -template cudaError_t cudaLaunchKernelEx(const cudaLaunchConfig_t*, void (*)(Params...), Args&&...); -struct cudaDeviceProp { char name[256]; int major, minor, multiProcessorCount, warpSize, maxThreadsPerBlock; size_t totalGlobalMem, sharedMemPerBlock, sharedMemPerBlockOptin; }; -const char* cudaGetErrorString(cudaError_t); -cudaError_t cudaGetLastError(); -cudaError_t cudaPeekAtLastError(); -cudaError_t cudaDeviceSynchronize(); -cudaError_t cudaStreamSynchronize(cudaStream_t); -cudaError_t cudaMalloc(void**, size_t); -cudaError_t cudaFree(void*); -cudaError_t cudaMemcpy(void*, const void*, size_t, cudaMemcpyKind); -cudaError_t cudaMemcpyAsync(void*, const void*, size_t, cudaMemcpyKind, cudaStream_t = nullptr); -cudaError_t cudaMemsetAsync(void*, int, size_t, cudaStream_t = nullptr); -cudaError_t cudaGetDevice(int*); -cudaError_t cudaGetDeviceProperties(cudaDeviceProp*, int); -cudaError_t cudaDeviceGetAttribute(int*, int, int); -cudaError_t cudaFuncGetAttributes(cudaFuncAttributes*, const void*); -cudaError_t cudaFuncSetAttribute(const void*, cudaFuncAttribute, int); -template cudaError_t cudaFuncSetAttribute(T* f, cudaFuncAttribute a, int v) { return cudaFuncSetAttribute((const void*) f, a, v); } -enum { cudaEventDisableTiming = 2, cudaEventDefault = 0, cudaStreamNonBlocking = 1, cudaStreamDefault = 0 }; -cudaError_t cudaGridDependencySynchronize(); -cudaError_t cudaTriggerProgrammaticLaunchCompletion(); -cudaError_t cudaEventCreateWithFlags(cudaEvent_t*, unsigned); -cudaError_t cudaEventCreate(cudaEvent_t*); -cudaError_t cudaEventDestroy(cudaEvent_t); -cudaError_t cudaEventRecord(cudaEvent_t, cudaStream_t = nullptr); -cudaError_t cudaEventSynchronize(cudaEvent_t); -cudaError_t cudaEventElapsedTime(float*, cudaEvent_t, cudaEvent_t); -cudaError_t cudaStreamWaitEvent(cudaStream_t, cudaEvent_t, unsigned = 0); -cudaError_t cudaStreamCreateWithFlags(cudaStream_t*, unsigned); -cudaError_t cudaStreamCreate(cudaStream_t*); -cudaError_t cudaStreamDestroy(cudaStream_t); -cudaError_t cudaSetDevice(int); -cudaError_t cudaGetDeviceCount(int*); -cudaError_t cudaMemGetInfo(size_t*, size_t*); -cudaError_t cudaMallocHost(void**, size_t); -cudaError_t cudaFreeHost(void*); -cudaError_t cudaMemset(void*, int, size_t); -// driver API / cuBLAS names that ggml-cuda/common.cuh mentions in host helpers -CUresult cuGetErrorString(CUresult, const char**); -const char* cublasGetStatusString(int); -cudaError_t cudaLaunchKernel(const void*, dim3, dim3, void**, size_t, cudaStream_t); - -// ---------------------------------------------------------------------------------------------------- integer / float intrinsics -// min / max exactly as crt/math_functions.hpp offers them (the mixed signed / unsigned overloads are real). -static inline int min(int a, int b) { return a < b ? a : b; } -static inline int max(int a, int b) { return a < b ? b : a; } -static inline unsigned min(unsigned a, unsigned b) { return a < b ? a : b; } -static inline unsigned max(unsigned a, unsigned b) { return a < b ? b : a; } -static inline unsigned min(int a, unsigned b) { return (unsigned) a < b ? (unsigned) a : b; } -static inline unsigned min(unsigned a, int b) { return a < (unsigned) b ? a : (unsigned) b; } -static inline unsigned max(int a, unsigned b) { return (unsigned) a < b ? b : (unsigned) a; } -static inline unsigned max(unsigned a, int b) { return a < (unsigned) b ? (unsigned) b : a; } -static inline long long min(long long a, long long b) { return a < b ? a : b; } -static inline long long max(long long a, long long b) { return a < b ? b : a; } -static inline unsigned long long min(unsigned long long a, unsigned long long b) { return a < b ? a : b; } -static inline unsigned long long max(unsigned long long a, unsigned long long b) { return a < b ? b : a; } -static inline unsigned long long min(long long a, unsigned long long b) { return (unsigned long long) a < b ? (unsigned long long) a : b; } -static inline unsigned long long min(unsigned long long a, long long b) { return a < (unsigned long long) b ? a : (unsigned long long) b; } -static inline unsigned long long max(long long a, unsigned long long b) { return (unsigned long long) a < b ? b : (unsigned long long) a; } -static inline unsigned long long max(unsigned long long a, long long b) { return a < (unsigned long long) b ? (unsigned long long) b : a; } -static inline long min(long a, long b) { return a < b ? a : b; } -static inline long max(long a, long b) { return a < b ? b : a; } -static inline unsigned long min(unsigned long a, unsigned long b) { return a < b ? a : b; } -static inline unsigned long max(unsigned long a, unsigned long b) { return a < b ? b : a; } -static inline float min(float a, float b) { return fminf(a, b); } -static inline float max(float a, float b) { return fmaxf(a, b); } -static inline double min(double a, double b) { return fmin(a, b); } -static inline double max(double a, double b) { return fmax(a, b); } -static inline double min(float a, double b) { return fmin((double) a, b); } -static inline double min(double a, float b) { return fmin(a, (double) b); } -static inline double max(float a, double b) { return fmax((double) a, b); } -static inline double max(double a, float b) { return fmax(a, (double) b); } - -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline int __isnanf(float x) { return std::isnan(x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline int __isinff(float x) { return std::isinf(x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline int __finitef(float x) { return std::isfinite(x); } -#endif -static inline float rsqrtf(float x) { return 1.0f / sqrtf(x); } -static inline double rsqrt(double x) { return 1.0 / sqrt(x); } -static inline float rcbrtf(float x) { return 1.0f / cbrtf(x); } -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline float exp10f(float x) { return powf(10.0f, x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline void sincosf(float x, float* s, float* c) { *s = sinf(x); *c = cosf(x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline float __expf(float x) { return expf(x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline float __logf(float x) { return logf(x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline float __log2f(float x) { return log2f(x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline float __log10f(float x) { return log10f(x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline float __sinf(float x) { return sinf(x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline float __cosf(float x) { return cosf(x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline float __tanf(float x) { return tanf(x); } -#endif -#ifndef __GLIBC__ // glibc (with libstdc++/_GNU_SOURCE) already declares this name; the stub would clash with it -static inline float __powf(float x, float y) { return powf(x, y); } -#endif -static inline float __fdividef(float x, float y) { return x / y; } -static inline double __ddiv_rn(double x, double y) { return x / y; } -static inline float __saturatef(float x) { return x < 0.f ? 0.f : (x > 1.f ? 1.f : x); } -static inline float __frcp_rn(float x) { return 1.0f / x; } -static inline float __frcp_rz(float x) { return 1.0f / x; } -static inline float __frsqrt_rn(float x) { return 1.0f / sqrtf(x); } -static inline float __fsqrt_rn(float x) { return sqrtf(x); } -static inline float __fsqrt_rz(float x) { return sqrtf(x); } -static inline float __fdiv_rn(float x, float y) { return x / y; } -static inline float __fdiv_rz(float x, float y) { return x / y; } -static inline float __fadd_rn(float x, float y) { return x + y; } -static inline float __fadd_rz(float x, float y) { return x + y; } -static inline float __fadd_rd(float x, float y) { return x + y; } -static inline float __fadd_ru(float x, float y) { return x + y; } -static inline float __fsub_rn(float x, float y) { return x - y; } -static inline float __fsub_rz(float x, float y) { return x - y; } -static inline float __fmul_rn(float x, float y) { return x * y; } -static inline float __fmul_rz(float x, float y) { return x * y; } -static inline float __fmaf_rn(float x, float y, float z) { return fmaf(x, y, z); } -static inline float __fmaf_rz(float x, float y, float z) { return fmaf(x, y, z); } -static inline float __fmaf_rd(float x, float y, float z) { return fmaf(x, y, z); } -static inline float __fmaf_ru(float x, float y, float z) { return fmaf(x, y, z); } -static inline double __dadd_rn(double x, double y) { return x + y; } -static inline double __dmul_rn(double x, double y) { return x * y; } -static inline double __fma_rn(double x, double y, double z) { return fma(x, y, z); } -static inline double __dsqrt_rn(double x) { return sqrt(x); } -static inline float __double2float_rn(double x) { return (float) x; } -static inline float __double2float_rz(double x) { return (float) x; } -static inline int __float2int_rn(float x) { return (int) nearbyintf(x); } -static inline int __float2int_rz(float x) { return (int) x; } -static inline int __float2int_rd(float x) { return (int) floorf(x); } -static inline int __float2int_ru(float x) { return (int) ceilf(x); } -static inline unsigned __float2uint_rn(float x) { return (unsigned) nearbyintf(x); } -static inline unsigned __float2uint_rz(float x) { return (unsigned) x; } -static inline unsigned __float2uint_rd(float x) { return (unsigned) floorf(x); } -static inline unsigned __float2uint_ru(float x) { return (unsigned) ceilf(x); } -static inline long long __float2ll_rn(float x) { return (long long) nearbyintf(x); } -static inline long long __float2ll_rz(float x) { return (long long) x; } -static inline unsigned long long __float2ull_rz(float x) { return (unsigned long long) x; } -static inline unsigned long long __float2ull_rn(float x) { return (unsigned long long) nearbyintf(x); } -static inline long long __double2ll_rn(double x) { return (long long) nearbyint(x); } -static inline long long __double2ll_rz(double x) { return (long long) x; } -static inline int __double2int_rn(double x) { return (int) nearbyint(x); } -static inline int __double2int_rz(double x) { return (int) x; } -static inline float __int2float_rn(int x) { return (float) x; } -static inline float __int2float_rz(int x) { return (float) x; } -static inline float __uint2float_rn(unsigned x) { return (float) x; } -static inline float __uint2float_rz(unsigned x) { return (float) x; } -static inline float __ll2float_rn(long long x) { return (float) x; } -static inline float __ull2float_rn(unsigned long long x) { return (float) x; } -static inline double __int2double_rn(int x) { return (double) x; } -static inline double __uint2double_rn(unsigned x) { return (double) x; } -static inline double __ll2double_rn(long long x) { return (double) x; } -static inline int __float_as_int(float x) { int r; memcpy(&r, &x, 4); return r; } -static inline unsigned __float_as_uint(float x) { unsigned r; memcpy(&r, &x, 4); return r; } -static inline float __int_as_float(int x) { float r; memcpy(&r, &x, 4); return r; } -static inline float __uint_as_float(unsigned x) { float r; memcpy(&r, &x, 4); return r; } -static inline long long __double_as_longlong(double x) { long long r; memcpy(&r, &x, 8); return r; } -static inline double __longlong_as_double(long long x) { double r; memcpy(&r, &x, 8); return r; } -static inline int __double2hiint(double x) { long long r = __double_as_longlong(x); return (int) (r >> 32); } -static inline int __double2loint(double x) { long long r = __double_as_longlong(x); return (int) r; } -static inline double __hiloint2double(int hi, int lo) { return __longlong_as_double(((long long) hi << 32) | (unsigned) lo); } -static inline int __popc(unsigned x) { return __builtin_popcount(x); } -static inline int __popcll(unsigned long long x) { return __builtin_popcountll(x); } -static inline int __clz(int x) { return x ? __builtin_clz((unsigned) x) : 32; } -static inline int __clzll(long long x) { return x ? __builtin_clzll((unsigned long long) x) : 64; } -static inline int __ffs(int x) { return __builtin_ffs(x); } -static inline int __ffsll(long long x) { return __builtin_ffsll(x); } -static inline unsigned __brev(unsigned x) { unsigned r = 0; for (int i = 0; i < 32; ++i) r |= ((x >> i) & 1u) << (31 - i); return r; } -static inline unsigned __byte_perm(unsigned x, unsigned y, unsigned s) { - const unsigned long long v = ((unsigned long long) y << 32) | x; unsigned r = 0; - for (int i = 0; i < 4; ++i) r |= (unsigned) ((v >> (8 * ((s >> (4 * i)) & 7))) & 0xffu) << (8 * i); - return r; -} -static inline unsigned __funnelshift_l(unsigned lo, unsigned hi, unsigned s) { s &= 31; return s ? (hi << s) | (lo >> (32 - s)) : hi; } -static inline unsigned __funnelshift_lc(unsigned lo, unsigned hi, unsigned s) { s = s > 32 ? 32 : s; return s == 0 ? hi : (s == 32 ? lo : (hi << s) | (lo >> (32 - s))); } -static inline unsigned __funnelshift_r(unsigned lo, unsigned hi, unsigned s) { s &= 31; return s ? (lo >> s) | (hi << (32 - s)) : lo; } -static inline unsigned __umulhi(unsigned a, unsigned b) { return (unsigned) (((unsigned long long) a * b) >> 32); } -static inline int __mulhi(int a, int b) { return (int) (((long long) a * b) >> 32); } -static inline unsigned long long __umul64hi(unsigned long long a, unsigned long long b) { return (unsigned long long) (((__uint128_t) a * b) >> 64); } -static inline int __mul24(int a, int b) { return a * b; } -static inline unsigned __umul24(unsigned a, unsigned b) { return (a & 0xffffffu) * (b & 0xffffffu); } -static inline int __sad(int a, int b, unsigned c) { return (a > b ? a - b : b - a) + (int) c; } -static inline unsigned __usad(unsigned a, unsigned b, unsigned c) { return (a > b ? a - b : b - a) + c; } -static inline int __dp4a(int a, int b, int c) { - for (int i = 0; i < 4; ++i) c += (int) (signed char) (a >> (8 * i)) * (int) (signed char) (b >> (8 * i)); - return c; -} -static inline unsigned __dp4a(unsigned a, unsigned b, unsigned c) { - for (int i = 0; i < 4; ++i) c += ((a >> (8 * i)) & 0xffu) * ((b >> (8 * i)) & 0xffu); - return c; -} -static inline int __dp4a(int a, unsigned b, int c) { - for (int i = 0; i < 4; ++i) c += (int) (signed char) (a >> (8 * i)) * (int) ((b >> (8 * i)) & 0xffu); - return c; -} -static inline int __dp4a(unsigned a, int b, int c) { return __dp4a(b, a, c); } -static inline int __dp2a_lo(int a, int b, int c) { return c + (short) a * (signed char) b + (short) (a >> 16) * (signed char) (b >> 8); } -#define CUDA_STUB_SIMD4(name) static inline unsigned name(unsigned a, unsigned b) { unsigned r = 0; for (int i = 0; i < 4; ++i) { (void) i; } return a ^ b ^ r; } -CUDA_STUB_SIMD4(__vadd4) CUDA_STUB_SIMD4(__vsub4) CUDA_STUB_SIMD4(__vcmpeq4) CUDA_STUB_SIMD4(__vcmpne4) -CUDA_STUB_SIMD4(__vcmpgtu4) CUDA_STUB_SIMD4(__vcmpltu4) CUDA_STUB_SIMD4(__vcmpleu4) CUDA_STUB_SIMD4(__vcmpgeu4) -CUDA_STUB_SIMD4(__vcmpgts4) CUDA_STUB_SIMD4(__vcmplts4) CUDA_STUB_SIMD4(__vcmples4) CUDA_STUB_SIMD4(__vcmpges4) -CUDA_STUB_SIMD4(__vabsdiffu4) CUDA_STUB_SIMD4(__vabsdiffs4) CUDA_STUB_SIMD4(__vmaxu4) CUDA_STUB_SIMD4(__vminu4) -CUDA_STUB_SIMD4(__vmaxs4) CUDA_STUB_SIMD4(__vmins4) CUDA_STUB_SIMD4(__vsubss4) CUDA_STUB_SIMD4(__vaddss4) -CUDA_STUB_SIMD4(__vsubus4) CUDA_STUB_SIMD4(__vaddus4) CUDA_STUB_SIMD4(__vavgu4) CUDA_STUB_SIMD4(__vhaddu4) -#undef CUDA_STUB_SIMD4 -static inline unsigned __vabs4(unsigned a) { return a; } -static inline unsigned __vneg4(unsigned a) { return a; } -static inline unsigned __vnegss4(unsigned a) { return a; } -static inline unsigned __vsads4(unsigned a, unsigned b) { return a ^ b; } -static inline unsigned __vsadu4(unsigned a, unsigned b) { return a ^ b; } -static inline int __viaddmax_s32(int a, int b, int c) { return max(a + b, c); } -static inline int __vimax_s32(int a, int b) { return max(a, b); } -static inline int __vimin_s32(int a, int b) { return min(a, b); } - -// ---------------------------------------------------------------------------------------------------- synchronisation, warp, memory -#if !defined(__CUDA__) -void __syncthreads(); -#endif -int __syncthreads_count(int); -int __syncthreads_and(int); -int __syncthreads_or(int); -void __syncwarp(unsigned mask = 0xffffffffu); -void __threadfence(); -void __threadfence_block(); -void __threadfence_system(); -void __nanosleep(unsigned); -long long clock64(); -void __trap(); -void __brkpt(); -unsigned __activemask(); -unsigned __ballot_sync(unsigned, int); -int __any_sync(unsigned, int); -int __all_sync(unsigned, int); -unsigned __match_any_sync(unsigned, unsigned); -unsigned __match_any_sync(unsigned, int); -unsigned __match_any_sync(unsigned, float); -unsigned __match_all_sync(unsigned, unsigned, int*); -template T __shfl_sync(unsigned, T, int, int = 32); -template T __shfl_up_sync(unsigned, T, unsigned, int = 32); -template T __shfl_down_sync(unsigned, T, unsigned, int = 32); -template T __shfl_xor_sync(unsigned, T, int, int = 32); -template T __reduce_add_sync(unsigned, T); -template T __reduce_max_sync(unsigned, T); -template T __reduce_min_sync(unsigned, T); -template T __ldg(const T*); -template T __ldcg(const T*); -template T __ldca(const T*); -template T __ldcs(const T*); -template T __ldlu(const T*); -template T __ldcv(const T*); -template void __stcg(T*, T); -template void __stcs(T*, T); -template void __stwb(T*, T); -template void __stwt(T*, T); -void __prefetch_global_l1(const void*); -void __prefetch_global_l2(const void*); -bool __isShared(const void*); -bool __isGlobal(const void*); -bool __isConstant(const void*); -bool __isLocal(const void*); -unsigned long long __cvta_generic_to_shared(const void*); -unsigned long long __cvta_generic_to_global(const void*); -void* __cvta_shared_to_generic(unsigned long long); -void* __cvta_global_to_generic(unsigned long long); - -int atomicAdd(int*, int); -unsigned atomicAdd(unsigned*, unsigned); -unsigned long long atomicAdd(unsigned long long*, unsigned long long); -float atomicAdd(float*, float); -double atomicAdd(double*, double); -int atomicSub(int*, int); -unsigned atomicSub(unsigned*, unsigned); -int atomicExch(int*, int); -unsigned atomicExch(unsigned*, unsigned); -unsigned long long atomicExch(unsigned long long*, unsigned long long); -float atomicExch(float*, float); -int atomicMin(int*, int); -unsigned atomicMin(unsigned*, unsigned); -unsigned long long atomicMin(unsigned long long*, unsigned long long); -long long atomicMin(long long*, long long); -int atomicMax(int*, int); -unsigned atomicMax(unsigned*, unsigned); -unsigned long long atomicMax(unsigned long long*, unsigned long long); -long long atomicMax(long long*, long long); -unsigned atomicInc(unsigned*, unsigned); -unsigned atomicDec(unsigned*, unsigned); -int atomicCAS(int*, int, int); -unsigned atomicCAS(unsigned*, unsigned, unsigned); -unsigned long long atomicCAS(unsigned long long*, unsigned long long, unsigned long long); -unsigned short atomicCAS(unsigned short*, unsigned short, unsigned short); -int atomicAnd(int*, int); -unsigned atomicAnd(unsigned*, unsigned); -unsigned long long atomicAnd(unsigned long long*, unsigned long long); -int atomicOr(int*, int); -unsigned atomicOr(unsigned*, unsigned); -unsigned long long atomicOr(unsigned long long*, unsigned long long); -int atomicXor(int*, int); -unsigned atomicXor(unsigned*, unsigned); -unsigned long long atomicXor(unsigned long long*, unsigned long long); - -// ---------------------------------------------------------------------------------------------------- inline PTX -// check-cu.py turns `asm volatile("..." : outs : ins : clobbers)` into cuda_stub_asm(op0, op1, ...) so the operand -// expressions are still type-checked; the PTX text itself is never examined. -template inline void cuda_stub_asm(T&&...) {} -// check-cu.py turns `K<<>>(args)` into (cuda_stub_cfg(grid, block, smem, stream), K(args)). -struct cuda_stub_cfg_t {}; -template cuda_stub_cfg_t cuda_stub_cfg(A&&, B&&) { return {}; } -template cuda_stub_cfg_t cuda_stub_cfg(A&&, B&&, C&&) { return {}; } -template cuda_stub_cfg_t cuda_stub_cfg(A&&, B&&, C&&, D&&) { return {}; } - -#if defined(__CUDA__) -#pragma clang force_cuda_host_device end -#endif -#if defined(__CUDA__) -extern "C" unsigned __cudaPushCallConfiguration(dim3, dim3, size_t = 0, void* = nullptr); -extern "C" int cudaConfigureCall(dim3, dim3, size_t = 0, void* = nullptr); // older toolkit spelling, clang looks for either -#endif -// ---- device libm: __host__ __device__ statics so device code resolves expf(x) etc. (clang's own wrappers do the same) -#if defined(__CUDA__) -static __device__ inline float sinf(float x) { return __builtin_sinf(x); } -static __device__ inline float cosf(float x) { return __builtin_cosf(x); } -static __device__ inline float tanf(float x) { return __builtin_tanf(x); } -static __device__ inline float asinf(float x) { return __builtin_asinf(x); } -static __device__ inline float acosf(float x) { return __builtin_acosf(x); } -static __device__ inline float atanf(float x) { return __builtin_atanf(x); } -static __device__ inline float sinhf(float x) { return __builtin_sinhf(x); } -static __device__ inline float coshf(float x) { return __builtin_coshf(x); } -static __device__ inline float tanhf(float x) { return __builtin_tanhf(x); } -static __device__ inline float asinhf(float x) { return __builtin_asinhf(x); } -static __device__ inline float acoshf(float x) { return __builtin_acoshf(x); } -static __device__ inline float atanhf(float x) { return __builtin_atanhf(x); } -static __device__ inline float expf(float x) { return __builtin_expf(x); } -static __device__ inline float exp2f(float x) { return __builtin_exp2f(x); } -static __device__ inline float expm1f(float x) { return __builtin_expm1f(x); } -static __device__ inline float logf(float x) { return __builtin_logf(x); } -static __device__ inline float log2f(float x) { return __builtin_log2f(x); } -static __device__ inline float log10f(float x) { return __builtin_log10f(x); } -static __device__ inline float log1pf(float x) { return __builtin_log1pf(x); } -static __device__ inline float sqrtf(float x) { return __builtin_sqrtf(x); } -static __device__ inline float cbrtf(float x) { return __builtin_cbrtf(x); } -static __device__ inline float fabsf(float x) { return __builtin_fabsf(x); } -static __device__ inline float floorf(float x) { return __builtin_floorf(x); } -static __device__ inline float ceilf(float x) { return __builtin_ceilf(x); } -static __device__ inline float roundf(float x) { return __builtin_roundf(x); } -static __device__ inline float rintf(float x) { return __builtin_rintf(x); } -static __device__ inline float truncf(float x) { return __builtin_truncf(x); } -static __device__ inline float nearbyintf(float x) { return __builtin_nearbyintf(x); } -static __device__ inline float erff(float x) { return __builtin_erff(x); } -static __device__ inline float erfcf(float x) { return __builtin_erfcf(x); } -static __device__ inline float lgammaf(float x) { return __builtin_lgammaf(x); } -static __device__ inline float tgammaf(float x) { return __builtin_tgammaf(x); } -static __device__ inline float logbf(float x) { return __builtin_logbf(x); } -static __device__ inline float atan2f(float x, float y) { return __builtin_atan2f(x, y); } -static __device__ inline float powf(float x, float y) { return __builtin_powf(x, y); } -static __device__ inline float fmaxf(float x, float y) { return __builtin_fmaxf(x, y); } -static __device__ inline float fminf(float x, float y) { return __builtin_fminf(x, y); } -static __device__ inline float fmodf(float x, float y) { return __builtin_fmodf(x, y); } -static __device__ inline float copysignf(float x, float y) { return __builtin_copysignf(x, y); } -static __device__ inline float hypotf(float x, float y) { return __builtin_hypotf(x, y); } -static __device__ inline float remainderf(float x, float y) { return __builtin_remainderf(x, y); } -static __device__ inline float nextafterf(float x, float y) { return __builtin_nextafterf(x, y); } -static __device__ inline float fdimf(float x, float y) { return __builtin_fdimf(x, y); } -static __device__ inline double sin(double x) { return __builtin_sin(x); } -static __device__ inline double cos(double x) { return __builtin_cos(x); } -static __device__ inline double tan(double x) { return __builtin_tan(x); } -static __device__ inline double asin(double x) { return __builtin_asin(x); } -static __device__ inline double acos(double x) { return __builtin_acos(x); } -static __device__ inline double atan(double x) { return __builtin_atan(x); } -static __device__ inline double sinh(double x) { return __builtin_sinh(x); } -static __device__ inline double cosh(double x) { return __builtin_cosh(x); } -static __device__ inline double tanh(double x) { return __builtin_tanh(x); } -static __device__ inline double exp(double x) { return __builtin_exp(x); } -static __device__ inline double exp2(double x) { return __builtin_exp2(x); } -static __device__ inline double expm1(double x) { return __builtin_expm1(x); } -static __device__ inline double log(double x) { return __builtin_log(x); } -static __device__ inline double log2(double x) { return __builtin_log2(x); } -static __device__ inline double log10(double x) { return __builtin_log10(x); } -static __device__ inline double log1p(double x) { return __builtin_log1p(x); } -static __device__ inline double sqrt(double x) { return __builtin_sqrt(x); } -static __device__ inline double cbrt(double x) { return __builtin_cbrt(x); } -static __device__ inline double fabs(double x) { return __builtin_fabs(x); } -static __device__ inline double floor(double x) { return __builtin_floor(x); } -static __device__ inline double ceil(double x) { return __builtin_ceil(x); } -static __device__ inline double round(double x) { return __builtin_round(x); } -static __device__ inline double rint(double x) { return __builtin_rint(x); } -static __device__ inline double trunc(double x) { return __builtin_trunc(x); } -static __device__ inline double nearbyint(double x) { return __builtin_nearbyint(x); } -static __device__ inline double erf(double x) { return __builtin_erf(x); } -static __device__ inline double erfc(double x) { return __builtin_erfc(x); } -static __device__ inline double lgamma(double x) { return __builtin_lgamma(x); } -static __device__ inline double tgamma(double x) { return __builtin_tgamma(x); } -static __device__ inline double atan2(double x, double y) { return __builtin_atan2(x, y); } -static __device__ inline double pow(double x, double y) { return __builtin_pow(x, y); } -static __device__ inline double fmax(double x, double y) { return __builtin_fmax(x, y); } -static __device__ inline double fmin(double x, double y) { return __builtin_fmin(x, y); } -static __device__ inline double fmod(double x, double y) { return __builtin_fmod(x, y); } -static __device__ inline double copysign(double x, double y) { return __builtin_copysign(x, y); } -static __device__ inline double hypot(double x, double y) { return __builtin_hypot(x, y); } -static __device__ inline double remainder(double x, double y) { return __builtin_remainder(x, y); } -static __device__ inline float fmaf(float x, float y, float z) { return __builtin_fmaf(x, y, z); } -static __device__ inline double fma(double x, double y, double z) { return __builtin_fma(x, y, z); } -static __device__ inline float ldexpf(float x, int e) { return __builtin_ldexpf(x, e); } -static __device__ inline float frexpf(float x, int* e) { return __builtin_frexpf(x, e); } -static __device__ inline float scalbnf(float x, int e) { return __builtin_scalbnf(x, e); } -static __device__ inline long lroundf(float x) { return __builtin_lroundf(x); } -static __device__ inline long lrintf(float x) { return __builtin_lrintf(x); } -static __device__ inline int abs(int x) { return x < 0 ? -x : x; } -static __device__ inline long long llabs(long long x) { return x < 0 ? -x : x; } -static __device__ inline bool isnan(float x) { return __builtin_isnan(x); } -static __device__ inline bool isinf(float x) { return __builtin_isinf(x); } -static __device__ inline bool isfinite(float x) { return __builtin_isfinite(x); } -static __device__ inline bool isnan(double x) { return __builtin_isnan(x); } -static __device__ inline bool isinf(double x) { return __builtin_isinf(x); } -static __device__ inline bool isfinite(double x) { return __builtin_isfinite(x); } -static __device__ inline void* memcpy(void* d, const void* s, size_t n) { return __builtin_memcpy(d, s, n); } -static __device__ inline void* memset(void* d, int c, size_t n) { return __builtin_memset(d, c, n); } -static __device__ inline void* memmove(void* d, const void* s, size_t n) { return __builtin_memmove(d, s, n); } -static __device__ inline int memcmp(const void* a, const void* b, size_t n) { return __builtin_memcmp(a, b, n); } -extern "C" __device__ int vprintf(const char*, const char*); -template __device__ inline int cuda_stub_printf(const char*, A...) { return 0; } // check-cu.py rewrites printf( call sites to it -static __device__ inline bool signbit(float x) { return __builtin_signbit(x); } -#endif -#endif diff --git a/scripts/cuda-stubs/device_launch_parameters.h b/scripts/cuda-stubs/device_launch_parameters.h deleted file mode 100644 index 23af62ab..00000000 --- a/scripts/cuda-stubs/device_launch_parameters.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include "cuda_stub.h" diff --git a/scripts/cuda-stubs/literal_diff.py b/scripts/cuda-stubs/literal_diff.py deleted file mode 100755 index 478326c5..00000000 --- a/scripts/cuda-stubs/literal_diff.py +++ /dev/null @@ -1,205 +0,0 @@ -#!/usr/bin/env python3 -"""Function-level literalness check of a ported .cu against the Original CUDA sources (engine/strata/src + include). - -usage: scripts/cuda-stubs/literal_diff.py crates/cuda-driver/src/.cu [-v] - SOURCES=1 ... print which Original files the matched functions come from (flag-policy audit) - RESID=n ... show n residual port lines that exist nowhere in the Original (default 60) - -Comments and whitespace are normalised away; each port function is matched to an Original function with an identical -body (LITERAL, possibly renamed), else to the closest one and the remaining diff is printed (DIFFERS). Wrappers -(extern "C" entries, baked template arguments) show up as DIFFERS and must be justified by hand.""" -# normalise a CUDA source: strip comments, collapse whitespace, one statement per line (prep for diff) -import re, sys -def norm(t): - t = re.sub(r'/\*.*?\*/', ' ', t, flags=re.S) - out = [] - for line in t.split('\n'): - # strip // comments (naive: not inside strings; sources have none with //) - i = line.find('//') - while i >= 0 and line[:i].count('"') % 2 == 1: - i = line.find('//', i + 1) - if i >= 0: line = line[:i] - out.append(line) - t = '\n'.join(out) - lines = [] - for line in t.split('\n'): - if line.lstrip().startswith('#'): - lines.append('\x00' + line.strip() + '\x00') - else: - lines.append(line) - t = '\n'.join(lines) - res = [] - for chunk in re.split(r'(\x00[^\x00]*\x00)', t): - if chunk.startswith('\x00'): - res.append('\n' + re.sub(r'\s+', ' ', chunk.strip('\x00')) + '\n') - else: - c = re.sub(r'\s+', ' ', chunk) - c = re.sub(r'\s*([;{}])\s*', r'\1\n', c) - c = re.sub(r'\s*,\s*', ', ', c) - res.append(c) - t = ''.join(res) - t = re.sub(r'\n+', '\n', t) - # drop trailing spaces - return '\n'.join(l.strip() for l in t.split('\n') if l.strip()) + '\n' - -"""Function-level literalness check of a port .cu against the Original corpus. -usage: fcmp.py port.cu [--orig file ...] [-v] (corpus default: engine/strata/src + include)""" -import re, sys, os, difflib, collections, glob, pickle, tempfile -ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) - -def extract(text): - """-> list of (name, head, body, order) for every function definition in normalised text""" - funcs = [] - stack = [] # kinds - i = 0; n = len(text); head_start = 0 - pend = [] # indices of open braces with info - while i < n: - c = text[i] - if c == '"' or c == "'": - j = i + 1 - while j < n and text[j] != c: - j += 2 if text[j] == '\\' else 1 - i = j + 1; continue - if c == '\n' and text[head_start:i].lstrip().startswith('#'): - head_start = i + 1; i += 1; continue - if c in ';}': - if c == '}': - if stack: - kind, start, hd = stack.pop() - if kind == 'fn': - funcs.append((hd[0], hd[1], text[start:i + 1].strip())) - head_start = i + 1; i += 1; continue - if c == '{': - head = text[head_start:i].strip() - head = re.sub(r'(?m)^#.*$', '', head).strip() - if re.match(r'^(inline\s+)?namespace\b', head) or re.match(r'^extern\s+"C"$', head) or re.match(r'^(template\s*<.*?>\s*)?(typedef\s+)?(struct|class|union|enum)\b', head, re.S) or head.endswith('=') or head.endswith('='): - stack.append(('ns', i, None)) - elif '(' in head and re.search(r'\)\s*(const|noexcept|__restrict__)*\s*$', head) and all(k[0] == 'ns' for k in stack) and not re.match(r'^(if|for|while|switch|else|do)\b', head): - # function head: name = identifier before first '(' that is at paren depth 0 and not an attribute macro - m = re.search(r'([~\w:]+|operator\s*\(\s*\))\s*\(', re.sub(r'__launch_bounds__\s*\([^)]*\)', '', head)) - name = m.group(1) if m else '?' - params = head[head.find('(', m.end() - 1 if m else 0):] if m else head - stack.append(('fn', i, (name.split('::')[-1], head))) - else: - stack.append(('blk', i, None)) - head_start = i + 1; i += 1; continue - i += 1 - return funcs - -def load(path): - return extract(norm(open(path, encoding='utf-8', errors='replace').read())) - -def body_of(f): - name, head, full = f - return full[full.index('{'):] # body from first brace (head excluded, kept separately) - -def params_of(head, name): - k = head.find(name + '(') if name + '(' in head else head.find('(') - k2 = head.find('(', k) - d = 0; j = k2 - while j < len(head): - if head[j] == '(': d += 1 - elif head[j] == ')': - d -= 1 - if d == 0: break - j += 1 - return head[k2:j + 1], head[:k] + head[j + 1:] - -def corpus(): - cache = os.path.join(tempfile.gettempdir(), '_leleka_literal_corpus.pkl') - paths = [] - for base in ('engine/strata/src', 'engine/strata/include'): - for dp, dn, fn in os.walk(os.path.join(ROOT, base)): - for f in fn: - if f.endswith(('.cu', '.cuh', '.hpp', '.h', '.cpp')): paths.append(os.path.join(dp, f)) - paths.sort() - key = [(p, os.path.getmtime(p)) for p in paths] - if os.path.exists(cache): - k, data = pickle.load(open(cache, 'rb')) - if k == key: return data - data = [] - for p in paths: - for f in load(p): - data.append((os.path.relpath(p, ROOT), f)) - pickle.dump((key, data), open(cache, 'wb')) - return data - -def main(): - a = sys.argv[1:] - verbose = '-v' in a; a = [x for x in a if x != '-v'] - port = a[0] - data = corpus() - if '--orig' in a: - extra = a[a.index('--orig') + 1:] - data = [(os.path.relpath(p, ROOT), f) for p in [os.path.join(ROOT, e) for e in extra] for f in load(p)] - byname = collections.defaultdict(list); bybody = collections.defaultdict(list) - for src, f in data: - byname[f[0]].append((src, f)); bybody[re.sub(r'\s+', '', body_of(f))].append((src, f)) - res = [] - for f in load(os.path.join(ROOT, port) if not os.path.isabs(port) else port): - name, head, full = f - pb = body_of(f); pbn = re.sub(r'\s+', '', pb) - pp, ppre = params_of(head, name) - hit = bybody.get(pbn) - if hit: - same_params = [h for h in hit if re.sub(r'\s+', '', params_of(h[1][1], h[1][0])[0]) == re.sub(r'\s+', '', pp)] - if same_params: - s, o = same_params[0] - tag = 'LITERAL' if o[0] == name else 'LITERAL(renamed %s)' % o[0] - res.append((name, tag, s + ('' if len(hit) == 1 else ' +%d' % (len(hit) - 1)), None)); continue - s, o = hit[0] - res.append((name, 'BODY-LITERAL, PARAMS DIFFER from ' + o[0], s, '- ' + params_of(o[1], o[0])[0] + '\n+ ' + pp)); continue - # best candidate: same stripped name, else similarity - stem = re.sub(r'^(leleka_|original_|mtp_|native_head_)+', '', name) - cands = [c for c in byname.get(name, [])] or [c for k, v in byname.items() if k.endswith(stem) or stem.endswith(k) for c in v] - if not cands: - toks = set(re.findall(r'\w+', pb)) - sc = [] - for src, o in data: - ot = set(re.findall(r'\w+', body_of(o))) - if not ot: continue - j = len(toks & ot) / len(toks | ot) - sc.append((j, src, o)) - sc.sort(key=lambda x: -x[0]) - cands = [(s, o) for j, s, o in sc[:3] if j > 0.5] - best = None - for s, o in cands: - r = difflib.SequenceMatcher(None, body_of(o), pb, autojunk=False).quick_ratio() - if best is None or r > best[0]: best = (r, s, o) - if best is None: - res.append((name, 'NO-ORIGINAL-FOUND', '', None)); continue - r, s, o = best - # refine ratio on the best by line-diff - ol = body_of(o).split('\n'); pl = pb.split('\n') - d = list(difflib.unified_diff(ol, pl, 'orig:' + s + ':' + o[0], 'port:' + name, n=1, lineterm='')) - pd = params_of(o[1], o[0])[0] - if re.sub(r'\s+', '', pd) != re.sub(r'\s+', '', pp): - d = ['PARAMS:', '- ' + pd, '+ ' + pp] + d - res.append((name, 'DIFFERS from %s::%s' % (s, o[0]), s, '\n'.join(d))) - if os.environ.get('SOURCES'): - cnt = collections.Counter() - for name, tag, src, d in res: - if tag.startswith('LITERAL') or tag.startswith('BODY-LIT') or tag.startswith('DIFFERS'): - cnt[src.split(' +')[0]] += 1 - print(dict(cnt)); return - # residual: port lines outside the LITERAL functions that exist nowhere in the Original corpus - ptxt = norm(open(os.path.join(ROOT, port) if not os.path.isabs(port) else port, encoding='utf-8', errors='replace').read()) - for f in load(os.path.join(ROOT, port) if not os.path.isabs(port) else port): - if any(r[0] == f[0] and r[1].startswith('LITERAL') for r in res): - ptxt = ptxt.replace(f[2], '').replace(f[1], '') - allorig = set() - paths_all = [] - for base in ('engine/strata/src', 'engine/strata/include', 'engine/strata/third_party/ggml'): - for dp, dn, fn in os.walk(os.path.join(ROOT, base)): - for fnm in fn: - if fnm.endswith(('.cu', '.cuh', '.hpp', '.h', '.cpp')): paths_all.append(os.path.join(dp, fnm)) - for p in paths_all: - for l in norm(open(p, encoding='utf-8', errors='replace').read()).split('\n'): allorig.add(re.sub(r'\s+', '', l)) - resid = [l for l in ptxt.split('\n') if l.strip() and re.sub(r'\s+', '', l) not in allorig] - for name, tag, src, d in res: - print('%-60s %s [%s]' % (name, tag, src)) - if d and (verbose or tag.startswith('DIFFERS') or tag.startswith('BODY-LIT')): - print('\n'.join(' ' + l for l in d.split('\n')[:80])) - print('--- residual port lines not found anywhere in the Original (%d):' % len(resid)) - for l in resid[:int(os.environ.get('RESID', '60'))]: print(' | ' + l[:200]) -main() diff --git a/scripts/cuda-stubs/mma.h b/scripts/cuda-stubs/mma.h deleted file mode 100644 index 474a8f5c..00000000 --- a/scripts/cuda-stubs/mma.h +++ /dev/null @@ -1,20 +0,0 @@ -// Stub of (nvcuda::wmma): fragment types only, enough for declarations to parse. -#pragma once -#include "cuda_stub.h" -#if defined(__CUDA__) -#pragma clang force_cuda_host_device begin -#endif -namespace nvcuda { namespace wmma { -struct row_major {}; struct col_major {}; -struct matrix_a {}; struct matrix_b {}; struct accumulator {}; -enum layout_t { mem_row_major, mem_col_major }; -template struct fragment { T x[16]; int num_elements = 16; }; -template void fill_fragment(F&, const T&); -template void load_matrix_sync(F&, const T*, unsigned); -template void load_matrix_sync(F&, const T*, unsigned, layout_t); -template void store_matrix_sync(T*, const F&, unsigned, layout_t); -template void mma_sync(D&, const A&, const B&, const C&); -} } -#if defined(__CUDA__) -#pragma clang force_cuda_host_device end -#endif diff --git a/scripts/cuda-stubs/vector_types.h b/scripts/cuda-stubs/vector_types.h deleted file mode 100644 index 23af62ab..00000000 --- a/scripts/cuda-stubs/vector_types.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include "cuda_stub.h" diff --git a/scripts/decode-sm120/make_iq_prefix.py b/scripts/decode-sm120/make_iq_prefix.py deleted file mode 100644 index 0afb2a8f..00000000 --- a/scripts/decode-sm120/make_iq_prefix.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python3 -"""Regenerate (or --check) crates/cuda-driver/src/sm120_iq_prefix.cuh: lines 1..END of engine/strata/src/kernels/cuda/iq_kernels.cu. - -END is the line before the `dequant (dequantize.cuh)` banner, i.e. everything up to and including native_gu_swiglu_kernel. The whole file instantiates ~60 MB of PTX -through its host launchers (past the 16 MiB asset limit); the prefix holds every trait, row dot and q8_1_store the fused expert kernel needs and no launcher. -The prefix is byte for byte the upstream text (plus a two-line header), so it is checked against the engine tree: --check fails when the pinned file changed. -""" -import sys - -SRC = "engine/strata/src/kernels/cuda/iq_kernels.cu" -DST = "crates/cuda-driver/src/sm120_iq_prefix.cuh" -BANNER = "// ---------------------------------------------------------------- dequant (dequantize.cuh)" -HEADER = ("// GENERATED by scripts/decode-sm120/make_iq_prefix.py from " + SRC + " (the pinned upstream, docs/upstream.md): the file up to the dequant banner,\n" - "// unchanged. Do not edit; `make_iq_prefix.py --check` compares it with the engine tree. Opens `namespace strata::kernels { namespace {` and leaves both open.\n") - -lines = open(SRC, newline="").read().split("\n") -end = next(i for i, l in enumerate(lines) if l.rstrip("\r") == BANNER) -want = HEADER + "\n".join(lines[:end]) + "\n" -if "--check" in sys.argv: - have = open(DST, newline="").read() - sys.exit(0 if have == want else "sm120_iq_prefix.cuh is stale against " + SRC) -open(DST, "w", newline="").write(want) -print("wrote", DST, end, "upstream lines") diff --git a/scripts/dev/rename_strata_names.py b/scripts/dev/rename_strata_names.py index c9ea7454..22fbefca 100644 --- a/scripts/dev/rename_strata_names.py +++ b/scripts/dev/rename_strata_names.py @@ -5,7 +5,7 @@ strata-desktop-core -> leleka-engine-host (the crate of desktop-core/: it hosts the engine process leleka-inference and the node, pool and gateway services around it) -The `STRATA_*` environment variables stay (the language shared with the Original). Not touched: `engine/strata` (the +The `STRATA_*` environment variables stay (the language shared with the Original). Not touched: `third_party/strata/` (the Original, including its Python package `strata_control`), the experiment records and measured data, `*.patch` files and `docs/upstream/` (diffs against the Original), `Cargo.lock` (regenerate it with `cargo metadata --offline`). The underscore forms (`strata_control`, `strata_desktop_core`) are the crate identifiers and change in `.rs` and `.toml` @@ -16,7 +16,7 @@ import subprocess import sys SKIP_PREFIXES = ( - "engine/strata/", "experiments/", "artifacts/", "docs/experiments/", "docs/e2e-data/", "benchmarks/e2e-data/", "docs/upstream/", + "third_party/strata/", "experiments/", "artifacts/", "docs/experiments/", "docs/e2e-data/", "benchmarks/e2e-data/", "docs/upstream/", "docs/ledger", "Cargo.lock", "scripts/dev/rename_strata_names.py", ) HYPHEN = (("strata-next", "leleka-api"), ("strata-control", "leleka-control-plane"), diff --git a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/build.sh b/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/build.sh deleted file mode 100755 index 2fdd752b..00000000 --- a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/build.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env bash -# Builds the micro-benchmark on the 5090 server (no GPU needed). Run from anywhere: -# bash build.sh /data/leleka-e2e/spd-gap/microbench/verify-hc-down-kernel-microbench-vs-upstream -# Layout under that directory (see MANIFEST there): -# upstream-src/ git archive of strata-upstream/main (include/, src/kernels/cuda/fused_gr.cu, s26_tsum.cuh), unmodified -# ours-src/ git archive of the repository commit (crates/cuda-driver/src/chain_window.{cu,ptx}, engine/strata/include) -# harness/ this directory of the repository (scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/): -# microbench.cu, upstream_down_launch.inc, compare_outputs.inc, summarize.py, build.sh, and -# ours-shim/ = the 112-byte FusedGrArgs header the sealed chain kernels were built against (see its comment) -# build/ microbench (binary), chain_window.cubin, chain_window.regen.ptx -set -euo pipefail -ROOT=${1:?directory} -NVCC=${NVCC:-$HOME/cuda-toolkits/13.2.2/bin/nvcc} -cd "$ROOT/build" -# 1. our kernels from source with the flags of extra-seal-plan.json (chain_window): PTX (to check it is the sealed one) and a cubin -OURS_FLAGS="-O3 -arch=sm_120 -std=c++17 --fmad=true --ftz=false -I$ROOT/harness/ours-shim -I$ROOT/ours-src/engine/strata/include" -nice -n 10 "$NVCC" -ptx $OURS_FLAGS "$ROOT/ours-src/crates/cuda-driver/src/chain_window.cu" -o chain_window.regen.ptx -nice -n 10 "$NVCC" -cubin $OURS_FLAGS "$ROOT/ours-src/crates/cuda-driver/src/chain_window.cu" -o chain_window.cubin -# the regenerated PTX equals the sealed one except for the hash in the mangled anonymous-namespace names and the sampler kernel (not used here) -norm() { grep -v '^//' "$1" | tr -d '\0' | sed -E 's/GLOBAL__N__[0-9a-f]+_/GLOBAL__N__X_/g'; } -diff <(norm chain_window.regen.ptx) <(norm "$ROOT/ours-src/crates/cuda-driver/src/chain_window.ptx") | grep -c '^[<>]' | sed 's/^/regenerated-vs-sealed PTX: differing lines (mangled-name hash excluded): /' || true -# 2. the micro-benchmark: upstream fused_gr.cu included whole, flags of a Release build for compute capability 12.0 (cmake/backends/cuda.cmake: architecture 120) -nice -n 10 "$NVCC" -O3 -DNDEBUG -std=c++17 -arch=sm_120 -diag-suppress 128 -I"$ROOT/upstream-src/include" -I"$ROOT/upstream-src/src/kernels/cuda" -I"$ROOT/harness" \ - "$ROOT/harness/microbench.cu" -o microbench -lcuda -ls -l microbench chain_window.cubin diff --git a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/compare_outputs.inc b/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/compare_outputs.inc deleted file mode 100644 index 9301ad1c..00000000 --- a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/compare_outputs.inc +++ /dev/null @@ -1,115 +0,0 @@ -// Included by microbench.cu inside namespace strata::kernels::microbench: the byte-level comparison of the outputs, per window rows T. -// -// A. upstream down kernel alone, masks 0 / 5 / 133: `part` and `ssg` (its own output buffers) byte for byte against mask 0 -// (upstream claims bitwise: gr_v3_screen), then through mb_finalize_down the quantities ours writes: lo, inject_out, rs. -// B. ours down alone (chain_gr_split + chain_gr_down_t2w8_nb4): sealed PTX against the nvcc cubin byte for byte (lo, inject_out, rs). -// C. ours (sealed PTX) against each upstream mask: lo, inject_out, rs (the down stage's result), as bit differences, largest absolute / -// relative difference and largest distance in units in the last place. -// D. the whole read (ours split+down+up8, upstream fused_gr_read_multi = gr_down_v3 + gr_up_v3): R (updated in place), rs, inject_out, mixed. -// Ours and upstream do NOT sum the 10240 products of a dot in the same order (ours: the activations normalised by the split kernel, tiles in -// order, one warp row; upstream: per stream on unnormalised values, scaled afterwards), so bitwise equality is not expected: the numbers are the answer. -struct Diff { size_t n = 0, bits = 0, nonfinite_a = 0, nonfinite_b = 0; double max_abs = 0, max_rel = 0; long long max_ulp = 0; }; -static long long ordered_bits(float x) { int32_t i; std::memcpy(&i, &x, 4); return i < 0 ? (long long) INT32_MIN - i : (long long) i; } -static Diff diff_floats(const std::vector& a, const std::vector& b) { - Diff d; d.n = a.size(); - for (size_t i = 0; i < a.size(); ++i) { - uint32_t ua, ub; std::memcpy(&ua, &a[i], 4); std::memcpy(&ub, &b[i], 4); - d.nonfinite_a += !std::isfinite(a[i]); d.nonfinite_b += !std::isfinite(b[i]); - if (ua == ub) continue; - ++d.bits; - const double abs = std::fabs((double) a[i] - (double) b[i]), mag = std::max(std::fabs((double) a[i]), std::fabs((double) b[i])); - d.max_abs = std::max(d.max_abs, abs); - if (mag > 0) d.max_rel = std::max(d.max_rel, abs / mag); - d.max_ulp = std::max(d.max_ulp, std::llabs(ordered_bits(a[i]) - ordered_bits(b[i]))); - } - return d; -} -static std::vector fetch(const float* p, size_t n) { std::vector v(n); CU_RT(cudaMemcpy(v.data(), p, n * 4, cudaMemcpyDeviceToHost)); return v; } -static void print_diff(int T, const char* what, const char* a_name, const char* b_name, const Diff& d) { - std::printf("DIFF T=%d %-12s %-34s vs %-34s words %6zu differing %6zu (%6.2f%%) max_abs %.3e max_rel %.3e max_ulp %lld nonfinite %zu/%zu\n", T, what, a_name, b_name, d.n, d.bits, - 100.0 * (double) d.bits / (double) std::max(d.n, 1), d.max_abs, d.max_rel, d.max_ulp, d.nonfinite_a, d.nonfinite_b); -} - -struct DownResult { std::vector part, ssg, lo, inject, rs; }; -struct ReadResult { std::vector lo, inject, rs, R, mixed; }; - -static int compare_outputs(const Options& o, Context& c, bool have_cubin, cudaStream_t s) { - int unexpected = 0; - const int masks[3] = {0, 5, 133}; - const char* mask_name[3] = {"upstream_mask0", "upstream_mask5", "upstream_mask133"}; - Work pu[3], po, pc; - float *d_lo[3], *d_inj[3], *d_rs[3]; - for (int i = 0; i < 3; ++i) { pu[i] = new_work(c.in); d_lo[i] = dev_floats(kTokensMax * LR); d_inj[i] = dev_floats(kTokensMax * HC); d_rs[i] = dev_floats(kTokensMax * HC); } - po = new_work(c.in); pc = new_work(c.in); - const WeightSet& ws = c.sets[0]; - for (int T = o.tmin; T <= o.tmax; ++T) { - std::printf("CORRECTNESS T=%d (apply=1, w_inject on, weight set 0, seed 7)\n", T); - DownResult up[3]; - for (int i = 0; i < 3; ++i) { // A - reset_work(pu[i], c.in); - const GrMulti m = upstream_multi(T, pu[i], ws, c.in); - mb_launch_upstream_down(masks[i], T, m, mb_part(pu[i].scratch), mb_ssg(pu[i].scratch, T), s); - mb_finalize_down<<<1, THREADS, 0, s>>>(m, mb_part(pu[i].scratch), mb_ssg(pu[i].scratch, T), d_lo[i], d_inj[i], d_rs[i]); - CU_RT(cudaStreamSynchronize(s)); - up[i] = {fetch(mb_part(pu[i].scratch), (size_t) T * HC * PR), fetch(mb_ssg(pu[i].scratch, T), (size_t) T * HC), fetch(d_lo[i], (size_t) T * LR), - fetch(d_inj[i], (size_t) T * HC), fetch(d_rs[i], (size_t) T * HC)}; - } - for (int i = 1; i < 3; ++i) { - const Diff dp = diff_floats(up[i].part, up[0].part), ds = diff_floats(up[i].ssg, up[0].ssg); - print_diff(T, "part", mask_name[i], mask_name[0], dp); print_diff(T, "ssg", mask_name[i], mask_name[0], ds); - unexpected += (dp.bits != 0) + (ds.bits != 0); - } - ReadResult ours[2]; // B: 0 = sealed PTX, 1 = cubin - for (int k = 0; k < (have_cubin ? 2 : 1); ++k) { - Work& w = k == 0 ? po : pc; - const OursKernels& kern = k == 0 ? c.ptx : c.cubin; - reset_work(w, c.in); - const OursByValue m = ours_multi(T, w, ws, c.in); - ours_launch(kern.split, m, ours_split_grid(T), 0, s); - ours_launch(kern.down, m, ours_down_grid(T), ours_down_shared(T), s); - CU_RT(cudaStreamSynchronize(s)); - ours[k].lo = fetch(w.lo, (size_t) T * LR); ours[k].inject = fetch(w.inject_out, (size_t) T * HC); ours[k].rs = fetch(w.rs, (size_t) T * HC); - } - if (have_cubin) { - const char* a = "ours_sealed_ptx"; const char* b = "ours_nvcc_cubin"; - const Diff dl = diff_floats(ours[0].lo, ours[1].lo), di = diff_floats(ours[0].inject, ours[1].inject), dr = diff_floats(ours[0].rs, ours[1].rs); - print_diff(T, "lo", a, b, dl); print_diff(T, "inject_out", a, b, di); print_diff(T, "rs", a, b, dr); - unexpected += (dl.bits != 0) + (di.bits != 0) + (dr.bits != 0); - } - for (int i = 0; i < 3; ++i) { // C - print_diff(T, "lo", "ours_sealed_ptx", mask_name[i], diff_floats(ours[0].lo, up[i].lo)); - print_diff(T, "inject_out", "ours_sealed_ptx", mask_name[i], diff_floats(ours[0].inject, up[i].inject)); - print_diff(T, "rs", "ours_sealed_ptx", mask_name[i], diff_floats(ours[0].rs, up[i].rs)); - } - // D: the whole read - Work& wr = po; - reset_work(wr, c.in); - const OursByValue m = ours_multi(T, wr, ws, c.in); - ours_launch(c.ptx.split, m, ours_split_grid(T), 0, s); ours_launch(c.ptx.down, m, ours_down_grid(T), ours_down_shared(T), s); ours_launch(c.ptx.up8, m, ours_up8_grid(), 0, s); - CU_RT(cudaStreamSynchronize(s)); - const ReadResult whole_ours{fetch(wr.lo, (size_t) T * LR), fetch(wr.inject_out, (size_t) T * HC), fetch(wr.rs, (size_t) T * HC), fetch(wr.R, (size_t) T * D), fetch(wr.mixed, (size_t) T * N)}; - ReadResult whole_up[3]; - for (int i = 0; i < 3; ++i) { - reset_work(pu[i], c.in); - FusedGrArgs a[kTokensMax]; - for (int t = 0; t < T; ++t) a[t] = upstream_args(t, pu[i], ws, c.in); - fused_gr_v3_pf(masks[i]); - fused_gr_read_multi(a, T, pu[i].scratch, (void*) s); - CU_RT(cudaStreamSynchronize(s)); - whole_up[i] = {{}, fetch(pu[i].inject_out, (size_t) T * HC), fetch(pu[i].rs, (size_t) T * HC), fetch(pu[i].R, (size_t) T * D), fetch(pu[i].mixed, (size_t) T * N)}; - print_diff(T, "rs(real up)", "ours_pipeline", mask_name[i], diff_floats(whole_ours.rs, whole_up[i].rs)); - print_diff(T, "inject(real)", "ours_pipeline", mask_name[i], diff_floats(whole_ours.inject, whole_up[i].inject)); - print_diff(T, "R updated", "ours_pipeline", mask_name[i], diff_floats(whole_ours.R, whole_up[i].R)); - print_diff(T, "mixed", "ours_pipeline", mask_name[i], diff_floats(whole_ours.mixed, whole_up[i].mixed)); - if (i > 0) { - const Diff dm = diff_floats(whole_up[i].mixed, whole_up[0].mixed), dr = diff_floats(whole_up[i].R, whole_up[0].R); - print_diff(T, "mixed", mask_name[i], mask_name[0], dm); print_diff(T, "R updated", mask_name[i], mask_name[0], dr); - unexpected += (dm.bits != 0) + (dr.bits != 0); - } - } - const Diff nf = diff_floats(whole_ours.mixed, whole_ours.mixed); - unexpected += (int) nf.nonfinite_a; - } - std::printf("CORRECTNESS summary: %d unexpected (upstream masks not equal to each other, ptx vs cubin differing, or non-finite outputs); ours-vs-upstream differences are data, not counted\n", unexpected); - return unexpected; -} diff --git a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/microbench.cu b/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/microbench.cu deleted file mode 100644 index 9dc3694e..00000000 --- a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/microbench.cu +++ /dev/null @@ -1,356 +0,0 @@ -// Kernel micro-benchmark: upstream Strata's hyper-connection down kernel (gr_down_v3_kernel, STRATA_GR_V3_PF masks 0 / 5 / 133) against -// our chain_gr_down_t2w8_nb4 (sealed PTX through the driver API, as the product loads it; and the same source built by nvcc), window -// rows T = 1..8, same random inputs. -// -// One translation unit: upstream's fused_gr.cu is #included whole (unmodified, from git object strata-upstream/main), so the kernels, the -// geometry constants and the launch helpers are upstream's own. -#include - -#include "fused_gr.cu" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace strata::kernels { -// defined in upstream's verify_kernels.cu (timestamp kernel for its profile windows); fused_gr.cu only calls it when a stamp buffer is passed, which this harness never does -void gpu_stamp(unsigned long long*, int, void*) {} -namespace microbench { - -#define CU_RT(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { std::fprintf(stderr, "%s:%d %s: %s\n", __FILE__, __LINE__, #x, cudaGetErrorString(e_)); std::exit(2); } } while (0) -#define CU_DRV(x) do { CUresult r_ = (x); if (r_ != CUDA_SUCCESS) { const char* m_ = "?"; cuGetErrorString(r_, &m_); std::fprintf(stderr, "%s:%d %s: %s\n", __FILE__, __LINE__, #x, m_); std::exit(2); } } while (0) - -#include "upstream_down_launch.inc" - -constexpr int kTokensMax = kFusedGrMaxT; // 8 -constexpr int kOursWords = 114; // GrMulti of the sealed chain kernels: 8 x 14 words of FusedGrArgs (112 B), xn, T = 912 bytes -struct OursByValue { uint64_t w[kOursWords]; }; -static_assert(sizeof(OursByValue) == 912, "GrMulti of the sealed chain kernels"); -__global__ void __launch_bounds__(THREADS) mb_empty_ours_shape(OursByValue m) { if (m.w[113] == ~0ull) *reinterpret_cast(m.w[10]) = 0.0f; } -__global__ void mb_spin_ns(unsigned long long ns) { - unsigned long long t0, t; - asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t0)); - do { asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); } while (t - t0 < ns); -} - -static uint16_t bf16_bits(float x) { uint32_t u; std::memcpy(&u, &x, 4); return (uint16_t) ((u + 0x7fff + ((u >> 16) & 1)) >> 16); } - -struct WeightSet { uint16_t *down, *up, *inject; float* norm; }; -struct Work { float *R, *lo, *rs, *inject_out, *mixed, *scratch; }; -struct Inputs { float *bo, *inj; std::vector R0; }; - -static float* dev_floats(size_t n) { float* p; CU_RT(cudaMalloc((void**) &p, n * 4)); CU_RT(cudaMemset(p, 0xff, n * 4)); return p; } -static Work new_work(const Inputs& in) { - Work w{dev_floats((size_t) kTokensMax * D), dev_floats((size_t) kTokensMax * LR), dev_floats((size_t) kTokensMax * HC), dev_floats((size_t) kTokensMax * HC), - dev_floats((size_t) kTokensMax * N), dev_floats((size_t) kTokensMax * D * 4)}; - CU_RT(cudaMemcpy(w.R, in.R0.data(), in.R0.size() * 4, cudaMemcpyHostToDevice)); - CU_RT(cudaDeviceSynchronize()); // see reset_work: the memsets of dev_floats are on the default stream - return w; -} -static void reset_work(const Work& w, const Inputs& in) { - CU_RT(cudaMemcpy(w.R, in.R0.data(), in.R0.size() * 4, cudaMemcpyHostToDevice)); - CU_RT(cudaMemset(w.lo, 0xff, kTokensMax * LR * 4)); CU_RT(cudaMemset(w.rs, 0xff, kTokensMax * HC * 4)); - CU_RT(cudaMemset(w.inject_out, 0xff, kTokensMax * HC * 4)); CU_RT(cudaMemset(w.mixed, 0xff, (size_t) kTokensMax * N * 4)); - CU_RT(cudaMemset(w.scratch, 0xff, (size_t) kTokensMax * D * 4 * 4)); - // The copies and memsets above run on the legacy default stream and the kernels on `s`, a non-blocking stream: the two are NOT ordered by the - // runtime, so a poison memset could land after (or beside) the kernel that was meant to overwrite it. That race, not the input values, made the - // first run's outputs NaN (0xffffffff). Wait for the poison before any launch. - CU_RT(cudaDeviceSynchronize()); -} - -static FusedGrArgs upstream_args(int t, const Work& w, const WeightSet& ws, const Inputs& in) { - FusedGrArgs a; - a.R = w.R + (size_t) t * D; a.R_out = w.R + (size_t) t * D; a.apply = true; - a.bo_prev = in.bo + (size_t) t * N; a.inj_prev = in.inj + (size_t) t * HC; - a.w_norm = ws.norm; a.w_down = ws.down; a.w_up = ws.up; a.w_inject = ws.inject; - a.lo = w.lo + (size_t) t * LR; a.rs = w.rs + (size_t) t * HC; a.inject_out = w.inject_out + (size_t) t * HC; a.mixed = w.mixed + (size_t) t * N; - return a; -} -static GrMulti upstream_multi(int T, const Work& w, const WeightSet& ws, const Inputs& in) { - GrMulti m{}; - for (int t = 0; t < T; ++t) m.a[t] = upstream_args(t, w, ws, in); - m.xn = w.scratch; m.T = T; - return m; -} -// the 14 words per row of `multi_words` (crates/cuda-driver/src/original_verify_window_gr/assets.rs), then xn and T -static OursByValue ours_multi(int T, const Work& w, const WeightSet& ws, const Inputs& in) { - OursByValue o{}; - auto p = [](const void* x) { return (uint64_t) (uintptr_t) x; }; - const float eps = 1e-6f; uint32_t eps_bits; std::memcpy(&eps_bits, &eps, 4); - for (int t = 0; t < T; ++t) { - uint64_t* a = &o.w[t * 14]; - a[0] = p(w.R + (size_t) t * D); a[1] = a[0]; a[2] = 1; a[3] = p(in.bo + (size_t) t * N); a[4] = p(in.inj + (size_t) t * HC); - a[5] = p(ws.norm); a[6] = p(ws.down); a[7] = p(ws.up); a[8] = p(ws.inject); a[9] = eps_bits; - a[10] = p(w.lo + (size_t) t * LR); a[11] = p(w.rs + (size_t) t * HC); a[12] = p(w.inject_out + (size_t) t * HC); a[13] = p(w.mixed + (size_t) t * N); - } - o.w[112] = p(w.scratch); o.w[113] = (uint64_t) T; - return o; -} - -struct OursKernels { CUmodule mod = nullptr; CUfunction split = nullptr, down = nullptr, up8 = nullptr; std::string label; }; -static bool load_ours(const std::string& path, bool is_ptx, const char* label, OursKernels& k) { - std::ifstream f(path, std::ios::binary); - if (!f) { std::fprintf(stderr, "cannot read %s\n", path.c_str()); return false; } - std::vector image((std::istreambuf_iterator(f)), std::istreambuf_iterator()); - if (is_ptx) { while (!image.empty() && image.back() == '\0') image.pop_back(); image.push_back('\0'); } // the product appends one NUL to the PTX text - CU_DRV(cuModuleLoadData(&k.mod, image.data())); - CU_DRV(cuModuleGetFunction(&k.split, k.mod, "chain_gr_split")); - CU_DRV(cuModuleGetFunction(&k.down, k.mod, "chain_gr_down_t2w8_nb4")); - CU_DRV(cuModuleGetFunction(&k.up8, k.mod, "chain_gr_up8")); - k.label = label; - return true; -} -static void ours_launch(CUfunction fn, OursByValue m, dim3 grid, unsigned shared, cudaStream_t s) { - void* params[1] = {&m}; - CU_DRV(cuLaunchKernel(fn, grid.x, grid.y, grid.z, THREADS, 1, 1, shared, (CUstream) s, params, nullptr)); -} -static dim3 ours_split_grid(int T) { return dim3(T, HC); } -static dim3 ours_down_grid(int T) { return dim3(LR / 8 + 1, (T + 1) / 2); } // original_verify_window_gr::tiled_down_geometry: 41 blocks of 8 rows, grid.y = ceil(T / 2) -static unsigned ours_down_shared(int T) { return 4u * (unsigned) std::min(T, 2) * 1280u * 4u; } -static dim3 ours_up8_grid() { return dim3((N / 16) * 2); } // UP_BLOCKS * 2 = 320 blocks of 256 threads - -// ------------------------------------------------------------------------------------------------ variants -struct Variant { std::string name; std::function run; }; // (T, weight set, stream) -struct Context { - std::vector sets; Inputs in; - Work w_down_u, w_down_o, w_down_c, w_pipe_u, w_pipe_o; // separate output buffers per measured variant family - OursKernels ptx, cubin; -}; - -static std::vector down_variants(Context& c, bool with_cubin) { - std::vector v; - const int masks[] = {0, 5, 133}; - const char* names[] = {"upstream_mask0_plain", "upstream_mask5_batched_staging_loads", "upstream_mask133_register_blocked_dot"}; - for (int i = 0; i < 3; ++i) { - const int mask = masks[i]; - v.push_back({names[i], [&c, mask](int T, int set, cudaStream_t s) { - const GrMulti m = upstream_multi(T, c.w_down_u, c.sets[set], c.in); - mb_launch_upstream_down(mask, T, m, mb_part(c.w_down_u.scratch), mb_ssg(c.w_down_u.scratch, T), s); - }}); - } - v.push_back({"ours_down_t2w8_nb4_sealed_ptx", [&c](int T, int set, cudaStream_t s) { - ours_launch(c.ptx.down, ours_multi(T, c.w_down_o, c.sets[set], c.in), ours_down_grid(T), ours_down_shared(T), s); - }}); - if (with_cubin) v.push_back({"ours_down_t2w8_nb4_nvcc_cubin", [&c](int T, int set, cudaStream_t s) { - ours_launch(c.cubin.down, ours_multi(T, c.w_down_c, c.sets[set], c.in), ours_down_grid(T), ours_down_shared(T), s); - }}); - v.push_back({"ours_split_plus_down_sealed_ptx", [&c](int T, int set, cudaStream_t s) { - const OursByValue m = ours_multi(T, c.w_down_o, c.sets[set], c.in); - ours_launch(c.ptx.split, m, ours_split_grid(T), 0, s); - ours_launch(c.ptx.down, m, ours_down_grid(T), ours_down_shared(T), s); - }}); - v.push_back({"empty_kernel_with_upstream_mask133_launch_shape", [&c](int T, int, cudaStream_t s) { - const MbLaunchShape sh = mb_upstream_down_shape(133, T); - mb_empty_upstream_shape<<>>(upstream_multi(T, c.w_down_u, c.sets[0], c.in)); - }}); - v.push_back({"empty_kernel_with_our_launch_shape", [&c](int T, int, cudaStream_t s) { - mb_empty_ours_shape<<>>(ours_multi(T, c.w_down_o, c.sets[0], c.in)); - }}); - return v; -} -static std::vector pipeline_variants(Context& c) { - std::vector v; - for (int mask : {0, 5, 133}) { - const std::string name = "pipeline_upstream_mask" + std::to_string(mask) + "_down_plus_up"; - v.push_back({name, [&c, mask](int T, int set, cudaStream_t s) { - FusedGrArgs a[kTokensMax]; - for (int t = 0; t < T; ++t) a[t] = upstream_args(t, c.w_pipe_u, c.sets[set], c.in); - fused_gr_v3_pf(mask); - fused_gr_read_multi(a, T, c.w_pipe_u.scratch, (void*) s); // upstream's own entry point: STRATA_GR_V3=1 -> gr_down_v3 + gr_up_v3 - }}); - } - v.push_back({"pipeline_ours_split_down_up8_sealed_ptx", [&c](int T, int set, cudaStream_t s) { - const OursByValue m = ours_multi(T, c.w_pipe_o, c.sets[set], c.in); - ours_launch(c.ptx.split, m, ours_split_grid(T), 0, s); - ours_launch(c.ptx.down, m, ours_down_grid(T), ours_down_shared(T), s); - ours_launch(c.ptx.up8, m, ours_up8_grid(), 0, s); - }}); - return v; -} - -// ------------------------------------------------------------------------------------------------ statistics -struct Stat { double median, p10, p90, mn, mean, round_med_lo, round_med_hi; size_t n; }; -static double pick(const std::vector& s, double p) { return s[(size_t) std::floor(p * (double) (s.size() - 1) + 0.5)]; } -static Stat summarize(const std::vector>& rounds) { - std::vector all, meds; - for (auto r : rounds) { std::sort(r.begin(), r.end()); meds.push_back(pick(r, 0.5)); all.insert(all.end(), r.begin(), r.end()); } - std::sort(all.begin(), all.end()); std::sort(meds.begin(), meds.end()); - double sum = 0; for (double x : all) sum += x; - return {pick(all, 0.5), pick(all, 0.1), pick(all, 0.9), all.front(), sum / (double) all.size(), meds.front(), meds.back(), all.size()}; -} -static void print_stat(const char* mode, int T, const std::string& name, const Stat& s) { - std::printf("TIME %-26s T=%d %-52s median %8.3f p10 %8.3f p90 %8.3f min %8.3f mean %8.3f round-medians %8.3f..%8.3f n=%zu\n", mode, T, name.c_str(), s.median, s.p10, s.p90, s.mn, - s.mean, s.round_med_lo, s.round_med_hi, s.n); - std::printf("CSV,%s,%d,%s,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%zu\n", mode, T, name.c_str(), s.median, s.p10, s.p90, s.mn, s.mean, s.round_med_lo, s.round_med_hi, s.n); -} - -struct Options { int tmin = 1, tmax = 8, rounds = 7, replays = 40, nodes = 64, sets = 64, single = 120; std::string ptx, cubin; }; - -// graph-batched: `nodes` launches (cycling over the weight sets when cold) captured into one CUDA graph; per-launch time = graph time / nodes -static void time_graphs(const Options& o, Context& c, const std::vector& vars, int T, bool cold, cudaStream_t s) { - const char* mode = cold ? "graph_cold_weights" : "graph_warm_weights"; - std::vector exec(vars.size()); - for (size_t vi = 0; vi < vars.size(); ++vi) { - for (int i = 0; i < 2; ++i) vars[vi].run(T, 0, s); // first-use attribute setup and module state outside the capture - CU_RT(cudaStreamSynchronize(s)); - cudaGraph_t g; - CU_RT(cudaStreamBeginCapture(s, cudaStreamCaptureModeRelaxed)); - for (int i = 0; i < o.nodes; ++i) vars[vi].run(T, cold ? i % (int) c.sets.size() : 0, s); - CU_RT(cudaStreamEndCapture(s, &g)); - CU_RT(cudaGraphInstantiate(&exec[vi], g, 0)); - CU_RT(cudaGraphDestroy(g)); - } - std::vector e0(o.replays), e1(o.replays); - for (int i = 0; i < o.replays; ++i) { CU_RT(cudaEventCreate(&e0[i])); CU_RT(cudaEventCreate(&e1[i])); } - std::vector>> data(vars.size()); - for (int r = 0; r < o.rounds; ++r) - for (size_t k = 0; k < vars.size(); ++k) { - const size_t vi = (k + (size_t) r) % vars.size(); // rotate the start so no variant always follows the same neighbour - for (int i = 0; i < 3; ++i) CU_RT(cudaGraphLaunch(exec[vi], s)); - for (int i = 0; i < o.replays; ++i) { CU_RT(cudaEventRecord(e0[i], s)); CU_RT(cudaGraphLaunch(exec[vi], s)); CU_RT(cudaEventRecord(e1[i], s)); } - CU_RT(cudaStreamSynchronize(s)); - std::vector us; - for (int i = 0; i < o.replays; ++i) { float ms; CU_RT(cudaEventElapsedTime(&ms, e0[i], e1[i])); us.push_back(1000.0 * ms / o.nodes); } - data[vi].push_back(us); - } - for (size_t vi = 0; vi < vars.size(); ++vi) { print_stat(mode, T, vars[vi].name, summarize(data[vi])); CU_RT(cudaGraphExecDestroy(exec[vi])); } - for (int i = 0; i < o.replays; ++i) { cudaEventDestroy(e0[i]); cudaEventDestroy(e1[i]); } -} - -// single launch: a 50 us spin kernel keeps the stream ahead of the host, then event, launch(es), event; weights rotate over the sets -static void time_single(const Options& o, Context& c, const std::vector& vars, int T, cudaStream_t s) { - std::vector e0(o.single), e1(o.single); - for (int i = 0; i < o.single; ++i) { CU_RT(cudaEventCreate(&e0[i])); CU_RT(cudaEventCreate(&e1[i])); } - std::vector>> data(vars.size()); - int counter = 0; - for (int r = 0; r < o.rounds; ++r) - for (size_t k = 0; k < vars.size(); ++k) { - const size_t vi = (k + (size_t) r) % vars.size(); - for (int i = 0; i < o.single; ++i) { - mb_spin_ns<<<1, 1, 0, s>>>(50000ull); - CU_RT(cudaEventRecord(e0[i], s)); - vars[vi].run(T, counter++ % (int) c.sets.size(), s); - CU_RT(cudaEventRecord(e1[i], s)); - } - CU_RT(cudaStreamSynchronize(s)); - std::vector us; - for (int i = 0; i < o.single; ++i) { float ms; CU_RT(cudaEventElapsedTime(&ms, e0[i], e1[i])); us.push_back(1000.0 * ms); } - data[vi].push_back(us); - } - for (size_t vi = 0; vi < vars.size(); ++vi) print_stat("single_launch_cold_weights", T, vars[vi].name, summarize(data[vi])); - for (int i = 0; i < o.single; ++i) { cudaEventDestroy(e0[i]); cudaEventDestroy(e1[i]); } -} - -#include "compare_outputs.inc" - -static int run(int argc, char** argv) { - Options o; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - auto next = [&]() { return i + 1 < argc ? std::atoi(argv[++i]) : 0; }; - if (a == "--ptx" && i + 1 < argc) o.ptx = argv[++i]; - else if (a == "--cubin" && i + 1 < argc) o.cubin = argv[++i]; - else if (a == "--rounds") o.rounds = next(); - else if (a == "--replays") o.replays = next(); - else if (a == "--nodes") o.nodes = next(); - else if (a == "--sets") o.sets = next(); - else if (a == "--single") o.single = next(); - else if (a == "--tmin") o.tmin = next(); - else if (a == "--tmax") o.tmax = next(); - else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 1; } - } - if (o.ptx.empty()) { std::fprintf(stderr, "usage: microbench --ptx chain_window.ptx [--cubin chain_window.cubin] [--rounds R --replays N --nodes B --sets S --single N --tmin 1 --tmax 8]\n"); return 1; } - setenv("STRATA_GR_V3", "1", 1); // upstream's own entry point (fused_gr_read_multi) takes the v3 read, as on an sm_120 card by default - setvbuf(stdout, nullptr, _IOLBF, 0); - CU_RT(cudaFree(0)); - int dev = 0, rtv = 0, drv = 0; - CU_RT(cudaGetDevice(&dev)); cudaRuntimeGetVersion(&rtv); cudaDriverGetVersion(&drv); - cudaDeviceProp prop; CU_RT(cudaGetDeviceProperties(&prop, dev)); - std::printf("device %d %s cc %d.%d SMs %d L2 %d MiB runtime %d driver %d\n", dev, prop.name, prop.major, prop.minor, prop.multiProcessorCount, prop.l2CacheSize >> 20, rtv, drv); - std::printf("config rounds %d replays %d nodes %d sets %d single %d T %d..%d N %d HC %d LR %d D %d\n", o.rounds, o.replays, o.nodes, o.sets, o.single, o.tmin, o.tmax, N, HC, LR, D); - std::printf("upstream default mask on cc 12.0 is 133 (include/strata/core/bw_dense_defaults.hpp gr_v3_pf_default); gr_r2() = %d (STRATA_GR_R2 default)\n", gr_r2()); - - Context c; - std::mt19937 rng(7); // the seed and the distributions of upstream's tools gr_v3_screen.cpp - std::normal_distribution nd(0.f, 1.f); - std::vector bo((size_t) kTokensMax * N), inj((size_t) kTokensMax * HC), wn(D); - c.in.R0.resize((size_t) kTokensMax * D); - for (auto& x : c.in.R0) x = nd(rng); - for (auto& x : bo) x = 0.5f * nd(rng); - for (auto& x : inj) x = nd(rng); - for (auto& x : wn) x = 1.0f + 0.3f * nd(rng); - std::vector wd((size_t) LR * D), wu((size_t) D * LR), wi((size_t) HC * D); - for (auto& x : wd) x = bf16_bits(0.02f * nd(rng)); - for (auto& x : wu) x = bf16_bits(0.05f * nd(rng)); - for (auto& x : wi) x = bf16_bits(0.02f * nd(rng)); - // the inputs are finite by construction (normal distributions, weights rounded to bf16); say so in the log, so a NaN in an output can only be a bug - { - size_t bad = 0; - for (const auto* v : {&bo, &inj, &wn, &c.in.R0}) for (float x : *v) bad += !std::isfinite(x); - for (const auto* v : {&wd, &wu, &wi}) for (uint16_t x : *v) bad += ((x & 0x7f80u) == 0x7f80u); - std::printf("inputs: %zu non-finite values (must be 0)\n", bad); - if (bad != 0) return 2; - } - CU_RT(cudaMalloc((void**) &c.in.bo, bo.size() * 4)); CU_RT(cudaMemcpy(c.in.bo, bo.data(), bo.size() * 4, cudaMemcpyHostToDevice)); - CU_RT(cudaMalloc((void**) &c.in.inj, inj.size() * 4)); CU_RT(cudaMemcpy(c.in.inj, inj.data(), inj.size() * 4, cudaMemcpyHostToDevice)); - for (int i = 0; i < o.sets; ++i) { - WeightSet w; - CU_RT(cudaMalloc((void**) &w.down, wd.size() * 2)); CU_RT(cudaMemcpy(w.down, wd.data(), wd.size() * 2, cudaMemcpyHostToDevice)); - CU_RT(cudaMalloc((void**) &w.up, wu.size() * 2)); CU_RT(cudaMemcpy(w.up, wu.data(), wu.size() * 2, cudaMemcpyHostToDevice)); - CU_RT(cudaMalloc((void**) &w.inject, wi.size() * 2)); CU_RT(cudaMemcpy(w.inject, wi.data(), wi.size() * 2, cudaMemcpyHostToDevice)); - CU_RT(cudaMalloc((void**) &w.norm, wn.size() * 4)); CU_RT(cudaMemcpy(w.norm, wn.data(), wn.size() * 4, cudaMemcpyHostToDevice)); - c.sets.push_back(w); - } - c.w_down_u = new_work(c.in); c.w_down_o = new_work(c.in); c.w_down_c = new_work(c.in); c.w_pipe_u = new_work(c.in); c.w_pipe_o = new_work(c.in); - CU_RT(cudaFuncSetAttribute(mb_empty_upstream_shape, cudaFuncAttributeMaxDynamicSharedMemorySize, 8 * N * (int) sizeof(float))); - mb_set_upstream_attributes(); - - CU_DRV(cuInit(0)); - if (!load_ours(o.ptx, true, "sealed PTX via cuModuleLoadData", c.ptx)) return 1; - const bool have_cubin = !o.cubin.empty() && load_ours(o.cubin, false, "nvcc cubin", c.cubin); - cudaStream_t s; CU_RT(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking)); - CU_RT(cudaDeviceSynchronize()); - - const int failures = compare_outputs(o, c, have_cubin, s); - - // the activations of the ours-down-only timing: what the split kernel writes for a full window (the down kernel reads xn and nothing else) - for (Work* w : {&c.w_down_o, &c.w_down_c}) { - ours_launch(c.ptx.split, ours_multi(kTokensMax, *w, c.sets[0], c.in), ours_split_grid(kTokensMax), 0, s); - CU_RT(cudaStreamSynchronize(s)); - } - const std::vector down = down_variants(c, have_cubin), pipe = pipeline_variants(c); - { // clocks up before the first measurement: about two seconds of the real kernels, all window sizes - const auto t0 = std::chrono::steady_clock::now(); - while (std::chrono::duration(std::chrono::steady_clock::now() - t0).count() < 2.0) { - for (int i = 0; i < 200; ++i) { down[3].run(1 + i % kTokensMax, i % (int) c.sets.size(), s); down[0].run(1 + i % kTokensMax, i % (int) c.sets.size(), s); } - CU_RT(cudaStreamSynchronize(s)); - } - } - for (int T = o.tmin; T <= o.tmax; ++T) { - const MbLaunchShape u133 = mb_upstream_down_shape(133, T), u5 = mb_upstream_down_shape(5, T), u0 = mb_upstream_down_shape(0, T); - std::printf("SHAPE T=%d upstream mask0: grid (%d,%d) block %d dyn %zu B %s | mask5: grid (%d,%d) dyn %zu B %s | mask133: grid (%d,%d) dyn %zu B %s | ours down: grid (%d,%d) block %d dyn %u B\n", - T, u0.blocks_x, u0.blocks_y, THREADS, u0.shared, u0.kernel, u5.blocks_x, u5.blocks_y, u5.shared, u5.kernel, u133.blocks_x, u133.blocks_y, u133.shared, u133.kernel, - ours_down_grid(T).x, ours_down_grid(T).y, THREADS, ours_down_shared(T)); - time_graphs(o, c, down, T, true, s); - time_graphs(o, c, down, T, false, s); - time_graphs(o, c, pipe, T, true, s); - time_single(o, c, down, T, s); - } - std::printf("microbench done, correctness failures: %d\n", failures); - return failures ? 3 : 0; -} - -} // namespace microbench -} // namespace strata::kernels - -int main(int argc, char** argv) { return strata::kernels::microbench::run(argc, argv); } diff --git a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/ours-shim/strata/kernels/fused_gr.hpp b/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/ours-shim/strata/kernels/fused_gr.hpp deleted file mode 100644 index 032247bd..00000000 --- a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/ours-shim/strata/kernels/fused_gr.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// Shim for the microbench only: the 112-byte FusedGrArgs ABI that the sealed chain_window.ptx was built against -// (crates/cuda-driver static_asserts sizeof(FusedGrArgs) == 112 and sizeof(GrMulti) == 912); the header in engine/strata/include -// has later fields (q8_*, s_*), 168 bytes, which the sealed kernels do not know. Only the fields chain_window.cu uses. -#pragma once -#include -namespace strata::kernels { -struct FusedGrArgs { - const float* R = nullptr; - float* R_out = nullptr; - bool apply = false; - const float* bo_prev = nullptr; - const float* inj_prev = nullptr; - const float* w_norm = nullptr; - const uint16_t* w_down = nullptr; - const uint16_t* w_up = nullptr; - const uint16_t* w_inject = nullptr; - float eps = 1e-6f; - float* lo = nullptr; - float* rs = nullptr; - float* inject_out = nullptr; - float* mixed = nullptr; -}; -constexpr int kFusedGrMaxT = 8; -} // namespace strata::kernels diff --git a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/summarize.py b/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/summarize.py deleted file mode 100644 index 32ed4e23..00000000 --- a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/summarize.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python3 -"""Per-T tables from the CSV lines of microbench (stdlib only): python3 -I summarize.py result.txt - -CSV,mode,T,variant,median,p10,p90,min,mean,round_median_lo,round_median_hi,n (microseconds per launch) -A difference "resolved" means |ours - upstream| is larger than the spread of the per-round medians of both (noise bound of the run). -Sign: delta = ours - upstream; positive = upstream is faster. -""" -import sys -from collections import defaultdict - -SHORT = { - "upstream_mask0_plain": "up_m0", - "upstream_mask5_batched_staging_loads": "up_m5", - "upstream_mask133_register_blocked_dot": "up_m133", - "ours_down_t2w8_nb4_sealed_ptx": "ours_ptx", - "ours_down_t2w8_nb4_nvcc_cubin": "ours_cubin", - "ours_split_plus_down_sealed_ptx": "ours_split+down", - "empty_kernel_with_upstream_mask133_launch_shape": "empty_up", - "empty_kernel_with_our_launch_shape": "empty_ours", - "pipeline_upstream_mask0_down_plus_up": "pipe_up_m0", - "pipeline_upstream_mask5_down_plus_up": "pipe_up_m5", - "pipeline_upstream_mask133_down_plus_up": "pipe_up_m133", - "pipeline_ours_split_down_up8_sealed_ptx": "pipe_ours", -} - - -def load(path): - data = defaultdict(lambda: defaultdict(dict)) - for line in open(path, errors="replace"): - if not line.startswith("CSV,"): - continue - f = line.rstrip("\n").split(",") - mode, t, name = f[1], int(f[2]), SHORT.get(f[3], f[3]) - v = [float(x) for x in f[4:11]] - data[mode][t][name] = dict(median=v[0], p10=v[1], p90=v[2], mn=v[3], mean=v[4], lo=v[5], hi=v[6]) - return data - - -def table(data, mode, cols, title): - if mode not in data: - return - print(f"\n== {title}: median us per launch (p10..p90)") - print("T " + "".join(f"{c:>26}" for c in cols)) - for t in sorted(data[mode]): - row = data[mode][t] - cells = [] - for c in cols: - x = row.get(c) - cells.append(f"{x['median']:8.3f} ({x['p10']:6.2f}..{x['p90']:6.2f})" if x else "-") - print(f"{t:<2} " + "".join(f"{c:>26}" for c in cells)) - - -def deltas(data, mode, ours, ups, title): - if mode not in data: - return - print(f"\n== {title}: delta = {ours} - upstream, us per launch (positive: upstream faster); '*' = larger than the round-to-round spread of both") - print("T " + "".join(f"{u:>26}" for u in ups)) - for t in sorted(data[mode]): - row = data[mode][t] - if ours not in row: - continue - cells = [] - for u in ups: - if u not in row: - cells.append("-") - continue - a, b = row[ours], row[u] - d = a["median"] - b["median"] - spread = (a["hi"] - a["lo"]) + (b["hi"] - b["lo"]) - cells.append(f"{d:+8.3f} ({100 * d / b['median']:+6.1f}%) {'*' if abs(d) > spread else ' '}") - print(f"{t:<2} " + "".join(f"{c:>26}" for c in cells)) - - -def main(path): - d = load(path) - down = ["up_m0", "up_m5", "up_m133", "ours_ptx", "ours_cubin", "ours_split+down", "empty_up", "empty_ours"] - for mode, title in (("graph_cold_weights", "graph-batched, cold weights (headline)"), ("graph_warm_weights", "graph-batched, warm weights (L2-resident)"), - ("single_launch_cold_weights", "single launch with events (includes event overhead; see the empty-kernel columns)")): - table(d, mode, down, title) - deltas(d, mode, "ours_ptx", ["up_m133", "up_m5", "up_m0"], title + ", our down kernel alone") - deltas(d, mode, "ours_split+down", ["up_m133", "up_m5", "up_m0"], title + ", our split+down (upstream's down kernel also does the norm's sum of squares and staging)") - table(d, "graph_cold_weights", ["pipe_up_m0", "pipe_up_m5", "pipe_up_m133", "pipe_ours"], "whole read (down+up for upstream, split+down+up8 for ours), cold weights") - deltas(d, "graph_cold_weights", "pipe_ours", ["pipe_up_m133", "pipe_up_m5", "pipe_up_m0"], "whole read") - - -if __name__ == "__main__": - main(sys.argv[1]) diff --git a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/upstream_down_launch.inc b/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/upstream_down_launch.inc deleted file mode 100644 index d53a3eb9..00000000 --- a/scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/upstream_down_launch.inc +++ /dev/null @@ -1,115 +0,0 @@ -// Included by microbench.cu INSIDE namespace strata::kernels::microbench, after upstream's fused_gr.cu was included whole -// (so N, HC, D, LR, PR, THREADS, WARPS, GrMulti, gr_down_v3_kernel, gr_down_pf_dispatch, ... are upstream's own, unmodified). -// -// 1. mb_launch_upstream_down: the down-kernel selection of upstream's fused_gr_read_multi_slice (fused_gr.cu, the lines from -// `const int pfm = ...` to the `else gr_down_v3_kernel<1, kFusedGrMaxT, false>` ladder), copied in the same order, for S == 1 -// (split == 1, the case on an sm_120 card), calling upstream's own static launch helpers and kernels. -// 2. mb_set_upstream_attributes: the cudaFuncSetAttribute calls of the same function (its split3 block), for the instantiations the -// plain ladder launches (the PF and RB helpers set their own attributes on first use, as upstream does). -// 3. mb_finalize_down: a TRANSCRIPTION (not upstream's compiled code) of the lines of gr_up_v3_kernel (S == 1, PF == 0 path) that turn -// the down kernel's `part` / `ssg` into rs, lo and inject_out, so the down stage's result can be compared with ours. -// Upstream's up kernel keeps lo in shared memory only, hence the transcription. The same lines run inside the real up kernel in the -// pipeline measurement (whose rs / inject_out / mixed outputs are compared with the real kernel's, not the transcription's). - -static void mb_set_upstream_attributes() { - const int need1 = (int) (kFusedGrMaxT * N * sizeof(float)), need5 = (int) (5 * N * sizeof(float)), need6 = (int) (6 * N * sizeof(float)); - const int need7 = (int) (7 * N * sizeof(float)), need8 = (int) (8 * N * sizeof(float)); - const cudaFuncAttribute dyn = cudaFuncAttributeMaxDynamicSharedMemorySize, carve = cudaFuncAttributePreferredSharedMemoryCarveout; - cudaFuncSetAttribute(gr_down_v3_kernel<1, kFusedGrMaxT, false>, dyn, need1); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 6, true>, dyn, need6); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 5, true>, dyn, need5); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 5, true, 2>, dyn, need5); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 6, true, 2>, dyn, need6); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 7, true, 1>, dyn, need7); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 7, true, 2>, dyn, need7); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 7, true, 4>, dyn, need7); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 8, true, 1>, dyn, need8); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 8, true, 2>, dyn, need8); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 8, true, 4>, dyn, need8); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 1, true>, carve, 100); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 2, true>, carve, 100); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 3, true>, carve, 100); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 4, true>, carve, 100); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 5, true>, carve, 100); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 6, true>, carve, 100); - cudaFuncSetAttribute(gr_down_v3_kernel<1, 4, false>, carve, 100); - cudaFuncSetAttribute(gr_down_v3_kernel<1, kFusedGrMaxT, false>, carve, 100); -} - -// grid / dynamic shared bytes the selection above gives for `mask` and `n_tok` rows (reported next to the timings) -struct MbLaunchShape { int blocks_x, blocks_y; size_t shared; const char* kernel; }; -static MbLaunchShape mb_upstream_down_shape(int mask, int n_tok) { - const size_t sm = (size_t) n_tok * N * sizeof(float); - if ((mask & 128) != 0 && n_tok >= 5) return {LR / (WARPS * 2) + 1, HC, sm, "gr_down_v3_kernel<1,T,exact,R2V=2,PF=0,RB=true>"}; - if ((mask & 3) != 0) return {LR / WARPS + 1, HC, sm, "gr_down_v3_kernel<1,T,exact,R2V=1,PF=mask&3>"}; - if (n_tok >= 5) return {LR / (WARPS * 2) + 1, HC, sm, "gr_down_v3_kernel<1,T,exact,R2V=2,PF=0> (STRATA_GR_R2 default 2)"}; - return {LR / WARPS + 1, HC, sm, "gr_down_v3_kernel<1,T,exact,R2V=1,PF=0>"}; -} - -static void mb_launch_upstream_down(int pfm, int n_tok, const GrMulti& m, float* part, float* ssg, cudaStream_t st) { - const size_t sm = (size_t) n_tok * N * sizeof(float); - if ((pfm & 128) != 0 && n_tok >= 5 && gr_down_rb_dispatch_k<2>(n_tok, m, part, ssg, st)) {} - else if ((pfm & 256) != 0 && gr_down_rb_dispatch_k<4>(n_tok, m, part, ssg, st)) {} - else if (((pfm >> 4) & 3) == 1 && gr_down_r2_dispatch_k<2>(n_tok, m, part, ssg, st)) {} - else if (((pfm >> 4) & 3) == 2 && gr_down_r2_dispatch_k<4>(n_tok, m, part, ssg, st)) {} - else if ((pfm & 3) != 0 && gr_down_pf_dispatch(pfm & 3, n_tok, m, part, ssg, st)) {} - else if (n_tok == 1) gr_down_v3_kernel<1, 1, true><<>>(m, part, ssg); - else if (n_tok == 2) gr_down_v3_kernel<1, 2, true><<>>(m, part, ssg); - else if (n_tok == 3) gr_down_v3_kernel<1, 3, true><<>>(m, part, ssg); - else if (n_tok == 4) gr_down_v3_kernel<1, 4, true><<>>(m, part, ssg); - else if (n_tok == 5 && gr_r2() == 2) gr_down_v3_kernel<1, 5, true, 2><<>>(m, part, ssg); - else if (n_tok == 5) gr_down_v3_kernel<1, 5, true><<>>(m, part, ssg); - else if (n_tok == 6 && gr_r2() == 2) gr_down_v3_kernel<1, 6, true, 2><<>>(m, part, ssg); - else if (n_tok == 6) gr_down_v3_kernel<1, 6, true><<>>(m, part, ssg); - else if (n_tok == 7 && gr_r2() == 2) gr_down_v3_kernel<1, 7, true, 2><<>>(m, part, ssg); - else if (n_tok == 7 && gr_r2() == 4) gr_down_v3_kernel<1, 7, true, 4><<>>(m, part, ssg); - else if (n_tok == 7 && gr_r2() == 1) gr_down_v3_kernel<1, 7, true, 1><<>>(m, part, ssg); - else if (n_tok == 8 && gr_r2() == 2) gr_down_v3_kernel<1, 8, true, 2><<>>(m, part, ssg); - else if (n_tok == 8 && gr_r2() == 4) gr_down_v3_kernel<1, 8, true, 4><<>>(m, part, ssg); - else if (n_tok == 8 && gr_r2() == 1) gr_down_v3_kernel<1, 8, true, 1><<>>(m, part, ssg); - else gr_down_v3_kernel<1, kFusedGrMaxT, false><<>>(m, part, ssg); -} - -// part / ssg live in the read's scratch exactly as fused_gr_read_multi_slice lays them out -static float* mb_part(float* scratch) { return scratch; } -static float* mb_ssg(float* scratch, int n_tok) { return scratch + (size_t) n_tok * HC * 2 * PR; } - -__global__ void __launch_bounds__(THREADS) mb_finalize_down(GrMulti m, const float* part, const float* ssg, float* lo_out, float* inject_out_out, float* rs_out) { - __shared__ float rsS[kFusedGrMaxT][HC]; - const int t = threadIdx.x, T = m.T; - if (t < T * HC) { // gr_up_v3_kernel: the rms scale of (token, stream) - const int k = t / HC, c = t - k * HC; - float ss = 0.0f; - ss += ssg[t]; - const float r = rsqrtf(ss / (float) N + m.a[k].eps); - rsS[k][c] = r; - rs_out[t] = r; - } - __syncthreads(); - for (int i = t; i < T * LR; i += THREADS) { - const int k = i / LR, r = i - k * LR; - float sum = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) { - float p = 0.0f; - p += part[(((size_t) k * HC + c) * 1 + 0) * PR + r]; - sum = fmaf(rsS[k][c], p, sum); - } - const float x = sum / (float) HC; - lo_out[(size_t) k * LR + r] = x / (1.0f + __expf(-x)); - } - if (t < T * HC) { - const int k = t / HC, cc = t - k * HC; - float sum = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) { - float p = 0.0f; - p += part[(((size_t) k * HC + c) * 1 + 0) * PR + LR + cc]; - sum = fmaf(rsS[k][c], p, sum); - } - inject_out_out[t] = sum; - } -} - -// launch-shape floor: a kernel with the same grid / block / dynamic shared memory / by-value argument and an empty body -__global__ void __launch_bounds__(THREADS) mb_empty_upstream_shape(GrMulti m) { if (m.T < 0) m.a[0].lo[0] = 0.0f; } diff --git a/scripts/gpu-bringup/bringup_lib.py b/scripts/gpu-bringup/bringup_lib.py index b28e422f..1be439e8 100644 --- a/scripts/gpu-bringup/bringup_lib.py +++ b/scripts/gpu-bringup/bringup_lib.py @@ -21,7 +21,8 @@ SEAL_PLAN_DIR = "crates/cuda-driver/seal-plans" ROPE_DOC = "scripts/gpu-bringup/rope-regeneration.json" ABI_SOURCE = "crates/context/src/ptx_abi.rs" -# -I set of scripts/build-original-verify-ptx.sh (repo-root relative). +# -I set the sealed PTX were built with (repo-root relative). The two engine/strata directories were the vendored Strata tree, removed in +# STRA-406 (history: third_party/strata/UPSTREAM.md); an asset whose source includes a strata/ header needs them restored there to compile. STANDARD_INCLUDES = [ "engine/strata/include", "engine/strata/third_party/ggml", diff --git a/scripts/gpu-bringup/sm86_assets.py b/scripts/gpu-bringup/sm86_assets.py index bd4188f2..502ae05c 100644 --- a/scripts/gpu-bringup/sm86_assets.py +++ b/scripts/gpu-bringup/sm86_assets.py @@ -56,7 +56,7 @@ MANIFEST_NAME = "MANIFEST.json" ARCH = "sm_86" SRC_ARCH = "sm_120" -# Union of the include sets used by the repo's recipes (scripts/build-original-verify-ptx.sh, the seal plans and the +# Union of the include sets used by the repo's recipes (the retired scripts/build-original-verify-ptx.sh, the seal plans and the # scalar-MTP recipe); a missing directory is dropped, and the round trip proves the choice. INCLUDES = L.STANDARD_INCLUDES + ["engine/strata/src", "engine/strata/third_party/ggml/src"] diff --git a/scripts/gpu-bringup/tests/test_gpu_bringup.py b/scripts/gpu-bringup/tests/test_gpu_bringup.py index c0d4e393..0c914ea3 100644 --- a/scripts/gpu-bringup/tests/test_gpu_bringup.py +++ b/scripts/gpu-bringup/tests/test_gpu_bringup.py @@ -589,7 +589,7 @@ class RealTreeFakeSeal(unittest.TestCase): with tempfile.TemporaryDirectory() as d: scratch = Path(d) / "tree" ignore = shutil.ignore_patterns(".git", "target", "*.gguf") - for sub in ("crates", "deploy", "engine/strata/include", "engine/strata/third_party", "scripts/gpu-bringup"): + for sub in ("crates", "deploy", "scripts/gpu-bringup"): shutil.copytree(REPO / sub, scratch / sub, ignore=ignore) out = Path(d) / "ptx" code, _, err = run_quiet(C.main, ["--root", str(scratch), "--fake-nvcc", "--out", str(out), "--rope-flags", "preserve", diff --git a/scripts/native-pack-fixture.py b/scripts/native-pack-fixture.py new file mode 100644 index 00000000..8e06309f --- /dev/null +++ b/scripts/native-pack-fixture.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Synthetic GGUF fixtures for the native pack smokes (imported by the smoke scripts as a module). + +The independent Python pack oracle this file used to compare against (`tools/iq_pack.py` of the vendored Strata tree) is gone with the +tree (STRA-406); the pack bytes are covered by the Rust tests and the checked-in goldens. +""" +import struct + + +def string(s): + b = s.encode() + return struct.pack('']), + ('tokenizer.ggml.merges', ['a b'])]: + fields.append((k, 9, struct.pack(' [--cases N] [--seed S] -""" -import json -import random -import subprocess -import sys -from pathlib import Path - -REPO = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(REPO / 'engine/strata/serve')) -sys.path.insert(0, str(REPO / 'engine/strata')) -import jinja2 # noqa: E402,F401 -from frontend import ChatTemplate, TemplateRequestError # noqa: E402 (the oracle, unchanged) - -TEXTS = ['Hello', '', ' ', ' padded ', 'line1\nline2\n\n', '你好,世界 😀', 'tab\there', ' nbsp ', '\x1c\x1dsep\x1f', - ' ideographic ', 'quote " and \\ backslash', '\n{"temp": 3}\n', - 'x trailing', 'no', '{{ not a template }} {% nope %}', - 'a' * 300, 'é' * 40, '\x00nul', '

', '<|im_end|><|im_start|>user'] -NAMES = ['get_weather', 'search', 'ls', 'my.tool-1', 'ünï', 'a b'] - - -def rand_value(rng, depth=0): - kinds = ['s', 'i', 'f', 'b', 'n'] + (['l', 'd'] if depth < 3 else []) - k = rng.choice(kinds) - if k == 's': - return rng.choice(TEXTS[:12] + ['x']) - if k == 'i': - return rng.choice([0, 1, -5, 2 ** 40, 18446744073709551615]) - if k == 'f': - return rng.choice([0.5, 1.0, 1e16, 1e-5, 123456789.125, -0.0, 2.5e300]) - if k == 'b': - return rng.random() < 0.5 - if k == 'n': - return None - if k == 'l': - return [rand_value(rng, depth + 1) for _ in range(rng.randint(0, 3))] - return {rng.choice(['z', 'a', 'type', 'ключ', 'k y', '']) + str(i): rand_value(rng, depth + 1) - for i in range(rng.randint(0, 3))} - - -def rand_content(rng): - r = rng.random() - if r < 0.6: - return rng.choice(TEXTS) - if r < 0.68: - return None - if r < 0.72: - return 42 - parts = [] - for _ in range(rng.randint(0, 4)): - p = rng.random() - if p < 0.5: - parts.append({'type': 'text', 'text': rng.choice(TEXTS)}) - elif p < 0.7: - parts.append({'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,AAAA'}}) - elif p < 0.8: - parts.append({'type': 'image'}) - elif p < 0.88: - parts.append({'type': 'video', 'video': 'x.mp4'}) - elif p < 0.94: - parts.append({'text': rng.choice(TEXTS)}) - else: - parts.append({'type': 'audio'}) # unexpected: the template raises - return parts - - -def rand_tool_calls(rng): - calls = [] - for _ in range(rng.randint(1, 3)): - r = rng.random() - args = rng.choice([{}, {'city': 'Oslo'}, {'z': 1, 'a': [1, 2], 'm': {'y': None, 'b': True}}, {'q': 'multi\nline'}, - {'n': 1.5, 'u': 'ünï'}]) - if r < 0.55: - calls.append({'type': 'function', 'function': {'name': rng.choice(NAMES), 'arguments': args}}) - elif r < 0.75: - calls.append({'name': rng.choice(NAMES), 'arguments': args}) - elif r < 0.82: - calls.append({'function': {'name': rng.choice(NAMES), 'arguments': json.dumps(args)}}) - elif r < 0.88: - calls.append({'function': {'name': rng.choice(NAMES), 'arguments': ''}}) - elif r < 0.92: - calls.append({'function': {'arguments': args}}) # no name: raises - elif r < 0.96: - calls.append({'function': {'name': 'f', 'arguments': 5}}) # not an object: raises - else: - calls.append({'function': {'name': 'f'}}) - return calls - - -def rand_messages(rng): - n = rng.randint(1, 7) - messages = [] - leading = rng.choice([0, 0, 1, 2, 3]) - for i in range(leading): - messages.append({'role': rng.choice(['system', 'developer']), 'content': rand_content(rng)}) - for _ in range(n): - role = rng.choices(['user', 'assistant', 'tool', 'system', 'developer', 'robot'], [8, 6, 3, 0.4, 0.3, 0.2])[0] - m = {'role': role, 'content': rand_content(rng)} - if role == 'assistant': - if rng.random() < 0.5: - m['reasoning_content'] = rng.choice(TEXTS + [None, 5]) - if rng.random() < 0.4: - m['tool_calls'] = rand_tool_calls(rng) - elif rng.random() < 0.1: - m['tool_calls'] = [] - messages.append(m) - return messages - - -def rand_tools(rng): - if rng.random() < 0.55: - return None - tools = [] - for _ in range(rng.randint(0, 3)): - schema = {'type': 'object', 'properties': {rng.choice(['city', 'path', 'q', 'zz']) + str(i): { - 'type': rng.choice(['string', 'integer']), 'description': rng.choice(TEXTS[:8])} for i in range(rng.randint(0, 3))}, - 'required': ['city']} - if rng.random() < 0.3: - schema['additionalProperties'] = False - fn = {'name': rng.choice(NAMES), 'description': rng.choice(['Get the weather', 'ünï "q"', '']), 'parameters': schema} - if rng.random() < 0.3: - fn['strict'] = True - tools.append({'type': 'function', 'function': fn} if rng.random() < 0.9 else fn) - return tools if rng.random() < 0.9 else rng.choice([[], {'type': 'function'}]) - - -def rand_kwargs(rng): - kw = {} - if rng.random() < 0.3: - kw['enable_thinking'] = rng.choice([True, False, None]) - if rng.random() < 0.4: - kw['reasoning_effort'] = rng.choice(['low', 'medium', 'high', 'xhigh', 'xhigh', 'extreme', None]) - if rng.random() < 0.2: - kw['preserve_thinking'] = rng.choice([True, False]) - return kw - - -def main(): - args = sys.argv[1:] - cases = int(args[args.index('--cases') + 1]) if '--cases' in args else 3000 - seed = int(args[args.index('--seed') + 1]) if '--seed' in args else 20261014 - binary = str(Path(args[0]).resolve()) - rng = random.Random(seed) - template = ChatTemplate(REPO / 'engine/strata/serve/chat_template.jinja') - requests, expected = [], [] - for _ in range(cases): - req = {'messages': rand_messages(rng), 'tools': rand_tools(rng), - 'add_generation_prompt': rng.random() < 0.9, 'kwargs': rand_kwargs(rng)} - requests.append(req) - try: - expected.append({'ok': template.render(req['messages'], req['tools'], req['add_generation_prompt'], - **req['kwargs'])}) - except TemplateRequestError as e: - expected.append({'error': str(e), 'raised': True}) - except Exception as e: # noqa: BLE001 (jinja2 UndefinedError, TypeError ...: the Python server answers 400/500) - expected.append({'error': f'{type(e).__name__}: {e}', 'raised': False}) - payload = ''.join(json.dumps(r, ensure_ascii=False) + '\n' for r in requests).encode('utf-8') - run = subprocess.run([binary, 'model', 'render-chat'], input=payload, capture_output=True) - if run.returncode: - print('FAIL render-chat exited', run.returncode, run.stderr.decode()[-300:]) - return 1 - got = [json.loads(l) for l in run.stdout.decode('utf-8').split('\n')[:-1]] - bad, both_error, agree_ok = [], 0, 0 - for i, (want, have, req) in enumerate(zip(expected, got, requests)): - if 'ok' in want and 'ok' in have: - if want['ok'] != have['ok']: - bad.append(f'case {i}: bytes differ\n python: {want["ok"]!r}\n rust: {have["ok"]!r}\n request: {json.dumps(req, ensure_ascii=False)[:400]}') - else: - agree_ok += 1 - elif 'error' in want and 'error' in have: - both_error += 1 - if want['raised'] and want['error'] != have['error']: - bad.append(f'case {i}: raise_exception messages differ: {want["error"]!r} vs {have["error"]!r}') - else: - bad.append(f'case {i}: python {list(want)} vs rust {list(have)}: {want.get("error") or have.get("error")}\n request: {json.dumps(req, ensure_ascii=False)[:400]}') - assert len(got) == len(expected) - for b in bad[:12]: - print('FAIL', b) - print(json.dumps({'cases': cases, 'identical_renders': agree_ok, 'both_refused': both_error, 'failures': len(bad), - 'jinja2': jinja2.__version__, 'oracle': 'serve/frontend.py ChatTemplate (unmodified)'})) - return 1 if bad else 0 - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/scripts/offline/diff_dequant.py b/scripts/offline/diff_dequant.py deleted file mode 100644 index e34c43ac..00000000 --- a/scripts/offline/diff_dequant.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python3 -"""Dequantization parity: `leleka-api model export-tensor-f32` (the production visitor: independent Rust decoders -for IQ2_S/IQ3_S/IQ3_XXS/IQ4_NL/IQ4_XS/Q2_0/Q4_K/Q5_K/Q6_K/Q8_0, the pinned ggml C bridge for the rest) against -the gguf-py dequantizer of the pinned llama.cpp commit, bit for bit. - -Fixtures are tools/iq_fixture.py's (10 types, seeded) plus the other block types gguf-py can dequantize (Q4_0, Q4_1, -Q5_0, Q5_1, Q8_0, Q2_K, Q4_K, Q5_K, Q6_K, IQ1_S, MXFP4, NVFP4) and Q8_K (gguf-py has none: d * qs). - - STRATA_GGUF_PY=/gguf-py python scripts/offline/diff_dequant.py [--seeds 3] -""" -import json -import struct -import subprocess -import sys -import tempfile -from pathlib import Path - -import numpy as np - -REPO = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(REPO / 'engine/strata/tools')) -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import _paths # noqa: E402 - -_paths.add_gguf_py() -import iq_fixture as F # noqa: E402 (the oracle's fixture generator, unchanged) -from gguf import GGMLQuantizationType as Q # noqa: E402 -from gguf.quants import dequantize # noqa: E402 -from ggufgen import write_gguf # noqa: E402 - -# name -> (kind id, block elements, block bytes, [(offset, kind of scale)]) -EXTRA = { - 'Q4_0': (2, 32, 18, [(0, 'f16')]), 'Q4_1': (3, 32, 20, [(0, 'f16'), (2, 'f16')]), - 'Q5_0': (6, 32, 22, [(0, 'f16')]), 'Q5_1': (7, 32, 24, [(0, 'f16'), (2, 'f16')]), - 'Q8_0': (8, 32, 34, [(0, 'f16')]), 'Q2_K': (10, 256, 84, [(80, 'f16'), (82, 'f16')]), - 'Q4_K': (12, 256, 144, [(0, 'f16'), (2, 'f16')]), 'Q5_K': (13, 256, 176, [(0, 'f16'), (2, 'f16')]), - 'Q6_K': (14, 256, 210, [(208, 'f16')]), 'IQ1_S': (19, 256, 50, [(0, 'f16')]), - 'MXFP4': (39, 32, 17, [(0, 'e8m0')]), 'NVFP4': (40, 64, 36, [(0, 'ue4m3'), (1, 'ue4m3'), (2, 'ue4m3'), (3, 'ue4m3')]), - 'Q8_K': (15, 256, 292, [(0, 'f32')]), -} - - -def extra_blocks(name, rows, cols, rng): - kind, elems, size, scales = EXTRA[name] - n = rows * cols // elems - raw = rng.randint(0, 256, (n, size)).astype(np.uint8) - for at, how in scales: - for b in range(n): - if how == 'f16': - raw[b, at:at + 2] = np.frombuffer(np.float16(rng.uniform(0.002, 0.08)).tobytes(), np.uint8) - elif how == 'f32': - raw[b, at:at + 4] = np.frombuffer(np.float32(rng.uniform(0.002, 0.5)).tobytes(), np.uint8) - elif how == 'e8m0': - raw[b, at] = rng.randint(110, 135) - else: - raw[b, at] = rng.randint(0x20, 0x50) - flat = raw.reshape(-1) - if name == 'Q8_K': - out = np.empty((n, 256), np.float32) - for b in range(n): - d = np.frombuffer(raw[b, 0:4].tobytes(), np.float32)[0] - out[b] = d * raw[b, 4:260].view(np.int8).astype(np.float32) - ref = out.reshape(-1) - else: - ref = np.asarray(dequantize(flat, getattr(Q, name)), np.float32).reshape(-1) - return kind, flat.tobytes(), ref - - -def fixtures(seed, rows, cols): - """[(name, kind id, blocks bytes, expected float32 array)]""" - out = [] - for name in F.KERNEL_IDS: - blob, ref = F.build(name, rows, cols, seed) - out.append((name, F.KERNEL_IDS[name], blob[12:], ref)) - rng = np.random.RandomState(seed) - for name in EXTRA: - kind, blocks, ref = extra_blocks(name, rows, cols, rng) - out.append((name, kind, blocks, ref)) - return out - - -def main(): - args = sys.argv[1:] - binary = str(Path(args[0]).resolve()) - seeds = int(args[args.index('--seeds') + 1]) if '--seeds' in args else 3 - rows, cols = 32, 256 - root = Path(tempfile.mkdtemp(prefix='strata-dequant-')) - bad, count = [], 0 - for seed in range(7, 7 + seeds): - for name, kind, blocks, ref in fixtures(seed, rows, cols): - path = root / f'{name}.gguf' - write_gguf(path, [('w', [cols, rows], kind, blocks)]) - out = root / f'{name}.f32' - out.unlink(missing_ok=True) - r = subprocess.run([binary, 'model', 'export-tensor-f32', str(path), 'w', '--output', str(out)], - capture_output=True, text=True) - count += 1 - if r.returncode: - bad.append(f'{name} seed {seed}: export failed: {r.stderr.strip()[-160:]}') - continue - got = np.frombuffer(out.read_bytes(), np.uint32) - want = np.ascontiguousarray(ref, ' [--cases N] [--seed S] - -Random files cover all 13 metadata value types, arrays of every element type, unicode strings, `general.alignment`, -split keys and 1-4 dimensional tensors of every block geometry both sides know. Pure stdlib + the oracle. -""" -import json -import random -import struct -import subprocess -import sys -import tempfile -from pathlib import Path - -REPO = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(REPO / 'engine/strata/tools')) -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import gguf_reader as G # noqa: E402 (the oracle, unchanged) -from ggufgen import write_gguf, string # noqa: E402 - -SCALAR_KINDS = ['u8', 'i8', 'u16', 'i16', 'u32', 'i32', 'f32', 'bool', 'u64', 'i64', 'f64'] -RANGES = {'u8': (0, 255), 'i8': (-128, 127), 'u16': (0, 65535), 'i16': (-32768, 32767), 'u32': (0, 2**32 - 1), - 'i32': (-2**31, 2**31 - 1), 'u64': (0, 2**64 - 1), 'i64': (-2**63, 2**63 - 1)} -GEOM = {name: g for name, g in G.BLOCK_GEOMETRY.items()} -TYPE_IDS = {name: i for i, name in G.GGML_TYPES.items() if name in GEOM} - - -def rand_string(rng): - alphabet = 'abcXYZ019 _-./äöüéßçñΩλπЖ中文日本語한국어😀🧪‍́' - return ''.join(rng.choice(alphabet) for _ in range(rng.randint(0, 24))) - - -def rand_scalar(rng, kind): - if kind == 'bool': - return rng.random() < 0.5 - if kind == 'f32': - return struct.unpack(' -""" -import hashlib -import http.server -import json -import shutil -import struct -import subprocess -import sys -import tempfile -import threading -from pathlib import Path -from unittest import mock - -REPO = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(REPO / 'engine/strata/tools')) -import mtp_fetch as M # noqa: E402 (the oracle, unchanged) - - -def shard(tensors): - header, data = {}, b'' - for name, blob in tensors: - header[name] = {'dtype': 'BF16', 'shape': [len(blob) // 2], 'data_offsets': [len(data), len(data) + len(blob)]} - data += blob - h = json.dumps(header).encode() - return struct.pack('/gguf-py python scripts/offline/diff_native_pack.py [--quick] - -Needs numpy and the pinned gguf-py (quantized sources). Offline, CPU only, synthetic data. -""" -import contextlib -import re -import zlib -import hashlib -import io -import json -import os -import shutil -import struct -import subprocess -import sys -import tempfile -from pathlib import Path - -import numpy as np - -REPO = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(REPO / 'engine/strata/tools')) -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import iq_pack # noqa: E402 (the oracle, unchanged) -from ggufgen import write_gguf, string # noqa: E402 - -H, E = 256, 2 # hidden size / experts of the synthetic model -GGML = {'F32': 0, 'F16': 1, 'Q8_0': 8, 'Q4_K': 12, 'Q5_K': 13, 'Q6_K': 14, 'IQ3_XXS': 18, 'IQ4_NL': 20, - 'IQ3_S': 21, 'IQ2_S': 22, 'IQ4_XS': 23, 'BF16': 30, 'Q2_0': 42} -BLOCK = {'Q8_0': (32, 34), 'Q4_K': (256, 144), 'Q5_K': (256, 176), 'Q6_K': (256, 210), 'IQ3_XXS': (256, 98), - 'IQ4_NL': (32, 18), 'IQ3_S': (256, 110), 'IQ2_S': (256, 82), 'IQ4_XS': (256, 136), 'Q2_0': (64, 18)} -SCALE_AT = {'Q6_K': 208} # super-block scale `d` position (f16); the others start with it -FORM_NAMES = list(iq_pack.FORM) - - -def tokenizer_meta(): - out = [('tokenizer.ggml.model', 'str', 'gpt2'), ('tokenizer.ggml.pre', 'str', 'qwen35'), - ('tokenizer.chat_template', 'str', '{{ messages }}'), - ('tokenizer.ggml.tokens', ('array', 'str'), ['a', 'b', 'ab', '<|im_end|>']), - ('tokenizer.ggml.merges', ('array', 'str'), ['a b']), - ('tokenizer.ggml.token_type', ('array', 'u32'), [1, 1, 1, 3]), - ('tokenizer.ggml.eos_token_id', 'u32', 3)] - return out - - -def quant_bytes(rng, kind, n_elements, bad_scale=None): - elems, size = BLOCK[kind] - n = n_elements // elems - raw = rng.integers(0, 256, size=(n, size), dtype=np.uint8) - d = np.float16(rng.uniform(0.001, 0.05)) if bad_scale is None else np.float16(bad_scale) - at = SCALE_AT.get(kind, 0) - for b in range(n): - raw[b, at:at + 2] = np.frombuffer(np.float16(rng.uniform(0.001, 0.05) if bad_scale is None else d).tobytes(), np.uint8) - if kind in ('Q4_K', 'Q5_K'): # dmin follows d - for b in range(n): - raw[b, 2:4] = np.frombuffer(np.float16(rng.uniform(0.001, 0.05)).tobytes(), np.uint8) - return raw.tobytes() - - -def value_class(rng, cls, n): - """(ggml type name, raw bytes) for a source class.""" - f32 = lambda a: ('F32', np.asarray(a, np.float32).tobytes()) - if cls == 'f32_bf16x': - a = rng.normal(size=n).astype(np.float32) - return f32((a.view(np.uint32) & 0xFFFF0000).view(np.float32)) - if cls == 'f32_bf16x_inf': - a = (rng.normal(size=n).astype(np.float32).view(np.uint32) & 0xFFFF0000).view(np.float32).copy() - a[3] = np.inf - return f32(a) - if cls == 'f32_bf16x_nan': - a = (rng.normal(size=n).astype(np.float32).view(np.uint32) & 0xFFFF0000).view(np.float32).copy() - a[5] = np.uint32(0x7FC00000).view(np.float32) - return f32(a) - if cls == 'f32_random': - return f32(rng.normal(size=n)) - if cls == 'f32_one_off': # one value off BF16 among exact ones - a = (rng.normal(size=n).astype(np.float32).view(np.uint32) & 0xFFFF0000).view(np.float32).copy() - a[7] = np.float32(1.00001) - return f32(a) - if cls == 'f32_halfway': # BF16 ties: even and odd mantissas, plus negatives - base = np.array([0x3F800000, 0x3F810000, 0x3F808000, 0x3F818000, 0xBF808000, 0xBF818000, 0x00008000, - 0x7F7F8000, 0x00018000, 0x80008000], np.uint32) - a = np.resize(base, n).view(np.float32) - return f32(a) - if cls == 'f32_f16x': # exactly representable in F16 - return f32(rng.normal(size=n).astype(np.float16).astype(np.float32)) - if cls == 'f32_f16edge': # F16 subnormals, ties, max, overflow-rounding - base = np.array([0x33000000, 0x33800000, 0x34000000, 0x387FC000, 0x477FE000, 0x477FF000, 0x477FEFFF, - 0xB8000000, 0x38000000, 0x33000001, 0x00000001, 0x80000000, 0x477FF001], np.uint32) - return f32(np.resize(base, n).view(np.float32)) - if cls == 'f32_big': - a = rng.normal(size=n).astype(np.float32) - a[2] = 1e10 - return f32(a) - if cls == 'f32_inf': - a = rng.normal(size=n).astype(np.float32) - a[1] = -np.inf - return f32(a) - if cls == 'f32_nan': - a = rng.normal(size=n).astype(np.float32) - a[4] = np.nan - return f32(a) - if cls in ('f16', 'f16_edge', 'f16_inf', 'f16_nan'): - a = rng.normal(size=n).astype(np.float16) - bits = a.view(np.uint16).copy() - if cls == 'f16_edge': - bits[:6] = [0x0001, 0x0400, 0x7BFF, 0x8001, 0x3C00, 0x8000] - if cls == 'f16_inf': - bits[2] = 0x7C00 - if cls == 'f16_nan': - # Quiet NaNs only: numpy's F16 to F32 widening of a SIGNALING NaN (the former 0x7D55) is not the same on every numpy - # build and CPU (numpy 2.0.2 keeps it signaling, 0x7FAAA000; the 2.5.4 run of the CI audit differed on x86), so the oracle - # itself disagrees across hosts. The Rust widening keeps the payload and the quiet bit exactly (quant-core). - bits[2], bits[6] = 0x7E00, 0x7F55 - return ('F16', bits.tobytes()) - if cls in ('bf16', 'bf16_inf', 'bf16_nan', 'bf16_edge'): - a = (rng.normal(size=n).astype(np.float32).view(np.uint32) >> 16).astype(np.uint16) - if cls == 'bf16_inf': - a[2] = 0x7F80 - if cls == 'bf16_nan': - a[2], a[6] = 0x7FC0, 0x7FA1 - if cls == 'bf16_edge': - a[:4] = [0x0001, 0x0080, 0x7F7F, 0x8001] - return ('BF16', a.tobytes()) - if cls == 'q:Q8_0_inf': - return ('Q8_0', quant_bytes(rng, 'Q8_0', n, bad_scale=np.inf)) - if cls.startswith('q:'): - kind = cls[2:] - return (kind, quant_bytes(rng, kind, n)) - raise KeyError(cls) - - -FLOAT_CLASSES = ['f32_bf16x', 'f32_bf16x_inf', 'f32_bf16x_nan', 'f32_random', 'f32_one_off', 'f32_halfway', - 'f32_f16x', 'f32_f16edge', 'f32_big', 'f32_inf', 'f32_nan', 'f16', 'f16_edge', 'f16_inf', - 'f16_nan', 'bf16', 'bf16_inf', 'bf16_nan', 'bf16_edge'] -QUANT_CLASSES = ['q:' + k for k in BLOCK] + ['q:Q8_0_inf'] - - -def base_tensors(rng): - """The tensors every pack needs: layer-0 router and experts, an unlisted float, token_embd, the PLE table.""" - zeros = lambda kind, nel: quant_bytes(rng, kind, nel) - return [ - ('blk.0.ffn_gate_inp.weight', [H, E], 0, np.full(H * E, 1.5, np.float32).tobytes()), - ('blk.0.attn_q_norm.weight', [H], 30, np.full(H, 0x3fc0, np.uint16).tobytes()), - ('unlisted_float.weight', [3], 1, np.arange(1, 4, dtype=np.float16).tobytes()), - ('token_embd.weight', [H, 2], 21, zeros('IQ3_S', H * 2)), - ('blk.1.ple_key.weight', [H, 2], 8, zeros('Q8_0', H * 2)), - ('per_layer_token_embd.weight', [H, 2], 8, zeros('Q8_0', H * 2)), - *expert_tensors(rng, 0)] - - -def expert_tensors(rng, layer, gate_kind='IQ3_S', down_kind='IQ3_S'): - return [(f'blk.{layer}.ffn_gate_exps.weight', [H, H, E], GGML[gate_kind], quant_bytes(rng, gate_kind, H * H * E)), - (f'blk.{layer}.ffn_up_exps.weight', [H, H, E], GGML[gate_kind], quant_bytes(rng, gate_kind, H * H * E)), - (f'blk.{layer}.ffn_down_exps.weight', [H, H, E], GGML[down_kind], quant_bytes(rng, down_kind, H * H * E))] - - -def write_model(root, stem, shards, architecture='qwen4exp', total=None, split_override=None): - """shards: list of tensor lists. Returns the shard paths (shard 1 first).""" - n = len(shards) - total = sum(len(s) for s in shards) if total is None else total - paths = [root / (f'{stem}-{i + 1:05}-of-{n:05}.gguf' if n > 1 else f'{stem}.gguf') for i in range(n)] - for i, (path, tensors) in enumerate(zip(paths, shards)): - meta = [] - if i == 0: - if architecture: - meta.append(('general.architecture', 'str', architecture)) - meta += tokenizer_meta() - if n > 1: - no, count, tt = (split_override or {}).get(i, (i, n, total)) - meta += [('split.no', 'u16', no), ('split.count', 'u16', count), ('split.tensors.count', 'i32', tt)] - write_gguf(path, tensors, meta) - return paths - - -class Harness: - def __init__(self, binary): - self.binary = str(Path(binary).resolve()) - self.root = Path(tempfile.mkdtemp(prefix='strata-pack-matrix-')) - self.count = 0 - self.accepted = 0 - self.rejected = 0 - self.failures = [] - self.unsupported = 0 - self.known_stricter = 0 - - def close(self): - shutil.rmtree(self.root, ignore_errors=True) - - def oracle(self, paths, compat): - out = self.root / 'oracle' - shutil.rmtree(out, ignore_errors=True) - out.mkdir() - with contextlib.redirect_stdout(io.StringIO()): - try: - model = iq_pack.Model(paths[0]) - table = iq_pack.expert_layout(model, paths[0]) - if isinstance(table, str): - return None - if iq_pack.index_standalone(paths[0], out, model, compat) != 0: - return None - except NotImplementedError: - return 'unsupported' # gguf-py cannot dequantize this type (Q2_0): nothing to compare against - except Exception: # noqa: BLE001 (a KeyError in the oracle is a refusal too) - return None - (out / 'native_experts.txt').write_text(table[1]) - return out - - def rust(self, paths, compat, extra=()): - out = self.root / 'rust' - shutil.rmtree(out, ignore_errors=True) - manifest = {'schema_version': 1, 'files': [ - {'name': p.name, 'url': 'https://example.invalid/' + p.name, 'size': p.stat().st_size, - 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()} for p in reversed(paths)]} - mpath = self.root / 'manifest.json' - mpath.write_text(json.dumps(manifest)) - cmd = [self.binary, 'model', 'prepare-native-pack', str(mpath), '--source-dir', str(paths[0].parent), - '--output', str(out)] + (['--compat-bf16'] if compat else []) + list(extra) - r = subprocess.run(cmd, env={'PATH': os.defpath}, text=True, capture_output=True, timeout=60) - stage = list(self.root.glob('.rust.native-pack-*.tmp')) - assert not stage, 'unremoved failed stage' - if r.returncode != 0: - assert not out.exists(), 'failed run published output' - return None, r.stderr - return out, json.loads(r.stdout) - - def check(self, label, paths, compat=False): - self.count += 1 - want = self.oracle(paths, compat) - if want == 'unsupported': - self.unsupported += 1 - return - got, info = self.rust(paths, compat) - if want is not None and got is None and \ - any(r['max_abs_err'] == float('inf') for r in json.loads((want / 'conversions.json').read_text())['tensors']): - # KNOWN DIVERGENCE (deliberate): iq_pack.py writes an infinity that BF16 rounding overflowed into and - # records max_abs_err=inf; the Rust packer refuses it, as both refuse F16 overflow. - self.known_stricter += 1 - return - if (want is None) != (got is None): - self.failures.append(f'{label} compat={compat}: oracle {"accepts" if want else "rejects"}, ' - f'rust {"accepts" if got else "rejects: " + str(info).strip()[-160:]}') - return - if want is None: - self.rejected += 1 - return - self.accepted += 1 - problems = compare_packs(want, got, compat) - if problems: - self.failures.append(f'{label} compat={compat}: ' + '; '.join(problems)) - - -def rows(path): - return [ln for ln in path.read_text().splitlines() if not ln.startswith('#')] - - -def compare_packs(want, got, compat, base=False): - bad = [] - if (want / 'dense.bin').read_bytes() != (got / 'dense.bin').read_bytes(): - bad.append('dense.bin differs') - if rows(want / 'index.txt') != rows(got / 'index.txt'): - bad.append('index rows differ') - if (want / 'index.txt').read_text().splitlines()[1:2] != (got / 'index.txt').read_text().splitlines()[1:2]: - bad.append('index pool/tensor header differs') - if (want / 'native_experts.txt').read_text() != (got / 'native_experts.txt').read_text(): - bad.append('native_experts.txt differs') - if base: # iq_pack.py --base writes no conversions.json (the Rust pack needs one: empty list) - return bad - a = json.loads((want / 'conversions.json').read_text()) - b = json.loads((got / 'conversions.json').read_text()) - for key in ('schema', 'compat_bf16', 'source_shards'): - if a[key] != b[key]: - bad.append(f'conversions.{key} differs') - if a['tensors'] != b['tensors']: - first = next((x, y) for x, y in zip(a['tensors'] + [None], b['tensors'] + [None]) if x != y) - bad.append('conversions tensors differ: oracle %s vs rust %s' % first) - if compat: - c = json.loads((want / 'compat-bf16.json').read_text()) - d = json.loads((got / 'compat-bf16.json').read_text()) - if (c['rounding'], c['tensors']) != (d['rounding'], d['tensors']): - bad.append('compat-bf16.json differs') - elif (got / 'compat-bf16.json').exists(): - bad.append('unexpected compat-bf16.json') - return bad - - -def single_tensor_cases(h, rng, quick): - names = [] - for key in FORM_NAMES: - names += [key, 'blk.1.' + key] - names += ['blk.2.ple_key.weight'] - classes = FLOAT_CLASSES + QUANT_CLASSES - quantized_names = {'ffn_gate_inp.weight', 'ple_conv1d.weight', 'attn_q_norm.weight', 'ple_key.weight', - 'ssm_a', 'ple_value.weight', 'hc_attn_down.weight'} - for name in names: - for cls in classes: - seed = zlib.crc32(f'{name}/{cls}'.encode()) - if quick and seed % 5: - continue - if cls.startswith('q:') and re.sub(r'^blk\.\d+\.', '', name) not in quantized_names: - continue - type_name, raw = value_class(np.random.default_rng(seed), cls, H * 2) - tensors = [t for t in base_tensors(rng) if t[0] != name] - tensors.append((name, [H, 2], GGML[type_name], raw)) - paths = write_model(h.root, 'case', [tensors]) - for compat in (False, True): - h.check(f'{name} <- {cls}', paths, compat) - - -def topology_cases(h, rng): - def layer_rows(layers, gate='IQ3_S', down='IQ3_S'): - out = [] - for layer in range(layers): - out.append((f'blk.{layer}.ffn_gate_inp.weight', [H, E], 0, np.full(H * E, 1.5, np.float32).tobytes())) - out += expert_tensors(rng, layer, gate, down) - return out - - common = [('token_embd.weight', [H, 2], 21, quant_bytes(rng, 'IQ3_S', H * 2)), - ('unlisted.weight', [4], 0, np.arange(4, dtype=np.float32).tobytes())] - # single shard, several layers with mixed expert types - t = common + layer_rows(1) + layer_rows(3)[4:] - t = [x for x in t if not (x[0] == 'blk.0.ffn_gate_inp.weight' and sum(1 for y in t if y[0] == x[0]) > 1)] - seen, uniq = set(), [] - for x in t: - if x[0] not in seen: - seen.add(x[0]) - uniq.append(x) - h.check('multi-layer single shard', write_model(h.root, 'multi', [uniq])) - mixed = common + layer_rows(1, 'IQ3_S', 'IQ4_NL') + [ - x for x in layer_rows(2, 'IQ2_S', 'Q2_0')[4:]] - h.check('mixed expert types', write_model(h.root, 'mixed', [mixed])) - # split topologies over 3 layers - allt = common + layer_rows(3) - by_name = {x[0]: x for x in allt} - layers = [[by_name[f'blk.{l}.ffn_gate_inp.weight'], by_name[f'blk.{l}.ffn_gate_exps.weight'], - by_name[f'blk.{l}.ffn_up_exps.weight'], by_name[f'blk.{l}.ffn_down_exps.weight']] for l in range(3)] - flat = lambda *groups: [x for g in groups for x in g] - h.check('2 shards: layers 1-2 in shard 2', write_model(h.root, 'two', [common + layers[0], flat(layers[1], layers[2])])) - h.check('2 shards: down roles in shard 2', write_model(h.root, 'twor', [ - common + [x for l in layers for x in l[:3]], [l[3] for l in layers]])) - h.check('2 shards: layer split mid-layer', write_model(h.root, 'twom', [ - common + layers[0] + layers[1][:2], [layers[1][2], layers[1][3]] + layers[2][:]])) - h.check('2 shards: shard 1 holds no expert at all', write_model(h.root, 'twoe', [ - common + [layers[0][0], layers[1][0], layers[2][0]], - flat(*[l[1:] for l in layers])])) - h.check('4 shards: one layer per shard + dense first', write_model(h.root, 'four', [ - common + [layers[0][0]], layers[0][1:] + [layers[1][0]], layers[1][1:] + [layers[2][0]], layers[2][1:]])) - h.check('4 shards: roles scattered', write_model(h.root, 'fours', [ - common + [layers[0][0], layers[1][0], layers[2][0]], - [layers[0][1], layers[1][3]], [layers[0][2], layers[2][1]], [layers[0][3], layers[1][2], layers[2][2], - layers[2][3]]])) - h.check('pruned experts (router 2 cols everywhere)', write_model(h.root, 'pr', [common + layers[0]])) - # malformed - h.check('reject: duplicate tensor in two shards', write_model(h.root, 'dup', [ - common + layers[0], [layers[0][3]]], total=len(common + layers[0]) + 1)) - h.check('reject: shard 2 declares a foreign split', write_model(h.root, 'foreign', [ - common + layers[0][:2], layers[0][2:]], split_override={1: (1, 2, 999)})) - h.check('reject: shard 2 declares split.no 0', write_model(h.root, 'norepeat', [ - common + layers[0][:2], layers[0][2:]], split_override={1: (0, 2, len(common + layers[0]))})) - h.check('reject: missing expert role', write_model(h.root, 'missing', [common + layers[0][:3]])) - h.check('reject: missing router', write_model(h.root, 'norouter', [common + layers[0][1:]])) - h.check('reject: router disagrees on expert count', write_model(h.root, 'rdis', [ - common + layers[0] + [('blk.1.ffn_gate_inp.weight', [H, E + 1], 0, np.zeros(H * (E + 1), np.float32).tobytes())] - + layers[1][1:]])) - h.check('reject: gate/up types differ', write_model(h.root, 'gudiff', [ - common + [layers[0][0], expert_tensors(rng, 0, 'IQ3_S')[0], expert_tensors(rng, 0, 'IQ2_S')[1], - expert_tensors(rng, 0)[2]]])) - h.check('reject: 3-D dense tensor', write_model(h.root, 'dense3', [ - common + layers[0] + [('odd.weight', [4, 2, 2], 0, np.zeros(16, np.float32).tobytes())]])) - h.check('reject: expert has wrong expert count', write_model(h.root, 'badE', [ - common + [layers[0][0]] + [(n, [H, H, E + 1], k, quant_bytes(rng, 'IQ3_S', H * H * (E + 1))) - for n, _, k, _ in layers[0][1:]]])) - # truncated file: cut the last tensor - paths = write_model(h.root, 'trunc', [common + layers[0]]) - data = paths[0].read_bytes() - paths[0].write_bytes(data[:-100]) - h.check('reject: truncated shard', paths) - - -def full_pack_cases(h, rng): - """Whole-CLI comparison: tools/iq_pack.py as a subprocess (tokenizer, experts.bin, --base) vs leleka-api.""" - py = sys.executable - tool = str(REPO / 'engine/strata/tools/iq_pack.py') - - def cli(label, paths, flags, base_flags=(), rust_flags=None): - h.count += 1 - want = h.root / 'cli-oracle' - shutil.rmtree(want, ignore_errors=True) - r = subprocess.run([py, tool, '--gguf', str(paths[0]), '--out', str(want), *flags], text=True, - capture_output=True, env={**os.environ, 'PYTHONWARNINGS': 'ignore'}) - got, info = h.rust(paths, False, rust_flags if rust_flags is not None else flags) - if (r.returncode == 0) != (got is not None): - h.failures.append(f'{label}: oracle rc={r.returncode} ({r.stdout.strip()[-100:]}), rust ' - f'{"accepts" if got else "rejects: " + str(info)[-200:]}') - return None - if got is None: - h.rejected += 1 - return None - h.accepted += 1 - problems = compare_packs(want, got, '--compat-bf16' in flags, '--base' in flags) - for name in ('experts.bin', 'extra.bin'): - if (want / name).exists() != (got / name).exists(): - problems.append(f'{name} presence differs') - elif (want / name).exists() and (want / name).read_bytes() != (got / name).read_bytes(): - problems.append(f'{name} differs') - if (want / 'experts.bin.src.json').exists(): - if json.loads((want / 'experts.bin.src.json').read_text()) != \ - json.loads((got / 'experts.bin.src.json').read_text()): - problems.append('experts.bin.src.json differs') - for name in ('vocab.json', 'token_type.json'): - if json.loads((want / 'tokenizer' / name).read_text()) != json.loads((got / 'tokenizer' / name).read_text()): - problems.append(f'tokenizer/{name} differs') - for name in ('merges.txt', 'chat_template.jinja'): - if (want / 'tokenizer' / name).read_bytes() != (got / 'tokenizer' / name).read_bytes(): - problems.append(f'tokenizer/{name} differs') - a = json.loads((want / 'tokenizer/tokenizer.json').read_text()) - b = json.loads((got / 'tokenizer/tokenizer.json').read_text()) - for k in a: - if k in b and a[k] != b[k]: - problems.append(f'tokenizer.json {k}: {a[k]!r} vs {b[k]!r}') - if problems: - h.failures.append(f'{label}: ' + '; '.join(problems)) - return got - - def layer(i, gate='IQ3_S', down='IQ3_S'): - return [(f'blk.{i}.ffn_gate_inp.weight', [H, E], 0, np.full(H * E, 1.5, np.float32).tobytes()), - *expert_tensors(rng, i, gate, down)] - - dense = [('token_embd.weight', [H, 2], 21, quant_bytes(rng, 'IQ3_S', H * 2)), - ('blk.0.attn_q_norm.weight', [H], 30, np.full(H, 0x3fc0, np.uint16).tobytes()), - ('blk.1.ple_conv1d.weight', [2], 0, np.array([1.00001, -2.0], np.float32).tobytes()), - ('blk.1.ple_key.weight', [H, 2], 8, quant_bytes(rng, 'Q8_0', H * 2)), - ('blk.3.hc_attn_down.weight', [H, 2], 0, - (rng.normal(size=H * 2).astype(np.float32).view(np.uint32) & 0xFFFF0000).view(np.float32).tobytes()), - ('blk.0.ssm_a', [4], 1, np.arange(1, 5, dtype=np.float16).tobytes()), - ('per_layer_token_embd.weight', [H, 2], 8, quant_bytes(rng, 'Q8_0', H * 2))] - model = dense + layer(0) + layer(1, 'IQ4_NL', 'Q2_0') + layer(2) - one = write_model(h.root, 'cli1', [model]) - cli('cli: default single', one, []) - q8 = [t if t[0] != 'blk.3.hc_attn_down.weight' else (t[0], t[1], 8, quant_bytes(rng, 'Q8_0', H * 2)) - for t in model] - q8p = write_model(h.root, 'cliq8', [q8]) - cli('cli: Q8_0 projection without --compat-bf16 (reject)', q8p, []) - cli('cli: --compat-bf16', q8p, ['--compat-bf16']) - cli('cli: --experts-bin', one, ['--experts-bin']) - cli('cli: --compat-bf16 --experts-bin', q8p, ['--compat-bf16', '--experts-bin']) - by = {t[0]: t for t in model} - lay = lambda i: [by[f'blk.{i}.ffn_gate_inp.weight'], by[f'blk.{i}.ffn_gate_exps.weight'], - by[f'blk.{i}.ffn_up_exps.weight'], by[f'blk.{i}.ffn_down_exps.weight']] - two = write_model(h.root, 'cli2', [dense[:-1] + lay(0) + [lay(1)[0]] + lay(1)[1:2], - lay(1)[2:] + lay(2) + dense[-1:]]) - cli('cli: 2 shards, layer split inside layer 1, --experts-bin', two, ['--experts-bin']) - cli('cli: 2 shards, --compat-bf16', two, ['--compat-bf16']) - - # --base: a canonical pack of a model whose PLE key is quantized; the new model has it as BF16 - model = q8 - base_model = [t if t[0] != 'blk.1.ple_key.weight' else ('blk.1.ple_key.weight', [H, 2], GGML['Q2_0'], - quant_bytes(rng, 'Q2_0', H * 2)) for t in model] - for variant in ('plain', 'ple-bf16', 'q8-both'): - new_model = [t for t in base_model] - if variant == 'ple-bf16': - new_model = [t if t[0] != 'blk.1.ple_key.weight' else ('blk.1.ple_key.weight', [H, 2], 30, - np.full(H * 2, 0x3f80, np.uint16).tobytes()) - for t in base_model] - if variant == 'q8-both': - base_model2 = base_model - base_paths = write_model(h.root, f'base-{variant}', [base_model]) - base_out = h.root / f'base-pack-{variant}' - shutil.rmtree(base_out, ignore_errors=True) - r = subprocess.run([py, tool, '--gguf', str(base_paths[0]), '--out', str(base_out), '--compat-bf16'], capture_output=True, - text=True, env={**os.environ, 'PYTHONWARNINGS': 'ignore'}) - assert r.returncode == 0, r.stdout + r.stderr - (base_out / 'manifest.json').write_text(json.dumps({'source': {'shard1': str(base_paths[0].absolute())}})) - new_paths = write_model(h.root, f'new-{variant}', [new_model]) - flags = ['--base', str(base_out)] - cli(f'cli: --base ({variant})', new_paths, flags) - # --base refused: a float tensor differs from the base; missing tensor; sharded; compat together - changed = [t if t[0] != 'blk.0.ssm_a' else ('blk.0.ssm_a', [4], 1, np.arange(2, 6, dtype=np.float16).tobytes()) - for t in base_model] - cli('cli: --base reject (float tensor differs)', write_model(h.root, 'new-diff', [changed]), ['--base', str(base_out)]) - cli('cli: --base reject (tensor missing)', write_model(h.root, 'new-miss', [[t for t in base_model if t[0] != 'blk.0.ssm_a']]), - ['--base', str(base_out)]) - - -def main(): - quick = '--quick' in sys.argv - args = [a for a in sys.argv[1:] if not a.startswith('--')] - h = Harness(args[0]) - rng = np.random.default_rng(1234) - try: - topology_cases(h, rng) - full_pack_cases(h, rng) - single_tensor_cases(h, rng, quick) - finally: - h.close() - for f in h.failures[:60]: - print('FAIL', f) - print(json.dumps({'cases': h.count, 'accepted': h.accepted, 'rejected': h.rejected, - 'oracle_cannot_dequantize': h.unsupported, 'known_stricter_bf16_overflow': h.known_stricter, 'failures': len(h.failures), 'oracle': 'tools/iq_pack.py (unmodified)'})) - return 1 if h.failures else 0 - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/scripts/offline/diff_tokenizer.py b/scripts/offline/diff_tokenizer.py deleted file mode 100644 index 73c85946..00000000 --- a/scripts/offline/diff_tokenizer.py +++ /dev/null @@ -1,276 +0,0 @@ -#!/usr/bin/env python3 -"""Tokenizer differential: leleka-api (crates/tokenizer, extract-tokenizer) vs the unmodified tools/strata_tokenizer.py. - - 1. pre-tokenizer: for EVERY Unicode scalar value, the qwen35 split of 13 one-character contexts (alone, next to a - letter / space / digit / punctuation / newline, doubled) in Rust's `fancy_regex` vs Python's `regex`. - 2. a synthetic GGUF (full 256-byte alphabet, BPE-trained merges that reach words past the 64-symbol heap path, - type-3 and type-4 specials, some with regex metacharacters): `extract-tokenizer` against `extract()` for all - five files, then ids from `tokenize-batch` (with and without special parsing) and text from `detokenize-batch` - over a boundary corpus plus fuzzed Unicode. - - python scripts/offline/diff_tokenizer.py [--stride N] [--fuzz N] [--seed S] - -Needs `regex` (pip install regex). --stride N checks every Nth scalar value (default 1 = all 1,112,064). -""" -import json -import random -import subprocess -import sys -import tempfile -from pathlib import Path - -REPO = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(REPO / 'engine/strata/tools')) -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import regex # noqa: E402 -import strata_tokenizer as T # noqa: E402 (the oracle, unchanged) -from ggufgen import write_gguf # noqa: E402 - -CONTEXTS = ['{c}', 'a{c}', '{c}a', ' {c}', '{c} ', '1{c}', '{c}1', '!{c}', '{c}!', '\n{c}', '{c}\n', '\r{c}', - '{c}{c}'] - - -def run_batch(binary, args, lines, chunk=200_000): - out = [] - for at in range(0, len(lines), chunk): - payload = ('\n'.join(lines[at:at + chunk]) + '\n').encode('utf-8') - r = subprocess.run([binary, 'model', *args], input=payload, capture_output=True, timeout=3600) - if r.returncode: - raise RuntimeError(r.stderr.decode('utf-8', 'replace')[-300:]) - out.extend(r.stdout.decode('utf-8').split('\n')[:-1]) # not splitlines(): U+2028, U+0085 ... - return out - - -def per_codepoint(binary, stride): - """-> (strings checked, version-skew strings, real mismatches). - - Python's `regex` (pinned 2026.9.10 by requirements.txt) carries Unicode 17 tables; Rust's regex-syntax carries - Unicode 16 (the same as Python 3.14's `unicodedata`); the pinned llama.cpp C++ tables are older still. A code - point that is unassigned in Unicode 16 (category Cn) but assigned in 17 may therefore split differently - that is - table skew, counted and reported, not a defect of the port. Anything else is a real mismatch.""" - import unicodedata - pattern = regex.compile(T.QWEN35_PATTERN) - scalars = [c for c in range(0x110000) if not 0xD800 <= c <= 0xDFFF] - scalars = scalars[::stride] if stride > 1 else scalars - real, skew, checked, groups = [], 0, 0, 20_000 - for at in range(0, len(scalars), groups): - batch = scalars[at:at + groups] - texts = [ctx.format(c=chr(c)) for c in batch for ctx in CONTEXTS] - owners = [c for c in batch for _ in CONTEXTS] - got = run_batch(binary, ['pre-tokenize-batch'], [json.dumps(t, ensure_ascii=True) for t in texts]) - assert len(got) == len(texts) - for text, owner, line in zip(texts, owners, got): - checked += 1 - have = json.loads(line) - if have == pattern.findall(text): - continue - if unicodedata.category(chr(owner)) == 'Cn': - skew += 1 - else: - real.append(f'U+{owner:04X} text={text!r}: regex={pattern.findall(text)!r} fancy={have!r}') - return checked, skew, real - - -def train_bpe(rng, merges_wanted=700): - """Byte-level BPE merges over a synthetic multilingual corpus, in GGUF order (tokens, merges).""" - b2u = T.BYTE_TO_UNICODE - pattern = regex.compile(T.QWEN35_PATTERN) - pools = ['the quick brown fox jumps over the lazy dog ', 'def foo(bar):\n return bar + 1\n', '你好,世界!今日は天気です。', - 'héllo wörld ça va ', 'Привет мир, как дела? ', 'x = [1, 2, 3] # list\n', "it's don't we're I'll they've ", - '😀🚀 emoji ', 'aaaa' * 40, 'abababababab' * 30, 'tool_call response result '] - words = {} - for _ in range(1500): - text = ''.join(rng.choice(pools) for _ in range(rng.randint(1, 4))) - for piece in pattern.findall(text): - word = tuple(b2u[b] for b in piece.encode('utf-8')) - words[word] = words.get(word, 0) + 1 - for n in (70, 100, 130): # long words that exercise the heap path (> 64 symbols) - words[tuple('a' for _ in range(n))] = 50 - words[tuple(b2u[b] for b in ('ab' * n).encode())] = 40 - words[tuple(b2u[b] for b in ('中文' * n).encode())] = 30 - merges = [] - for _ in range(merges_wanted): - counts = {} - for word, freq in words.items(): - for pair in zip(word, word[1:]): - counts[pair] = counts.get(pair, 0) + freq - if not counts: - break - best = max(counts.items(), key=lambda kv: (kv[1], kv[0]))[0] - merges.append(best) - merged = {} - for word, freq in words.items(): - out, i = [], 0 - while i < len(word): - if i + 1 < len(word) and (word[i], word[i + 1]) == best: - out.append(word[i] + word[i + 1]) - i += 2 - else: - out.append(word[i]) - i += 1 - merged[tuple(out)] = merged.get(tuple(out), 0) + freq - words = merged - tokens = [b2u[b] for b in range(256)] - for left, right in merges: - tokens.append(left + right) - return tokens, [f'{l} {r}' for l, r in merges] - - -SPECIALS = [('<|im_start|>', 3), ('<|im_end|>', 3), ('<|endoftext|>', 3), ('', 4), ('', 4), - ('', 4), ('', 4), ('<|a[b|>', 3), ('(x*)', 4), ('<|im_', 3)] - - -def build_gguf(root, rng): - tokens, merges = train_bpe(rng) - types = [1] * len(tokens) - for text, ty in SPECIALS: - tokens.append(text) - types.append(ty) - n_plain = len(tokens) - len(SPECIALS) - meta = [('general.architecture', 'str', 'qwen4exp'), ('tokenizer.ggml.model', 'str', 'gpt2'), - ('tokenizer.ggml.pre', 'str', 'qwen35'), - ('tokenizer.ggml.tokens', ('array', 'str'), tokens), ('tokenizer.ggml.merges', ('array', 'str'), merges), - ('tokenizer.ggml.token_type', ('array', 'i32'), types), - ('tokenizer.ggml.eos_token_id', 'u32', n_plain + 1), ('tokenizer.ggml.padding_token_id', 'u32', n_plain + 2), - ('tokenizer.ggml.bos_token_id', 'u32', n_plain), - ('tokenizer.chat_template', 'str', "{%- for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{%- endfor %}\nünïcode ✓")] - path = root / 'synthetic-tokenizer.gguf' - write_gguf(path, [('w', [1], 0, bytes(4))], meta) - return path, tokens, merges - - -def stricter_cases(binary, root): - """Inputs the Python tokenizer accepts that the Rust extractor refuses on purpose (each one asserted both ways).""" - bad = [] - b2u = T.BYTE_TO_UNICODE - base_tokens = [b2u[b] for b in range(256)] + ['ab'] - base = [('general.architecture', 'str', 'qwen4exp'), ('tokenizer.ggml.model', 'str', 'gpt2'), - ('tokenizer.ggml.pre', 'str', 'qwen35'), ('tokenizer.ggml.tokens', ('array', 'str'), base_tokens), - ('tokenizer.ggml.merges', ('array', 'str'), ['a b']), ('tokenizer.chat_template', 'str', 'tpl')] - - def case(label, meta): - path = root / f'stricter-{label}.gguf' - write_gguf(path, [('w', [1], 0, bytes(4))], meta) - T.Tokenizer.from_gguf(path) # the oracle accepts it - r = subprocess.run([binary, 'model', 'extract-tokenizer', str(path), '--output', str(root / f'out-{label}')], - capture_output=True, text=True) - if r.returncode == 0: - bad.append(f'{label}: rust accepted') - - merges = base[4] - case('duplicate-merge', [m if m is not merges else ('tokenizer.ggml.merges', ('array', 'str'), ['a b', 'a b']) - for m in base]) - case('no-chat-template', base[:5]) - case('negative-special-id', base + [('tokenizer.ggml.padding_token_id', 'i32', -1)]) - return bad - - -def compare_extraction(binary, gguf, root): - bad = [] - py_out, rs_out = root / 'py', root / 'rs' - T.extract(gguf, py_out) - r = subprocess.run([binary, 'model', 'extract-tokenizer', str(gguf), '--output', str(rs_out)], - capture_output=True, text=True) - if r.returncode: - return [f'extract-tokenizer failed: {r.stderr[-200:]}'] - a, b = py_out / 'tokenizer', rs_out / 'tokenizer' - if sorted(p.name for p in a.iterdir()) != sorted(p.name for p in b.iterdir()): - bad.append('file sets differ') - for name in ('vocab.json', 'token_type.json'): - if json.loads((a / name).read_text('utf-8')) != json.loads((b / name).read_text('utf-8')): - bad.append(f'{name} differs') - for name in ('merges.txt', 'chat_template.jinja'): - if (a / name).read_bytes() != (b / name).read_bytes(): - bad.append(f'{name} differs') - ca, cb = json.loads((a / 'tokenizer.json').read_text('utf-8')), json.loads((b / 'tokenizer.json').read_text('utf-8')) - if ca != cb: - bad.append(f'tokenizer.json differs: {[(k, ca.get(k), cb.get(k)) for k in set(ca) | set(cb) if ca.get(k) != cb.get(k)]}') - return bad - - -BOUNDARY = ['', ' ', 'Hello, world!', ' leading and trailing ', 'a\n\n\nb', 'def f(x):\n\treturn x # comment\n', - '你好,世界', 'مرحبا', '\U0001f600\U0001f680\U0001f1fa\U0001f1f8', 'é́ combining', '\x00\x01\x7f control', - ' non-breaking space', '1234567890', 'MixedCASE_and-dashes', '\r\n\r\n', '

', 'x' * 5000, - "it's don't WE'RE I'LL they've 'D 'm", '<|im_start|>user\nhi<|im_end|>\n', '<|im_star', '<|im_', 'x', - '', '(x*)(x*)', '<|a[b|>', 'a<|im_end|>b<|endoftext|>', '<<|im_end|>>', - '中' * 3000, '中文' * 600, 'a' * 500, 'ab' * 400, 'a' * 64, 'a' * 65, 'ab' * 32, 'ab' * 33, - 'तुम्हें नमस्ते', 'ก็ไป', '́leading mark', '٣١٢ ½ Ⅷ ² 𝟘', '\x1c\x1d\x1e\x1f', '\x85    ', - ' \n \n ', 'a b c d', ' \n', '\n ', '!!!\n\n', 'a‍b', '👨‍👩‍👧', 'BOM', '�', - '"quoted"', 'path/to/file.txt', 'a.b.c', 'x.y_z-9'] - - -def fuzz_text(rng): - pools = [ - list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), list('0123456789'), list(' \t\n\r\x0b\x0c'), - list("'s't're've'm'll'd'S'T'RE"), list('.,;:!?()[]{}<>/\\|_-+=*&^%$#@~`"'), - list('ً̀́̂̈҃ؐͅऀ़ั⃐️\U000e0100'), - list('éüñßçøåÆŒΩλπΣЖЯ中文日本語한국어กขคअआइ'), list('٣١٢½Ⅷ²𝟘¼'), - list('     

   \x85\x1c\x1f'), - list('​‌‍⁠�'), list('😀😂🚀🎉👨👩👧🏳🌈'), [chr(i) for i in range(0, 32)], - ['<|im_start|>', '<|im_end|>', '', '', '', '<|im_', '(x*)', '<|a[b|>'], - ['ab', 'abab', 'aaaa', 'tool', 'call', 'the ', 'ing ', 'ion', '中文'], - ] - out = [] - for _ in range(rng.choice([1, 3, 8, 20, 60, 200])): - pool = rng.choice(pools) - out.append(rng.choice(pool)) - return ''.join(out) - - -def compare_tokenization(binary, gguf, root, fuzz, rng): - bad = [] - tk = T.Tokenizer.from_gguf(gguf) - tok_dir = str(root / 'rs' / 'tokenizer') - texts = BOUNDARY + [fuzz_text(rng) for _ in range(fuzz)] - lines = [json.dumps(t) for t in texts] - for special in (False, True): - got = run_batch(binary, ['tokenize-batch', tok_dir] + (['--special'] if special else []), lines) - for text, line in zip(texts, got): - want = tk.encode(text, parse_special=special) - have = json.loads(line) - if have != want: - bad.append(f'encode(special={special}) {text[:60]!r}: python {want[:12]}.. rust {str(have)[:80]}') - if len(bad) > 15: - return bad - # decode: the ids Python produced, plus random id lists (multi-byte characters split across tokens) - id_lists = [tk.encode(t, parse_special=True) for t in texts] - n = len(tk.tokens) - for _ in range(max(200, fuzz // 4)): - id_lists.append([rng.randrange(n) for _ in range(rng.randint(0, 30))]) - got = run_batch(binary, ['detokenize-batch', tok_dir], [json.dumps(ids) for ids in id_lists]) - for ids, line in zip(id_lists, got): - try: - want = tk.decode(ids) - except KeyError: - want = None # a special token such as <|im_ is not in the byte alphabet (neither side decodes) - if json.loads(line) != want: - bad.append(f'decode {ids[:10]}: python {want!r} rust {line[:80]}') - if len(bad) > 15: - break - return bad - - -def main(): - args = sys.argv[1:] - opt = lambda name, default: int(args[args.index(name) + 1]) if name in args else default - binary = str(Path(args[0]).resolve()) - stride, fuzz, seed = opt('--stride', 1), opt('--fuzz', 4000), opt('--seed', 20261014) - rng = random.Random(seed) - failures = [] - root = Path(tempfile.mkdtemp(prefix='strata-tokenizer-diff-')) - gguf, tokens, merges = build_gguf(root, rng) - failures += ['extract: ' + b for b in compare_extraction(binary, gguf, root)] - failures += ['stricter: ' + b for b in stricter_cases(binary, root)] - failures += ['tokenize: ' + b for b in compare_tokenization(binary, gguf, root, fuzz, rng)] - checked, skew, real = per_codepoint(binary, stride) - failures += ['pre-tokenize: ' + b for b in real] - for f in failures[:50]: - print('FAIL', f[:400]) - print(json.dumps({'pretokenizer_strings_checked': checked, 'unicode17_table_skew_strings': skew, 'pretokenizer_real_mismatches': len(real), - 'vocab': len(tokens), 'merges': len(merges), 'fuzz_texts': fuzz, 'failures': len(failures), - 'oracle': 'tools/strata_tokenizer.py (unmodified) with regex ' + regex.__version__})) - return 1 if failures else 0 - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/scripts/offline/diff_tools.py b/scripts/offline/diff_tools.py deleted file mode 100644 index cd31e70f..00000000 --- a/scripts/offline/diff_tools.py +++ /dev/null @@ -1,302 +0,0 @@ -#!/usr/bin/env python3 -"""Differential for the small offline tools: leleka-api `tools ...` vs the unmodified Python originals. - - embd_bf16_pack.py -> tools embd-bf16-pack (synthetic safetensors checkpoint, BF16 table) - ple_fp8_pack.py -> tools ple-fp8-pack (3 shards of F8_E4M3 + BF16 scale) - draft_vocab.py -> tools draft-vocab (synthetic vocabulary with Han/kana/Hangul/Cyrillic tokens) - make_profile.py -> tools make-profile (ranked base + routing traces; 512, 256 and 8 experts) - mtp_rt.py -> tools mtp-rt (Q2_0 experts at the real H/FF geometry, 2 experts) - -Every output file must be byte-identical. Needs numpy, regex (draft_vocab imports the tokenizer) and the pinned -gguf-py (mtp_rt imports it): STRATA_GGUF_PY=/gguf-py python scripts/offline/diff_tools.py -""" -import contextlib -import io -import json -import random -import runpy -import struct -import subprocess -import sys -import tempfile -from pathlib import Path - -import numpy as np - -REPO = Path(__file__).resolve().parents[2] -TOOLS = REPO / 'engine/strata/tools' -sys.path.insert(0, str(TOOLS)) -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from ggufgen import write_gguf # noqa: E402 - -MASK = (1 << 64) - 1 - - -class SplitMix: - """splitmix64: the shared deterministic byte source of the Python generators and the Rust golden tests.""" - - def __init__(self, seed): - self.state = seed & MASK - - def next(self): - self.state = (self.state + 0x9E3779B97F4A7C15) & MASK - z = self.state - z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK - z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK - return z ^ (z >> 31) - - def bytes(self, n): - out = bytearray() - while len(out) < n: - out += struct.pack('> 1) % 0x12) << 7) | ((r >> 40) & 0x7F)) - return np.array(words, dtype='', 'ab'] - # a token that is only a piece of a multi-byte character, and special tokens - tokens += [b2u[0xE4] + b2u[0xB8]] - types = [1] * len(tokens) - types[-2] = 1 - meta = [('general.architecture', 'str', 'qwen4exp'), ('tokenizer.ggml.model', 'str', 'gpt2'), - ('tokenizer.ggml.pre', 'str', 'qwen35'), ('tokenizer.ggml.tokens', ('array', 'str'), tokens), - ('tokenizer.ggml.merges', ('array', 'str'), ['a b']), ('tokenizer.ggml.token_type', ('array', 'i32'), types), - ('tokenizer.chat_template', 'str', 'x')] - write_gguf(path, [('w', [1], 0, bytes(4))], meta) - return tokens - - -def check_draft_vocab(binary, root, bad): - gguf = root / 'vocab.gguf' - tokens = vocab_gguf(gguf) - rnd = random.Random(3) - base_ids = sorted(rnd.sample(range(len(tokens)), 40)) - base_file = root / 'base.bin' - base_file.write_bytes(struct.pack('<%di' % len(base_ids), *base_ids)) - dup_file = root / 'base-dup.bin' - dup_file.write_bytes(struct.pack('<%di' % 4, 300, 5, 300, 1)) - odd = root / 'odd.bin' - odd.write_bytes(b'abc') - far = root / 'far.bin' - far.write_bytes(struct.pack('<2i', 3, len(tokens) + 5)) - cases = [(None, ''), (None, 'cjk'), (None, 'han'), (None, 'kana,hangul'), (None, 'cyrillic'), - (None, 'cjk, cyrillic'), (None, 'cjk_punct'), (base_file, ''), (base_file, 'cjk'), - (base_file, 'cyrillic,han'), (dup_file, 'kana'), (base_file, 'bogus'), (odd, 'cjk'), (far, 'cjk')] - for number, (base, add) in enumerate(cases): - for with_out in (True, False): - for stats in (False, True): - args = ['--gguf', gguf] + (['--base', base] if base else []) + (['--add', add] if add else []) + \ - (['--stats'] if stats else []) - py_out, rs_out = root / f'd{number}-py.bin', root / f'd{number}-rs.bin' - for f in (py_out, rs_out): - f.unlink(missing_ok=True) - py = run_py('draft_vocab.py', *args, *(['--out', py_out] if with_out else [])) - rs = run_rust(binary, 'draft-vocab', *args, *(['--out', rs_out] if with_out else [])) - label = f'draft_vocab case {number} base={base and base.name} add={add!r} out={with_out} stats={stats}' - if (py.returncode == 0) != (rs.returncode == 0): - bad.append(f'{label}: python rc {py.returncode} ({py.stderr.strip()[-80:]}), rust rc ' - f'{rs.returncode} ({rs.stderr.strip()[-80:]})') - continue - if py.returncode: - continue - if with_out: - same_files(py_out, rs_out, [''], label, bad) - strip = lambda text, path: ''.join(l + '\n' for l in text.splitlines() if not l.startswith('wrote ')) - if strip(py.stdout, py_out) != strip(rs.stdout, rs_out): - bad.append(f'{label}: printed statistics differ:\n{py.stdout!r}\n{rs.stdout!r}') - - -# ------------------------------------------------------------------------------------------------ make_profile -def check_make_profile(binary, root, bad): - import make_profile as MP - rnd = random.Random(11) - for n_expert in (512, 256, 8): - base_pairs = [(l, e) for e in rnd.sample(range(n_expert), min(n_expert, 20)) for l in rnd.sample(range(48), 6)] - base_pairs = list(dict.fromkeys(base_pairs)) - base = root / f'base{n_expert}.bin' - MP.write_profile(base, base_pairs, n_expert) - traces = [] - for t in range(3): - blob = bytearray() - for _ in range(rnd.randint(1, 40)): - layer, k = rnd.randint(-1, 49), rnd.randint(0, 6) - blob += struct.pack('/gguf-py python scripts/offline/gen_goldens.py [name ...] - -Output directory: control-plane/tests/fixtures/offline/. Deterministic (fixed seeds); no model data. -""" -import json -import struct -import sys -from pathlib import Path - -import numpy as np - -REPO = Path(__file__).resolve().parents[2] -OUT = REPO / 'control-plane/tests/fixtures/offline' -sys.path.insert(0, str(REPO / 'engine/strata/tools')) -sys.path.insert(0, str(Path(__file__).resolve().parent)) -sys.path.insert(0, str(REPO / 'engine/strata')) - -GENERATORS = {} - - -def golden(fn): - GENERATORS[fn.__name__] = fn - return fn - - -@golden -def f16_bf16_vectors(): - """f32 bits -> numpy F16 (RNE, overflow -> inf) and gguf-py BF16 (ggml_compute_fp32_to_bf16) bits.""" - rng = np.random.default_rng(20261014) - edge = [0x00000000, 0x80000000, 0x00000001, 0x007FFFFF, 0x33000000, 0x33000001, 0x33800000, 0x34000000, - 0x387FC000, 0x38800000, 0x477FE000, 0x477FEFFF, 0x477FF000, 0x477FF001, 0x47800000, 0x7F7FFFFF, - 0x7F800000, 0xFF800000, 0x7FC00000, 0x7F800001, 0x3F800000, 0x3F808000, 0x3F818000, 0x3F7F8000, - 0x7F7F8000, 0xBF808000, 0x00008000, 0x00018000, 0x80008000] - random = rng.integers(0, 2**32, size=3600, dtype=np.uint64).astype(np.uint32) - # concentrate half of the random patterns where F16 is normal/subnormal and ties are likely - near = (rng.integers(0, 2, 400, dtype=np.uint32) << 31) | rng.integers(0x32000000, 0x47900000, 400, dtype=np.uint32) - bits = np.concatenate([np.array(edge, np.uint32), random, near.astype(np.uint32)]) - values = bits.view(np.float32) - with np.errstate(over='ignore', invalid='ignore'): - f16 = values.astype(np.float16).view(np.uint16) - from gguf import quants, GGMLQuantizationType as Q - bf16 = quants.quantize(values, Q.BF16).view(np.uint16) - out = bytearray() - for b, h, g in zip(bits, f16, bf16): - out += struct.pack(' 2500: - continue - try: - text = template.render(req['messages'], req['tools'], req['add_generation_prompt'], **req['kwargs']) - if len(cases['ok']) < 90: - cases['ok'].append({**req, 'rendered': text}) - except D.TemplateRequestError as e: - if len(cases['raised']) < 25: - cases['raised'].append({**req, 'error': str(e)}) - except Exception: # noqa: BLE001 (jinja2 errors: not part of the contract) - pass - (OUT / 'chat_template_oracle.json').write_text(json.dumps(cases, ensure_ascii=False, separators=(',', ':')) + '\n', - encoding='utf-8') - - -class _Vocab: - """A byte-level toy vocabulary for the reasoning-budget differential: ids 0-255 are single bytes, then specials and - a few multi-byte pieces. encode() is greedy longest-match over the pieces (all the wrap-up text needs).""" - - def __init__(self): - self.pieces = [bytes([i]) for i in range(256)] - for text in ('', '<|im_end|>', '<|endoftext|>', '\n\n', '\n\n', 'I have', - ' thought', ' about', ' this', ' long', ' enough', '; time', ' to', ' give', ' my', ' answer', - '.\n', '你', '好'): - self.pieces.append(text.encode()) - self.by_bytes = {} - for i, piece in enumerate(self.pieces): - self.by_bytes.setdefault(piece, i) - self.longest = max(len(p) for p in self.pieces) - - def token_bytes(self, i): - return self.pieces[i] - - def encode(self, text, parse_special=False): - data, out, at = text.encode(), [], 0 - while at < len(data): - for size in range(min(self.longest, len(data) - at), 0, -1): - i = self.by_bytes.get(data[at:at + size]) - if i is not None: - out.append(i) - at += size - break - return out - - def decode(self, ids): - return b''.join(self.pieces[i] for i in ids).decode('utf-8', 'replace') - - -@golden -def reasoning_budget_oracle(): - """Service.reasoning_budget over request/default values, and Service.run (the unmodified one, a scripted engine) - over generated token streams: the engine's calls (prompt, max_new), the ids generated, the finish reason, the - completion tokens and the text the output parser was fed.""" - import contextlib - import io - import random - import threading - sys.path.insert(0, str(REPO / 'engine/strata/serve')) - import frontend - import server - vocab = _Vocab() - - # -- reasoning_budget ------------------------------------------------------------------------------------------ - odd_strings = ['abc', "it's", 'a"b', 'both \' and "', 'new\nline', 'tab\t', '\x00', 'é', '你', '​', - ' ', '
', '\U0001f600', 'back\\slash', '', '12'] - values = [0, 1, 7, -1, -10 ** 12, 2 ** 40, 2 ** 63, 2 ** 64 - 1, 3.0, 0.0, -2.0, 1e15, 1e20, 1.5, 0.5, 1e-5, 2.5e-7, - True, False, None, [], [1, 'a', None], {'a': 1, 'b': [True, 2.5]}] + odd_strings - parse_cases = [] - svc = server.Service(object(), vocab, None) - for default in (0, 5, 2.0, 1.25, True, 'x'): - svc.reasoning_budget_tokens = default - for value in [*values, '__absent__', '__not_an_object__']: - if value == '__absent__': - req = {'other': 1} - elif value == '__not_an_object__': - req = [1, 2] - else: - req = {'reasoning_budget_tokens': value} - try: - case = {'request': req, 'default': default, 'ok': svc.reasoning_budget(req)} - except ValueError as e: - case = {'request': req, 'default': default, 'error': str(e)} - parse_cases.append(case) - case = {'request': None, 'default': 3} - svc.reasoning_budget_tokens = 3 - case['ok'] = svc.reasoning_budget(None) - parse_cases.append(case) - - # -- Service.run ----------------------------------------------------------------------------------------------- - rng = random.Random(20261014) - ID = {t: vocab.encode(t)[0] for t in ('', '<|im_end|>', '\n\n', '你', '好')} - letters = list(b'abcdefgh ,.\n') - - class Engine: - def __init__(self, streams): - self.streams, self.calls = streams, [] - - def generate(self, prompt, max_new, sampling, cancel): - self.calls.append([list(prompt), max_new]) - stream = self.streams[len(self.calls) - 1] if len(self.calls) <= len(self.streams) else [] - return (t for t in stream[:max_new]) - - class Recorder(frontend.OutputParser): - deltas = [] - - def feed(self, delta): - Recorder.deltas.append(delta) - return super().feed(delta) - - def thinking_stream(): - out = [] - for _ in range(rng.randint(0, 40)): - r = rng.random() - if r < .55: - out.append(rng.choice(letters)) - elif r < .65: - out.append(ord('<')) - elif r < .72: - out.append(ord('/')) - elif r < .78: - out += [0xE4, 0xBD, 0xA0][:rng.randint(1, 3)] - elif r < .84: - out += [ID['']) - elif r < .96: - out += [ord('<'), ord('/'), ord('t'), ord('h'), ord('i'), ord('n'), ord('k'), ord('>')] - else: - out.append(ID['<|im_end|>']) - return out - - run_cases = [] - for _ in range(400): - streams = [thinking_stream(), [rng.choice(letters) for _ in range(rng.randint(0, 12))] - + ([ID['<|im_end|>']] if rng.random() < .5 else [])] - case = {'prompt': [rng.randrange(256) for _ in range(rng.randint(0, 4))], - 'thinking': rng.random() < .85, - 'sampling': {} if rng.random() < .5 else {'reasoning_budget_tokens': rng.choice([None, 0, 1, 2, 3, 5, 8, 13, 40])}, - 'default': rng.choice([0, 0, 2, 4, 9]), - 'max_new': rng.choice([1, 2, 5, 10, 20, 31, 32, 33, 40, 60, 100]), - 'cancel': rng.random() < .08, - 'streams': streams} - svc = server.Service(Engine(streams), vocab, None) - svc.reasoning_budget_tokens = case['default'] - server.OutputParser = Recorder - Recorder.deltas = [] - cancel = threading.Event() - if case['cancel']: - cancel.set() - done, events = None, 0 - with contextlib.redirect_stdout(io.StringIO()): - for kind, payload in svc.run(case['prompt'], case['thinking'], None, case['max_new'], case['sampling'], - cancel): - if kind == 'done': - done = payload - case['expect'] = {'calls': svc.engine.calls, 'finish': done['finish'], - 'completion_tokens': done['completion_tokens'], 'text': ''.join(Recorder.deltas)} - run_cases.append(case) - server.OutputParser = frontend.OutputParser - - out = {'vocab': [p.hex() for p in vocab.pieces], 'wrap_up_ids': vocab.encode(server.REASONING_WRAP_UP), - 'wrap_up': server.REASONING_WRAP_UP, 'stop_ids': sorted(server.Service(object(), vocab, None).stop_ids), - 'budget': parse_cases, 'run': run_cases} - (OUT / 'reasoning_budget_oracle.json').write_text(json.dumps(out, ensure_ascii=False, separators=(',', ':')) + '\n', - encoding='utf-8') - - -def main(): - OUT.mkdir(parents=True, exist_ok=True) - names = sys.argv[1:] or list(GENERATORS) - for name in names: - GENERATORS[name]() - print('wrote', name) - - -if __name__ == '__main__': - import _paths - _paths.add_gguf_py() - main() diff --git a/scripts/offline/ggufgen.py b/scripts/offline/ggufgen.py deleted file mode 100644 index 010f0e25..00000000 --- a/scripts/offline/ggufgen.py +++ /dev/null @@ -1,53 +0,0 @@ -"""Synthetic GGUF v3 writer for the offline differential harnesses (small fixtures only, no model data). - -Metadata values are written from (key, type, value) triples; `type` is one of the 13 GGUF value types spelled -u8 i8 u16 i16 u32 i32 f32 bool str u64 i64 f64, or ('array', element_type). Tensors are (name, dims, ggml_type, -raw_bytes) with dims fastest-first, laid out sequentially at the file's alignment, as llama.cpp writes them. -""" -import struct - -SCALARS = {'u8': 'B', 'i8': 'b', 'u16': 'H', 'i16': 'h', 'u32': 'I', 'i32': 'i', 'f32': 'f', 'bool': '?', - 'u64': 'Q', 'i64': 'q', 'f64': 'd'} -TYPE_ID = {'u8': 0, 'i8': 1, 'u16': 2, 'i16': 3, 'u32': 4, 'i32': 5, 'f32': 6, 'bool': 7, 'str': 8, - 'array': 9, 'u64': 10, 'i64': 11, 'f64': 12} - - -def string(s): - b = s.encode() if isinstance(s, str) else s - return struct.pack(' (type id word, payload)""" - if isinstance(kind, tuple): - assert kind[0] == 'array' - element = kind[1] - payload = struct.pack(' threshold - if not np.any(live): - raise ValueError("value projection has zero usable rank") - inverse = (vec[:, live] / eig[live]) @ vec[:, live].T - route = (wk @ wv.T) @ inverse - residual = wk - route @ wv - qgram = wq @ wq.T - reference_sq = float(np.sum(qgram * (wk @ wk.T))) - error_sq = max(0.0, float(np.sum(qgram * (residual @ residual.T)))) - return route, { - "value_rank": int(np.sum(live)), - "head_dim": len(eig), - "value_gram_condition": float(eig[-1] / eig[live][0]), - "score_weight_relative_l2": float(np.sqrt(error_sq / reference_sq)) if reference_sq > 0 else None, - "key_subspace_relative_l2": float(np.linalg.norm(residual) / np.linalg.norm(wk)) if np.any(wk) else 0.0, - } - - -def load_tensor(binary, shard, name, root): - output = root / (name + ".f32") - run = subprocess.run([str(binary), "model", "export-tensor-f32", str(shard), name, - "--output", str(output)], capture_output=True, text=True) - if run.returncode: - raise RuntimeError(f"native projection export failed for {name}: {run.stderr[-1000:]}") - meta = json.loads(run.stdout) - dimensions = meta["dimensions"] - data = np.fromfile(output, dtype=" rows [output,input]. - return data.reshape(tuple(reversed(dimensions))), meta - - -def prepare(args): - shards = [p.resolve(strict=True) for p in args.shard] - manifest = json.loads(args.manifest.read_text()) - identities = manifest["files"] - entries = {Path(e.get("name", e.get("filename", ""))).name: e for e in identities} - if len(entries) != len(identities): - raise ValueError("manifest has duplicate or missing shard names") - if set(p.name for p in shards) != set(entries): - raise ValueError("provide exactly the manifest's verified source shards") - for p in shards: - if p.stat().st_size != entries[p.name]["size"]: - raise ValueError(f"source shard size mismatch: {p.name}") - if len(entries[p.name]["sha256"]) != 64: - raise ValueError("manifest must supply each verified model digest") - output = args.output.resolve() - if REPO == output or REPO in output.parents: - raise ValueError("routing weights must remain outside Git") - if output.exists() or Path(str(output) + ".json").exists(): - raise ValueError("refusing to overwrite a routing artifact") - # Header readers inspect metadata; export uses the pinned native GGUF decoder. - import sys - sys.path.insert(0, str(REPO / "engine/strata/tools")) - from gguf_reader import GGUFFile - locations = {} - for shard in shards: - for tensor in GGUFFile(shard).tensors: - if tensor.name in locations: - raise ValueError(f"duplicate tensor across shards: {tensor.name}") - locations[tensor.name] = shard - layers = sorted({int(name.split(".")[1]) for name in locations - if name.startswith("blk.") and name.endswith(".attn_k.weight")}) - if len(layers) != args.layers: - raise ValueError(f"expected {args.layers} QSA layers, found {len(layers)}") - output.parent.mkdir(parents=True, exist_ok=True) - old_mask = os.umask(0o077) - try: - with tempfile.TemporaryDirectory(prefix="query-route-", dir=output.parent) as tmp: - records, weights = [], [] - for layer in layers: - row, tensors = {"layer": layer, "heads": []}, {} - for role in ("q", "k", "v", "q_norm", "k_norm"): - name = f"blk.{layer}.attn_{role}.weight" - if name not in locations: - raise ValueError(f"missing QSA tensor {name}") - tensors[role], row[role] = load_tensor(args.binary, locations[name], name, Path(tmp)) - q, k, v = (tensors[role] for role in ("q", "k", "v")) - if q.shape != (args.heads * 2 * args.head_dim, k.shape[1]): - raise ValueError("expected Qwen interleaved per-head query/gate projection") - if k.shape != (args.kv_heads * args.head_dim, q.shape[1]) or v.shape != k.shape: - raise ValueError("unexpected GQA projection geometry") - q = q.reshape(args.heads, 2, args.head_dim, -1)[:, 0] - k = k.reshape(args.kv_heads, args.head_dim, -1) - v = v.reshape(args.kv_heads, args.head_dim, -1) - matrices = [] - for head in range(args.heads): - kv_head = head // (args.heads // args.kv_heads) - route, metrics = query_routing(q[head], k[kv_head], v[kv_head], args.rcond) - row["heads"].append({"head": head, "kv_head": kv_head, **metrics}) - matrices.append(route.T.astype(" per-head routing -> RoPE; score against RoPE(V), retrieve raw V", - "normalization": "linear weight-space initialization only; source Q/K RMS norms recorded but not folded", - "quality_gate": "not_run", "experimental": True, - "rcond": args.rcond, "layers": records} - with Path(str(output) + ".json").open("x") as stream: - json.dump(report, stream, indent=2, allow_nan=False) - stream.write("\n") - finally: - os.umask(old_mask) - - -def main(): - p = argparse.ArgumentParser(description=__doc__) - p.add_argument("--binary", type=Path, required=True) - p.add_argument("--shard", type=Path, action="append", required=True) - p.add_argument("--manifest", type=Path, required=True) - p.add_argument("--output", type=Path, required=True) - p.add_argument("--layers", type=int, default=12) - p.add_argument("--heads", type=int, default=24) - p.add_argument("--kv-heads", type=int, default=2) - p.add_argument("--head-dim", type=int, default=256) - p.add_argument("--rcond", type=float, default=1e-10) - args = p.parse_args() - if min(args.layers, args.heads, args.kv_heads, args.head_dim) < 1 or args.heads % args.kv_heads: - p.error("invalid layer/head geometry") - if not 0 < args.rcond < 1: - p.error("rcond must lie strictly between zero and one") - prepare(args) - - -if __name__ == "__main__": - main() diff --git a/scripts/q8/rebuild_quantizer_ptx.sh b/scripts/q8/rebuild_quantizer_ptx.sh deleted file mode 100644 index 27435ff7..00000000 --- a/scripts/q8/rebuild_quantizer_ptx.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/bin/bash -# Build the spliced PTX of every q8_1-quantizer asset from the modified .cu. -# Linux, CUDA 13.2.2 at ~/cuda-toolkits/13.2.2, run from the repository root: `bash scripts/q8/rebuild_quantizer_ptx.sh`. -# Output in $W/out (default /tmp/q8new/out); nothing is installed. -set -e -cd "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" -export PATH=$HOME/cuda-toolkits/13.2.2/bin:$PATH -R=$PWD; SRC=crates/cuda-driver/src; W=${W:-/tmp/q8new}; mkdir -p $W -INC="-I$R/engine/strata/include -I$R/engine/strata/third_party/ggml -I$R/$SRC/third_party/llamacpp/ggml-cuda -I$R/$SRC/third_party/llamacpp/ggml-include -I$R/$SRC/third_party/llamacpp/ggml-src" -FAST="-std=c++17 -O3 -arch=sm_120 --use_fast_math" -PREC="--ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false" -nvcc --ptx --fmad=true $FAST $INC $SRC/mtp_original_full_head_native.cu -o $W/mtp_original_full_head_native.ptx -nvcc -ptx $FAST $INC $SRC/native_head_native.cu -o $W/native_head_native.ptx -nvcc -ptx $FAST $INC $SRC/native_head_iq.cu -o $W/native_head_iq.ptx -nvcc $PREC $INC $SRC/mtp_original_full_head_iq.cu -o $W/mtp_original_full_head_iq.ptx -nvcc $PREC $INC $SRC/mtp_original_tail.cu -o $W/mtp_original_tail.ptx -nvcc $PREC $INC $SRC/mtp_original_full_checks.cu -o $W/mtp_original_full_checks.ptx -# chain_window.cu no longer compiles against the merged engine headers (FusedGrArgs ABI of 0.1.50): compile the kernel region alone -python3 - <<'PY' -import re -s=open("crates/cuda-driver/src/chain_window.cu").read() -a=s.index("namespace {\nstruct Q81Block") -b=s.index("// `native_scalar_sigmoid(_multi)_kernel`") -pre="#include \n#include \n#include \n#include \"strata/kernels/q8_1_finite.hpp\"\nusing strata::kernels::q8_1_ds;\nusing strata::kernels::q8_1_finite;\nusing strata::kernels::q8_1_quant;\n" -open("/tmp/q8new/chain_swiglu_only.cu","w").write(pre+s[a:b]) -PY -nvcc -ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --ftz=false $INC $W/chain_swiglu_only.cu -o $W/chain_window_swiglu.ptx -D=$W/out; mkdir -p $D -S="python3 scripts/q8/splice_ptx.py" -$S $SRC/mtp_original_full_head_native.ptx $W/mtp_original_full_head_native.ptx $D/mtp_original_full_head_native.ptx head_quant suffix:native_quantize_q8_1_kernelEPKfPNS1_8Q81BlockEi -$S $SRC/native_head_native.ptx $W/native_head_native.ptx $D/native_head_native.ptx head_quant suffix:native_quantize_q8_1_kernelEPKfPNS1_8Q81BlockEi -$S $SRC/native_head_iq.ptx $W/native_head_iq.ptx $D/native_head_iq.ptx suffix:quantize_q8_1_kernelEPKfP10block_q8_1x -$S $SRC/mtp_original_full_head_iq.ptx $W/mtp_original_full_head_iq.ptx $D/mtp_original_full_head_iq.ptx suffix:quantize_q8_1_kernelEPKfP10block_q8_1x -$S $SRC/mtp_original_tail.ptx $W/mtp_original_tail.ptx $D/mtp_original_tail.ptx mtp_original_quantize -$S $SRC/mtp_original_full_checks.ptx $W/mtp_original_full_checks.ptx $D/mtp_original_full_checks.ptx mtp_original_quantize -$S $SRC/chain_window.ptx $W/chain_window_swiglu.ptx $D/chain_window.ptx chain_swiglu_quant_kernel -# the sealed files end with one NUL (the loaders terminate the text with it); ptxas wants the text without it -for f in $D/*.ptx; do python3 -c "import sys; sys.stdout.buffer.write(open(sys.argv[1], 'rb').read().rstrip(bytes([0])))" $f > $W/check.ptx; ptxas -arch=sm_120 -o /dev/null $W/check.ptx && echo "ptxas ok $(basename $f)"; done -sha256sum $D/*.ptx diff --git a/scripts/smoke-controller-deployment.py b/scripts/smoke-controller-deployment.py index 3d3f9f72..eb41b982 100644 --- a/scripts/smoke-controller-deployment.py +++ b/scripts/smoke-controller-deployment.py @@ -27,7 +27,7 @@ def module(name, file): m = module('switcher', 'strata-model-switch.py') -fixture = module('pack_fixture', 'smoke-native-pack.py') +fixture = module('pack_fixture', 'native-pack-fixture.py') helper = module('cancel_fixture', 'smoke-worker-cancel.py') NATIVE = {'backend':'native'} BAD = {'backend':'agent','profile':'failed-cpu-fixture'} diff --git a/scripts/smoke-mtp-pack.py b/scripts/smoke-mtp-pack.py deleted file mode 100644 index e4afb978..00000000 --- a/scripts/smoke-mtp-pack.py +++ /dev/null @@ -1,181 +0,0 @@ -#!/usr/bin/env python3 -"""Pinned MTP acquisition and structural preflight; synthetic CPU worker only.""" -import copy -import hashlib -import http.client -import http.server -import importlib.util -import json -import os -from pathlib import Path -import re -import shutil -import socket -import subprocess -import struct -import sys -import tempfile -import threading -import time - -REPO = Path(__file__).resolve().parents[1] - - -def main(): - binary = str(Path(sys.argv[1]).resolve()) - spec = importlib.util.spec_from_file_location('native_pack_fixture', Path(__file__).with_name('smoke-native-pack.py')) - fixture = importlib.util.module_from_spec(spec) - spec.loader.exec_module(fixture) - with tempfile.TemporaryDirectory(prefix='strata-mtp-bootstrap-') as tmp: - root = Path(tmp).resolve() - source = root / 'http'; source.mkdir() - # Independent engine-consumer names, rather than the validator's own table. - consumer = (REPO / 'engine/strata/src/core/mtp.cpp').read_text() - # Engine 0.1.50 reads the Q8_0 weights through `wq("name", type)` (Q8_0, or Q4_0 under --mtp-q4) after checking them - # against the `required[]` list; the f32 and bf16 ones still go through `f32("name")` / `bf16("name")`. - required = re.search(r'const char\* required\[\] = \{(.*?)\};', consumer, re.S).group(1) - q8_names = set(re.findall(r'\bwq\("([^" ]+)"', consumer)) | set(re.findall(r'"([^"]+)"', required)) - assert len(q8_names) == 9, q8_names # the drafter's nine Q8_0 projections; another count means mtp.cpp changed again - names = sorted(set(re.findall(r'\b(q8|bf16|f32)\("([^" ]+)"\)', consumer)) | {('q8', name) for name in q8_names}) - records = json.loads((REPO / 'engine/strata/bench/results/2026-09-30-community-rtx-5090/mtp-manifest.json').read_text()) - shapes = {t['name'].removeprefix('mtp.').removeprefix('layers.0.'): t['shape'] for t in records} - names += [('q8', 'self_attn.indexer.index_qk_proj.weight'), ('f32', 'self_attn.indexer.k_layernorm.weight'), ('f32', 'self_attn.indexer.q_layernorm.weight')] - offset = 0; lines = [] - for kind, name in names: - kind = 'q8_0' if kind == 'q8' else kind - shape = shapes[name] - rows, cols = (1, shape[0]) if len(shape) == 1 else shape - offset = (offset + 255) // 256 * 256 - size = rows * (cols // 32 * 34 if kind == 'q8_0' else cols * (4 if kind == 'f32' else 2)) - lines.append(f'{name} {kind} {rows} {cols} {offset} {size}') - offset += size - with (source / 'dense.bin').open('wb') as f: - f.truncate(offset) # sparse synthetic values; geometry from independent pinned source - good_index = '\n'.join(lines) + '\n' - (source / 'dense.txt').write_text(good_index) - # Invalid pinned pack is deliberately tiny: verify no base-model fetch. - (source / 'experts.bin').write_bytes(b'invalid') - fixture.write_gguf(source / 'model.gguf', fixture.fixtures(), extra_fields=[ - ('qwen4exp.' + k, 4, struct.pack(' "$2" -printf 'READY 256 stop\\n' -while IFS= read -r line; do case "$line" in QUIT) exit 0 ;; esac; done -''') - worker.chmod(0o700) - with socket.socket() as probe: - probe.bind(('127.0.0.1', 0)); port = probe.getsockname()[1] - mtp = root / 'mtp-v1' - config = {'bind': f'127.0.0.1:{port}', 'mtp_pack': str(mtp), - 'assets': [{'manifest': str(mtp_manifest), 'directory': str(mtp)}], - 'native_model': {'manifest': str(model_manifest), 'source_dir': str(root / 'base'), 'output': str(root / 'pack'), 'runtime_profile': 'qwen4exp-flash-next'}, - 'engine': {'executable': str(worker), 'args': [str(marker)], 'startup_timeout_s': 5, 'max_restarts': 0}} - path = root / 'config.json' - env = {'PATH': os.defpath} - def run(command='provision', ok=True): - path.write_text(json.dumps(config)) - result = subprocess.run([binary, command, '--config', str(path)], env=env, capture_output=True, timeout=60) - assert (result.returncode == 0) == ok, (result.stdout, result.stderr) - return result - process = None - try: - assert json.loads(run('check-config').stdout)['mtp_pack'] == 'pinned_structural_check_pending' - assert not mtp.exists() and not requests - original = copy.deepcopy(config) - for args in [[str(marker), '--mtp', '/unused'], [str(marker), '--mtp=/unused']]: - config['engine']['args'] = args - run('serve', ok=False) - assert not requests and not marker.exists() - config = copy.deepcopy(original); config['assets'] = [] - run('serve', ok=False); assert not requests - config = copy.deepcopy(original) - run('serve', ok=False) - assert requests == ['/dense.txt', '/dense.bin', '/experts.bin'] - assert not (root / 'base').exists() and not marker.exists() - invalid = (mtp / 'experts.bin').read_bytes() - # Valid sparse shape/size fixture: no inference-quality assertion. - with (source / 'experts.bin').open('wb') as f: - f.truncate(512 * 3 * (2560 * 640 * 18 // 64)) - manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin']) - mtp = root / 'mtp-v2' - config['mtp_pack'] = str(mtp); config['assets'][0]['directory'] = str(mtp) - # Correct bytes/ranges, but transpose the rectangular Q projection. - bad_index = good_index.replace('self_attn.q_proj.weight q8_0 12288 2560', 'self_attn.q_proj.weight q8_0 2560 12288') - assert bad_index != good_index - (source / 'dense.txt').write_text(bad_index) - manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin']) - assert b'geometry' in run(ok=False).stderr - assert not (root / 'base').exists() and not marker.exists() - assert '/model.gguf' not in requests - assert (mtp / 'dense.txt').read_text() == bad_index - # Publish the good profile as a new version; preserve both rejected versions. - (source / 'dense.txt').write_text(good_index) - manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin']) - mtp = root / 'mtp-v3' - config['mtp_pack'] = str(mtp); config['assets'][0]['directory'] = str(mtp) - assert json.loads(run().stdout)['mtp_pack_structurally_validated'] is True - assert requests[-4:] == ['/dense.txt', '/dense.bin', '/experts.bin', '/model.gguf'] - assert (root / 'mtp-v1/experts.bin').read_bytes() == invalid and not marker.exists() - server.shutdown(); server.server_close(); thread.join() - count = len(requests) - run() # SHA verification and structural checks, offline reuse. - assert len(requests) == count - with tempfile.TemporaryFile() as log: - process = subprocess.Popen([binary, 'serve', '--config', str(path)], env=env, stdout=log, stderr=log) - deadline = time.monotonic() + 60 - while True: - assert process.poll() is None and time.monotonic() < deadline - try: - c = http.client.HTTPConnection('127.0.0.1', port, timeout=1) - c.request('GET', '/ready'); response = c.getresponse(); response.read(); c.close() - if response.status == 200: break - except OSError: - pass - time.sleep(.03) - assert marker.read_text().splitlines() == [str(mtp), str(root / 'pack'), str(root / 'base/model.gguf')] - process.terminate(); assert process.wait(timeout=8) == 0 - finally: - if process and process.poll() is None: - process.kill(); process.wait(timeout=5) - if thread.is_alive(): - server.shutdown(); server.server_close(); thread.join() - print('MTP bootstrap passed: pinned HTTP, invalid pack before base fetch/worker, exact args, offline reuse and previous version preserved; independent pinned geometry and byte-consistent transpose rejection, synthetic values only, no GPU/model quality qualification') - - -if __name__ == '__main__': - main() diff --git a/scripts/smoke-native-bootstrap.py b/scripts/smoke-native-bootstrap.py index e7712559..b53f7063 100644 --- a/scripts/smoke-native-bootstrap.py +++ b/scripts/smoke-native-bootstrap.py @@ -19,7 +19,7 @@ import time def main(): binary = str(Path(sys.argv[1]).resolve()) - spec = importlib.util.spec_from_file_location('pack_fixture', Path(__file__).with_name('smoke-native-pack.py')) + spec = importlib.util.spec_from_file_location('pack_fixture', Path(__file__).with_name('native-pack-fixture.py')) fixture = importlib.util.module_from_spec(spec) spec.loader.exec_module(fixture) requests = [] diff --git a/scripts/smoke-native-pack.py b/scripts/smoke-native-pack.py deleted file mode 100644 index dd36f66d..00000000 --- a/scripts/smoke-native-pack.py +++ /dev/null @@ -1,167 +0,0 @@ -#!/usr/bin/env python3 -"""Independent pinned Python pack oracle versus the native Rust CLI, CPU only.""" -import contextlib -import hashlib -import io -import json -import os -from pathlib import Path -import struct -import subprocess -import sys -import tempfile - -REPO = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO / 'engine/strata/tools')) -import iq_pack # Existing oracle, unchanged; numpy is test-only. - - -def string(s): - b = s.encode() - return struct.pack('']), - ('tokenizer.ggml.merges', ['a b'])]: - fields.append((k, 9, struct.pack('': 3} - assert (output / 'tokenizer/merges.txt').read_text() == 'a b' - assert [p.read_bytes() for p in paths] == source_before - before = (output / 'dense.bin').read_bytes() - run(paths, output, ok=False) - assert (output / 'dense.bin').read_bytes() == before - - # Failed preparation must publish no output, even after partial dense writes. - source = root / 'failure.gguf' - cases = [] - t = fixtures(); t[0] = (*t[0][:3], struct.pack(' "$out/SHA256SUMS" diff --git a/tools/kernel-ab/README.md b/tools/kernel-ab/README.md index 03e29be4..5eb63af6 100644 --- a/tools/kernel-ab/README.md +++ b/tools/kernel-ab/README.md @@ -1,7 +1,11 @@ # tools/kernel-ab - the C++ reference half of the CPU kernel A/B (STRA-248, S0.8a) +> **Retired (STRA-406).** The C++ driver (`cpp/`) and its wrappers (`smoke.sh`, `time_smoke.sh`, `aa.sh`) compiled the Strata CPU kernels from the +> vendored tree, which was removed (history: `third_party/strata/UPSTREAM.md`). Only `verify_manifest.py` (the KAB1 reader rule) is kept; the sections +> below describe the measurement as it was run. + Out-of-tree measurement tooling in the pattern of `scripts/cuda-q5-oracle`, `scripts/cuda-qsa-oracle` and -`scripts/cuda-projection-family-oracle`: the kernels are the **unchanged** `engine/strata` sources, built outside the tree, +`scripts/cuda-projection-family-oracle`: the kernels are the **unchanged** Strata 41cf05a0 sources, built outside the tree, and every output goes to a private run directory outside Git. Nothing here is a Cargo package, nothing is linked into production, and Python is used offline only (`verify_manifest.py`, standard library, Python >= 3.9). @@ -21,13 +25,13 @@ The Rust half (`examples/kernel_ab/main.rs`, reader, comparison, alternation) is ## Why a Makefile and not CMake -The leaf was written as a CMake project that `add_subdirectory(engine/strata)`. The Linux server has no `cmake` (attempt 1 of +The leaf was written as a CMake project that `add_subdirectory()`. The Linux server has no `cmake` (attempt 1 of the leaf stopped there). By the orchestrator's decision of 2026-10-28 (comment `49943e61` on STRA-248) the driver is built from the needed translation units with the server's `g++` 15.2.0 / `make`, in a user-space directory, with no installation, no container and no change to the host. The KAB1 contract is unchanged; only the build recipe differs. What "the flags are the engine's by construction" becomes: the Makefile transcribes the Release flags and per-file options of -`engine/strata/CMakeLists.txt` and of ggml 3cf03257f's own CMake files, and `make check-pin` greps both CMake trees for every +`Strata 41cf05a0, CMakeLists.txt` and of ggml 3cf03257f's own CMake files, and `make check-pin` greps both CMake trees for every transcribed string (the five per-file option lists, `CMAKE_CXX_STANDARD 20`, `CMAKE_CXX_EXTENSIONS OFF`, Release, `GGML_NATIVE ON`, the source lists, the ggml `-march=native` / `GGML_USE_CPU_REPACK` / `_XOPEN_SOURCE` / `_GNU_SOURCE` lines, the llama.cpp `GIT_TAG`). A drift of the engine's flags makes `check-pin` fail instead of being copied silently. This is a transcription with a drift @@ -37,7 +41,7 @@ Recorded in `manifest.json` (`provenance`) and printed by the build: compiler id strings (`strata_cxx_flags`, `strata_per_file_flags`, `ggml_c_flags`, `ggml_cxx_flags`, `ggml_cpu_arch_flags`), `GGML_NATIVE=ON` (ggml-cpu is built with `-march=native` for the **build host**, so build and run on the same machine), `STRATA_PORTABLE=OFF`, `STRATA_ISA_FLOOR` empty, `STRATA_ENABLE_CUDA=OFF`, the ggml commit (pin + the checkout's actual HEAD), -the `engine/strata` pin from `third_party/strata/UPSTREAM.md`, and the tools commit. The comparator flags are the **pin's CMake flags**, not +the Strata 41cf05a0 pin from `third_party/strata/UPSTREAM.md`, and the tools commit. The comparator flags are the **pin's CMake flags**, not those of upstream's release packaging (`third_party/strata/UPSTREAM.md`: the packaging recipes were not run here). The Makefile's `STRATA_AVXVNNI` define comes from running the engine's own probe (`cpp/avxvnni_probe.cpp`); ggml's own @@ -97,11 +101,11 @@ recorded `false` and the two trees are identical by construction. ## Stage composition (parent AC7 / this leaf's AC6) `kab` computes nothing itself. `compose_expert()` in `cpp/kab.cpp` calls the stage entry points declared in -`engine/strata/include/strata/kernels/cpu/native_expert.hpp` (`native_fmt` line 49, `native_quant_act` line 52, `native_quant_h` line 54, +`Strata 41cf05a0, include/strata/kernels/cpu/native_expert.hpp` (`native_fmt` line 49, `native_quant_act` line 52, `native_quant_h` line 54, `native_gu_rows` line 60, `native_down_rows` line 63) and the Q2_0 kernels of `expert_layout.hpp` (`q2_native_kernels` line 81, `q2_rows_any`, `act_quant_any`), in the order and with the branches the engine's pool uses for one routed expert over `nt` tokens: -| Step | Engine C++ (pin, `engine/strata`) | `kab.cpp` | +| Step | Engine C++ (pin, Strata 41cf05a0) | `kab.cpp` | | --- | --- | --- | | layer format | `crates/native-cpu-expert/src/miss_abi.cpp:91` `native_fmt(gu, down, H, FF, ...)` | `format_for()` (also asserts the engine's `up_off` / `bytes - down_off` equal the KAB1 sizes) | | quantize each token | `miss_abi.cpp:108-109`: `gu_type == 42 ? act_quant_any : native_quant_act` | first loop of `compose_expert()` | @@ -153,7 +157,7 @@ The command line is the same as the Rust half's (STRA-318), so one runner can al and TSC ticks (lfence-serialised `rdtsc`) per call, plus the dependent-add core-clock calibration before and after. * **Dropped slices.** The method and the constant are `tq_cpu_parity --bench`'s: `core_ghz()` (`tq_cpu_parity.cpp` lines 273-284) and `time_slice()` (lines 290-304); a slice is dropped when `std::fabs(g1 - g0) > 0.05 * g0`, i.e. the clock moved by more than 5 percent - (**`engine/strata/src/kernels/cpu/tq_cpu_parity.cpp`, line 303**, copied, no new threshold). `slices[]` holds the kept slices, `dropped[]` + (**`Strata 41cf05a0, src/kernels/cpu/tq_cpu_parity.cpp`, line 303**, copied, no new threshold). `slices[]` holds the kept slices, `dropped[]` the dropped ones, `dropped_count` and `slices_kept` the counts; the median of the kept slices is in `median_ns_per_call` / `median_tsc_per_call`. * **Recorded in `F.json`**: `manifest_sha256` and the case's `input_sha256` (checked against the manifest before use; a mismatch refuses the run), `tree` (`avx512` | `avx2`, from `cpu_avx512_ok()`) with its probes, `effective_env` (every `STRATA_*` / `LELEKA_*` variable the process saw), diff --git a/tools/kernel-ab/aa.sh b/tools/kernel-ab/aa.sh deleted file mode 100755 index 83b556c7..00000000 --- a/tools/kernel-ab/aa.sh +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/env bash -# tools/kernel-ab/aa.sh - STRA-317 (S0.8a2): the C++ A/A control of the CPU kernel A/B timing. -# -# bash tools/kernel-ab/aa.sh D -# -# D a KAB1 run directory written by `kab gen` (STRA-248); never written to (an extra file would make verify_manifest.py refuse it) -# case case id, e.g. 18-20-r1 -# rounds number of rounds (30 for the A/A control of the plan) -# seed integer; writes the order schedule BEFORE the first run (balanced: half of the rounds "a first", half "b first", shuffled by the seed) -# cpu the logical CPU both processes are pinned to (a physical core whose SMT sibling is idle) -# -# One round = two FRESH `kab time` processes of the SAME binary, labelled a and b, run one after the other in the scheduled order, -# both pinned to , STRATA_* / LELEKA_* scrubbed from their environment (the cell avx2 sets only STRATA_FORCE_AVX2=1). Per round -# and regime the ratio is median slice ns of b / median slice ns of a (the same statistic the Rust/C++ comparison uses). Only the -# ratios are written: NO verdict and no class (the A/A class is computed later by the S0.10b classifier, STRA-313). -# -# Output (default: next to D, never inside it): /aa---s/ -# schedule.tsv written first: roundfirst (a|b)pincell -# rounds/rNN-a.json, rNN-b.json the full `kab time` records -# ratios.tsv "#" comment lines (the column header is one of them), then EXACTLY data lines: -# round first ratio_resident ratio_streamed median_ns_a_resident median_ns_b_resident median_ns_a_streamed median_ns_b_streamed -# kept_a_resident kept_b_resident kept_a_streamed kept_b_streamed dropped_total -# -# Environment: KAB (binary; default $E2E_ROOT/build/kernel-ab/kab) E2E_ROOT (default $HOME/work/leleka-e2e) -# AA_CELL avx512|avx2 (default avx512) AA_SLICES (default 50) AA_SLICE_MS (default: kab's 60) AA_OUT (output dir) -# PYTHON (default python3; stdlib only, offline arithmetic and JSON reading) -# CPU only, no GPU, nothing installed. Timing taken on a shared host is noisy and is not evidence by itself: each record carries the -# load average and the SMT sibling's busy fraction. -set -euo pipefail - -if [ "$#" -ne 5 ]; then - echo "usage: bash tools/kernel-ab/aa.sh D " >&2 - exit 2 -fi -d="${1%/}"; cas="$2"; rounds="$3"; seed="$4"; cpu="$5" -here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -repo="$(cd "${here}/../.." && pwd)" -root="${E2E_ROOT:-${HOME}/work/leleka-e2e}" -kab="${KAB:-${root}/build/kernel-ab/kab}" -cell="${AA_CELL:-avx512}" -slices="${AA_SLICES:-50}" -py="${PYTHON:-python3}" -export PYTHONDONTWRITEBYTECODE=1 - -case "${rounds}" in ''|*[!0-9]*) echo "aa.sh: rounds must be a positive integer" >&2; exit 2;; esac -case "${seed}" in ''|*[!0-9]*) echo "aa.sh: seed must be a non-negative integer" >&2; exit 2;; esac -case "${cpu}" in ''|*[!0-9]*) echo "aa.sh: cpu must be a logical CPU number" >&2; exit 2;; esac -[ "${rounds}" -ge 1 ] || { echo "aa.sh: rounds must be >= 1" >&2; exit 2; } -case "${cell}" in avx512|avx2) ;; *) echo "aa.sh: AA_CELL must be avx512 or avx2" >&2; exit 2;; esac -[ -f "${d}/manifest.json" ] || { echo "aa.sh: ${d} has no manifest.json (not a complete KAB1 run directory)" >&2; exit 2; } -[ -f "${d}/case-${cas}.in" ] || { echo "aa.sh: ${d}/case-${cas}.in does not exist" >&2; exit 2; } -[ -x "${kab}" ] || { echo "aa.sh: ${kab} is not an executable (build with make -C tools/kernel-ab/cpp BUILD=...)" >&2; exit 2; } - -dabs="$(cd "${d}" && pwd)" -out="${AA_OUT:-$(dirname "${dabs}")/aa-$(basename "${dabs}")-${cas}-s${seed}}" -case "${out}/" in "${repo}/"*) echo "aa.sh: output directory ${out} is inside the repository" >&2; exit 1;; esac -case "${out}/" in "${dabs}/"*) echo "aa.sh: output directory ${out} is inside the KAB1 run directory" >&2; exit 1;; esac -[ ! -e "${out}" ] || { echo "aa.sh: ${out} exists; remove it or set AA_OUT" >&2; exit 1; } -mkdir -p "${out}/rounds" - -# ---- the schedule, written BEFORE the first run ------------------------------------------------------------------------------- -"${py}" -I - "${rounds}" "${seed}" "${cpu}" "${cell}" > "${out}/schedule.tsv" <<'PY' -import sys -rounds, seed, cpu, cell = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3], sys.argv[4] -M = (1 << 64) - 1 -state = seed & M -def nxt(): # SplitMix64: the same sequence on every host and Python version - global state - state = (state + 0x9E3779B97F4A7C15) & M - z = state - z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & M - z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & M - return z ^ (z >> 31) -order = ["a"] * ((rounds + 1) // 2) + ["b"] * (rounds // 2) # balanced -for i in range(len(order) - 1, 0, -1): # Fisher-Yates - j = nxt() % (i + 1) - order[i], order[j] = order[j], order[i] -print("# seed=%d rounds=%d (balanced: %d a-first, %d b-first)" % (seed, rounds, order.count("a"), order.count("b"))) -print("round\tfirst\tpin\tcell") -for r, f in enumerate(order, 1): - print("%d\t%s\t%s\t%s" % (r, f, cpu, cell)) -PY -echo "aa: schedule written to ${out}/schedule.tsv" - -# ---- the scrubbed environment of the cell ------------------------------------------------------------------------------------- -scrub=() -while IFS= read -r v; do scrub+=(-u "$v"); done < <(compgen -e | grep -E '^(STRATA_|LELEKA_)' || true) -cellenv=() -[ "${cell}" = "avx2" ] && cellenv=(STRATA_FORCE_AVX2=1) -extra=() -[ -z "${AA_SLICE_MS:-}" ] || extra=(--slice-ms "${AA_SLICE_MS}") - -run_one() { #